repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maxiwinkler07/pop-the-lock | Pop The Lock!/Pop The Lock!/GameScene.swift | 1 | 5572 | //
// GameScene.swift
// Pop The Lock!
//
// Created by Maxi Winkler on 19/9/15.
// Copyright (c) 2015 Informaticamaxi. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var Circle = SKSpriteNode()
var Person = SKSpriteNode()
var Path = UIBezierPath()
var Dot = SKSpriteNode()
var gameStarted = Bool()
var movingClockwise = Bool()
var intersected = false
override func didMoveToView(view: SKView) {
loadView()
}
func loadView(){
backgroundColor = SKColor.whiteColor()
Circle = SKSpriteNode(imageNamed: "Circle")
Circle.size = CGSize(width: 300, height: 300)
Circle.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(Circle)
Person = SKSpriteNode(imageNamed: "Person")
Person.size = CGSize(width: 40, height: 7)
Person.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 120)
Person.zRotation = 3.14 / 2
Person.zPosition = 2.0
self.addChild(Person)
AddDot()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if gameStarted == false{
moveClockWise()
movingClockwise = true
gameStarted = true
}
else if gameStarted == true{
dotTouched()
if movingClockwise == true{
moveCounterClockWise()
movingClockwise = false
}
else if movingClockwise == false{
moveClockWise()
movingClockwise = true
}
}
}
func AddDot (){
Dot = SKSpriteNode(imageNamed: "Dot")
Dot.size = CGSize(width: 30, height: 30)
Dot.zPosition = 1.0
let dx = Person.position.x - self.frame.width / 2
let dy = Person.position.y - self.frame.height / 2
let rad = atan2(dy, dx)
if movingClockwise == true {
let tempAngle = CGFloat.random(min: rad + 1.0, max: rad + 2.5 )
let Path2 = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: tempAngle, endAngle: tempAngle + CGFloat(M_PI * 4), clockwise: true)
Dot.position = Path2.currentPoint
}
else if movingClockwise==false{
let tempAngle = CGFloat.random(min: rad - 1.0, max: rad - 2.5 )
let Path2 = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: tempAngle, endAngle: tempAngle + CGFloat(M_PI * 4), clockwise: true)
Dot.position = Path2.currentPoint
}
self.addChild(Dot)
}
func moveClockWise(){
let dx = Person.position.x - self.frame.width / 2
let dy = Person.position.y - self.frame.height / 2
let rad = atan2(dy, dx)
Path = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
let follow = SKAction.followPath(Path.CGPath, asOffset: false, orientToPath: true, speed: 200)
Person.runAction(SKAction.repeatActionForever(follow).reversedAction())
}
func moveCounterClockWise(){
let dx = Person.position.x - self.frame.width / 2
let dy = Person.position.y - self.frame.height / 2
let rad = atan2(dy, dx)
Path = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
let follow = SKAction.followPath(Path.CGPath, asOffset: false, orientToPath: true, speed: 200)
Person.runAction(SKAction.repeatActionForever(follow))
}
func dotTouched(){
if intersected == true{
Dot.removeFromParent()
AddDot()
intersected = false
}else if intersected == false{
died()
}
}
func died(){
let action1 = SKAction.colorizeWithColor(UIColor.redColor(), colorBlendFactor: 1.0, duration: 0.2)
let action2 = SKAction.colorizeWithColor(UIColor.whiteColor(), colorBlendFactor: 1.0, duration: 0.2)
self.scene?.runAction(SKAction.sequence([action1, action2]))
movingClockwise = false
intersected = false
gameStarted = false
self.loadView()
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if Person.intersectsNode(Dot){
intersected = true
}
else{
if intersected == true{
if Person.intersectsNode(Dot) == false{
died()
}
}
}
}
}
| mit | 3d46f96100775a472b87c81dd82f75f7 | 26.448276 | 201 | 0.515075 | 4.909251 | false | false | false | false |
WebAPIKit/WebAPIKit | Sources/WebAPIKit/Request/Request+Config.swift | 1 | 4508 | /**
* WebAPIKit
*
* Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
// MARK: Config `sender`
extension WebAPIRequest {
@discardableResult
open func setHttpClient(_ httpClient: HTTPClient) -> Self {
self.httpClient = httpClient
return self
}
}
// MARK: Config plugins
extension WebAPIRequest {
@discardableResult
open func setPlugins(_ plugins: PluginHub) -> Self {
self.plugins = plugins
return self
}
@discardableResult
open func addPlugin(_ plugin: WebAPIPlugin) -> Self {
let plugins = self.plugins ?? PluginHub()
plugins.add(plugin)
self.plugins = plugins
return self
}
@discardableResult
open func addPlugins(block: (PluginHub) -> Void) -> Self {
let plugins = self.plugins ?? PluginHub()
block(plugins)
self.plugins = plugins
return self
}
}
// MARK: Config `authentication`
extension WebAPIRequest {
@discardableResult
open func setRequireAuthentication(_ requireAuthentication: Bool) -> Self {
self.requireAuthentication = requireAuthentication
return self
}
@discardableResult
open func setAuthentication(_ authentication: WebAPIAuthentication) -> Self {
self.authentication = authentication
return self
}
}
// MARK: Config `queryItems`
extension WebAPIRequest {
@discardableResult
open func setQueryItems(_ queryItems: [URLQueryItem]) -> Self {
self.queryItems = queryItems
return self
}
@discardableResult
open func setQueryItems(_ queryItems: [(name: String, value: String)]) -> Self {
self.queryItems = queryItems.map { URLQueryItem(name: $0.name, value: $0.value) }
return self
}
@discardableResult
open func addQueryItem(name: String, value: String) -> Self {
queryItems.append(URLQueryItem(name: name, value: value))
return self
}
}
// MARK: Config `headers`
extension WebAPIRequest {
@discardableResult
open func setHeaders(_ headers: [String: String]) -> Self {
self.headers = headers
return self
}
@discardableResult
open func addHeader(key: String, value: String) -> Self {
self.headers[key] = value
return self
}
@discardableResult
open func setHeaders(_ headers: [RequestHeaderKey: String]) -> Self {
self.headers = [:]
headers.forEach { self.headers[$0.rawValue] = $1 }
return self
}
@discardableResult
open func addHeader(key: RequestHeaderKey, value: String) -> Self {
self.headers[key.rawValue] = value
return self
}
}
// MARK: Config `parameters` & `httpBody`
extension WebAPIRequest {
@discardableResult
open func setParameters(_ parameters: [String: Any]) -> Self {
self.parameters = parameters
return self
}
@discardableResult
open func addParameter(key: String, value: Any) -> Self {
parameters[key] = value
return self
}
@discardableResult
open func setParameterEncoding(_ parameterEncoding: ParameterEncoding) -> Self {
self.parameterEncoding = parameterEncoding
return self
}
@discardableResult
open func setHTTPBody(_ httpBody: Data) -> Self {
self.httpBody = httpBody
return self
}
}
| mit | 9783f75333ea9c58ec6513e5f69e8ec2 | 26.82716 | 89 | 0.667036 | 4.647423 | false | false | false | false |
Ruenzuo/fansabisu | FanSabisuKit/Sources/Authorizer.swift | 1 | 11438 | import Foundation
import CommonCrypto
import SafariServices
public enum AuthorizerError: Error {
case couldNotAuthenticate
case couldNotParseResponse
case couldNotBuildUrl
case couldNotCompleteOAuth
case couldNotBuildRequest
}
public class Authorizer {
public static let applicationDidReceiveOAuthCallback = "applicationDidReceiveOAuthCallback"
let session: URLSession
var oauthToken: String?
var oauthTokenSecret: String?
let tokenProvider: TokenProvider
public init(session: URLSession) {
self.session = session
let keychain = Keychain()
oauthToken = try? keychain.retrieve(for: KeychainKey.oauthToken.rawValue)
oauthTokenSecret = try? keychain.retrieve(for: KeychainKey.oauthTokenSecret.rawValue)
tokenProvider = TokenProvider(session: session)
}
public func buildRequest(for url: URL, completionHandler: @escaping (Result<URLRequest>) -> Void) {
if let _ = self.oauthToken, let _ = self.oauthTokenSecret {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
var params = [String: String]()
components?.queryItems?.forEach({ (item) in
if let value = item.value {
params.updateValue(value, forKey: item.name)
}
})
let header = authorizationHeader(with: request, params: params)
request.addValue(header, forHTTPHeaderField: "Authorization")
request.addValue("*/*", forHTTPHeaderField: "Accept")
completionHandler(Result.success(request))
} else {
tokenProvider.provideToken(with: { (result) in
guard let token = try? result.resolve() else {
return completionHandler(Result.failure(AuthorizerError.couldNotBuildUrl))
}
var request = URLRequest(url: url)
request.addValue("Bearer ".appending(token), forHTTPHeaderField: "Authorization")
completionHandler(Result.success(request))
})
}
}
public func requestOAuth(presentingViewController: UIViewController, completionHandler: @escaping (Result<OAuth>) -> Void) {
let url = URL(string: "https://api.twitter.com/oauth/request_token")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let header = authorizationHeader(with: request, params: ["oauth_callback": "fansabisu://oauth"])
request.addValue(header, forHTTPHeaderField: "Authorization")
request.addValue("*/*", forHTTPHeaderField: "Accept")
let dataTask = session.dataTask(with: request) { (data, response, error) in
if (response as? HTTPURLResponse)?.statusCode != 200 {
return completionHandler(Result.failure(AuthorizerError.couldNotAuthenticate))
}
guard let data = data else {
return completionHandler(Result.failure(AuthorizerError.couldNotAuthenticate))
}
guard let responseString = String(data: data, encoding: .utf8) else {
return completionHandler(Result.failure(AuthorizerError.couldNotParseResponse))
}
let accessToken = RequestToken(response: responseString)
guard let oauthToken = accessToken.oauthToken else {
return completionHandler(Result.failure(AuthorizerError.couldNotParseResponse))
}
guard let url = URL(string: "https://api.twitter.com/oauth/authenticate?oauth_token=".appending(oauthToken)) else {
return completionHandler(Result.failure(AuthorizerError.couldNotBuildUrl))
}
let safariViewController = SFSafariViewController(url: url)
presentingViewController.present(safariViewController, animated: true, completion: nil)
FSKNotificationCenter.default.registerNotificationName(Authorizer.applicationDidReceiveOAuthCallback) { (parameters) in
FSKNotificationCenter.default.unregisterNotificationName(Authorizer.applicationDidReceiveOAuthCallback)
guard let query = parameters?["query"] as? String else {
return completionHandler(Result.failure(AuthorizerError.couldNotCompleteOAuth))
}
let tokenVerifier = TokenVerifier(response: query)
let url = URL(string: "https://api.twitter.com/oauth/access_token")!
guard let oauthToken = tokenVerifier.oauthToken, let oauthVerififer = tokenVerifier.oauthVerififer else {
return completionHandler(Result.failure(AuthorizerError.couldNotParseResponse))
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let header = self.authorizationHeader(with: request, params: ["oauth_token": oauthToken])
request.addValue(header, forHTTPHeaderField: "Authorization")
request.addValue("*/*", forHTTPHeaderField: "Accept")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(String(oauthVerififer.characters.count), forHTTPHeaderField: "Content-Length")
request.httpBody = "oauth_verifier=".appending(oauthVerififer).data(using: .utf8)
let dataTask = self.session.dataTask(with: request) { (data, response, error) in
if (response as? HTTPURLResponse)?.statusCode != 200 {
return completionHandler(Result.failure(AuthorizerError.couldNotAuthenticate))
}
guard let data = data else {
return completionHandler(Result.failure(AuthorizerError.couldNotAuthenticate))
}
guard let responseString = String(data: data, encoding: .utf8) else {
return completionHandler(Result.failure(AuthorizerError.couldNotParseResponse))
}
let oauth = OAuth(response: responseString)
completionHandler(Result.success(oauth))
}
dataTask.resume()
}
}
dataTask.resume()
}
func authorizationHeader(with urlRequest: URLRequest, params: [String: String]?) -> String {
let nonce = Data.nonce()
let timestamp = String(Int64(Date().timeIntervalSince1970))
var parameters = ["oauth_consumer_key": TwitterCredentials.consumerKey,
"oauth_nonce": nonce,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": timestamp,
"oauth_version": "1.0",
]
params?.forEach { (key, value) in
parameters.updateValue(value, forKey: key)
}
if let oauthToken = oauthToken {
parameters.updateValue(oauthToken, forKey: "oauth_token")
}
var components = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false)
components?.query = nil
let signatureUrl = components?.url
let signature = Signature(with: parameters, url: signatureUrl!, httpMethod: urlRequest.httpMethod!, consumerSecret: TwitterCredentials.consumerSecret, oauthTokenSecret: self.oauthTokenSecret).generate()
var header = ""
header.append("OAuth ")
params?.forEach { (key, value) in
header.append(key.percentEncoded())
header.append("=\"")
header.append(value.percentEncoded())
header.append("\", ")
}
header.append("oauth_consumer_key".percentEncoded())
header.append("=\"")
header.append(TwitterCredentials.consumerKey.percentEncoded())
header.append("\", ")
header.append("oauth_nonce".percentEncoded())
header.append("=\"")
header.append(nonce.percentEncoded())
header.append("\", ")
header.append("oauth_signature".percentEncoded())
header.append("=\"")
header.append(signature.percentEncoded())
header.append("\", ")
header.append("oauth_signature_method".percentEncoded())
header.append("=\"")
header.append("HMAC-SHA1".percentEncoded())
header.append("\", ")
header.append("oauth_timestamp".percentEncoded())
header.append("=\"")
header.append(timestamp.percentEncoded())
header.append("\", ")
if let oauthToken = oauthToken {
header.append("oauth_token".percentEncoded())
header.append("=\"")
header.append(oauthToken.percentEncoded())
header.append("\", ")
}
header.append("oauth_version".percentEncoded())
header.append("=\"")
header.append("1.0".percentEncoded())
header.append("\"")
return header
}
}
struct RequestToken {
let oauthToken: String?
let oauthTokenSecret: String?
let oauthCallbackConfirmed: Bool?
init(response: String) {
let parsedInfo = response.parse()
self.oauthToken = parsedInfo["oauth_token"]
self.oauthTokenSecret = parsedInfo["oauth_token_secret"]
self.oauthCallbackConfirmed = parsedInfo["oauth_callback_confirmed"] == "true"
}
}
struct TokenVerifier {
let oauthToken: String?
let oauthVerififer: String?
init(response: String) {
let parsedInfo = response.parse()
self.oauthToken = parsedInfo["oauth_token"]
self.oauthVerififer = parsedInfo["oauth_verifier"]
}
}
public struct OAuth {
public let oauthToken: String?
public let oauthTokenSecret: String?
public let userID: String?
public let screenName: String?
init(response: String) {
let parsedInfo = response.parse()
self.oauthToken = parsedInfo["oauth_token"]
self.oauthTokenSecret = parsedInfo["oauth_token_secret"]
self.userID = parsedInfo["user_id"]
self.screenName = parsedInfo["screen_name"]
}
init(oauthToken: String, oauthTokenSecret: String, userID: String, screenName: String) {
self.oauthToken = oauthToken
self.oauthTokenSecret = oauthTokenSecret
self.userID = userID
self.screenName = screenName
}
}
extension Data {
static func nonce() -> String {
guard let data = NSMutableData(length: 32) else {
return ""
}
if CCRandomGenerateBytes(data.mutableBytes, data.length) != CCRNGStatus(kCCSuccess) {
return ""
}
let encondedData = data.base64EncodedString()
let alphanumeric = encondedData.components(separatedBy: CharacterSet.alphanumerics.inverted).joined(separator: "")
return alphanumeric
}
}
extension String {
func parse() -> [String: String] {
let components = self.components(separatedBy: "&")
var parsedInfo = [String: String]()
for component in components {
let parsedComponent = component.components(separatedBy: "=")
if let value = parsedComponent.last, let key = parsedComponent.first {
parsedInfo.updateValue(value, forKey: key)
}
}
return parsedInfo
}
}
| mit | 95a2fefd2f04ec1d9cd076f8bca1b4e5 | 41.206642 | 210 | 0.625896 | 5.332401 | false | false | false | false |
azimin/Rainbow | Rainbow/ColorDifference.swift | 1 | 5325 | //
// ColorDifference.swift
// Rainbow
//
// Created by Alex Zimin on 20/03/16.
// Copyright © 2016 Alex Zimin. All rights reserved.
//
// Thanks to Indragie Karunaratne ( https://github.com/indragiek )
import GLKit.GLKMath
internal protocol ColorDifference {
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float
}
internal struct CIE76SquaredColorDifference: ColorDifference {
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE76.html
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE76SquaredColorDifferenceFunction(lab1.toVector(), lab2: lab2.toVector())
}
}
internal func CIE76SquaredColorDifferenceFunction(lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
return pow(L2 - L1, 2) + pow(a2 - a1, 2) + pow(b2 - b1, 2)
}
internal struct CIE94SquaredColorDifference: ColorDifference {
private(set) var kL: Float
private(set) var kC: Float
private(set) var kH: Float
private(set) var K1: Float
private(set) var K2: Float
init(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015) {
self.kL = kL
self.kC = kC
self.kH = kH
self.K1 = K1
self.K2 = K2
}
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE94SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, K1: K1, K2: K2, lab1: lab1, lab2: lab2)
}
}
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html
// Created for optimization
internal func CIE94SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015, lab1: LABColor, lab2: LABColor) -> Float {
return CIE94SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, K1: K1, K2: K2, lab1: lab1.toVector(), lab2: lab1.toVector())
}
internal func CIE94SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, K1: Float = 0.045, K2: Float = 0.015, lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
let ΔL = L1 - L2
let (C1, C2) = (C(a1, b: b1), C(a2, b: b2))
let ΔC = C1 - C2
let ΔH = sqrt(pow(a1 - a2, 2) + pow(b1 - b2, 2) - pow(ΔC, 2))
let Sl: Float = 1
let Sc = 1 + K1 * C1
let Sh = 1 + K2 * C1
return pow(ΔL / (kL * Sl), 2) + pow(ΔC / (kC * Sc), 2) + pow(ΔH / (kH * Sh), 2)
}
internal struct CIE2000SquaredColorDifference: ColorDifference {
private(set) var kL: Float
private(set) var kC: Float
private(set) var kH: Float
init(kL: Float = 1, kC: Float = 1, kH: Float = 1) {
self.kL = kL
self.kC = kC
self.kH = kH
}
func colorDifference(lab1: LABColor, lab2: LABColor) -> Float {
return CIE2000SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, lab1: lab1, lab2: lab2)
}
}
// From http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE2000.html
// Created for optimization
internal func CIE2000SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, lab1: LABColor, lab2: LABColor) -> Float {
return CIE2000SquaredColorDifferenceFunction(kL, kC: kC, kH: kH, lab1: lab1.toVector(), lab2: lab2.toVector())
}
internal func CIE2000SquaredColorDifferenceFunction(kL: Float = 1, kC: Float = 1, kH: Float = 1, lab1: Vector3D, lab2: Vector3D) -> Float {
let (L1, a1, b1) = lab1.toFloatTuple()
let (L2, a2, b2) = lab2.toFloatTuple()
let ΔLp = L2 - L1
let Lbp = (L1 + L2) / 2
let (C1, C2) = (C(a1, b: b1), C(a2, b: b2))
let Cb = (C1 + C2) / 2
let G = (1 - sqrt(pow(Cb, 7) / (pow(Cb, 7) + pow(25, 7)))) / 2
let ap: Float -> Float = { a in
return a * (1 + G)
}
let (a1p, a2p) = (ap(a1), ap(a2))
let (C1p, C2p) = (C(a1p, b: b1), C(a2p, b: b2))
let ΔCp = C2p - C1p
let Cbp = (C1p + C2p) / 2
let hp: (Float, Float) -> Float = { ap, b in
if ap == 0 && b == 0 { return 0 }
let θ = GLKMathRadiansToDegrees(atan2(b, ap))
return fmod(θ < 0 ? (θ + 360) : θ, 360)
}
let (h1p, h2p) = (hp(a1p, b1), hp(a2p, b2))
let Δhabs = abs(h1p - h2p)
let Δhp: Float = {
if (C1p == 0 || C2p == 0) {
return 0
} else if Δhabs <= 180 {
return h2p - h1p
} else if h2p <= h1p {
return h2p - h1p + 360
} else {
return h2p - h1p - 360
}
}()
let ΔHp = 2 * sqrt(C1p * C2p) * sin(GLKMathDegreesToRadians(Δhp / 2))
let Hbp: Float = {
if (C1p == 0 || C2p == 0) {
return h1p + h2p
} else if Δhabs > 180 {
return (h1p + h2p + 360) / 2
} else {
return (h1p + h2p) / 2
}
}()
var T = 1 - 0.17 * cos(GLKMathDegreesToRadians(Hbp - 30))
T += 0.24 * cos(GLKMathDegreesToRadians(2 * Hbp))
T += 0.32 * cos(GLKMathDegreesToRadians(3 * Hbp + 6))
T -= 0.20 * cos(GLKMathDegreesToRadians(4 * Hbp - 63))
let Sl = 1 + (0.015 * pow(Lbp - 50, 2)) / sqrt(20 + pow(Lbp - 50, 2))
let Sc = 1 + 0.045 * Cbp
let Sh = 1 + 0.015 * Cbp * T
let Δθ = 30 * exp(-pow((Hbp - 275) / 25, 2))
let Rc = 2 * sqrt(pow(Cbp, 7) / (pow(Cbp, 7) + pow(25, 7)))
let Rt = -Rc * sin(GLKMathDegreesToRadians(2 * Δθ))
let Lterm = ΔLp / (kL * Sl)
let Cterm = ΔCp / (kC * Sc)
let Hterm = ΔHp / (kH * Sh)
return pow(Lterm, 2) + pow(Cterm, 2) + pow(Hterm, 2) + Rt * Cterm * Hterm
}
| mit | 80d16e1e72fd57867f5d549515d89669 | 30.164706 | 175 | 0.605512 | 2.683891 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/SLV_220_SearchCategoryController.swift | 1 | 10166 | //
// SLV_220_SearchCategoryController.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
/*
검색창 카테고리 컨트롤러
*/
import UIKit
import SnapKit
class SLV_220_SearchCategoryController: ButtonBarPagerTabStripViewController, NavgationTransitionable {
public weak var tr_pushTransition: TRNavgationTransitionDelegate?
var tr_presentTransition: TRViewControllerTransitionDelegate?
public weak var modalDelegate: ModalViewControllerDelegate?
@IBOutlet weak var hConstraint: NSLayoutConstraint!
var preTabIndex: Int = 0
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.resetupNavigationBar()
tabController.animationTabBarHidden(false)//탭바 보여준다.
tabController.hideFab()
self.binding()
}
override func viewDidLoad() {
self.resetupNavigationBar()
self.setupButtonBar()
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.hidesBackButton = true
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
self.setupNavigationButtons()
self.contentInsetY = 44
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 0, right: 0)
// let barFrame = self.buttonBarView.frame
// self.buttonBarView.frame = CGRect(x: barFrame.origin.x, y: barFrame.origin.y, width: 200, height: barFrame.size.height)
// self.buttonBarView.clipsToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden: Bool {
return false
}
func resetupNavigationBar() {
self.navigationBar?.isHidden = false
self.navigationBar?.barHeight = 44
_ = self.navigationBar?.sizeThatFits(.zero)
}
func setupButtonBar() {
// change selected bar color
settings.style.buttonBarBackgroundColor = .white
settings.style.buttonBarItemBackgroundColor = .white
settings.style.selectedBarBackgroundColor = text_color_bl51
settings.style.buttonBarItemFont = .systemFont(ofSize: 16, weight: UIFontWeightMedium)
settings.style.selectedBarHeight = 4.0 //스토리보드에서 높이만큼 컨테이너 뷰의 간격을 더 내려준다.(높이의 배수?)
settings.style.buttonBarMinimumLineSpacing = 0
settings.style.buttonBarItemTitleColor = text_color_bl51
settings.style.buttonBarItemsShouldFillAvailiableWidth = false
settings.style.buttonBarLeftContentInset = 40
settings.style.buttonBarRightContentInset = 40
settings.style.buttonBarHeight = 44
settings.style.buttonBarItemsLine = 2
changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
guard changeCurrentIndex == true else { return }
oldCell?.label.textColor = text_color_g153
oldCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular)
newCell?.label.textColor = text_color_bl51
newCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightSemibold)
if newCell != nil {
// let path = self?.buttonBarView.indexPath(for: newCell!)//TODO: 작업 중 nil 확인하고, 스크롤 관련 spliter 처리할 것...
// log.debug("pathInfo ---> \(path?.item)")
// if path != nil {
// }
}
self?.resetupNavigationBar()
}
}
func setupNavigationButtons() {
let back = UIButton()
back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal)
back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20)
back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26)
back.addTarget(self, action: #selector(SLV_220_SearchCategoryController.back(sender:)), for: .touchUpInside)
let item1 = UIBarButtonItem(customView: back)
self.navigationItem.leftBarButtonItem = item1
let filter = UIButton()
filter.setImage(UIImage(named:"search_header_ic_filter.png"), for: .normal)
filter.frame = CGRect(x: 0, y: 0, width: 24 + 20, height: 30)
filter.imageEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
filter.addTarget(self, action: #selector(SLV_220_SearchCategoryController.filter(sender:)), for: .touchUpInside)
let item2 = UIBarButtonItem(customView: filter)
self.navigationItem.rightBarButtonItem = item2
}
func binding() {
if self.preTabIndex != 0 {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller1 = board.instantiateViewController(withIdentifier: "SLV_221_SearchCategoryHot") as! SLV_221_SearchCategoryHot
controller1.linkDelegate(controller: self)
let controller2 = board.instantiateViewController(withIdentifier:"SLV_222_SearchCategoryItems") as! SLV_222_SearchCategoryItems
controller2.linkDelegate(controller: self)
self.moveToViewController(at: self.preTabIndex, animated: false)
}
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let board = UIStoryboard(name:"Search", bundle: nil)
let controller1 = board.instantiateViewController(withIdentifier: "SLV_221_SearchCategoryHot") as! SLV_221_SearchCategoryHot
controller1.linkDelegate(controller: self)
let controller2 = board.instantiateViewController(withIdentifier:"SLV_222_SearchCategoryItems") as! SLV_222_SearchCategoryItems
controller2.linkDelegate(controller: self)
return [controller1, controller2]
}
func moveUserPage(userId: String) {
let board = UIStoryboard(name:"Me", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_800_UserPageController") as! SLV_800_UserPageController
controller.sellerId = userId
self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
}
}
//MARK: EVENT
func dismiss(callBack: AnyObject? = nil) {
_ = self.navigationController?.tr_popViewController()
// modalDelegate?.modalViewControllerDismiss(callbackData: callBack)
}
func back(sender: UIButton?) {
self.dismiss()
}
func filter(sender: UIButton?) {
}
func like(sender: UIButton?) {
}
func moveBrandDetail(brand: Brand) {
let brandId = brand.id.copy() as! String
let board = UIStoryboard(name:"Brand", bundle: nil)
let controller = board.instantiateViewController(withIdentifier: "SLV_441_BrandPageController") as! SLV_441_BrandPageController
controller.brandId = brandId
self.navigationController?.tr_pushViewController(controller, method: TRPushTransitionMethod.fade, statusBarStyle: .default) {
}
}
}
extension SLV_220_SearchCategoryController: SLVButtonBarDelegate {
func showByScroll() {//down scroll
if self.hConstraint.constant > 0 {
return
}
tabController.hideFab()
tabController.animationTabBarHidden(false)
tabController.tabBar.needsUpdateConstraints()
self.hConstraint.constant = 44
self.buttonBarView.needsUpdateConstraints()
self.contentInsetY = 44
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 64, right: 0)
self.containerView.needsUpdateConstraints()
UIView.animate(withDuration: 0.2, animations: {
self.buttonBarView.layoutIfNeeded()
self.containerView.layoutIfNeeded()
}, completion: {
completed in
})
}
func hideByScroll() {// up scroll
//top
if self.hConstraint.constant == 0 {
return
}
tabController.showFab()
tabController.animationTabBarHidden(true)
tabController.tabBar.needsUpdateConstraints()
self.hConstraint.constant = 0
self.buttonBarView.needsUpdateConstraints()
self.contentInsetY = 0
self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 20, right: 0)
self.containerView.needsUpdateConstraints()
UIView.animate(withDuration: 0.5, animations: {
self.buttonBarView.layoutIfNeeded()
self.containerView.layoutIfNeeded()
}, completion: {
completed in
})
}
}
extension SLV_220_SearchCategoryController: SLVNavigationControllerDelegate {
func linkMyNavigationForTransition() -> UINavigationController? {
return self.navigationController
}
// 현재의 탭정보를 반환하다.
func currentTabIndex() -> Int! {
return self.currentIndex
}
}
extension SLV_220_SearchCategoryController: ModalTransitionDelegate {
func modalViewControllerDismiss(callbackData data:AnyObject?) {
log.debug("SLV_220_SearchCategoryController(callbackData:)")
tr_dismissViewController(completion: {
if let back = data {
let cb = back as! [String: String]
let keys = cb.keys
if keys.contains("from") == true {
let key = cb["from"]
if key != nil {
}
}
}
})
}
}
| mit | 4dc01bb84a97c2b67ea3c81908a76315 | 37.644788 | 194 | 0.652912 | 4.967246 | false | false | false | false |
therealbnut/UIntExtend | source/UnsignedIntegerExtend.swift | 1 | 10506 | //
// UnsignedIntegerExtend.swift
// Earley
//
// Created by Andrew Bennett on 4/11/2015.
// Copyright © 2015 TeamBnut. All rights reserved.
//
public struct UnsignedIntegerExtend<HalfType: UnsignedIntegerExtendType> {
public let lo: HalfType
public let hi: HalfType
public init(lo: HalfType, hi: HalfType) {
self.lo = lo
self.hi = hi
}
public static var bitCount: UIntMax { return HalfType.bitCount << 1 }
}
extension UnsignedIntegerExtend: IntegerLiteralConvertible {
public typealias IntegerLiteralType = UIntMax
public init(integerLiteral value: UIntMax) {
lo = HalfType(value)
hi = HalfType.allZeros
}
public init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {
value
}
}
extension UnsignedIntegerExtend: UnsignedIntegerType {
public init(_ value: UIntMax) {
lo = HalfType(value)
hi = HalfType.allZeros
}
}
extension UnsignedIntegerExtend: CustomStringConvertible {
public var description: String {
if self == UnsignedIntegerExtend.allZeros {
return "0"
}
let base = UnsignedIntegerExtend(10)
var value = self, string = ""
while !(value == UnsignedIntegerExtend.allZeros) {
let digit = UnsignedIntegerExtend.remainderWithOverflow(value, base).0
let digitChar = UnicodeScalar(48 + Int(digit.toIntMax()))
string.append(digitChar)
value = UnsignedIntegerExtend.divideWithOverflow(value, base).0
}
return string
}
}
extension UnsignedIntegerExtend: Hashable {
public var hashValue: Int {
return Int(truncatingBitPattern: UIntMax(0x784dd2271e0f0f17)) &* lo.hashValue &+ hi.hashValue
}
}
extension UnsignedIntegerExtend: IntegerArithmeticType {
public func toIntMax() -> IntMax {
return lo.toIntMax()
}
public func toUIntMax() -> UIntMax {
return lo.toUIntMax()
}
public static func addWithOverflow(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (UnsignedIntegerExtend, overflow: Bool)
{
let lo = lhs.lo &+ rhs.lo
var hi = lhs.hi &+ rhs.hi
if (lo < lhs.lo) {
hi = hi &+ 1
}
return (UnsignedIntegerExtend(lo: lo, hi: hi), hi < lhs.hi)
}
public static func subtractWithOverflow(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (UnsignedIntegerExtend, overflow: Bool)
{
let v = UnsignedIntegerExtend.addWithOverflow(lhs, UnsignedIntegerExtend.addWithOverflow(~rhs, UnsignedIntegerExtend(1)).0).0
return (v, lhs < rhs)
}
public static func multiplyWithOverflow(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (UnsignedIntegerExtend, overflow: Bool)
{
let zero = UnsignedIntegerExtend.allZeros, one = UnsignedIntegerExtend(1)
if lhs == zero || rhs == zero {
return (zero, false)
}
if rhs == one {
return (lhs, false)
}
if lhs == one {
return (rhs, false)
}
var a = lhs, t = rhs, out: UnsignedIntegerExtend = zero, anyOverflow = false
for i in 0 ..< UnsignedIntegerExtend.bitCount {
if !((t & one) == zero) {
let overflow: Bool
(out, overflow) = UnsignedIntegerExtend.addWithOverflow(out, (a << UnsignedIntegerExtend(i)))
anyOverflow = anyOverflow || overflow
}
t = t >> one
}
return (out, anyOverflow)
}
public static func divideWithOverflow(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (UnsignedIntegerExtend, overflow: Bool)
{
if rhs == UnsignedIntegerExtend.allZeros {
return (UnsignedIntegerExtend.allZeros, true)
}
let v = UnsignedIntegerExtend.divide(lhs, rhs)
return (v.quotient, false)
}
public static func remainderWithOverflow(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (UnsignedIntegerExtend, overflow: Bool)
{
if rhs == UnsignedIntegerExtend.allZeros {
return (UnsignedIntegerExtend.allZeros, true)
}
let v = UnsignedIntegerExtend.divide(lhs, rhs)
return (v.remainder, false)
}
private static func divide(lhs: UnsignedIntegerExtend, _ rhs: UnsignedIntegerExtend)
-> (quotient: UnsignedIntegerExtend, remainder: UnsignedIntegerExtend)
{
let zero = UnsignedIntegerExtend(0), one = UnsignedIntegerExtend(1)
assert(!(rhs == zero), "divide by zero: \(lhs) / \(rhs)")
var n = lhs, d = rhs
var x: UnsignedIntegerExtend = one, answer: UnsignedIntegerExtend = zero
let mask: UnsignedIntegerExtend = one << UnsignedIntegerExtend(UnsignedIntegerExtend.bitCount - 1)
while n >= d && (d & mask) == zero {
x = x << one
d = d << one
}
while !(x == zero) {
if(n >= d) {
n = UnsignedIntegerExtend.subtractWithOverflow(n, d).0
answer = answer | x
}
x = x >> one
d = d >> one
}
return (answer, n)
}
}
extension UnsignedIntegerExtend: BitwiseOperationsType {
public init(_ halfType: HalfType) {
self.init(lo: halfType, hi: HalfType.allZeros)
}
public static var allZeros: UnsignedIntegerExtend {
return UnsignedIntegerExtend(lo: HalfType.allZeros, hi: HalfType.allZeros)
}
}
extension UnsignedIntegerExtend: BidirectionalIndexType {
public func predecessor() -> UnsignedIntegerExtend {
let value = UnsignedIntegerExtend<HalfType>.subtractWithOverflow(self, UnsignedIntegerExtend(1))
assert(!value.overflow, "Cannot find predecessor of \(self)")
return value.0
}
public func successor() -> UnsignedIntegerExtend {
let value = UnsignedIntegerExtend<HalfType>.addWithOverflow(self, UnsignedIntegerExtend(1))
assert(!value.overflow, "Cannot find successor of \(self)")
return value.0
}
}
extension UnsignedIntegerExtend: ForwardIndexType {
public typealias Distance = IntegerExtend<HalfType>
@warn_unused_result
public func advancedBy(n: Distance) -> UnsignedIntegerExtend {
let value = UnsignedIntegerExtend.addWithOverflow(self, UnsignedIntegerExtend(truncatingBitPattern: n))
assert(!value.overflow, "Overflow in advancedBy \(self)")
return value.0
}
@warn_unused_result
public func advancedBy(n: Distance, limit: UnsignedIntegerExtend) -> UnsignedIntegerExtend {
let value = UnsignedIntegerExtend.addWithOverflow(self, UnsignedIntegerExtend(truncatingBitPattern: n))
if value.overflow || value.0 > limit {
return limit
}
return value.0
}
@warn_unused_result
public func distanceTo(end: UnsignedIntegerExtend) -> Distance {
let value = UnsignedIntegerExtend<HalfType>.subtractWithOverflow(end, self)
assert(!value.overflow, "Cannot find distanceTo \(self)")
return Distance(truncatingBitPattern: value.0)
}
}
//extension UnsignedIntegerExtend: RandomAccessIndexType {
//}
//extension UnsignedIntegerExtend: Strideable {
//}
@warn_unused_result
public func == <T: Equatable>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> Bool {
return lhs.lo == rhs.lo && lhs.hi == rhs.hi
}
@warn_unused_result
public func < <T: Comparable>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> Bool {
return (lhs.hi < rhs.hi) || (lhs.hi == rhs.hi && lhs.lo < rhs.lo)
}
@warn_unused_result
public func <= <T: Comparable>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> Bool {
return (lhs.hi <= rhs.hi) || (lhs.hi == rhs.hi && lhs.lo <= rhs.lo)
}
@warn_unused_result
public func > <T: Comparable>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> Bool {
return (lhs.hi > rhs.hi) || (lhs.hi == rhs.hi && lhs.lo > rhs.lo)
}
@warn_unused_result
public func >= <T: Comparable>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> Bool {
return (lhs.hi >= rhs.hi) || (lhs.hi == rhs.hi && lhs.lo >= rhs.lo)
}
@warn_unused_result
public func & <T: BitwiseOperationsType>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T> {
return UnsignedIntegerExtend<T>(lo: lhs.lo & rhs.lo, hi: lhs.hi & rhs.hi)
}
@warn_unused_result
public func | <T: BitwiseOperationsType>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T> {
return UnsignedIntegerExtend(lo: lhs.lo | rhs.lo, hi: lhs.hi | rhs.hi)
}
@warn_unused_result
public func ^ <T: BitwiseOperationsType>(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T> {
return UnsignedIntegerExtend(lo: lhs.lo ^ rhs.lo, hi: lhs.hi ^ rhs.hi)
}
@warn_unused_result
public prefix func ~ <T: BitwiseOperationsType>(that: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T> {
return UnsignedIntegerExtend(lo: ~that.lo, hi: ~that.hi)
}
@warn_unused_result
public func << <T: BitwiseOperationsType where T: UnsignedIntegerType, T: UnsignedIntegerExtendType>
(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T>
{
let halfSize = T(T.bitCount)
if rhs.hi >= halfSize {
return UnsignedIntegerExtend.allZeros
}
var n = rhs.lo
var lo = lhs.lo, hi = lhs.hi
if n >= halfSize {
n -= halfSize
hi = lo
lo = T.allZeros
}
if n != T.allZeros {
let mask = ~((~T.allZeros) >> n)
hi = (hi << n) | ((lo & mask) >> (halfSize - n))
lo = lo << n
}
return UnsignedIntegerExtend(lo: lo, hi: hi)
}
@warn_unused_result
public func >> <T: BitwiseOperationsType where T: UnsignedIntegerType, T: UnsignedIntegerExtendType>
(lhs: UnsignedIntegerExtend<T>, rhs: UnsignedIntegerExtend<T>) -> UnsignedIntegerExtend<T>
{
let halfSize = T(T.bitCount)
if rhs.hi >= halfSize {
return UnsignedIntegerExtend.allZeros
}
var n = rhs.lo
var lo = lhs.lo, hi = lhs.hi
if n >= halfSize {
n -= halfSize
lo = hi
hi = T.allZeros
}
if n != T.allZeros {
let mask = ~((~T.allZeros) << n)
lo = (lo >> n) | ((hi & mask) >> (halfSize - n))
hi = hi >> n
}
return UnsignedIntegerExtend(lo: lo, hi: hi)
}
| mit | d4fc4878a319b7f35302547c1232cb41 | 32.996764 | 133 | 0.642361 | 4.481655 | false | false | false | false |
mozilla-mobile/focus-ios | Blockzilla/Tracking Protection/Presentation/SheetModalViewController.swift | 1 | 5695 | /* 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 SnapKit
class SheetModalViewController: UIViewController {
private lazy var containerView: UIView = {
let view = UIView()
view.backgroundColor = .systemGroupedBackground
view.layer.cornerRadius = metrics.cornerRadius
view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = Float(metrics.shadowOpacity)
view.layer.shadowRadius = metrics.shadowRadius
view.layer.shadowOffset = CGSize(width: 0, height: -1)
view.clipsToBounds = true
return view
}()
private lazy var dimmedView: UIView = {
let view = UIView()
view.backgroundColor = .black
view.alpha = 0
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(animateDismissView))
view.addGestureRecognizer(tapGesture)
return view
}()
private lazy var closeButton: UIButton = {
var button = UIButton()
button.setImage(UIImage(named: "close-button")!, for: .normal)
button.addTarget(self, action: #selector(animateDismissView), for: .touchUpInside)
button.accessibilityIdentifier = "closeSheetButton"
return button
}()
private let containerViewController: UIViewController
private let metrics: SheetMetrics
private let maximumDimmingAlpha: CGFloat = 0.5
private var containerViewHeightConstraint: Constraint!
private var containerViewBottomConstraint: Constraint!
init(containerViewController: UIViewController, metrics: SheetMetrics = .default) {
self.containerViewController = containerViewController
self.metrics = metrics
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
super.preferredContentSizeDidChange(forChildContentContainer: container)
let height = min(container.preferredContentSize.height + metrics.closeButtonSize + metrics.closeButtonInset, metrics.maximumContainerHeight)
animateContainerHeight(height)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
setupConstraints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animateShowDimmedView()
animatePresentContainer()
}
func setupConstraints() {
view.addSubview(dimmedView)
view.addSubview(containerView)
dimmedView.translatesAutoresizingMaskIntoConstraints = false
containerView.translatesAutoresizingMaskIntoConstraints = false
install(containerViewController, on: containerView)
dimmedView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
containerView.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
containerViewHeightConstraint = make.height.equalTo(metrics.bufferHeight).constraint
containerViewBottomConstraint = make.bottom.equalTo(view).offset(metrics.bufferHeight).constraint
}
containerView.addSubview(closeButton)
closeButton.snp.makeConstraints { make in
make.trailing.top.equalTo(containerView.safeAreaLayoutGuide).inset(metrics.closeButtonInset)
make.height.width.equalTo(metrics.closeButtonSize)
}
}
// MARK: Present and dismiss animation
func animatePresentContainer() {
let animator = UIViewPropertyAnimator(duration: .animationDuration, curve: .easeOut)
animator.addAnimations {
self.containerViewBottomConstraint.update(offset: 0)
self.view.layoutIfNeeded()
}
animator.startAnimation()
}
func animateContainerHeight(_ height: CGFloat) {
let animator = UIViewPropertyAnimator(duration: .animationDuration, curve: .easeOut) {
self.containerViewHeightConstraint?.update(offset: height)
self.view.layoutIfNeeded()
}
animator.startAnimation()
}
func animateShowDimmedView() {
UIView.animate(withDuration: .animationDuration) {
self.dimmedView.alpha = self.maximumDimmingAlpha
}
}
@objc func animateDismissView() {
UIImpactFeedbackGenerator(style: .light).impactOccurred()
dimmedView.alpha = maximumDimmingAlpha
let springTiming = UISpringTimingParameters(dampingRatio: 0.75, initialVelocity: CGVector(dx: 0, dy: 4))
let dimmAnimator = UIViewPropertyAnimator(duration: .animationDuration, timingParameters: springTiming)
let dismissAnimator = UIViewPropertyAnimator(duration: .animationDuration, curve: .easeOut)
dismissAnimator.addAnimations {
self.containerViewBottomConstraint?.update(offset: 1000)
self.view.layoutIfNeeded()
}
dimmAnimator.addAnimations {
self.dimmedView.alpha = 0
}
dimmAnimator.addCompletion { _ in
self.dismiss(animated: false)
}
dimmAnimator.startAnimation()
dismissAnimator.startAnimation()
}
}
fileprivate extension TimeInterval {
static let animationDuration: TimeInterval = 0.25
}
| mpl-2.0 | 635a18b62efcccd318e7a8cbdd9e3464 | 36.715232 | 148 | 0.694293 | 5.481232 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/MyFinalsSchedule/controller/MyFinalsScheduleListViewController.swift | 1 | 4984 | //
// MyFinalsScheduleListViewController.swift
// byuSuite
//
// Created by Erik Brady on 5/1/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
private let MAP_VC_INDEX = 1 //Index of the MyFinalsScheduleMapViewController for the Tab Bar Controller
class MyFinalsScheduleListViewController: ByuTableDataViewController, UITabBarControllerDelegate, SemesterButtonDelegate {
//MARK: IBOutlets
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Private Properties
private var semButton: SemesterButton2?
private var yearTerm: YearTerm2?
private var finals: [FinalExam]?
private var buildings: [CampusBuilding2]?
override func viewDidLoad() {
super.viewDidLoad()
tabBarController?.delegate = self
tableView.isHidden = true
tableView.hideEmptyCells()
loadBuildings()
//Finals data will be loaded after the semester button has loaded the current YearTerm
semButton = SemesterButton2(delegate: self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Since the semester button is removed from the tabBarController's navigationItem in the mapView, we need to put it back here
if let semButton = semButton {
tabBarController?.navigationItem.rightBarButtonItem = semButton
}
}
//MARK: UITabBarControllerDelegate Methods
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//We do not want the user to be able to switch tabs if the finals or buildings have not yet loaded
guard finals?.count != 0, buildings?.count != 0 else { return false }
if let vc = viewController as? MyFinalsScheduleMapViewController {
vc.finals = finals
vc.buildings = buildings
vc.selectedFinal = nil
}
return true
}
//MARK: ByuTableDataViewController Methods
override func getEmptyTableViewText() -> String {
return "No Scheduled Finals Found"
}
//MARK: SemesterButtonDelegate Methods
func selectedYearTerm(yearTerm: YearTerm2) {
self.yearTerm = yearTerm
tableView.isHidden = true
spinner.startAnimating()
loadFinals(yearTerm: yearTerm)
}
func createButtonSucceeded(button: SemesterButton2) {
yearTerm = button.selectedYearTerm
loadFinals(yearTerm: button.selectedYearTerm)
}
func createButtonFailed(button: SemesterButton2) {
spinner.stopAnimating()
super.displayAlert(message: "Unable to Load Year Terms")
}
func displaySemesterButtonActions(button: SemesterButton2, title: String, actions: [UIAlertAction]) {
super.displayActionSheet(from: button, title: title, actions: actions)
}
//MARK: Custom Methods
private func loadFinals(yearTerm: YearTerm2) {
//Reset in case the user changed the semester then tries to select the map before the new fianls are loaded
finals = nil
tableData = TableData()
MyFinalsScheduleClient.getFinalsExams(yearTerm: yearTerm) { (finalExams, error) in
if let finalExams = finalExams {
self.finals = finalExams
self.dataFinishedLoading()
} else {
super.displayAlert(error: error, title: "Unable to Load Data")
}
}
}
private func loadBuildings() {
CampusLocationsClient2.getCampusBuildings { (campusBuildings, error) in
if let buildings = campusBuildings {
self.buildings = buildings
self.dataFinishedLoading()
}
}
}
private func dataFinishedLoading() {
if buildings != nil, var finals = finals {
tableView.isHidden = false
spinner.stopAnimating()
//Separate the finals into arrays for scheduled and unscheduled
let testingCenterFinals = finals.filterAndRemove { $0.building == "CTR" && $0.room == "TEST" }
let unscheduledFinals = finals.filterAndRemove { $0.building == "" || $0.building == nil }
let scheduledFinals = finals
if testingCenterFinals.count > 0 {
tableData.add(section: Section(title: "Testing Center Finals", cellId: "testingCenterFinalCell", rows: testingCenterFinals.map { Row(text: $0.testDetailsText(), detailText: "Please check testing.byu.edu for location", enabled: false) }))
}
if scheduledFinals.count > 0 {
tableData.add(section: Section(title: "Scheduled Finals", cellId: "scheduledFinalCell", rows: scheduledFinals.map { (final) -> Row in
return Row(text: final.testDetailsText(), detailText: final.testLocationDetailsText(), action: {
if let vc = self.tabBarController?.viewControllers?[MAP_VC_INDEX] as? MyFinalsScheduleMapViewController, let finals = self.finals, let buildings = self.buildings {
vc.finals = finals
vc.buildings = buildings
vc.selectedFinal = final
self.tabBarController?.selectedIndex = MAP_VC_INDEX
}
}, enabled: true)
}))
}
if unscheduledFinals.count > 0 {
tableData.add(section: Section(title: "Unscheduled Finals", cellId: "unscheduledFinalCell", rows: unscheduledFinals.map { Row(text: $0.testDetailsText(), enabled: false) }))
}
tableView.reloadData()
}
}
}
| apache-2.0 | ff3649facb758184d0a1448da7c9c5a1 | 33.130137 | 241 | 0.734297 | 4.054516 | false | true | false | false |
everald/JetPack | Sources/Extensions/UIKit/UICollectionView.swift | 1 | 567 | import UIKit
public extension UICollectionView {
@nonobjc
public var firstResponderCell: UICollectionViewCell? {
guard let firstResponder = firstResponder as? UIView else {
return nil
}
var optionalView: UIView? = firstResponder
while let view = optionalView {
guard view.superview === self else {
optionalView = view.superview
continue
}
return view as? UICollectionViewCell
}
return nil
}
@nonobjc
public func performBatchUpdates(_ updates: @escaping Closure) {
self.performBatchUpdates(updates, completion: nil)
}
}
| mit | 669cec9a735bb38df59bfb8d64b83a3f | 17.9 | 64 | 0.728395 | 4.169118 | false | false | false | false |
herrkaefer/CaseAssistant | CaseAssistant/ChartViewController.swift | 1 | 17659 | //
// ChartViewController.swift
// CaseAssistant
//
// Created by HerrKaefer on 15/5/13.
// Copyright (c) 2015年 HerrKaefer. All rights reserved.
//
import UIKit
import PNChart
class ChartViewController: UIViewController, PNChartDelegate, UIScrollViewDelegate
{
var patient: Patient? {
didSet {
loadDataForCharts()
}
}
var firstRecordDate: Date?
// var operationDate: NSDate?
var dayIntervalLabels = [String]()
var dateLabels = [String]()
var rShiliData = [CGFloat]()
var lShiliData = [CGFloat]()
var rJiaozhengshiliData = [CGFloat]()
var lJiaozhengshiliData = [CGFloat]()
var rYanyaData = [CGFloat]()
var lYanyaData = [CGFloat]()
struct ChartConstants {
static let GreenColor = UIColor(red: 94/255.0, green: 189/255.0, blue: 86/255.0, alpha:1.0)
static let YellowColor = UIColor(red: 251/255.0, green: 183/255.0, blue: 47/255.0, alpha:1.0)
static let OrangeColor = UIColor(red: 245/255.0, green: 130/255.0, blue: 51/255.0, alpha:1.0)
static let RedColor = UIColor(red: 222/255.0, green: 78/255.0, blue: 81/255.0, alpha:1.0)
static let BlueColor = UIColor(red: 68/255.0, green: 163/255.0, blue: 205/255.0, alpha:1.0)
static let ChartHeight: CGFloat = 200.0
static let ChartMargin: CGFloat = 25.0
static let LegendLeftMargin: CGFloat = 20.0
static let TitleHeight: CGFloat = 15.0
}
var screenWidth: CGFloat {
return UIScreen.main.bounds.size.width
}
// MARK: - IBOutlets
@IBOutlet weak var scrollView: UIScrollView!
var containerView: UIView!
// MARK: - Helper Functions
func getShiliData(_ s: String) -> CGFloat {
if s.isEmpty {
return 1e-6
}
if s.beginsWith("无光感") {
return -2.4
} else if s.beginsWith("光感") {
return -2.1
} else if s.beginsWith("手动10cm") {
return -1.8
} else if s.beginsWith("手动30cm") {
return -1.5
} else if s.beginsWith("手动50cm") {
return -1.2
} else if s.beginsWith("指数10cm") {
return -0.9
} else if s.beginsWith("指数30cm") {
return -0.6
} else if s.beginsWith("指数50cm") {
return -0.3
} else {
return CGFloat((s as NSString).floatValue)
}
}
func getYanyaData(_ s: String) -> CGFloat {
if s.isEmpty {
return 1e-6
}
if s.beginsWith("测不出") {
return -10.0
} else {
return CGFloat((s as NSString).floatValue)
}
}
func loadDataForCharts() {
dayIntervalLabels.removeAll()
dateLabels.removeAll()
rShiliData.removeAll()
lShiliData.removeAll()
rJiaozhengshiliData.removeAll()
lJiaozhengshiliData.removeAll()
rYanyaData.removeAll()
lYanyaData.removeAll()
firstRecordDate = patient!.firstTreatmentDate as Date
for r in patient!.recordsSortedAscending {
let days = numberOfDaysBetweenTwoDates(firstRecordDate!, toDate: r.date)
dayIntervalLabels.append("\(days)d")
dateLabels.append(DateFormatter.localizedString(from: r.date as Date, dateStyle: .short, timeStyle: .none))
rShiliData.append(getShiliData(r.g("rShili")))
lShiliData.append(getShiliData(r.g("lShili")))
rJiaozhengshiliData.append(getShiliData(r.g("rJiaozhengshili")))
lJiaozhengshiliData.append(getShiliData(r.g("lJiaozhengshili")))
rYanyaData.append(getYanyaData(r.g("rYanya")))
lYanyaData.append(getYanyaData(r.g("lYanya")))
}
}
func createRShiliChart(_ originY: CGFloat) -> (chart: PNLineChart, titleLabel: UILabel, legend: UIView) {
let titleLabel = UILabel(frame: CGRect(x: 0, y: originY + ChartConstants.ChartMargin, width: containerView.frame.width, height: ChartConstants.TitleHeight))
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.text = "右眼视力"
let chart = PNLineChart(frame: CGRect(x: 0, y: titleLabel.frame.origin.y + titleLabel.frame.height, width: containerView.frame.width, height: ChartConstants.ChartHeight))
chart.yLabelFormat = "%1.1f";
chart.backgroundColor = UIColor.clear
chart.isShowCoordinateAxis = true;
chart.setXLabels(dayIntervalLabels, withWidth: chart.chartCavanWidth/CGFloat(dayIntervalLabels.count))
chart.yFixedValueMax = 2.5
// chart.yFixedValueMin = min(minElement(rShiliData), minElement(rJiaozhengshiliData)) - 0.1
chart.yFixedValueMin = min(rShiliData.min()!, rJiaozhengshiliData.min()!) - 0.1
let data1 = PNLineChartData()
data1.dataTitle = "右眼裸眼视力"
data1.color = ChartConstants.YellowColor
data1.alpha = 1.0
data1.itemCount = UInt(rShiliData.count)
data1.inflexionPointStyle = PNLineChartPointStyle.circle
data1.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.rShiliData[Int(index)]
print("y: \(yValue)")
let item = PNLineChartDataItem(y: yValue)
return item!
})
let data2 = PNLineChartData()
data2.dataTitle = "右眼矫正视力"
data2.color = ChartConstants.GreenColor
data2.alpha = 1.0
data2.itemCount = UInt(rJiaozhengshiliData.count)
data2.inflexionPointStyle = PNLineChartPointStyle.circle
data2.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.rJiaozhengshiliData[Int(index)]
let item = PNLineChartDataItem(y: yValue)
return item!
})
let zeroData = PNLineChartData()
zeroData.dataTitle = "零值参照"
zeroData.color = UIColor.lightGray
zeroData.alpha = 1.0
zeroData.itemCount = UInt(lJiaozhengshiliData.count)
zeroData.inflexionPointStyle = PNLineChartPointStyle.none
zeroData.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = 1e-6
let item = PNLineChartDataItem(y: yValue)
return item!
})
chart.chartData = [zeroData, data1, data2]
chart.stroke()
chart.delegate = self
chart.legendStyle = PNLegendItemStyle.stacked
chart.legendFont = UIFont.boldSystemFont(ofSize: 12.0)
chart.legendFontColor = UIColor.black
let legend = chart.getLegendWithMaxWidth(chart.bounds.width)
legend?.frame = CGRect(x: ChartConstants.LegendLeftMargin, y: chart.frame.origin.y + chart.frame.height, width: (legend?.frame.size.width)!, height: (legend?.frame.size.width)!)
return (chart, titleLabel, legend!)
}
func createLShiliChart(_ originY: CGFloat) -> (chart: PNLineChart, titleLabel: UILabel, legend: UIView) {
let titleLabel = UILabel(frame: CGRect(x: 0, y: originY + ChartConstants.ChartMargin, width: containerView.frame.width, height: ChartConstants.TitleHeight))
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.text = "左眼视力"
let chart = PNLineChart(frame: CGRect(x: 0, y: titleLabel.frame.origin.y + titleLabel.frame.height, width: containerView.frame.width, height: ChartConstants.ChartHeight))
chart.yLabelFormat = "%1.1f";
chart.backgroundColor = UIColor.clear
chart.isShowCoordinateAxis = true;
chart.setXLabels(dayIntervalLabels, withWidth: chart.chartCavanWidth/CGFloat(dayIntervalLabels.count))
chart.yFixedValueMax = 2.5
chart.yFixedValueMin = min(lShiliData.min()!, lJiaozhengshiliData.min()!) - 0.1
let data1 = PNLineChartData()
data1.dataTitle = "左眼裸眼视力"
data1.color = ChartConstants.YellowColor
data1.alpha = 1.0
data1.itemCount = UInt(lShiliData.count)
data1.inflexionPointStyle = PNLineChartPointStyle.circle
data1.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.lShiliData[Int(index)]
print("y: \(yValue)")
let item = PNLineChartDataItem(y: yValue)
return item!
})
let data2 = PNLineChartData()
data2.dataTitle = "左眼矫正视力"
data2.color = ChartConstants.BlueColor
data2.alpha = 1.0
data2.itemCount = UInt(lJiaozhengshiliData.count)
data2.inflexionPointStyle = PNLineChartPointStyle.circle
data2.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.lJiaozhengshiliData[Int(index)]
let item = PNLineChartDataItem(y: yValue)
return item!
})
let zeroData = PNLineChartData()
zeroData.dataTitle = "零值参照"
zeroData.color = UIColor.lightGray
zeroData.alpha = 1.0
zeroData.itemCount = UInt(lJiaozhengshiliData.count)
zeroData.inflexionPointStyle = PNLineChartPointStyle.none
zeroData.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = 1e-6
let item = PNLineChartDataItem(y: yValue)
return item!
})
chart.chartData = [zeroData, data1, data2]
chart.stroke()
chart.delegate = self
chart.legendStyle = PNLegendItemStyle.stacked
chart.legendFont = UIFont.boldSystemFont(ofSize: 12.0)
chart.legendFontColor = UIColor.black
let legend = chart.getLegendWithMaxWidth(chart.bounds.width)
legend?.frame = CGRect(x: ChartConstants.LegendLeftMargin, y: chart.frame.origin.y + chart.frame.height, width: (legend?.frame.size.width)!, height: (legend?.frame.size.width)!)
return (chart, titleLabel, legend!)
}
func createYanyaChart(_ originY: CGFloat) -> (chart: PNLineChart, titleLabel: UILabel, legend: UIView) {
let titleLabel = UILabel(frame: CGRect(x: 0, y: originY + ChartConstants.ChartMargin, width: containerView.frame.width, height: ChartConstants.TitleHeight))
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.text = "眼压"
let chart = PNLineChart(frame: CGRect(x: 0, y: titleLabel.frame.origin.y + titleLabel.frame.height, width: containerView.frame.width, height: ChartConstants.ChartHeight))
chart.yLabelFormat = "%1.1f";
chart.backgroundColor = UIColor.clear
chart.isShowCoordinateAxis = true;
chart.setXLabels(dayIntervalLabels, withWidth: chart.chartCavanWidth/CGFloat(dayIntervalLabels.count))
chart.yFixedValueMax = max(rYanyaData.max()!, lYanyaData.max()!) + 10
chart.yFixedValueMin = min(rYanyaData.max()!, lYanyaData.max()!) - 10
let data1 = PNLineChartData()
data1.dataTitle = "右眼眼压"
data1.color = ChartConstants.GreenColor
data1.alpha = 1.0
data1.itemCount = UInt(rYanyaData.count)
data1.inflexionPointStyle = PNLineChartPointStyle.circle
data1.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.rYanyaData[Int(index)]
let item = PNLineChartDataItem(y: yValue)
return item!
})
let data2 = PNLineChartData()
data2.dataTitle = "左眼眼压"
data2.color = ChartConstants.BlueColor
data2.alpha = 1.0
data2.itemCount = UInt(lYanyaData.count)
data2.inflexionPointStyle = PNLineChartPointStyle.circle
data2.getData = ({(index: UInt) -> PNLineChartDataItem in
let yValue:CGFloat = self.lYanyaData[Int(index)]
let item = PNLineChartDataItem(y: yValue)
return item!
})
chart.chartData = [data1, data2]
chart.stroke()
chart.delegate = self
chart.legendStyle = PNLegendItemStyle.stacked
chart.legendFont = UIFont.boldSystemFont(ofSize: 12.0)
chart.legendFontColor = UIColor.black
let legend = chart.getLegendWithMaxWidth(chart.bounds.width)
legend?.frame = CGRect(x: ChartConstants.LegendLeftMargin, y: chart.frame.origin.y + chart.frame.height, width: (legend?.frame.size.width)!, height: (legend?.frame.size.width)!)
return (chart, titleLabel, legend!)
}
func userClicked(onLinePoint point: CGPoint, lineIndex: Int) {
print("clicked on line \(lineIndex)")
}
func userClicked(onLineKeyPoint point: CGPoint, lineIndex: Int, pointIndex: Int) {
print("clicked on line \(lineIndex) point \(pointIndex)")
if lineIndex == 0 {
print("value: \(rShiliData[pointIndex])")
}
if lineIndex == 1 {
print("value: \(rJiaozhengshiliData[pointIndex])")
}
}
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size
var contentsFrame = containerView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
containerView.frame = contentsFrame
}
// horizontally left, vertically top
func topScrollViewContents() {
var contentsFrame = containerView.frame
contentsFrame.origin.x = 0.0
contentsFrame.origin.y = 0.0
containerView.frame = contentsFrame
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return containerView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
// centerScrollViewContents()
}
// IBActions
@IBAction func saveImageButtonPressed(_ sender: UIBarButtonItem) {
UIGraphicsBeginImageContextWithOptions(containerView.bounds.size, true, UIScreen.main.scale)
if containerView.responds(to: Selector(("drawViewHierarchyInRect"))
) {
containerView.drawHierarchy(in: containerView.bounds, afterScreenUpdates: true)
} else {
containerView.layer.render(in: UIGraphicsGetCurrentContext()!)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
// 弹出保存成功提示
popupPrompt("图片已保存到手机相册", inView: self.view)
}
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if patient!.records.count <= 1 {
// 不画图
popupPrompt("数据量太少,至少需要两条记录", inView: self.view)
}
}
// 在viewDidLoad()中得到的scrollView的width是600,在这里才足够晚来得到真实值。
// ref: http://stackoverflow.com/a/26533891
// 放在这里画图的另一个好处是,当设备旋转后也会调用,正好重绘
override func viewDidLayoutSubviews() {
// Set up the container view to hold your custom view hierarchy
// print("screenWidth: \(screenWidth)")
let containerSize = CGSize(width: screenWidth, height: 800.0)
containerView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size:containerSize))
containerView.backgroundColor = UIColor.white
scrollView.addSubview(containerView)
if patient!.records.count > 1 {
// create and add charts
let (chart1, title1, legend1) = createRShiliChart(0.0)
containerView.addSubview(title1)
containerView.addSubview(chart1)
containerView.addSubview(legend1)
let (chart2, title2, legend2) = createLShiliChart(legend1.frame.origin.y + ChartConstants.ChartMargin)
containerView.addSubview(title2)
containerView.addSubview(chart2)
containerView.addSubview(legend2)
let (chart3, title3, legend3) = createYanyaChart(legend2.frame.origin.y + ChartConstants.ChartMargin)
containerView.addSubview(title3)
containerView.addSubview(chart3)
containerView.addSubview(legend3)
// print("bottom: \(legend2.frame.origin.y)")
// Tell the scroll view the size of the contents
scrollView.contentSize = containerSize
// Set up the minimum & maximum zoom scales
// let scrollViewFrame = scrollView.frame
// print("scroll frame: \(scrollView.frame)")
// let scaleWidth = scrollViewFrame.size.width / scrollView.contentSize.width
// let scaleHeight = scrollViewFrame.size.height / scrollView.contentSize.height
// let minScale = min(scaleWidth, scaleHeight)
// print("minScale: \(minScale)")
scrollView.minimumZoomScale = 1.0 //minScale
scrollView.maximumZoomScale = 2.0
scrollView.zoomScale = 1.0
topScrollViewContents()
}
}
}
| mpl-2.0 | cf35cb5670244774b85e4c54dd7e5c92 | 39.150463 | 185 | 0.623869 | 4.562073 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/ProfileInfoDismissInteraction.swift | 1 | 1983 | //
// ProfileInfoDismissInteraction.swift
// Slide for Reddit
//
// Created by Carlos Crane on 9/15/19.
// Copyright © 2019 Haptic Apps. All rights reserved.
//
import UIKit
class ProfileInfoDismissInteraction: UIPercentDrivenInteractiveTransition {
var interactionInProgress = false
private var shouldCompleteTransition = false
private weak var viewController: UIViewController!
private var storedHeight: CGFloat = 400
init(viewController: UIViewController) {
super.init()
self.viewController = viewController
prepareGestureRecognizer(in: viewController.view)
}
private func prepareGestureRecognizer(in view: UIView) {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
gesture.direction = UIPanGestureRecognizer.Direction.vertical
view.addGestureRecognizer(gesture)
}
@objc func handleGesture(_ gestureRecognizer: UIPanGestureRecognizer) {
let vc = viewController as! ProfileInfoViewController
let translation = gestureRecognizer.translation(in: gestureRecognizer.view!.superview!)
let velocity = gestureRecognizer.velocity(in: gestureRecognizer.view!.superview!)
var progress = min(max(0, translation.y), storedHeight) / storedHeight
progress = max(min(progress, 1), 0) // Clamp between 0 and 1
switch gestureRecognizer.state {
case .began:
interactionInProgress = true
viewController.dismiss(animated: true, completion: nil)
storedHeight = vc.contentViewHeight
case .changed:
shouldCompleteTransition = progress > 0.5 || velocity.y > 1000
update(progress)
case .cancelled:
interactionInProgress = false
cancel()
case .ended:
interactionInProgress = false
shouldCompleteTransition ? finish() : cancel()
default:
break
}
}
}
| apache-2.0 | 86f56fc8cb5c5ac6d5d2cceced227db0 | 33.77193 | 96 | 0.677598 | 5.505556 | false | false | false | false |
kello711/HackingWithSwift | project34/Project34/ViewController.swift | 1 | 4453 | //
// ViewController.swift
// Project34
//
// Created by Hudzilla on 19/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import UIKit
class ViewController: UIViewController {
@IBOutlet var columnButtons: [UIButton]!
var placedChips = [[UIView]]()
var board: Board!
var strategist: GKMinmaxStrategist!
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0 ..< Board.width {
placedChips.append([UIView]())
}
strategist = GKMinmaxStrategist()
strategist.maxLookAheadDepth = 7
strategist.randomSource = nil
resetBoard()
}
func resetBoard() {
board = Board()
strategist.gameModel = board
updateUI()
for i in 0 ..< placedChips.count {
for chip in placedChips[i] {
chip.removeFromSuperview()
}
placedChips[i].removeAll(keepCapacity: true)
}
}
@IBAction func makeMove(sender: UIButton) {
let column = sender.tag
if let row = board.nextEmptySlotInColumn(column) {
board.addChip(board.currentPlayer.chip, inColumn: column)
addChipAtColumn(column, row: row, color: board.currentPlayer.color)
continueGame()
}
}
func addChipAtColumn(column: Int, row: Int, color: UIColor) {
let button = columnButtons[column]
let size = min(button.frame.width, button.frame.height / 6)
let rect = CGRect(x: 0, y: 0, width: size, height: size)
if (placedChips[column].count < row + 1) {
let newChip = UIView()
newChip.frame = rect
newChip.userInteractionEnabled = false
newChip.backgroundColor = color
newChip.layer.cornerRadius = size / 2
newChip.center = positionForChipAtColumn(column, row: row)
newChip.transform = CGAffineTransformMakeTranslation(0, -800)
view.addSubview(newChip)
UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseIn, animations: { () -> Void in
newChip.transform = CGAffineTransformIdentity
}, completion: nil)
placedChips[column].append(newChip)
}
}
func positionForChipAtColumn(column: Int, row: Int) -> CGPoint {
let button = columnButtons[column]
let size = min(button.frame.width, button.frame.height / 6)
let xOffset = button.frame.midX
var yOffset = button.frame.maxY - size / 2
yOffset -= size * CGFloat(row)
return CGPoint(x: xOffset, y: yOffset)
}
func updateUI() {
title = "\(board.currentPlayer.name)'s Turn"
if board.currentPlayer.chip == .Black {
startAIMove()
}
}
func continueGame() {
// 1
var gameOverTitle: String? = nil
// 2
if board.isWinForPlayer(board.currentPlayer) {
gameOverTitle = "\(board.currentPlayer.name) Wins!"
} else if board.isFull() {
gameOverTitle = "Draw!"
}
// 3
if gameOverTitle != nil {
let alert = UIAlertController(title: gameOverTitle, message: nil, preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "Play Again", style: .Default) { [unowned self] (action) in
self.resetBoard()
}
alert.addAction(alertAction)
presentViewController(alert, animated: true, completion: nil)
return
}
// 4
board.currentPlayer = board.currentPlayer.opponent
updateUI()
}
func columnForAIMove() -> Int? {
if let aiMove = strategist.bestMoveForPlayer(board.currentPlayer) as? Move {
return aiMove.column
}
return nil
}
func makeAIMoveInColumn(column: Int) {
columnButtons.forEach { $0.enabled = true }
navigationItem.leftBarButtonItem = nil
if let row = board.nextEmptySlotInColumn(column) {
board.addChip(board.currentPlayer.chip, inColumn: column)
addChipAtColumn(column, row:row, color: board.currentPlayer.color)
continueGame()
}
}
func startAIMove() {
columnButtons.forEach { $0.enabled = false }
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
spinner.startAnimating()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: spinner)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { [unowned self] in
let strategistTime = CFAbsoluteTimeGetCurrent()
let column = self.columnForAIMove()!
let delta = CFAbsoluteTimeGetCurrent() - strategistTime
let aiTimeCeiling = 1.0
let delay = min(aiTimeCeiling - delta, aiTimeCeiling)
self.runAfterDelay(delay) {
self.makeAIMoveInColumn(column)
}
}
}
func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), block)
}
}
| unlicense | d8c8cd1230e3d76b1c497fe66639ee3d | 24.44 | 101 | 0.708895 | 3.464591 | false | false | false | false |
LongPF/FaceTube | FaceTube/AppDelegate.swift | 1 | 4916 | //
// AppDelegate.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/2/24.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
import CoreData
@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame:UIScreen.main.bounds)
let tabbarController = FTTabbarContrller();
window?.rootViewController = tabbarController;
window?.makeKeyAndVisible()
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "FaceTube")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 79413d0b5be4caee09b9e37606127be2 | 45.733333 | 285 | 0.678011 | 5.793388 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Managers/Model/AuthManager.swift | 1 | 7708 | //
// AuthManager.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/8/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
struct AuthManager {
/**
- returns: Last auth object (sorted by lastAccess), if exists.
*/
static func isAuthenticated() -> Auth? {
guard let auths = try? Realm().objects(Auth.self).sorted(byKeyPath: "lastAccess", ascending: false) else { return nil}
return auths.first
}
/**
- returns: Current user object, if exists.
*/
static func currentUser() -> User? {
guard let auth = isAuthenticated() else { return nil }
guard let user = try? Realm().object(ofType: User.self, forPrimaryKey: auth.userId) else { return nil }
return user
}
}
// MARK: Socket Management
extension AuthManager {
/**
This method resumes a previous authentication with token
stored in the Realm object.
- parameter auth The Auth object that user wants to resume.
- parameter completion The completion callback that will be
called in case of success or error.
*/
static func resume(_ auth: Auth, completion: @escaping MessageCompletion) {
guard let url = URL(string: auth.serverURL) else { return }
SocketManager.connect(url) { (socket, connected) in
guard connected else {
guard let response = SocketResponse(
["error": "Can't connect to the socket"],
socket: socket
) else { return }
return completion(response)
}
let object = [
"msg": "method",
"method": "login",
"params": [[
"resume": auth.token ?? ""
]]
] as [String: Any]
SocketManager.send(object) { (response) in
guard !response.isError() else {
completion(response)
return
}
PushManager.updatePushToken()
completion(response)
}
}
}
/**
Method that creates an User account.
*/
static func signup(with name: String, _ email: String, _ password: String, completion: @escaping MessageCompletion) {
let object = [
"msg": "method",
"method": "registerUser",
"params": [[
"email": email,
"pass": password,
"name": name
]]
] as [String : Any]
SocketManager.send(object) { (response) in
guard !response.isError() else {
completion(response)
return
}
self.auth(email, password: password, completion: completion)
}
}
/**
Generic method that authenticates the user.
*/
static func auth(params: [String: Any], completion: @escaping MessageCompletion) {
let object = [
"msg": "method",
"method": "login",
"params": [params]
] as [String : Any]
SocketManager.send(object) { (response) in
guard !response.isError() else {
completion(response)
return
}
Realm.executeOnMainThread({ (realm) in
// Delete all the Auth objects, since we don't
// support multiple-server authentication yet
realm.delete(realm.objects(Auth.self))
let result = response.result
let auth = Auth()
auth.lastSubscriptionFetch = nil
auth.lastAccess = Date()
auth.serverURL = response.socket?.currentURL.absoluteString ?? ""
auth.token = result["result"]["token"].string
auth.userId = result["result"]["id"].string
if let date = result["result"]["tokenExpires"]["$date"].double {
auth.tokenExpires = Date.dateFromInterval(date)
}
PushManager.updatePushToken()
realm.add(auth)
})
completion(response)
}
}
/**
This method authenticates the user with email and password.
- parameter username: Username
- parameter password: Password
- parameter completion: The completion block that'll be called in case
of success or error.
*/
static func auth(_ username: String, password: String, code: String? = nil, completion: @escaping MessageCompletion) {
let usernameType = username.contains("@") ? "email" : "username"
var params: [String: Any]?
if let code = code {
params = [
"totp": [
"login": [
"user": [usernameType: username],
"password": [
"digest": password.sha256(),
"algorithm": "sha-256"
]
],
"code": code
]
]
} else {
params = [
"user": [usernameType: username],
"password": [
"digest": password.sha256(),
"algorithm": "sha-256"
]
]
}
if let params = params {
self.auth(params: params, completion: completion)
}
}
/**
Returns the username suggestion for the logged in user.
*/
static func usernameSuggestion(completion: @escaping MessageCompletion) {
let object = [
"msg": "method",
"method": "getUsernameSuggestion"
] as [String : Any]
SocketManager.send(object, completion: completion)
}
/**
Set username of logged in user
*/
static func setUsername(_ username: String, completion: @escaping MessageCompletion) {
let object = [
"msg": "method",
"method": "setUsername",
"params": [username]
] as [String : Any]
SocketManager.send(object, completion: completion)
}
/**
Logouts user from the app, clear database
and disconnects from the socket.
*/
static func logout(completion: @escaping VoidCompletion) {
SocketManager.disconnect { (_, _) in
SocketManager.clear()
GIDSignIn.sharedInstance().signOut()
Realm.executeOnMainThread({ (realm) in
realm.deleteAll()
})
completion()
}
}
static func updatePublicSettings(_ auth: Auth?, completion: @escaping MessageCompletionObject<AuthSettings?>) {
let object = [
"msg": "method",
"method": "public-settings/get"
] as [String : Any]
SocketManager.send(object) { (response) in
guard !response.isError() else {
completion(nil)
return
}
Realm.executeOnMainThread({ realm in
let settings = AuthManager.isAuthenticated()?.settings ?? AuthSettings()
settings.map(response.result["result"], realm: realm)
realm.add(settings, update: true)
if let auth = AuthManager.isAuthenticated() {
auth.settings = settings
realm.add(auth, update: true)
}
let unmanagedSettings = AuthSettings(value: settings)
completion(unmanagedSettings)
})
}
}
}
| mit | 792da892397f3d1a794917ec5c28f969 | 29.583333 | 126 | 0.512781 | 5.189899 | false | false | false | false |
googleads/googleads-mobile-ios-examples | Swift/advanced/APIDemo/APIDemo/AdManagerPPIDViewController.swift | 1 | 3205 | //
// Copyright (C) 2016 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import GoogleMobileAds
import UIKit
class AdManagerPPIDViewController: UIViewController {
/// The AdManager banner view.
@IBOutlet weak var bannerView: GAMBannerView!
/// The user name text field.
@IBOutlet weak var usernameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
bannerView.rootViewController = self
bannerView.adUnitID = Constants.AdManagerPPIDAdUnitID
}
@IBAction func loadAd(_ sender: AnyObject) {
view.endEditing(true)
if let username = usernameTextField.text, !username.isEmpty {
let request = GAMRequest()
request.publisherProvidedID = generatePublisherProvidedIdentifierFromUsername(username)
bannerView.load(request)
} else {
let alert = UIAlertController(
title: "Load Ad Error",
message: "Failed to load ad. Username is required",
preferredStyle: .alert)
let alertAction = UIAlertAction(
title: "OK",
style: .cancel,
handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func screenTapped(_ sender: AnyObject) {
view.endEditing(true)
}
/// Returns an MD5 hash `String` generated from the provided username `String` to use as the
/// Publisher-Provided Identifier (PPID). The MD5 hash `String` is being used here as a convenient
/// stand-in for a true PPID. In your own apps, you can decide for yourself how to generate the
/// PPID value, though there are some restrictions on what the values can be. For details, see:
/// https://support.google.com/dfp_premium/answer/2880055
func generatePublisherProvidedIdentifierFromUsername(_ username: String) -> String {
// The UTF8 C string representation of the username `String`.
let utf8Username = username.cString(using: String.Encoding.utf8)
// Allocate memory for a byte array of unsigned characters with size equal to
// CC_MD5_DIGEST_LENGTH.
let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.allocate(
capacity: Int(CC_MD5_DIGEST_LENGTH))
// Create the 16 byte MD5 hash value.
CC_MD5(utf8Username!, CC_LONG(strlen(utf8Username!)), md5Buffer)
// Convert the MD5 hash value to an NSString of hex values.
let publisherProvidedIdentifier = NSMutableString()
for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
publisherProvidedIdentifier.appendFormat("%02x", md5Buffer[index])
}
// Deallocate the memory for the byte array of unsigned characters.
md5Buffer.deallocate()
return publisherProvidedIdentifier as String
}
}
| apache-2.0 | 6fe76b247663f5472b8f7953d11726fe | 37.614458 | 100 | 0.716069 | 4.279039 | false | false | false | false |
amcnary/cs147_instagator | instagator-prototype/instagator-prototype/Poll.swift | 1 | 695 | //
// Poll.swift
// instagator-prototype
//
// Created by Tanner Gilligan on 11/17/15.
// Copyright © 2015 ThePenguins. All rights reserved.
//
import Foundation
class Poll: Activity {
var Name: String
var Description: String
var Options: [Event]
var Results: [Double]
var People: [Person]
var NumPeopleResponded: Int
init(name: String, description: String, options: [Event], results: [Double], people: [Person], numPeopleResponded: Int) {
self.Name = name
self.Description = description
self.Options = options
self.Results = results
self.People = people
self.NumPeopleResponded = numPeopleResponded
}
} | apache-2.0 | 5f17aa6f45f3b0e7c5b9312e8c6533aa | 24.740741 | 125 | 0.65562 | 3.965714 | false | false | false | false |
benlangmuir/swift | test/IRGen/class_resilience.swift | 2 | 36436 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/class_resilience.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -enable-objc-interop -I %t -emit-ir -enable-library-evolution %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefixes=CHECK,CHECK-objc,CHECK-objc%target-ptrsize,CHECK-%target-ptrsize,CHECK-%target-cpu,CHECK-%target-import-type-objc-STABLE-ABI-%target-mandates-stable-abi,CHECK-%target-sdk-name -DINT=i%target-ptrsize -D#MDWORDS=7 -D#MDSIZE32=52 -D#MDSIZE64=80 -D#WORDSIZE=%target-alignment
// RUN: %target-swift-frontend -disable-objc-interop -I %t -emit-ir -enable-library-evolution %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefixes=CHECK,CHECK-native,CHECK-native%target-ptrsize,CHECK-%target-ptrsize,CHECK-%target-cpu,CHECK-native-STABLE-ABI-%target-mandates-stable-abi,CHECK-%target-sdk-name -DINT=i%target-ptrsize -D#MDWORDS=4 -D#MDSIZE32=40 -D#MDSIZE64=56 -D#WORDSIZE=%target-alignment
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution -O %t/class_resilience.swift
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd" = hidden global [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience21ResilientGenericChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS:{ (i32|i64), i32, i32 }]] zeroinitializer
// CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC9resilient0H7_struct0G3IntVvpWvd" = hidden global [[INT]] 0,
// CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC9resilient0H7_struct0E3IntVvpWvd" = hidden global [[INT]] 0,
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-32-SAME: { [[INT]] [[#MDSIZE32]], i32 2, i32 [[#MDWORDS + 6 + 4]] }
// CHECK-64-SAME: { [[INT]] [[#MDSIZE64]], i32 2, i32 [[#MDWORDS + 3 + 4]] }
// CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|20}}
// CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|24}}
// CHECK: [[RESILIENTCHILD_NAME:@.*]] = private constant [15 x i8] c"ResilientChild\00"
// CHECK: @"$s16class_resilience14ResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS]] zeroinitializer
// CHECK-macosx: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor
// CHECK-iphoneos: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor
// CHECK-watchos: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor
// CHECK-tvos: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor
// CHECK: @"$s16class_resilience14ResilientChildCMn" = {{(protected )?}}{{(dllexport )?}}constant <{{.*}}> <{
// -- flags: class, unique, has vtable, has override table, in-place initialization, has resilient superclass
// CHECK-SAME: <i32 0xE201_0050>
// -- parent:
// CHECK-SAME: @"$s16class_resilienceMXM"
// -- name:
// CHECK-SAME: [15 x i8]* [[RESILIENTCHILD_NAME]]
// -- metadata accessor function:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMa"
// -- field descriptor:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMF"
// -- metadata bounds:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMo"
// -- metadata positive size in words (not used):
// CHECK-SAME: i32 0,
// -- num immediate members:
// CHECK-SAME: i32 4,
// -- num fields:
// CHECK-SAME: i32 1,
// -- field offset vector offset:
// CHECK-SAME: i32 0,
// -- superclass:
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s15resilient_class22ResilientOutsideParentCMn"
// -- singleton metadata initialization cache:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMl"
// -- resilient pattern:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMP"
// -- completion function:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMr"
// -- number of method overrides:
// CHECK-SAME: i32 2,
// CHECK-SAME: %swift.method_override_descriptor {
// -- base class:
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s15resilient_class22ResilientOutsideParentCMn"
// -- base method:
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq"
// -- implementation:
// CHECK-SAME: @"$s16class_resilience14ResilientChildC8getValueSiyF"
// CHECK-SAME: }
// CHECK-SAME: %swift.method_override_descriptor {
// -- base class:
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s15resilient_class22ResilientOutsideParentCMn"
// -- base method:
// CHECK-SAME: @"{{got.|\\01__imp__?}}$s15resilient_class22ResilientOutsideParentCACycfCTq"
// -- implementation:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCACycfC"
// CHECK-SAME: }
// CHECK-SAME: }>
// CHECK: @"$s16class_resilience14ResilientChildCMP" = internal constant <{{.*}}> <{
// -- instantiation function:
// CHECK-SAME: i32 0,
// -- destructor:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCfD"
// -- ivar destroyer:
// CHECK-SAME: i32 0,
// -- flags:
// CHECK-SAME: i32 2,
// -- RO data:
// CHECK-objc-SAME: @_DATA__TtC16class_resilience14ResilientChild
// CHECK-native-SAME: i32 0,
// -- metaclass:
// CHECK-objc-SAME: @"$s16class_resilience14ResilientChildCMm"
// CHECK-native-SAME: i32 0
// CHECK: @"$s16class_resilience17MyResilientParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-32-SAME: { [[INT]] [[#MDSIZE32]], i32 2, i32 [[#MDWORDS + 6 + 2]] }
// CHECK-64-SAME: { [[INT]] [[#MDSIZE64]], i32 2, i32 [[#MDWORDS + 3 + 2]] }
// CHECK: @"$s16class_resilience16MyResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-32-SAME: { [[INT]] [[#MDSIZE32 + WORDSIZE + WORDSIZE]], i32 2, i32 [[#MDWORDS + 6 + 3]] }
// CHECK-64-SAME: { [[INT]] [[#MDSIZE64 + WORDSIZE + WORDSIZE]], i32 2, i32 [[#MDWORDS + 3 + 3]] }
// CHECK: @"$s16class_resilience24MyResilientGenericParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-32-SAME: { [[INT]] [[#MDSIZE32]], i32 2, i32 [[#MDWORDS + 6 + 3]] }
// CHECK-64-SAME: { [[INT]] [[#MDSIZE64]], i32 2, i32 [[#MDWORDS + 3 + 3]] }
// CHECK: @"$s16class_resilience24MyResilientConcreteChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-32-SAME: { [[INT]] [[#MDSIZE32 + WORDSIZE + WORDSIZE + WORDSIZE]], i32 2, i32 [[#MDWORDS + 6 + 5]] }
// CHECK-64-SAME: { [[INT]] [[#MDSIZE64 + WORDSIZE + WORDSIZE + WORDSIZE]], i32 2, i32 [[#MDWORDS + 3 + 5]] }
// CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC5emptyAA0E0VvpWvd" = hidden constant [[INT]] 0,
// CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC5emptyAA0G0VvpWvd" = hidden constant [[INT]] 0,
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience17MyResilientParentCACycfCTq" = hidden alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience24MyResilientGenericParentC1tACyxGx_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience24MyResilientConcreteChildC1xACSi_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public var field: Int32 = 0
public override func getValue() -> Int {
return 1
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public var field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
public class MyResilientGenericParent<T> {
public let t: T
public init(t: T) {
self.t = t
}
}
public class MyResilientConcreteChild : MyResilientGenericParent<Int> {
public let x: Int
public init(x: Int) {
self.x = x
super.init(t: x)
}
}
extension ResilientGenericOutsideParent {
public func genericExtensionMethod() -> A.Type {
return A.self
}
}
// rdar://48031465
// Field offsets for empty fields in resilient classes should be initialized
// to their best-known value and made non-constant if that value might
// disagree with the dynamic value.
@frozen
public struct Empty {}
public class ClassWithEmptyThenResilient {
public let empty: Empty
public let resilient: ResilientInt
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
public class ClassWithResilientThenEmpty {
public let resilient: ResilientInt
public let empty: Empty
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg"(%T16class_resilience26ClassWithResilientPropertyC* swiftself %0)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg"(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself %0)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg"(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself %0)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience14ResilientChildC5fields5Int32Vvg"(%T16class_resilience14ResilientChildC* swiftself %0)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience21ResilientGenericChildC5fields5Int32Vvg"(%T16class_resilience21ResilientGenericChildC* swiftself %0)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience21ResilientGenericChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience16MyResilientChildC5fields5Int32Vvg"(%T16class_resilience16MyResilientChildC* swiftself %0)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK: ret i32 [[RESULT]]
// ResilientGenericOutsideParent.genericExtensionMethod()
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s15resilient_class29ResilientGenericOutsideParentC0B11_resilienceE22genericExtensionMethodxmyF"(%T15resilient_class29ResilientGenericOutsideParentC* swiftself %0) {{.*}} {
// CHECK: [[ISA_ADDR:%.*]] = bitcast %T15resilient_class29ResilientGenericOutsideParentC* %0 to %swift.type**
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s15resilient_class29ResilientGenericOutsideParentCMo", i32 0, i32 0)
// CHECK-NEXT: [[GENERIC_PARAM_OFFSET:%.*]] = add [[INT]] [[BASE]], 0
// CHECK-NEXT: [[ISA_TMP:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[GENERIC_PARAM_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_TMP]], [[INT]] [[GENERIC_PARAM_OFFSET]]
// CHECK-NEXT: [[GENERIC_PARAM_ADDR:%.*]] = bitcast i8* [[GENERIC_PARAM_TMP]] to %swift.type**
// CHECK-NEXT: [[GENERIC_PARAM:%.*]] = load %swift.type*, %swift.type** [[GENERIC_PARAM_ADDR]]
// CHECK: ret %swift.type* [[GENERIC_PARAM]]
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience26ClassWithResilientPropertyCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience26ClassWithResilientPropertyCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientProperty metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMr"(%swift.type* %0, i8* %1, i8** %2)
// CHECK: entry:
// CHECK-NEXT: [[FIELDS:%.*]] = alloca [3 x i8**]
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]*
// CHECK-objc-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}}
// CHECK-native-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{7|10}}
// CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [3 x i8**]* [[FIELDS]] to i8*
// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{12|24}}, i8* [[FIELDS_ADDR]])
// CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* [[FIELDS]], i32 0, i32 0
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63
// CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont
// CHECK: dependency-satisfied:
// -- ClassLayoutFlags = 0x100 (HasStaticVTable)
// CHECK-native: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-DIRECT-objc-STABLE-ABI-TRUE: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_updateClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-DIRECT-objc-STABLE-ABI-FALSE:[[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-INDIRECT-objc-STABLE-ABI-TRUE:[[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null
// CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont
// CHECK: dependency-satisfied1:
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd"
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd"
// CHECK: br label %metadata-dependencies.cont
// CHECK: metadata-dependencies.cont:
// CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientProperty method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience26ClassWithResilientPropertyCMu"(%swift.type* %0, %swift.method_descriptor* %1)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast ({{.*}}* @"$s16class_resilience26ClassWithResilientPropertyCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientlySizedProperty metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMr"(%swift.type* %0, i8* %1, i8** %2)
// CHECK: entry:
// CHECK-NEXT: [[FIELDS:%.*]] = alloca [2 x i8**]
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]*
// CHECK-objc-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}}
// CHECK-native-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{7|10}}
// CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [2 x i8**]* [[FIELDS]] to i8*
// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{8|16}}, i8* [[FIELDS_ADDR]])
// CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* [[FIELDS]], i32 0, i32 0
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 319)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63
// CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont
// CHECK: dependency-satisfied:
// -- ClassLayoutFlags = 0x100 (HasStaticVTable)
// CHECK-native: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-DIRECT-objc-STABLE-ABI-TRUE: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_updateClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-DIRECT-objc-STABLE-ABI-FALSE:[[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-INDIRECT-objc-STABLE-ABI-TRUE:[[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null
// CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont
// CHECK: dependency-satisfied1:
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd"
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd"
// CHECK: br label %metadata-dependencies.cont
// CHECK: metadata-dependencies.cont:
// CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientlySizedProperty method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMu"(%swift.type* %0, %swift.method_descriptor* %1)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast ({{.*}}* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ResilientChild metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience14ResilientChildCMr"(%swift.type* %0, i8* %1, i8** %2)
// Initialize field offset vector...
// CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 0, [[INT]] 1, i8*** {{.*}}, [[INT]]* {{.*}})
// CHECK: ret %swift.metadata_response
// ResilientChild method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience14ResilientChildCMu"(%swift.type* %0, %swift.method_descriptor* %1)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast ({{.*}}* @"$s16class_resilience14ResilientChildCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ResilientChild.field getter dispatch thunk
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience14ResilientChildC5fields5Int32VvgTj"(%T16class_resilience14ResilientChildC* swiftself %0)
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE_ADDR:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[BASE:%.*]] = add [[INT]] [[BASE_ADDR]], {{4|8}}
// CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[BASE]]
// CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to i32 (%T16class_resilience14ResilientChildC*)**
// CHECK-NEXT: [[METHOD:%.*]] = load i32 (%T16class_resilience14ResilientChildC*)*, i32 (%T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]]
// CHECK-arm64e-NEXT: ptrtoint i32 (%T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend
// CHECK-NEXT: [[RESULT:%.*]] = call swiftcc i32 [[METHOD]](%T16class_resilience14ResilientChildC* swiftself %0)
// CHECK-NEXT: ret i32 [[RESULT]]
// ResilientChild.field setter dispatch thunk
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience14ResilientChildC5fields5Int32VvsTj"(i32 %0, %T16class_resilience14ResilientChildC* swiftself %1)
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %1, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{8|16}}
// CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to void (i32, %T16class_resilience14ResilientChildC*)**
// CHECK-NEXT: [[METHOD:%.*]] = load void (i32, %T16class_resilience14ResilientChildC*)*, void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]]
// CHECK-arm64e-NEXT: ptrtoint void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]] to i64
// CHECK-arm64e-NEXT: call i64 @llvm.ptrauth.blend
// CHECK-NEXT: call swiftcc void [[METHOD]](i32 %0, %T16class_resilience14ResilientChildC* swiftself %1)
// CHECK-NEXT: ret void
// ResilientGenericChild metadata initialization function
// CHECK-LABEL: define internal %swift.type* @"$s16class_resilience21ResilientGenericChildCMi"(%swift.type_descriptor* %0, i8** %1, i8* %2)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* {{.*}}, i8** %1, i8* %2)
// CHECK: ret %swift.type* [[METADATA]]
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience21ResilientGenericChildCMr"
// CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8* %0, i8** %1)
// CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* [[METADATA]], [[INT]] 0,
// CHECK: ret %swift.metadata_response
// ResilientGenericChild method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience21ResilientGenericChildCMu"(%swift.type* %0, %swift.method_descriptor* %1)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast ({{.*}}* @"$s16class_resilience21ResilientGenericChildCMn{{(\.ptrauth.*)?}}" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
| apache-2.0 | 1115a1fff6de5ec7e41d9818ff51ec7c | 58.829228 | 446 | 0.685256 | 3.629445 | false | false | false | false |
google/iosched-ios | Source/Platform/Configuration/Configuration.swift | 1 | 2406 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
public class Configuration {
public static let sharedInstance = Configuration()
private init() {
configurationFilePath = Bundle.main.path(forResource: Constants.configFileName,
ofType: Constants.configFileExtension)
if let configurationFilePath = configurationFilePath {
configuration = NSDictionary(contentsOfFile: configurationFilePath)
}
}
private lazy var googleServiceInfo: [String: Any] = {
let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist")
if let plist = path.flatMap(NSDictionary.init(contentsOfFile:)) {
return plist as? [String: Any] ?? [:]
}
fatalError("Unable to locate GoogleService-Info.plist")
}()
private enum Constants {
static let configFileName = "configuration"
static let configFileExtension = "plist"
/// Google Maps API key
static let mapsKey = "GOOGLE_MAPS_KEY"
/// Base URL of the Google Cloud Storage bucket containing the conference schedule data
static let scheduleDataBaseURL = "SCHEDULE_DATA_BASE_URL"
static let registrationEndpointKey = ""
}
private var configurationFilePath: String?
private var configuration: NSDictionary?
public lazy var googleMapsApiKey: String = {
let apiKey = self.configuration?[Constants.mapsKey] as? String
assert(apiKey != "" && apiKey != nil, "Google maps API key not available. Check configuration.plist.")
return apiKey ?? ""
}()
public lazy var registrationEndpoint: String = {
guard let projectID = googleServiceInfo["PROJECT_ID"] as? String else {
fatalError("GoogleService-Info.plist does not contain a valid project ID")
}
return "https://\(projectID).appspot.com/_ah/api/registration/v1/register"
}()
}
| apache-2.0 | 0afec8a2a39e935c88a46f619e3c3953 | 34.382353 | 106 | 0.705736 | 4.497196 | false | true | false | false |
AlexRamey/mbird-iOS | iOS Client/Store/MBDevotionsStore.swift | 1 | 2116 | //
// MBDevotionsStore.swift
// iOS Client
//
// Created by Alex Ramey on 12/10/17.
// Copyright © 2017 Mockingbird. All rights reserved.
//
import Foundation
class MBDevotionsStore: NSObject {
private let client: MBClient
private let fileHelper: FileHelper
override init() {
client = MBClient()
fileHelper = FileHelper()
super.init()
}
func getDevotions() -> [LoadedDevotion] {
do {
return try fileHelper.read(fromPath: "devotions", [LoadedDevotion].self)
} catch {
return []
}
}
// New function for devotions until we figure out if this will have to go over network or can be stored locally
func syncDevotions(completion: @escaping ([LoadedDevotion]?, Error?) -> Void) {
self.client.getJSONFile(name: "devotions") { data, error in
if error == nil, let data = data {
do {
// We got some data now parse
print("fetched devotions from bundle")
let devotions = try self.fileHelper.parse(data, [MBDevotion].self)
let loadedDevotions = devotions.map {LoadedDevotion(devotion: $0, read: false)}
try self.fileHelper.saveJSON(loadedDevotions, forPath: "devotions")
completion(loadedDevotions, nil)
} catch let error {
completion(nil, error)
}
} else {
// Failed so complete with no devotions
completion(nil, error)
}
}
}
func saveDevotions(devotions: [LoadedDevotion]) throws {
try fileHelper.saveJSON(devotions, forPath: "devotions")
}
func replace(devotion: LoadedDevotion) throws {
let devotions = try fileHelper.read(fromPath: "devotions", [LoadedDevotion].self)
let markedDevotions = devotions.map { oldDevotion in
oldDevotion.date == devotion.date ? devotion : oldDevotion
}
try fileHelper.saveJSON(markedDevotions, forPath: "devotions")
}
}
| mit | 7a8be730a809d1def029390d50fa0467 | 33.672131 | 115 | 0.584397 | 4.862069 | false | false | false | false |
1amageek/Antenna | Antenna/AppDelegate.swift | 1 | 5349 | //
// AppDelegate.swift
// Antenna
//
// Created by 1amageek on 2016/01/01.
// Copyright © 2016年 Stamp inc. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
})
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: Beacon.BeaconDidReceiveWriteNotificationKey), object: nil, queue: nil) { (notification) in
print("😍😌")
let notification: UILocalNotification = UILocalNotification()
notification.fireDate = Date()
notification.alertTitle = "😁😆😍😌😝😜😚😙☹️"
notification.alertBody = "😁😆😍😌😝😜😚😙☹️"
notification.alertAction = "OK"
notification.soundName = UILocalNotificationDefaultSoundName
application.scheduleLocalNotification(notification)
}
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:.
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// debugPrint full message.
debugPrint(userInfo)
}
}
| mit | 456aea68705fb6f44d10eb521894a0d9 | 48.383178 | 285 | 0.710447 | 6.201878 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/01346-swift-tupletype-get.swift | 1 | 1387 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a {
var b = { _, Bool) -> ({
init() -> Any {
extension A where T, x = .b: A {
func a(f)
}
}
static let i<T>)
protocol a {
protocol a {
}
struct c
func c(T> {
}
}
enum B {
convenience init(() {
let f = Swift.b(")
}
func f: a {
struct X.C(g: Sequence> U>()
var b(v: b: ExtensibleCollectionType>() -> {
var a(n: B? = ""foobar"a<I : Any, Any) -> ([0x31] in
}
}() {
self.d {
}
enum A {
import Foundation
var b {
return "")
enum B {
func ^("cd")
class B = T]]
}
}
case C<D> Any) {
}
}
}
}
}
case c
func a<d = {
return "cd"A.Element == e> U {
}
let b in 0] == d(_ = nil
}
var b() -> {
case C: b[self, self.Type
return nil
for c = T> [T>(bytes: a<h> U {
enum A {
protocol a {
}
typealias f == f)(b[Byte]
f() -> {
import Foundation
protocol A {
}
typealias f : T) -> {
}
d.f : String = {
protocol A {
print()
}
return "]
static let f = [1
public class B : a {
assert(a(Any)
let a<T>] = B) -> String {
}
case C
struct c {
func a<h == "A>() { self.<T
return ")
typealias e : d = {
let t: B)-> U>: Any, Any, b {
class c<T! {
"""ab""
}
print() {
class A.advance() -> e? = B
return [0x31] {
}
return self.h>()
protocol A = B
}
d<T> String {
var b = {
class A {
}
}
}
func f())
| apache-2.0 | 6fdc9ffd44d279155e4f699fef858d82 | 12.732673 | 87 | 0.568854 | 2.467972 | false | false | false | false |
Mindera/Alicerce | Tests/AlicerceTests/DeepLinking/Route+TrieNode_MatchTests.swift | 1 | 13469 | import XCTest
@testable import Alicerce
class Route_TrieNode_MatchTests: XCTestCase {
typealias TrieNode = Route.TrieNode<String>
// MARK: - failure
// MARK: empty
func testMatch_WithEmptyRouteOnEmptyNode_ShouldReturnNil() {
XCTAssertMatchFails(initial: .empty, matchRoute: [])
}
// MARK: single component
func testMatch_WithSingleComponentOnEmptyNode_ShouldReturnNil() {
XCTAssertMatchFails(initial: .empty, matchRoute: ["a"])
XCTAssertMatchFails(initial: .empty, matchRoute: [":a"])
XCTAssertMatchFails(initial: .empty, matchRoute: ["*"])
XCTAssertMatchFails(initial: .empty, matchRoute: ["**a"])
XCTAssertMatchFails(initial: .empty, matchRoute: ["**"])
}
func testMatch_WithNonMatchingConstantComponent_ShouldReturnNil() {
XCTAssertMatchFails(initial: .constant("💣", node: .handler("💥")), matchRoute: ["a"])
}
// MARK: - success
// MARK: empty
func testMatch_WithEmptyRouteOnHandlerNode_ShouldReturnHandler() {
XCTAssertMatchSucceeeds(initial: .handler("🎉"), matchRoute: [], expectedHandler: "🎉")
}
// MARK: single component
func testMatch_WithSingleComponentRouteOnMatchingNode_ShouldReturnHandler() {
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .handler("🎉")),
matchRoute: ["👷♂️"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .handler("🎉")),
matchRoute: ["🏗"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗"]
)
XCTAssertMatchSucceeeds(initial: .wildcard(.handler("🎉")), matchRoute: ["🏗"], expectedHandler: "🎉")
XCTAssertMatchSucceeeds(
initial: .catchAll("👷♂️", handler: "🎉"),
matchRoute: ["🏗"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .catchAll(nil, handler: "🎉"),
matchRoute: ["🏗"],
expectedHandler: "🎉"
)
}
// MARK: multi component
func testMatch_WithMultiComponentRouteOnMatchingNode_ShouldReturnHandler() {
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .constant("👷♀️", node: .handler("🎉"))),
matchRoute: ["👷♂️", "👷♀️"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .parameter("👷♀️", node: .handler("🎉"))),
matchRoute: ["👷♂️", "🏗"],
expectedHandler: "🎉",
expectedParameters: ["👷♀️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .wildcard(.handler("🎉"))),
matchRoute: ["👷♂️", "🏗"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .catchAll("👷♀️", handler: "🎉")),
matchRoute: ["👷♂️", "🏗", "🚧"],
expectedHandler: "🎉",
expectedParameters: ["👷♀️": "🏗/🚧"]
)
XCTAssertMatchSucceeeds(
initial: .constant("👷♂️", node: .catchAll(nil, handler: "🎉")),
matchRoute: ["👷♂️", "🏗", "🚧"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .constant("👷♀️", node: .handler("🎉"))),
matchRoute: ["🏗", "👷♀️"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .parameter("👷♀️", node: .handler("🎉"))),
matchRoute: ["🏗", "🚧"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗", "👷♀️": "🚧"]
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .wildcard(.handler("🎉"))),
matchRoute: ["🏗", "👷♀️"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .catchAll("👷♀️", handler: "🎉")),
matchRoute: ["🏗", "🚧", "🏢"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗", "👷♀️": "🚧/🏢"]
)
XCTAssertMatchSucceeeds(
initial: .parameter("👷♂️", node: .catchAll(nil, handler: "🎉")),
matchRoute: ["🏗", "🚧", "🏢"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .wildcard(.constant("👷♂️", node: .handler("🎉"))),
matchRoute: ["🏗", "👷♂️"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .wildcard(.parameter("👷♂️", node: .handler("🎉"))),
matchRoute: ["🏗", "🚧"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🚧"]
)
XCTAssertMatchSucceeeds(
initial: .wildcard(.wildcard(.handler("🎉"))),
matchRoute: ["🏗", "🚧"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .wildcard(.catchAll("👷♂️", handler: "🎉")),
matchRoute: ["🏗", "🚧", "👷♀️"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🚧/👷♀️"]
)
XCTAssertMatchSucceeeds(
initial: .wildcard(.catchAll(nil, handler: "🎉")),
matchRoute: ["🏗", "🚧", "👷♀️"],
expectedHandler: "🎉"
)
}
// MARK: priority
func testMatch_WithRouteMatchingMultipleRoutesInNode_ShouldReturnMostPrioritaryHandler() {
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["👷♂️": .handler("🎉")],
parameter: .init(name: "👷♀️", node: .handler("💥")),
wildcard: .handler("💣"),
catchAll: .init(name: "🚧", handler: "🧨"),
handler: "🕳"
),
matchRoute: ["👷♂️"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["👷♀️": .handler("💥")],
parameter: .init(name: "👷♀️", node: .handler("🎉")),
wildcard: .handler("💣"),
catchAll: .init(name: "🚧", handler: "🧨"),
handler: "🕳"
),
matchRoute: ["🏗"],
expectedHandler: "🎉",
expectedParameters: ["👷♀️": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["👷♀️": .handler("💥")],
wildcard: .handler("🎉"),
catchAll: .init(name: "🚧", handler: "🧨"),
handler: "🕳"
),
matchRoute: ["🏗"],
expectedHandler: "🎉"
)
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["👷♀️": .handler("💥")],
catchAll: .init(name: "🚧", handler: "🎉"),
handler: "🕳"
),
matchRoute: ["🏗"],
expectedHandler: "🎉",
expectedParameters: ["🚧": "🏗"]
)
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["👷♀️": .handler("💥")],
catchAll: .init(name: nil, handler: "🎉"),
handler: "🕳"
),
matchRoute: ["🏗"],
expectedHandler: "🎉"
)
}
// MARK: backtracking
func testMatch_WithRoutePartiallyMatchingMorePrioritaryRoute_ShouldBacktrackAndReturnNextMostPrioritaryHandler() {
// match: 🏗/🚧
//
// ├──┬ 🏗
// │ └──● 💥
// │
// └──┬ :👷♂️
// └──┬ :👷♀️
// └──● 🎉
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["🏗": .handler("💥")],
parameter: .init(name: "👷♂️", node: .parameter("👷♀️", node: .handler("🎉")))
),
matchRoute: ["🏗", "🚧"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗", "👷♀️": "🚧"]
)
// match: 🏗/🚧/🛠
//
// ├──┬ 🏗
// │ ├──┬ 🚧
// │ │ └──● 💣
// │ │
// │ └──┬ :🔨
// │ └──┬ 🔧
// │ └──● 💥
// │
// └──┬ :👷♂️
// └──┬ :👷♀️
// └──┬ :🏢
// └──● 🎉
XCTAssertMatchSucceeeds(
initial: .init(
constants: [
"🏗": .init(
constants: ["🚧": .handler("💣")],
parameter: .init(
name: "🔨",
node: .constant("🔧", node: .handler("💥"))
)
)
],
parameter: .init(name: "👷♂️", node: .parameter("👷♀️", node: .parameter("🏢", node: .handler("🎉"))))
),
matchRoute: ["🏗", "🚧", "🛠"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗", "👷♀️": "🚧", "🏢": "🛠"]
)
// match: 🏗/🚧
//
// ├──┬ 🏗
// │ └──┬ 🚧
// │ └──┬ :🛠
// │ └──● 💥
// │
// └──┬ :👷♂️
// └──┬ :👷♀️
// └──● 🎉
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["🏗": .constant("🚧", node: .parameter("🛠", node: .handler("💥")))],
parameter: .init(name: "👷♂️", node: .parameter("👷♀️", node: .handler("🎉")))
),
matchRoute: ["🏗", "🚧"],
expectedHandler: "🎉",
expectedParameters: ["👷♂️": "🏗", "👷♀️": "🚧"]
)
// match 🏗/🚧/🛠/🏢
//
// ├──┬ 🏗
// │ └──┬ 🚧
// │ └──┬ :🛠
// │ └──● 💥
// │
// ├──┬ :👷♂️
// │ └──┬ :👷♀️
// │ └──┬ :🤷♂️
// │ └──● 💣
// │
// ├──┬ *
// │ └──┬ :🚧
// │ └──┬ 🛠
// │ └──┬ 🏠
// │ └──● 🧨
// │
// └──┬ **🕳
// └──● 🎉
XCTAssertMatchSucceeeds(
initial: .init(
constants: ["🏗": .constant("🚧", node: .parameter("🛠", node: .handler("💥")))],
parameter: .init(name: "👷♂️", node: .parameter("👷♀️", node: .parameter("🤷♂️", node: .handler("💣")))),
wildcard: .parameter("🚧", node: .constant("🛠", node: .constant("🏠", node: .handler("🧨")))),
catchAll: .init(name: "🕳", handler: "🎉")
),
matchRoute: ["🏗", "🚧", "🛠", "🏢"],
expectedHandler: "🎉",
expectedParameters: ["🕳": "🏗/🚧/🛠/🏢"]
)
}
}
private extension Route_TrieNode_MatchTests {
private func XCTAssertMatchFails(
initial node: TrieNode,
matchRoute: [String],
file: StaticString = #file,
line: UInt = #line
) {
var parameters = [String: String]()
XCTAssertNil(node.match(matchRoute, parameters: ¶meters), file: file, line: line)
XCTAssertEqual(parameters, [:], file: file, line: line)
}
private func XCTAssertMatchSucceeeds(
initial node: TrieNode,
matchRoute: [String],
expectedHandler: String,
expectedParameters: [String: String] = [:],
file: StaticString = #file,
line: UInt = #line
) {
var parameters = [String: String]()
XCTAssertEqual(node.match(matchRoute, parameters: ¶meters), expectedHandler, file: file, line: line)
XCTAssertEqual(parameters, expectedParameters, file: file, line: line)
}
}
| mit | 8d570d19726c6c74b550e18cc74818ff | 31.068306 | 120 | 0.424384 | 5.406264 | false | false | false | false |
coderQuanjun/PigTV | GYJTV/GYJTV/Classes/Home/Controller/AnchorViewController.swift | 1 | 4372 | //
// AnchorViewController.swift
// GYJTV
//
// Created by 田全军 on 2017/4/20.
// Copyright © 2017年 Quanjun. All rights reserved.
//
import UIKit
import MJRefresh
private let kEdgeMargin : CGFloat = 8
private let kHomeCellID : String = "homeCell"
class AnchorViewController: UIViewController {
// MARK: 对外属性
var homeType : HomeType!
// MARK: 定义属性
fileprivate lazy var homeView : HomeViewModel = HomeViewModel()
fileprivate lazy var collectionView : UICollectionView = {
let layout = WaterfallLayout()
layout.sectionInset = UIEdgeInsets(top: kEdgeMargin, left: kEdgeMargin, bottom: kEdgeMargin, right: kEdgeMargin)
layout.minimumLineSpacing = kEdgeMargin
layout.minimumInteritemSpacing = kEdgeMargin
layout.dataSource = self
let collection = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collection.delegate = self
collection.dataSource = self
collection.autoresizingMask = [.flexibleWidth,.flexibleHeight]
collection.backgroundColor = UIColor.white
collection.register(UINib.init(nibName: "HomeViewCell", bundle: nil), forCellWithReuseIdentifier: kHomeCellID)
return collection
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
//刷新控件
collectionViewRefresh()
}
}
// MARK: 设置界面和刷新控件
extension AnchorViewController{
fileprivate func setupViews(){
view.addSubview(collectionView)
}
//添加上拉下拉刷新
fileprivate func collectionViewRefresh(){
//下拉刷新
collectionView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadHeaderDataWithIndex))
//上拉加载
collectionView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadFooterDataWithIndex))
//进入页面开始刷新
collectionView.mj_header.beginRefreshing()
}
@objc fileprivate func loadHeaderDataWithIndex() {
//下拉刷新时,停止上拉加载
if collectionView.mj_footer.isRefreshing {
collectionView.mj_footer.endRefreshing()
}
collectionView.mj_header.beginRefreshing()
homeView.loadHomeData(type: homeType, index : 0, finishedCallback: {
self.collectionView.reloadData()
self.collectionView.mj_header.endRefreshing()
})
}
@objc fileprivate func loadFooterDataWithIndex() {
//上拉加载时,停止下拉刷新
if collectionView.mj_header.isRefreshing {
collectionView.mj_header.endRefreshing()
}
collectionView.mj_footer.beginRefreshing()
homeView.loadHomeData(type: homeType, index : homeView.anchorModels.count, finishedCallback: {
if self.homeView.anchorModels.count <= 0{
}
self.collectionView.reloadData()
self.collectionView.mj_footer.endRefreshing()
})
}
}
// MARK: WaterfallLayoutDataSource
extension AnchorViewController : WaterfallLayoutDataSource{
func waterfallLayout(_ layout: WaterfallLayout, indexPath: IndexPath) -> CGFloat {
return indexPath.item % 2 == 0 ? kScreenWidth * 2 / 3 : kScreenWidth * 0.5
}
}
// MARK: UICollectionViewDelegate,UICollectionViewDataSource
extension AnchorViewController : UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return homeView.anchorModels.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let homeCell = collectionView.dequeueReusableCell(withReuseIdentifier: kHomeCellID, for: indexPath) as! HomeViewCell
homeCell.anchorModel = homeView.anchorModels[indexPath.item]
return homeCell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
dismissScreenListPlayView()
let roomVc = RoomViewController()
roomVc.anchorM = homeView.anchorModels[indexPath.item]
navigationController?.pushViewController(roomVc, animated: true)
}
}
| mit | 1cdc6d5585c6a66c91521a7228243557 | 35.145299 | 138 | 0.694727 | 5.401022 | false | false | false | false |
stripe/stripe-ios | StripeCore/StripeCore/Source/Analytics/STPAnalyticEvent.swift | 1 | 7165 | //
// STPAnalyticEvent.swift
// StripeCore
//
// Created by Mel Ludowise on 3/12/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
/// Enumeration of all the analytic events logged by our SDK.
@_spi(STP) public enum STPAnalyticEvent: String {
// MARK: - Payment Creation
case tokenCreation = "stripeios.token_creation"
// This was "stripeios.source_creation" in earlier SDKs,
// but we need to support both the old and new values forever.
case sourceCreation = "stripeios.source_creationn"
case paymentMethodCreation = "stripeios.payment_method_creation"
case paymentMethodIntentCreation = "stripeios.payment_intent_confirmation"
case setupIntentConfirmationAttempt = "stripeios.setup_intent_confirmation"
// MARK: - Payment Confirmation
case _3DS2AuthenticationRequestParamsFailed =
"stripeios.3ds2_authentication_request_params_failed"
case _3DS2AuthenticationAttempt = "stripeios.3ds2_authenticate"
case _3DS2FrictionlessFlow = "stripeios.3ds2_frictionless_flow"
case urlRedirectNextAction = "stripeios.url_redirect_next_action"
case _3DS2ChallengeFlowPresented = "stripeios.3ds2_challenge_flow_presented"
case _3DS2ChallengeFlowTimedOut = "stripeios.3ds2_challenge_flow_timed_out"
case _3DS2ChallengeFlowUserCanceled = "stripeios.3ds2_challenge_flow_canceled"
case _3DS2ChallengeFlowCompleted = "stripeios.3ds2_challenge_flow_completed"
case _3DS2ChallengeFlowErrored = "stripeios.3ds2_challenge_flow_errored"
case _3DS2RedirectUserCanceled = "stripeios.3ds2_redirect_canceled"
// MARK: - Card Metadata
case cardMetadataLoadedTooSlow = "stripeios.card_metadata_loaded_too_slow"
case cardMetadataResponseFailure = "stripeios.card_metadata_load_failure"
case cardMetadataMissingRange = "stripeios.card_metadata_missing_range"
// MARK: - Card Scanning
case cardScanSucceeded = "stripeios.cardscan_success"
case cardScanCancelled = "stripeios.cardscan_cancel"
// MARK: - Identity Verification Flow
case verificationSheetPresented = "stripeios.idprod.verification_sheet.presented"
case verificationSheetClosed = "stripeios.idprod.verification_sheet.closed"
case verificationSheetFailed = "stripeios.idprod.verification_sheet.failed"
// MARK: - FinancialConnections
case financialConnectionsSheetPresented = "stripeios.financialconnections.sheet.presented"
case financialConnectionsSheetClosed = "stripeios.financialconnections.sheet.closed"
case financialConnectionsSheetFailed = "stripeios.financialconnections.sheet.failed"
// MARK: - PaymentSheet Init
case mcInitCustomCustomer = "mc_custom_init_customer"
case mcInitCompleteCustomer = "mc_complete_init_customer"
case mcInitCustomApplePay = "mc_custom_init_applepay"
case mcInitCompleteApplePay = "mc_complete_init_applepay"
case mcInitCustomCustomerApplePay = "mc_custom_init_customer_applepay"
case mcInitCompleteCustomerApplePay = "mc_complete_init_customer_applepay"
case mcInitCustomDefault = "mc_custom_init_default"
case mcInitCompleteDefault = "mc_complete_init_default"
// MARK: - PaymentSheet Show
case mcShowCustomNewPM = "mc_custom_sheet_newpm_show"
case mcShowCustomSavedPM = "mc_custom_sheet_savedpm_show"
case mcShowCustomApplePay = "mc_custom_sheet_applepay_show"
case mcShowCustomLink = "mc_custom_sheet_link_show"
case mcShowCompleteNewPM = "mc_complete_sheet_newpm_show"
case mcShowCompleteSavedPM = "mc_complete_sheet_savedpm_show"
case mcShowCompleteApplePay = "mc_complete_sheet_applepay_show"
case mcShowCompleteLink = "mc_complete_sheet_link_show"
// MARK: - PaymentSheet Payment
case mcPaymentCustomNewPMSuccess = "mc_custom_payment_newpm_success"
case mcPaymentCustomSavedPMSuccess = "mc_custom_payment_savedpm_success"
case mcPaymentCustomApplePaySuccess = "mc_custom_payment_applepay_success"
case mcPaymentCustomLinkSuccess = "mc_custom_payment_link_success"
case mcPaymentCompleteNewPMSuccess = "mc_complete_payment_newpm_success"
case mcPaymentCompleteSavedPMSuccess = "mc_complete_payment_savedpm_success"
case mcPaymentCompleteApplePaySuccess = "mc_complete_payment_applepay_success"
case mcPaymentCompleteLinkSuccess = "mc_complete_payment_link_success"
case mcPaymentCustomNewPMFailure = "mc_custom_payment_newpm_failure"
case mcPaymentCustomSavedPMFailure = "mc_custom_payment_savedpm_failure"
case mcPaymentCustomApplePayFailure = "mc_custom_payment_applepay_failure"
case mcPaymentCustomLinkFailure = "mc_custom_payment_link_failure"
case mcPaymentCompleteNewPMFailure = "mc_complete_payment_newpm_failure"
case mcPaymentCompleteSavedPMFailure = "mc_complete_payment_savedpm_failure"
case mcPaymentCompleteApplePayFailure = "mc_complete_payment_applepay_failure"
case mcPaymentCompleteLinkFailure = "mc_complete_payment_link_failure"
// MARK: - PaymentSheet Option Selected
case mcOptionSelectCustomNewPM = "mc_custom_paymentoption_newpm_select"
case mcOptionSelectCustomSavedPM = "mc_custom_paymentoption_savedpm_select"
case mcOptionSelectCustomApplePay = "mc_custom_paymentoption_applepay_select"
case mcOptionSelectCustomLink = "mc_custom_paymentoption_link_select"
case mcOptionSelectCompleteNewPM = "mc_complete_paymentoption_newpm_select"
case mcOptionSelectCompleteSavedPM = "mc_complete_paymentoption_savedpm_select"
case mcOptionSelectCompleteApplePay = "mc_complete_paymentoption_applepay_select"
case mcOptionSelectCompleteLink = "mc_complete_paymentoption_link_select"
// MARK: - Link Signup
case linkSignupCheckboxChecked = "link.signup.checkbox_checked"
case linkSignupFlowPresented = "link.signup.flow_presented"
case linkSignupStart = "link.signup.start"
case linkSignupComplete = "link.signup.complete"
case linkSignupFailure = "link.signup.failure"
// MARK: - Link 2FA
case link2FAStart = "link.2fa.start"
case link2FAStartFailure = "link.2fa.start_failure"
case link2FAComplete = "link.2fa.complete"
case link2FACancel = "link.2fa.cancel"
case link2FAFailure = "link.2fa.failure"
// MARK: - Link Misc
case linkAccountLookupFailure = "link.account_lookup.failure"
// MARK: - LUXE
case luxeSerializeFailure = "luxe_serialize_failure"
case luxeClientFilteredPaymentMethods = "luxe_client_filtered_payment_methods"
case luxeClientFilteredPaymentMethodsNone = "luxe_client_filtered_payment_methods_none"
case luxeImageSelectorIconDownloaded = "luxe_image_selector_icon_downloaded"
case luxeImageSelectorIconFromBundle = "luxe_image_selector_icon_from_bundle"
case luxeImageSelectorIconNotFound = "luxe_image_selector_icon_not_found"
// MARK: - Address Element
case addressShow = "mc_address_show"
case addressCompleted = "mc_address_completed"
// MARK: - PaymentMethodMessagingView
case paymentMethodMessagingViewLoadSucceeded = "pmmv_load_succeeded"
case paymentMethodMessagingViewLoadFailed = "pmmv_load_failed"
case paymentMethodMessagingViewTapped = "pmmv_tapped"
}
| mit | aae55e354bf58fb6d7784eee16620c6c | 49.808511 | 94 | 0.771636 | 4.172394 | false | false | false | false |
lzpfmh/actor-platform | actor-apps/app-ios/ActorApp/ACManagedBind.swift | 1 | 6764 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
protocol ACBindedCell {
typealias BindData
static func bindedCellHeight(table: ACManagedTable, item: BindData) -> CGFloat
func bind(item: BindData, table: ACManagedTable, index: Int, totalCount: Int)
}
protocol ACBindedSearchCell {
typealias BindData
static func bindedCellHeight(item: BindData) -> CGFloat
func bind(item: BindData, search: String?)
}
class ACBindedRows<BindCell where BindCell: UITableViewCell, BindCell: ACBindedCell>: NSObject, ACManagedRange, ARDisplayList_AppleChangeListener {
var displayList: ARBindedDisplayList!
var selectAction: ((BindCell.BindData) -> Bool)?
var canEditAction: ((BindCell.BindData) -> Bool)?
var editAction: ((BindCell.BindData) -> ())?
var didBind: ((BindCell, BindCell.BindData) -> ())?
var autoHide = true
private var table: ACManagedTable!
// Total items count
func rangeNumberOfItems(table: ACManagedTable) -> Int {
return Int(displayList.size())
}
// Cells
func rangeCellHeightForItem(table: ACManagedTable, indexPath: ACRangeIndexPath) -> CGFloat {
let data = displayList.itemWithIndex(jint(indexPath.item)) as! BindCell.BindData
return BindCell.self.bindedCellHeight(table, item: data)
}
func rangeCellForItem(table: ACManagedTable, indexPath: ACRangeIndexPath) -> UITableViewCell {
let data = displayList.itemWithIndex(jint(indexPath.item)) as! BindCell.BindData
let cell = table.dequeueCell(indexPath.indexPath) as BindCell
cell.bind(data, table: table, index: indexPath.item, totalCount: rangeNumberOfItems(table))
displayList.touchWithIndex(jint(indexPath.item))
didBind?(cell, data)
return cell
}
// Select
func rangeCanSelect(table: ACManagedTable, indexPath: ACRangeIndexPath) -> Bool {
return selectAction != nil
}
func rangeSelect(table: ACManagedTable, indexPath: ACRangeIndexPath) -> Bool {
return selectAction!(displayList.itemWithIndex(jint(indexPath.item)) as! BindCell.BindData)
}
// Delete
func rangeCanDelete(table: ACManagedTable, indexPath: ACRangeIndexPath) -> Bool {
if canEditAction != nil {
return canEditAction!(displayList.itemWithIndex(jint(indexPath.item)) as! BindCell.BindData)
}
return false
}
func rangeDelete(table: ACManagedTable, indexPath: ACRangeIndexPath) {
editAction!(displayList.itemWithIndex(jint(indexPath.item)) as! BindCell.BindData)
}
// Binding
func rangeBind(table: ACManagedTable, binder: Binder) {
self.table = table
displayList.addAppleListener(self)
updateVisibility()
}
@objc func onCollectionChangedWithChanges(modification: ARAppleListUpdate!) {
let tableView = self.table.tableView
let section = 0
if (modification.isLoadMore) {
UIView.setAnimationsEnabled(false)
}
if modification.nonUpdateCount() > 0 {
tableView.beginUpdates()
// Removed rows
if modification.removedCount() > 0 {
var rows = [NSIndexPath]()
for i in 0..<modification.removedCount() {
rows.append(NSIndexPath(forRow: Int(modification.getRemoved(jint(i))), inSection: section))
}
tableView.deleteRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Automatic)
}
// Added rows
if modification.addedCount() > 0 {
var rows = [NSIndexPath]()
for i in 0..<modification.addedCount() {
rows.append(NSIndexPath(forRow: Int(modification.getAdded(jint(i))), inSection: section))
}
tableView.insertRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Automatic)
}
// Moved rows
if modification.movedCount() > 0 {
for i in 0..<modification.movedCount() {
let mov = modification.getMoved(jint(i))
tableView.moveRowAtIndexPath(NSIndexPath(forRow: Int(mov.getSourceIndex()), inSection: section), toIndexPath: NSIndexPath(forRow: Int(mov.getDestIndex()), inSection: section))
}
}
tableView.endUpdates()
}
// Updated rows
if modification.updatedCount() > 0 {
let visibleIndexes = tableView.indexPathsForVisibleRows!
for i in 0..<modification.updatedCount() {
for visibleIndex in visibleIndexes {
if (visibleIndex.row == Int(modification.getUpdated(jint(i))) && visibleIndex.section == section) {
// Need to rebind manually because we need to keep cell reference same
if let item = displayList.itemWithIndex(jint(visibleIndex.row)) as? BindCell.BindData,
let cell = tableView.cellForRowAtIndexPath(visibleIndex) as? BindCell {
cell.bind(item, table: table, index: visibleIndex.row, totalCount: Int(displayList.size()))
}
}
}
}
}
updateVisibility()
if (modification.isLoadMore) {
UIView.setAnimationsEnabled(true)
}
}
func updateVisibility() {
if autoHide {
if displayList.size() == 0 {
table.hideTable()
} else {
table.showTable()
}
}
}
func rangeUnbind(table: ACManagedTable, binder: Binder) {
self.table = nil
displayList.removeAppleListener(self)
}
func filter(text: String) {
if (text.length == 0) {
self.displayList.initTopWithRefresh(false)
} else {
self.displayList.initSearchWithQuery(text, withRefresh: false)
}
}
private func checkInstallation() {
if displayList == nil {
fatalError("Display list not set!")
}
}
}
extension ACManagedSection {
func binded<T where T: UITableViewCell, T: ACBindedCell>(closure: (r: ACBindedRows<T>) -> ()) -> ACBindedRows<T> {
let r = ACBindedRows<T>()
regions.append(r)
closure(r: r)
r.checkInstallation()
return r
}
}
| mit | b2280cec28ca7600604a5f4d67975b91 | 31.834951 | 195 | 0.587522 | 5.243411 | false | false | false | false |
overtake/TelegramSwift | packages/TGUIKit/Sources/ShadowView.swift | 1 | 1976 | //
// ShadowView.swift
// TGUIKit
//
// Created by keepcoder on 02/08/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
public enum ShadowDirection {
case horizontal(Bool)
case vertical(Bool)
}
public class ShadowView: View {
public override init() {
super.init(frame: .zero)
setup()
}
public required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var gradient: CAGradientLayer {
return self.layer as! CAGradientLayer
}
private func setup() {
self.layer = CAGradientLayer()
self.shadowBackground = .white
}
public var direction: ShadowDirection = .vertical(true) {
didSet {
self.update()
}
}
public var shadowBackground: NSColor = .white {
didSet {
self.update()
}
}
private func update() {
self.gradient.colors = [shadowBackground.withAlphaComponent(0).cgColor, shadowBackground.cgColor];
// self.gradient.locations = [0.0, 1.0];
switch direction {
case let .vertical(reversed):
if reversed {
self.gradient.startPoint = CGPoint(x: 0, y: 0)
self.gradient.endPoint = CGPoint(x: 0.0, y: 1)
} else {
self.gradient.startPoint = CGPoint(x: 0, y: 1)
self.gradient.endPoint = CGPoint(x: 0.0, y: 0)
}
case let .horizontal(reversed):
if reversed {
self.gradient.startPoint = CGPoint(x: 0, y: 1)
self.gradient.endPoint = CGPoint(x: 1, y: 1)
} else {
self.gradient.startPoint = CGPoint(x: 1, y: 1)
self.gradient.endPoint = CGPoint(x: 0, y: 1)
}
}
}
}
| gpl-2.0 | c45d08ee2d51e85e6ec9fa2fa4b86868 | 25.689189 | 106 | 0.545823 | 4.238197 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/BrandOrOrganization.swift | 1 | 1813 | import Foundation
import CodablePlus
public enum BrandOrOrganization: Codable {
case brand(value: Brand)
case organization(value: Organization)
public init(_ value: Brand) {
self = .brand(value: value)
}
public init(_ value: Organization) {
self = .organization(value: value)
}
public init(from decoder: Decoder) throws {
let jsonContainer = try decoder.container(keyedBy: DictionaryKeys.self)
let dictionary = try jsonContainer.decode(Dictionary<String, Any>.self)
guard let type = dictionary[SchemaKeys.type.rawValue] as? String else {
throw SchemaError.typeDecodingError
}
let container = try decoder.singleValueContainer()
switch type {
case Brand.schemaName:
let value = try container.decode(Brand.self)
self = .brand(value: value)
case Organization.schemaName:
let value = try container.decode(Organization.self)
self = .organization(value: value)
default:
throw SchemaError.typeDecodingError
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .brand(let value):
try container.encode(value)
case .organization(let value):
try container.encode(value)
}
}
public var brand: Brand? {
switch self {
case .brand(let value):
return value
default:
return nil
}
}
public var organization: Organization? {
switch self {
case .organization(let value):
return value
default:
return nil
}
}
}
| mit | e273695b5336fdff3800f5583b21619f | 26.892308 | 79 | 0.581357 | 4.980769 | false | false | false | false |
postmanlabs/httpsnippet | test/fixtures/output/swift/nsurlsession/query.swift | 2 | 608 | import Foundation
var request = NSMutableURLRequest(URL: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
println(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
println(httpResponse)
}
})
dataTask.resume()
| mit | 62fd8228fa9750b1c8b54b5c48fd054a | 32.777778 | 114 | 0.646382 | 4.503704 | false | false | false | false |
antlr/antlr4 | runtime/Swift/Sources/Antlr4/tree/pattern/Chunk.swift | 6 | 1104 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
///
/// A chunk is either a token tag, a rule tag, or a span of literal text within a
/// tree pattern.
///
/// The method _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#split(String)_ returns a list of
/// chunks in preparation for creating a token stream by
/// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#tokenize(String)_. From there, we get a parse
/// tree from with _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)_. These
/// chunks are converted to _org.antlr.v4.runtime.tree.pattern.RuleTagToken_, _org.antlr.v4.runtime.tree.pattern.TokenTagToken_, or the
/// regular tokens of the text surrounding the tags.
///
public class Chunk: Equatable {
public static func ==(lhs: Chunk, rhs: Chunk) -> Bool {
return lhs.isEqual(rhs)
}
public func isEqual(_ other: Chunk) -> Bool {
return self === other
}
}
| bsd-3-clause | d27b7e8d317b5f9b583c93e1be94ab1b | 38.428571 | 135 | 0.709239 | 3.704698 | false | false | false | false |
nakiostudio/EasyPeasy | EasyPeasy/Item.swift | 1 | 6862 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
var easy_attributesReference: Int = 0
/**
Typealias of a tuple grouping an array of `NSLayoutConstraints`
to activate and another array of `NSLayoutConstraints` to
deactivate
*/
typealias ActivationGroup = ([NSLayoutConstraint], [NSLayoutConstraint])
/**
Protocol enclosing the objects a constraint will apply to
*/
public protocol Item: NSObjectProtocol {
/// Array of constraints installed in the current `Item`
var constraints: [NSLayoutConstraint] { get }
/// Owning `UIView` for the current `Item`. The concept varies
/// depending on the class conforming the protocol
var owningView: View? { get }
}
public extension Item {
/// Access to **EasyPeasy** `layout`, `reload` and `clear`operations
var easy: EasyPeasy {
return EasyPeasy(item: self)
}
/**
This method will trigger the recreation of the constraints
created using *EasyPeasy* for the current view. `Condition`
closures will be evaluated again
*/
@available(iOS, deprecated: 1.5.1, message: "Use easy.reload() instead")
func easy_reload() {
self.reload()
}
/**
Clears all the constraints applied with EasyPeasy to the
current `UIView`
*/
@available(iOS, deprecated: 1.5.1, message: "Use easy.clear() instead")
func easy_clear() {
self.clear()
}
}
/**
Internal extension that handles the storage and application
of `Attributes` in an `Item`
*/
extension Item {
/**
This method will trigger the recreation of the constraints
created using *EasyPeasy* for the current view. `Condition`
closures will be evaluated again
*/
func reload() {
var activateConstraints: [NSLayoutConstraint] = []
var deactivateConstraints: [NSLayoutConstraint] = []
for node in self.nodes.values {
let activationGroup = node.reload()
activateConstraints.append(contentsOf: activationGroup.0)
deactivateConstraints.append(contentsOf: activationGroup.1)
}
// Activate/deactivate the resulting `NSLayoutConstraints`
NSLayoutConstraint.deactivate(deactivateConstraints)
NSLayoutConstraint.activate(activateConstraints)
}
/**
Clears all the constraints applied with EasyPeasy to the
current `UIView`
*/
func clear() {
var deactivateConstraints: [NSLayoutConstraint] = []
for node in self.nodes.values {
deactivateConstraints.append(contentsOf: node.clear())
}
self.nodes = [:]
// Deactivate the resulting `NSLayoutConstraints`
NSLayoutConstraint.deactivate(deactivateConstraints)
}
}
/**
Internal extension that handles the storage and application
of `Attributes` in an `Item`
*/
extension Item {
/// Dictionary persisting the `Nodes` related with this `Item`
var nodes: [String:Node] {
get {
if let nodes = objc_getAssociatedObject(self, &easy_attributesReference) as? [String:Node] {
return nodes
}
let nodes: [String:Node] = [:]
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &easy_attributesReference, nodes, policy)
return nodes
}
set {
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &easy_attributesReference, newValue, policy)
}
}
/**
Applies the `Attributes` within the passed array to the current `Item`
- parameter attributes: Array of `Attributes` to apply into the `Item`
- returns the resulting `NSLayoutConstraints`
*/
func apply(attributes: [Attribute]) -> [NSLayoutConstraint] {
// Before doing anything ensure that this item has translates autoresizing
// mask into constraints disabled
self.disableAutoresizingToConstraints()
var layoutConstraints: [NSLayoutConstraint] = []
var activateConstraints: [NSLayoutConstraint] = []
var deactivateConstraints: [NSLayoutConstraint] = []
for attribute in attributes {
if let compoundAttribute = attribute as? CompoundAttribute {
layoutConstraints.append(contentsOf: self.apply(attributes: compoundAttribute.attributes))
continue
}
if let activationGroup = self.apply(attribute: attribute) {
layoutConstraints.append(contentsOf: activationGroup.0)
activateConstraints.append(contentsOf: activationGroup.0)
deactivateConstraints.append(contentsOf: activationGroup.1)
}
}
// Activate/deactivate the `NSLayoutConstraints` returned by the different `Nodes`
NSLayoutConstraint.deactivate(deactivateConstraints)
NSLayoutConstraint.activate(activateConstraints)
return layoutConstraints
}
func apply(attribute: Attribute) -> ActivationGroup? {
// Creates the `NSLayoutConstraint` of the `Attribute` holding
// a reference to it from the `Attribute` objects
attribute.createConstraints(for: self)
// Checks the node correspoding to the `Attribute` and creates it
// in case it doesn't exist
let node = self.nodes[attribute.signature] ?? Node()
// Set node
self.nodes[attribute.signature] = node
// Add the `Attribute` to the node and return the `NSLayoutConstraints`
// to be activated/deactivated
return node.add(attribute: attribute)
}
/**
Sets `translatesAutoresizingMaskIntoConstraints` to `false` if the
current `Item` implements it
*/
private func disableAutoresizingToConstraints() {
#if os(iOS) || os(tvOS)
(self as? UIView)?.translatesAutoresizingMaskIntoConstraints = false
#else
(self as? NSView)?.translatesAutoresizingMaskIntoConstraints = false
#endif
}
}
| mit | c300742de4bd80e053d724058dec1dc5 | 33.656566 | 106 | 0.644419 | 5.230183 | false | false | false | false |
vazteam/ProperMediaView | Classes/ProperMediaFullScreenViewController/ProperMediaFullScreenViewController.swift | 1 | 3429 | //
// ProperMediaViewController.swift
// ProperMediaView
//
// Created by Murawaki on 2017/02/19.
// Copyright © 2017年 Murawaki. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
public extension ProperMediaFullScreenViewController {
public static func show(mediaView: ProperMediaView, fromViewController: UIViewController) {
let mediaFullScreenVc = ProperMediaFullScreenViewController(mediaView: mediaView)
fromViewController.present(mediaFullScreenVc, animated: false, completion: nil)
}
}
public class ProperMediaFullScreenViewController: UIViewController {
var mediaView: ProperMediaFullScreenView
override public var prefersStatusBarHidden: Bool {
return true
}
public init(mediaView: ProperMediaView) {
self.mediaView = ProperMediaFullScreenView(displacedMediaView: mediaView)
super.init(nibName: nil, bundle: nil)
modalPresentationCapturesStatusBarAppearance = true
modalPresentationStyle = .overFullScreen
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - override UIViewController method
override public func loadView() {
self.view = mediaView
}
override public func viewDidLoad() {
super.viewDidLoad()
mediaView.closeButton.addTarget(self, action: #selector(self.closeButtonTouchUppedInside), for: .touchUpInside)
mediaView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.mediaViewPanGestured(gesture:))))
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
mediaView.initOverlayView()
mediaView.present()
if mediaView.isMovie() {
AVAudioSession.setVolumeWhenMannerMode(isVolume: true)
}
}
override public func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
AVAudioSession.setVolumeWhenMannerMode(isVolume: false)
}
func configureMediaView(velocityY: CGFloat) {
if fabs(velocityY) > 750 {
mediaView.dismiss(isPanUpward: velocityY > 0, completion: {
self.dismiss(animated: false, completion: nil)
})
} else {
mediaView.returnMovieViewCenter()
}
}
// MARK: - Action
func closeButtonTouchUppedInside() {
mediaView.dismiss(isPanUpward: true, completion: {
self.dismiss(animated: false, completion: nil)
})
}
func mediaViewPanGestured(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .changed:
let point: CGPoint = gesture.translation(in: self.view)
let moveView: UIView = mediaView.contentsView
let movedPoint: CGPoint = CGPoint(x: moveView.center.x, y: moveView.center.y + point.y)
moveView.center = movedPoint
gesture.setTranslation(CGPoint.zero, in: self.view)
mediaView.conformBlurToSwipe()
case .ended:
configureMediaView(velocityY: gesture.velocity(in: mediaView).y)
case .cancelled:
mediaView.returnMovieViewCenter()
default:
break
}
}
}
| mit | f488d2b102ae85b9de444fc0a233fefa | 31.018692 | 132 | 0.648278 | 5.128743 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/SMS/SMS_Paginator.swift | 1 | 11131 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension SMS {
/// Describes the connectors registered with the AWS SMS.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getConnectorsPaginator<Result>(
_ input: GetConnectorsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetConnectorsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getConnectors,
tokenKey: \GetConnectorsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getConnectorsPaginator(
_ input: GetConnectorsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetConnectorsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getConnectors,
tokenKey: \GetConnectorsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes the specified replication job or all of your replication jobs.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getReplicationJobsPaginator<Result>(
_ input: GetReplicationJobsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetReplicationJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getReplicationJobs,
tokenKey: \GetReplicationJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getReplicationJobsPaginator(
_ input: GetReplicationJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetReplicationJobsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getReplicationJobs,
tokenKey: \GetReplicationJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes the replication runs for the specified replication job.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getReplicationRunsPaginator<Result>(
_ input: GetReplicationRunsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetReplicationRunsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getReplicationRuns,
tokenKey: \GetReplicationRunsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getReplicationRunsPaginator(
_ input: GetReplicationRunsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetReplicationRunsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getReplicationRuns,
tokenKey: \GetReplicationRunsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes the servers in your server catalog. Before you can describe your servers, you must import them using ImportServerCatalog.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getServersPaginator<Result>(
_ input: GetServersRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetServersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getServers,
tokenKey: \GetServersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getServersPaginator(
_ input: GetServersRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetServersResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getServers,
tokenKey: \GetServersResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension SMS.GetConnectorsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SMS.GetConnectorsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension SMS.GetReplicationJobsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SMS.GetReplicationJobsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
replicationJobId: self.replicationJobId
)
}
}
extension SMS.GetReplicationRunsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SMS.GetReplicationRunsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
replicationJobId: self.replicationJobId
)
}
}
extension SMS.GetServersRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SMS.GetServersRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
vmServerAddressList: self.vmServerAddressList
)
}
}
| apache-2.0 | f6fc1c848f0d8906b6b491607bae7f67 | 41.162879 | 168 | 0.638757 | 5.167595 | false | false | false | false |
u10int/Kinetic | Pod/Classes/Timeline.swift | 1 | 10264 | //
// Timeline.swift
// Kinetic
//
// Created by Nicholas Shipes on 12/27/15.
// Copyright © 2015 Urban10 Interactive, LLC. All rights reserved.
//
import UIKit
internal class TimelineCallback {
var time: TimeInterval = 0
var block: () -> Void
var called = false
init(block: @escaping () -> Void) {
self.block = block
}
}
public enum TweenAlign {
case normal
case sequence
case start
}
public class TweenRange {
var tween: Tween
var start: TimeInterval
var end: TimeInterval {
return start + tween.delay + tween.duration
}
init(tween: Tween, position: TimeInterval) {
self.tween = tween
self.start = position
}
}
public class Timeline: Animation {
private(set) public var children = [TweenRange]()
weak public var timeline: Timeline?
override public var endTime: TimeInterval {
get {
var time: TimeInterval = 0
children.forEach { (range) in
time = max(time, range.end)
}
return time
}
}
override public var duration: TimeInterval {
get {
return endTime
}
set(newValue) {
}
}
override public var totalTime: TimeInterval {
get {
return runningTime
}
}
override public var totalDuration: TimeInterval {
get {
return (endTime * TimeInterval(repeatCount + 1)) + (repeatDelay * TimeInterval(repeatCount))
}
}
public var antialiasing: Bool = true {
didSet {
children.forEach { (range) in
range.tween.antialiasing = antialiasing
}
}
}
fileprivate var labels = [String: TimeInterval]()
fileprivate var callbacks = [TimeInterval: TimelineCallback]()
// MARK: Lifecycle
public convenience init(tweens: [Tween], align: TweenAlign = .normal) {
self.init()
add(tweens, position: 0, align: align)
}
public override init() {
super.init()
repeated.observe { [weak self] (timeline) in
self?.callbacks.forEach({ (time, fn) in
fn.called = false
})
}
}
deinit {
kill()
}
// MARK: Public Methods
@discardableResult
public func add(_ tween: Tween) -> Timeline {
add(tween, position: endTime)
return self
}
@discardableResult
public func add(_ value: Any, position: Any, align: TweenAlign = .normal) -> Timeline {
var tweensToAdd = [Tween]()
if let tween = value as? Tween {
tweensToAdd.append(tween)
} else if let items = value as? [Tween] {
tweensToAdd = items
} else {
assert(false, "Only a single Tween instance or an array of Tween instances can be provided")
return self
}
// by default, new tweens are added to the end of the timeline
var pos: TimeInterval = totalDuration
for (idx, tween) in tweensToAdd.enumerated() {
if idx == 0 {
if let label = position as? String {
pos = time(fromString:label, relativeToTime: endTime)
} else if let time = Double("\(position)") {
pos = TimeInterval(time * 1.0)
}
}
if align != .start {
pos += tween.delay
}
let range = TweenRange(tween: tween, position: pos)
// print("timeline - added tween at position \(position) with start time \(range.start), end time \(range.end)")
// remove tween from existing timeline (if `timeline` is not nil)... assign timeline to this
if let timeline = tween.timeline {
timeline.remove(tween: tween)
}
tween.timeline = self
children.append(range)
// increment position if items are being added sequentially
if align == .sequence {
pos += tween.totalDuration
}
}
return self
}
@discardableResult
public func add(_ tween: Tween, relativeToLabel label: String, offset: TimeInterval) -> Timeline {
if labels[label] == nil {
add(label: label)
}
if let position = labels[label] {
add(tween, position: position + offset)
}
return self
}
@discardableResult
public func add(label: String, position: Any = 0) -> Timeline {
var pos: TimeInterval = 0
if let label = position as? String {
pos = time(fromString:label, relativeToTime: endTime)
} else if let time = Double("\(position)") {
pos = TimeInterval(time)
}
labels[label] = pos
return self
}
@discardableResult
public func addCallback(_ position: Any, block: @escaping () -> Void) -> Timeline {
var pos: TimeInterval = 0
if let label = position as? String {
pos = time(fromString:label, relativeToTime: endTime)
} else if let time = Double("\(position)") {
pos = TimeInterval(time)
}
callbacks[pos] = TimelineCallback(block: block)
callbacks[pos]?.time = pos
return self
}
public func remove(_ label: String) {
labels[label] = nil
}
public func time(forLabel label: String) -> TimeInterval {
if let time = labels[label] {
return time
}
return 0
}
public func seek(toLabel label: String, pause: Bool = false) {
if let position = labels[label] {
seek(position)
if pause {
self.pause()
}
}
}
@discardableResult
public func shift(_ amount: TimeInterval, afterTime time: TimeInterval = 0) -> Timeline {
children.forEach { (range) in
if range.start >= time {
range.start += amount
if range.start < 0 {
range.start = 0
}
}
}
for (label, var labelTime) in labels {
if labelTime >= time {
labelTime += amount
if labelTime < 0 {
labelTime = 0
}
labels[label] = labelTime
}
}
return self
}
public func getActive() -> [Tween] {
var tweens = [Tween]()
children.forEach { (range) in
if range.tween.state == .running {
tweens.append(range.tween)
}
}
return tweens
}
public func remove(tween: Tween) {
if let timeline = tween.timeline {
if timeline == self {
tween.timeline = nil
children.enumerated().forEach({ (index, range) in
if range.tween == tween {
children.remove(at: index)
}
})
}
}
}
@discardableResult
public func from(_ props: Property...) -> Timeline {
children.forEach { (range) in
range.tween.from(props)
}
return self
}
@discardableResult
public func to(_ props: Property...) -> Timeline {
children.forEach { (range) in
range.tween.to(props)
}
return self
}
@discardableResult
override public func spring(tension: Double, friction: Double) -> Timeline {
children.forEach { (range) in
range.tween.spring(tension: tension, friction: friction)
}
return self
}
@discardableResult
public func perspective(_ value: CGFloat) -> Timeline {
children.forEach { (range) in
range.tween.perspective(value)
}
return self
}
@discardableResult
public func anchor(_ anchor: AnchorPoint) -> Timeline {
return anchorPoint(anchor.point())
}
@discardableResult
public func anchorPoint(_ point: CGPoint) -> Timeline {
children.forEach { (range) in
range.tween.anchorPoint(point)
}
return self
}
@discardableResult
public func stagger(_ offset: TimeInterval) -> Timeline {
children.enumerated().forEach { (index, range) in
range.start = offset * TimeInterval(index)
}
return self
}
public func goToAndPlay(_ label: String) {
let position = time(forLabel: label)
seek(position)
resume()
}
@discardableResult
public func goToAndStop(_ label: String) -> Timeline {
seek(toLabel: label, pause: true)
return self
}
// MARK: Animation
@discardableResult
override public func duration(_ duration: TimeInterval) -> Timeline {
children.forEach { (range) in
range.tween.duration(duration)
}
return self
}
@discardableResult
override public func ease(_ easing: EasingType) -> Timeline {
children.forEach { (range) in
range.tween.ease(easing)
}
return self
}
@discardableResult
override public func seek(_ time: TimeInterval) -> Timeline {
super.seek(time)
children.forEach { (range) in
let tween = range.tween
var tweenSeek = max(0, min(elapsed - range.start, tween.totalDuration))
tweenSeek = elapsed - range.start
// if timeline is reversed, then the tween's seek time should be relative to its end time
if direction == .reversed {
tweenSeek = range.end - elapsed
}
tween.seek(tweenSeek)
}
return self
}
override public func restart(_ includeDelay: Bool) {
super.restart(includeDelay)
for (_, callback) in callbacks {
callback.called = false
}
}
// MARK: TimeRenderable
override internal func render(time: TimeInterval, advance: TimeInterval = 0) {
super.render(time: time, advance: advance)
children.forEach { (range) in
if (elapsed >= range.start && (elapsed <= range.end || range.tween.spring != nil)) {
if range.tween.state != .running {
range.tween.play()
range.tween.state = .running
}
range.tween.render(time: elapsed - range.start, advance: advance)
} else if (elapsed < range.start) {
range.tween.render(time: 0, advance: advance)
} else if (elapsed > range.end) {
range.tween.render(time: elapsed - range.start, advance: advance)
}
}
// check for callbacks
callbacks.forEach({ (time, fn) in
if elapsed >= time && !fn.called {
fn.block()
fn.called = true
}
})
updated.trigger(self)
}
// MARK: Subscriber
override func advance(_ time: Double) {
guard shouldAdvance() else { return }
if children.count == 0 {
kill()
}
super.advance(time)
}
// MARK: Private Methods
fileprivate func time(fromString str: String, relativeToTime time: TimeInterval = 0) -> TimeInterval {
var position: TimeInterval = time
let string = NSString(string: str)
let regex = try! NSRegularExpression(pattern: "(\\w+)?([\\+,\\-\\+]=)([\\d\\.]+)", options: [])
let match = regex.firstMatch(in: string as String, options: [], range: NSRange(location: 0, length: string.length))
if let match = match {
var idx = 1
var multiplier: TimeInterval = 1
while idx < match.numberOfRanges {
let range = match.rangeAt(idx)
if range.length <= string.length && range.location < string.length {
let val = string.substring(with: range)
// label
if idx == 1 {
position = self.time(forLabel:val)
} else if idx == 2 {
if val == "-=" {
multiplier = -1
}
} else if idx == 3 {
if let offset = Double("\(val)") {
position += TimeInterval(offset)
}
}
}
idx += 1
}
position *= multiplier
}
return position
}
}
| mit | b6a18f6e4e92b389863a74501575c220 | 21.31087 | 117 | 0.648738 | 3.45323 | false | false | false | false |
kidaa/codecombat-ios | CodeCombat/PlayViewController.swift | 2 | 11568 | //
// PlayViewController.swift
// CodeCombat
//
// Created by Michael Schmatz on 8/6/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import UIKit
import WebKit
//I have subclassed UIScrollView so we can scroll on the WKWebView
class PlayViewScrollView:UIScrollView, UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
class PlayViewController: UIViewController {
@IBOutlet weak var runButton: UIButton!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var redoButton: UIButton!
@IBOutlet weak var undoButton: UIButton!
@IBOutlet weak var keyboardButton: UIButton!
@IBOutlet weak var resetCodeButton: UIButton!
var levelName = ""
var scrollView: UIScrollView!
var webView: WKWebView?
let editorContainerView = UIView()
var textViewController: EditorTextViewController!
var inventoryViewController: TomeInventoryViewController!
var inventoryFrame: CGRect!
let webManager = WebManager.sharedInstance
let backgroundImage = UIImage(named: "play_background")!
let lastSubmitString:String = ""
override func viewDidLoad() {
super.viewDidLoad()
listenToNotifications()
setupViews()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onWebViewReloadedFromCrash"), name: "webViewReloadedFromCrash", object: nil)
}
private func listenToNotifications() {
//webManager.subscribe(self, channel: "sprite:speech-updated", selector: Selector("onSpriteSpeechUpdated:"))
webManager.subscribe(self, channel: "tome:spell-loaded", selector: Selector("onTomeSpellLoaded:"))
webManager.subscribe(self, channel: "tome:winnability-updated", selector: Selector("onTomeWinnabilityUpdated:"))
let nc = NSNotificationCenter.defaultCenter()
//additional notifications are listened to below concerning undo manager in setupEditor
nc.addObserver(self, selector: Selector("setUndoRedoEnabled"), name: "textEdited", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onTextStorageFinishedTopLevelEditing"), name: "textStorageFinishedTopLevelEditing", object: nil)
}
func unsubscribeFromEverything() {
NSNotificationCenter.defaultCenter().removeObserver(self)
WebManager.sharedInstance.unsubscribe(self)
}
deinit {
print("PLAY VIEW CONTROLLER DE-INITED")
textViewController.textView.parentTextViewController = nil
webManager.unsubscribe(textViewController)
webManager.unsubscribe(inventoryViewController)
}
func onTextStorageFinishedTopLevelEditing() {
if getEscapedSourceString() != lastSubmitString {
runButton.enabled = true
} else {
//show error text view here
}
}
func setupViews() {
let frameWidth = view.frame.size.width
//let frameHeight = view.frame.size.height
let aspectRatio:CGFloat = 1.56888
let topBarHeight: CGFloat = 50
let backgroundImageVerticalOverlap: CGFloat = 11
editorContainerView.frame = CGRectMake(0, topBarHeight + frameWidth / aspectRatio - backgroundImageVerticalOverlap, frameWidth, backgroundImage.size.height)
setupScrollView()
setupInventory()
setupEditor()
setupBackgrounds()
setupToolbar()
setUndoRedoEnabled()
}
func setupScrollView() {
scrollView = PlayViewScrollView(frame: view.frame)
scrollView.contentSize = CGSizeMake(view.frame.size.width, editorContainerView.frame.origin.y + editorContainerView.frame.size.height)
scrollView.addSubview(editorContainerView)
scrollView.bounces = false
scrollView.contentOffset = CGPoint(x: 0, y: 200) // Helps for testing.
view.insertSubview(scrollView, atIndex: 0)
}
func setupInventory() {
let inventoryTopMargin: CGFloat = 51
let inventoryBottomMargin: CGFloat = 25
inventoryFrame = CGRectMake(0, inventoryTopMargin, 320, editorContainerView.frame.height - inventoryTopMargin - inventoryBottomMargin)
inventoryViewController = TomeInventoryViewController()
inventoryViewController.view.frame = inventoryFrame
inventoryViewController.inventoryView.frame = CGRect(x: 0, y: 0, width: inventoryFrame.width, height: inventoryFrame.height)
//helps to fix a scrolling bug
scrollView.panGestureRecognizer.requireGestureRecognizerToFail(inventoryViewController.inventoryView.panGestureRecognizer)
addChildViewController(inventoryViewController)
editorContainerView.addSubview(inventoryViewController.view)
}
func setupEditor() {
let editorVerticalMargin: CGFloat = 50
let editorTextViewFrame = CGRectMake(370, editorVerticalMargin, 630, editorContainerView.frame.height - 2 * editorVerticalMargin)
textViewController = EditorTextViewController()
textViewController.view.frame = editorTextViewFrame
textViewController.createTextViewWithFrame(editorTextViewFrame)
scrollView.panGestureRecognizer.requireGestureRecognizerToFail(textViewController.dragGestureRecognizer)
scrollView.panGestureRecognizer.requireGestureRecognizerToFail(textViewController.textView.panGestureRecognizer)
addChildViewController(textViewController)
editorContainerView.addSubview(textViewController.textView)
let undoManager = textViewController.textStorage.undoManager
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: Selector("setUndoRedoEnabled"), name: NSUndoManagerDidUndoChangeNotification, object: undoManager)
nc.addObserver(self, selector: Selector("setUndoRedoEnabled"), name: NSUndoManagerDidRedoChangeNotification, object: undoManager)
}
func setupWebView() {
webView = webManager.webView!
webView!.hidden = false
if webView != nil {
scrollView.addSubview(webView!)
}
}
func onWebViewReloadedFromCrash() {
webView = WebManager.sharedInstance.webView!
}
func setupBackgrounds() {
let editorBackground = UIImageView(image: backgroundImage)
editorContainerView.addSubview(editorBackground)
editorContainerView.sendSubviewToBack(editorBackground)
let bottomBackground = UIImageView(image: UIImage(named: "play_background_bottom"))
bottomBackground.frame.origin.y = view.frame.size.height - bottomBackground.frame.size.height
view.insertSubview(bottomBackground, aboveSubview: editorContainerView)
for button in [runButton, submitButton, redoButton, undoButton, keyboardButton, resetCodeButton] {
view.insertSubview(button, aboveSubview: bottomBackground)
}
}
func updateForLevel() {
let levelID = LevelSettingsManager.sharedInstance.level
if [.DungeonsOfKithgard, .GemsInTheDeep, .ShadowGuard, .KounterKithwise, .CrawlwaysOfKithgard, .ForgetfulGemsmith, .TrueNames, .FavorableOdds, .TheRaisedSword, .TheFirstKithmaze, .HauntedKithmaze, .DescendingFurther, .TheSecondKithmaze, .DreadDoor, .KnownEnemy, .MasterOfNames, .LowlyKithmen, .ClosingTheDistance, .TacticalStrike, .TheFinalKithmaze, .TheGauntlet, .KithgardGates, .CavernSurvival, .DefenseOfPlainswood, .WindingTrail].contains(levelID) {
submitButton.setTitle("DONE", forState: .Normal)
submitButton.setTitle("DONE", forState: .Highlighted)
submitButton.setTitle("DONE", forState: .Selected)
submitButton.setTitle("DONE", forState: .Disabled)
}
}
func setupToolbar() {
}
func onSpriteSpeechUpdated(note:NSNotification) {
// if let event = note.userInfo {
// println("Setting speech before unveil!")
// spriteMessageBeforeUnveil = SpriteDialogue(
// image: UIImage(named: "AnyaPortrait"),
// spriteMessage: event["message"]! as String,
// spriteName: event["spriteID"]! as String)
// }
}
func onTomeSpellLoaded(note:NSNotification) {
if let event = note.userInfo {
let spell = event["spell"] as! NSDictionary
let startingCode = spell["source"] as? String
if startingCode != nil {
textViewController.replaceTextViewContentsWithString(startingCode!)
print("set code before load to \(startingCode!)")
textViewController.textStorage.undoManager.removeAllActions()
setUndoRedoEnabled()
}
}
}
func onTomeWinnabilityUpdated(note: NSNotification) {
print("winnability updated \(note)")
if let event = note.userInfo {
let winnable = event["winnable"] as! Bool
runButton.selected = !winnable
submitButton.selected = winnable
}
}
@IBAction func onCodeRun(sender: UIButton) {
NSNotificationCenter.defaultCenter().postNotificationName("codeRun", object: nil)
handleTomeSourceRequest()
webManager.publish("tome:manual-cast", event: [:])
scrollView.contentOffset = CGPoint(x: 0, y: 0)
runButton.enabled = false
}
@IBAction func onCodeSubmitted(sender: UIButton) {
handleTomeSourceRequest()
webManager.publish("tome:manual-cast", event: ["realTime": true])
scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
@IBAction func onUndo(sender:UIButton) {
textViewController.textStorage.undoManager.undo()
textViewController.textView.setNeedsDisplay()
}
@IBAction func onRedo(sender:UIButton) {
textViewController.textStorage.undoManager.redo()
textViewController.textView.setNeedsDisplay()
}
@IBAction func onClickResetCode(sender:UIButton) {
let titleMessage = NSLocalizedString("Are you sure?", comment:"")
let messageString = NSLocalizedString("Reloading the original code will erase all of the code you've written. Are you sure?", comment:"")
let alertController = UIAlertController(title: titleMessage, message: messageString, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let resetAction = UIAlertAction(title: "Reset", style: .Destructive, handler: {(action) in
NSNotificationCenter.defaultCenter().postNotificationName("codeReset", object: nil)
self.webManager.publish("level:restart", event: [:])
})
alertController.addAction(resetAction)
presentViewController(alertController, animated: true, completion: nil)
}
func setUndoRedoEnabled() {
let undoManager = textViewController.textStorage.undoManager
undoButton.enabled = undoManager.canUndo
redoButton.enabled = undoManager.canRedo
}
func scrollToBottomOfScrollView() {
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - self.scrollView.frame.size.height)
scrollView.setContentOffset(bottomOffset, animated: true)
}
@IBAction func toggleKeyboard(sender:UIButton) {
if !textViewController.keyboardModeEnabled {
scrollToBottomOfScrollView()
}
textViewController.toggleKeyboardMode()
}
func getEscapedSourceString() -> String {
if textViewController.textView == nil {
return ""
}
var escapedString = textViewController.textView.text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
escapedString = escapedString.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
return escapedString
}
func handleTomeSourceRequest(){
let escapedString = getEscapedSourceString()
lastSubmitString == escapedString
let js = "if(currentView.tome.spellView) { currentView.tome.spellView.ace.setValue(\"\(escapedString)\"); } else { console.log('damn, no one was selected!'); }"
//println(js)
webManager.evaluateJavaScript(js, completionHandler: nil)
}
}
| mit | 3685541fd7e12b337e0de102bd071364 | 41.065455 | 457 | 0.751729 | 4.872789 | false | false | false | false |
CPRTeam/CCIP-iOS | Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift | 3 | 4119 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
/// A type that supports incremental updates. For example Digest or Cipher may be updatable
/// and calculate result incerementally.
public protocol Updatable {
/// Update given bytes in chunks.
///
/// - parameter bytes: Bytes to process.
/// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call.
/// - returns: Processed partial result data or empty array.
mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8>
/// Update given bytes in chunks.
///
/// - Parameters:
/// - bytes: Bytes to process.
/// - isLast: Indicate if given chunk is the last one. No more updates after this call.
/// - output: Resulting bytes callback.
/// - Returns: Processed partial result data or empty array.
mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool, output: (_ bytes: Array<UInt8>) -> Void) throws
}
extension Updatable {
public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws {
let processed = try update(withBytes: bytes, isLast: isLast)
if !processed.isEmpty {
output(processed)
}
}
public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
try self.update(withBytes: bytes, isLast: isLast)
}
public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
try self.update(withBytes: bytes.slice, isLast: isLast)
}
public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws {
try self.update(withBytes: bytes.slice, isLast: isLast, output: output)
}
/// Finish updates. This may apply padding.
/// - parameter bytes: Bytes to process
/// - returns: Processed data.
public mutating func finish(withBytes bytes: ArraySlice<UInt8>) throws -> Array<UInt8> {
try self.update(withBytes: bytes, isLast: true)
}
public mutating func finish(withBytes bytes: Array<UInt8>) throws -> Array<UInt8> {
try self.finish(withBytes: bytes.slice)
}
/// Finish updates. May add padding.
///
/// - Returns: Processed data
/// - Throws: Error
public mutating func finish() throws -> Array<UInt8> {
try self.update(withBytes: [], isLast: true)
}
/// Finish updates. This may apply padding.
/// - parameter bytes: Bytes to process
/// - parameter output: Resulting data
/// - returns: Processed data.
public mutating func finish(withBytes bytes: ArraySlice<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws {
let processed = try update(withBytes: bytes, isLast: true)
if !processed.isEmpty {
output(processed)
}
}
public mutating func finish(withBytes bytes: Array<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws {
try self.finish(withBytes: bytes.slice, output: output)
}
/// Finish updates. May add padding.
///
/// - Parameter output: Processed data
/// - Throws: Error
public mutating func finish(output: (Array<UInt8>) -> Void) throws {
try self.finish(withBytes: [], output: output)
}
}
| gpl-3.0 | 24b9d8813b75961a883a65196a0e91b8 | 41.453608 | 217 | 0.703497 | 4.155399 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/LostFound/Controller/LostFoundDetailViewController.swift | 1 | 5482 | //
// LostFoundDetailViewController.swift
// WePeiYang
//
// Created by Qin Yubo on 16/2/15.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import UIKit
import FXForms
import ObjectMapper
import SwiftyJSON
class LostFoundDetailViewController: UITableViewController, FXFormControllerDelegate {
var formController: FXFormController!
var type: String!
var index: String!
private var phoneNum = ""
override func viewDidLoad() {
super.viewDidLoad()
if type == "0" {
self.title = "丢失物品"
} else {
self.title = "捡到物品"
}
formController = FXFormController()
formController.tableView = self.tableView
formController.delegate = self
self.navigationItem.rightBarButtonItem = UIBarButtonItem().bk_initWithImage(UIImage(named: "lf_phone"), style: .Plain, handler: { handler in
if !self.phoneNum.isEmpty {
let phoneNumber = Int(self.phoneNum)
if phoneNumber != nil {
let alert = UIAlertController(title: "呼叫", message: "", preferredStyle: .ActionSheet)
let callAction = UIAlertAction(title: "\(phoneNumber!)", style: .Destructive, handler: {handler in
UIApplication.sharedApplication().openURL(NSURL(string: "tel://\(self.phoneNum)")!)
})
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler: nil)
alert.addAction(callAction)
alert.addAction(cancelAction)
alert.modalPresentationStyle = .Popover
alert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = self.view.bounds
self.presentViewController(alert, animated: true, completion: nil)
}
}
}) as? UIBarButtonItem
twtSDK.getLostFoundDetailWithID(index, success: {(task, responseObj) in
let dic = JSON(responseObj)
if dic["error_code"].int == -1 {
if let lostFoundDetail = Mapper<LostFoundDetail>().map(dic["data"].object) {
self.phoneNum = lostFoundDetail.phone
let form = LostFoundDetailForm()
form.detailItem = lostFoundDetail
self.formController.form = form
self.tableView.reloadData()
}
}
}, failure: {(task, error) in
MsgDisplay.showErrorMsg(error.localizedDescription)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 519b9f0ea34881dca27c11b639b91397 | 36.909722 | 157 | 0.629602 | 5.5818 | false | false | false | false |
phill84/mpx | mpx/MpvController.swift | 1 | 8603 | //
// MpvController.swift
// mpx
//
// Created by Jiening Wen on 01/08/15.
// Copyright (c) 2015 phill84.
//
// This file is part of mpx.
//
// mpx is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// mpx is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with mpx. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
import Foundation
import XCGLogger
class MpvController: NSObject {
let logger = XCGLogger.defaultInstance()
let playerWindowController: PlayerWindowController
let playlist = PlayList()
var context: COpaquePointer?
var mpvQueue: dispatch_queue_t?
var videoOriginalSize: NSSize?
var state: PlayerState = .Uninitialized
override init() {
playerWindowController = NSApplication.sharedApplication().windows[0].windowController as! PlayerWindowController
super.init()
playerWindowController.mpv = self
// initialize mpv
context = mpv_create()
if (context == nil) {
let error = "failed to create mpv context"
logger.severe(error)
playerWindowController.alertAndExit(error)
}
logger.debug("mpv context created: \(context!.debugDescription)")
checkError(mpv_initialize(context!), message: "mpv_initialize")
#if DEBUG
checkError(mpv_request_log_messages(context!, "info"), message: "mpv_request_log_messages")
#else
checkError(mpv_request_log_messages(context!, "warn"), message: "mpv_request_log_messages")
#endif
mpvQueue = dispatch_queue_create("mpv", DISPATCH_QUEUE_SERIAL)
// set default options
var videoView: AnyObject? = playerWindowController.window?.contentView!.subviews[0]
checkError(mpv_set_option(context!, "wid", MPV_FORMAT_INT64, &videoView), message: "mpv_set_option: wid")
checkError(mpv_set_option_string(context!, "audio-client-name", "mpx"), message: "mpv_set_option_string: audio-client-name")
checkError(mpv_set_option_string(context!, "hwdec", "auto"), message: "mpv_set_option_string: hwdec")
checkError(mpv_set_option_string(context!, "hwdec-codecs", "all"), message: "mpv_set_option_string: hwdec-codecs")
// register callbacks
func callback(context: UnsafeMutablePointer<Void>) -> Void {
let mpvController = unsafeBitCast(context, MpvController.self)
mpvController.readEvents()
}
mpv_set_wakeup_callback(context!, callback, unsafeBitCast(self, UnsafeMutablePointer<Void>.self));
// observe properties for UI update
mpv_observe_property(context!, 0, "pause", MPV_FORMAT_FLAG)
state = .Initialized
}
func checkError(status: Int32, message: String) {
if (status < 0) {
let error = String.fromCString(mpv_error_string(status))!
logger.error("mpv API error: \(error), \(message)")
playerWindowController.alertAndExit(error)
}
}
func readEvents() {
dispatch_async(mpvQueue!, {
while (self.context != nil) {
let event = mpv_wait_event(self.context!, 0).memory
let event_id = event.event_id.rawValue
if (event_id == MPV_EVENT_NONE.rawValue) {
break
}
self.handleEvent(event)
}
})
}
func handleEvent(event: mpv_event) {
switch event.event_id.rawValue {
case MPV_EVENT_IDLE.rawValue:
state = .Idle
case MPV_EVENT_SHUTDOWN.rawValue:
logger.debug("mpv shutdown")
case MPV_EVENT_LOG_MESSAGE.rawValue:
let msg = UnsafeMutablePointer<mpv_event_log_message>(event.data).memory
let prefix = String.fromCString(msg.prefix)!
let level = String.fromCString(msg.level)!
var text = String.fromCString(msg.text)!
text = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if !text.isEmpty {
NSLog("[\(prefix)] \(level): \(text)")
}
case MPV_EVENT_FILE_LOADED.rawValue:
logger.debug("file loaded")
state = .FileLoaded
// get video size and resize if necessary
videoOriginalSize = getVideoSize()
if AppDelegate.getInstance().fullscreen {
let mainFrame = NSScreen.mainScreen()!.frame
playerWindowController.resize(videoWidth: mainFrame.width, videoHeight: mainFrame.height, inRect: NSScreen.mainScreen()!.visibleFrame)
} else {
playerWindowController.resize(videoWidth: videoOriginalSize!.width, videoHeight: videoOriginalSize!.height, inRect: NSScreen.mainScreen()!.visibleFrame)
}
playerWindowController.showWindow()
AppDelegate.getInstance().mediaFileLoaded = true
// update window title
if let title = getVideoTitle() {
playerWindowController.updateTitle(title)
}
displayTextOSD(playlist.getCurrentFileName())
case MPV_EVENT_PLAYBACK_RESTART.rawValue:
if state != .Paused {
state = .Playing
}
logger.debug("playback restarted")
case MPV_EVENT_PAUSE.rawValue:
state = .Paused
logger.debug("playback paused")
case MPV_EVENT_UNPAUSE.rawValue:
logger.debug("playback unpaused")
case MPV_EVENT_END_FILE.rawValue:
let data = UnsafeMutablePointer<mpv_event_end_file>(event.data).memory
switch UInt32(data.reason) {
case MPV_END_FILE_REASON_ERROR.rawValue:
let error = String.fromCString(mpv_error_string(data.error))!
logger.error("end file: \(error)")
default:
logger.debug("end file: \(data.reason)")
}
if playlist.isEmpty() || playlist.isCurrentFileTheLast() {
NSApplication.sharedApplication().stop(self)
} else {
// play next in playlist
let nextFile = playlist.getNextFileForPlaying()
openMediaFile(nextFile)
}
case MPV_EVENT_PROPERTY_CHANGE.rawValue:
let data = UnsafeMutablePointer<mpv_event_property>(event.data).memory
let property_name = String.fromCString(data.name)!
switch property_name {
case "pause":
let flag = UnsafeMutablePointer<Int>(data.data).memory
if flag == 0 { // playing
state = .Playing
displayTextOSD("Play")
} else { // paused
displayTextOSD("Pause")
}
default:
break
}
default:
let eventName = String.fromCString(mpv_event_name(event.event_id))!
logger.debug("event name: \(eventName), error: \(event.error), data: \(event.data), reply userdata: \(event.reply_userdata)")
}
}
func getVideoSize() -> NSSize? {
var videoParams: mpv_node?
mpv_get_property(context!, "video-params", MPV_FORMAT_NODE, &videoParams)
if (videoParams == nil) {
return nil
}
let dict = get_mpv_node_list_as_dict(videoParams!) as! Dictionary<String, AnyObject>
let w: Int = dict["w"] as! Int
let h: Int = dict["h"] as! Int
logger.debug("original resolution: \(w)x\(h)")
return NSSize(width: w, height: h)
}
func getVideoTitle() -> String? {
let title = mpv_get_property_string(context!, "media-title")
if title == nil {
return nil
} else {
return String.fromCString(title)
}
}
func openMediaFiles(urls: [NSURL]) {
playlist.replacePlayList(urls)
openMediaFile(urls.first!)
}
func openMediaFile(url: NSURL) {
dispatch_async(mpvQueue!, {
self.logger.debug("attempt to open \(url.debugDescription)")
var cmd = [
("loadfile" as NSString).UTF8String,
(url.path! as NSString).UTF8String,
nil
]
mpv_command(self.context!, &cmd)
})
}
func togglePause() {
var pause = 1
if state == .Playing {
pause = 1
} else if state == .Paused {
pause = 0
}
mpv_set_property_async(context!, 0, "pause", MPV_FORMAT_FLAG, &pause);
}
func seekBySecond(seconds: Int) {
let values: [AnyObject] = [
"osd-msg",
"seek",
seconds
]
var mpv_formats: [mpv_format] = [
MPV_FORMAT_STRING,
MPV_FORMAT_STRING,
MPV_FORMAT_INT64
]
mpv_cmd_node_async(context!, values, &mpv_formats)
}
func displayTextOSD(text: String) {
var cmd = [
("show-text" as NSString).UTF8String,
(text as NSString).UTF8String,
nil
]
mpv_command(context!, &cmd)
}
} | gpl-2.0 | 15361750bc6416316fa874b9942a33cd | 30.632353 | 168 | 0.656515 | 3.751853 | false | false | false | false |
mirego/taylor-ios | Taylor/UI/UIDevice.swift | 1 | 2010 | // Copyright (c) 2016, Mirego
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// - Neither the name of the Mirego nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import Foundation
public extension UIDevice
{
// Returns true if the current device is an iPad (or an iPhone for isIPhone())
static func isIPad() -> Bool
{
return UIDevice.current.userInterfaceIdiom == .pad
}
static func isIPadPro() -> Bool
{
return isIPad() && UIScreen.main.bounds.size.height == 1024
}
static func isIPhone() -> Bool
{
return UIDevice.current.userInterfaceIdiom == .phone
}
}
| bsd-3-clause | 44ae30a51f3d48d4d449551ecc375ad1 | 41.765957 | 82 | 0.739801 | 4.785714 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/Login/LoginViewModel.swift | 1 | 20049 | //
// LoginViewModel.swift
// Habitica
//
// Created by Phillip Thelen on 25/12/2016.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import ReactiveCocoa
import ReactiveSwift
import AppAuth
import Keys
import FBSDKLoginKit
import AuthenticationServices
enum LoginViewAuthType {
case none
case login
case register
}
private struct AuthValues {
var authType: LoginViewAuthType = LoginViewAuthType.none
var email: String?
var username: String?
var password: String?
var passwordRepeat: String?
}
protocol LoginViewModelInputs {
func authTypeChanged()
func setAuthType(authType: LoginViewAuthType)
func emailChanged(email: String?)
func usernameChanged(username: String?)
func passwordChanged(password: String?)
func passwordRepeatChanged(passwordRepeat: String?)
func onePassword(isAvailable: Bool)
func onePasswordTapped()
func loginButtonPressed()
func googleLoginButtonPressed()
func facebookLoginButtonPressed()
func appleLoginButtonPressed()
func onSuccessfulLogin()
func setViewController(viewController: LoginTableViewController)
}
protocol LoginViewModelOutputs {
var authTypeButtonTitle: Signal<String, Never> { get }
var usernameFieldTitle: Signal<String, Never> { get }
var loginButtonTitle: Signal<String, Never> { get }
var socialLoginButtonTitle: Signal<(String) -> String, Never> { get }
var isFormValid: Signal<Bool, Never> { get }
var emailFieldVisibility: Signal<Bool, Never> { get }
var passwordRepeatFieldVisibility: Signal<Bool, Never> { get }
var passwordFieldReturnButtonIsDone: Signal<Bool, Never> { get }
var passwordRepeatFieldReturnButtonIsDone: Signal<Bool, Never> { get }
var onePasswordButtonHidden: Signal<Bool, Never> { get }
var onePasswordFindLogin: Signal<(), Never> { get }
var emailText: Signal<String, Never> { get }
var usernameText: Signal<String, Never> { get }
var passwordText: Signal<String, Never> { get }
var passwordRepeatText: Signal<String, Never> { get }
var showError: Signal<String, Never> { get }
var showNextViewController: Signal<String, Never> { get }
var formVisibility: Signal<Bool, Never> { get }
var beginButtonsVisibility: Signal<Bool, Never> { get }
var backButtonVisibility: Signal<Bool, Never> { get }
var backgroundScrolledToTop: Signal<Bool, Never> { get }
var loadingIndicatorVisibility: Signal<Bool, Never> { get }
var currentAuthType: LoginViewAuthType { get }
var arePasswordsSame: Signal<Bool, Never> { get }
}
protocol LoginViewModelType {
var inputs: LoginViewModelInputs { get }
var outputs: LoginViewModelOutputs { get }
}
class LoginViewModel: LoginViewModelType, LoginViewModelInputs, LoginViewModelOutputs {
private let userRepository = UserRepository()
//swiftlint:disable function_body_length
//swiftlint:disable cyclomatic_complexity
init() {
let authValues = Signal.combineLatest(
self.authTypeProperty.signal,
Signal.merge(emailChangedProperty.signal, prefillEmailProperty.signal),
Signal.merge(usernameChangedProperty.signal, prefillUsernameProperty.signal),
Signal.merge(passwordChangedProperty.signal, prefillPasswordProperty.signal),
Signal.merge(passwordRepeatChangedProperty.signal, prefillPasswordRepeatProperty.signal)
)
self.authValuesProperty = Property<AuthValues?>(initial: AuthValues(), then: authValues.map {
return AuthValues(authType: $0.0, email: $0.1, username: $0.2, password: $0.3, passwordRepeat: $0.4)
})
self.authTypeButtonTitle = self.authTypeProperty.signal.map { value -> String? in
switch value {
case .login:
return L10n.Login.register
case .register:
return L10n.Login.login
case .none:
return nil
}
}.skipNil()
self.loginButtonTitle = authTypeProperty.signal.map { value -> String? in
switch value {
case .login:
return L10n.Login.login
case .register:
return L10n.Login.register
case .none:
return nil
}
}.skipNil()
self.socialLoginButtonTitle = authTypeProperty.signal.map { value -> (String) -> String in
switch value {
case .login:
return L10n.Login.socialLogin
case .register:
return L10n.Login.socialRegister
case .none:
return { _ in return "" }
}
}
self.usernameFieldTitle = authTypeProperty.signal.map { value -> String? in
switch value {
case .login:
return L10n.Login.emailUsername
case .register:
return L10n.username
case .none:
return nil
}
}.skipNil()
let isRegistering = authTypeProperty.signal.map { value -> Bool? in
switch value {
case .login:
return false
case .register:
return true
case .none:
return nil
}
}.skipNil()
emailFieldVisibility = isRegistering
passwordRepeatFieldVisibility = isRegistering
passwordFieldReturnButtonIsDone = isRegistering.map({ value -> Bool in
return !value
})
passwordRepeatFieldReturnButtonIsDone = isRegistering
arePasswordsSame = Signal.combineLatest(passwordChangedProperty.signal, passwordRepeatChangedProperty.signal).map({ (password, passwordRepeat) -> Bool in
return password == passwordRepeat
})
isFormValid = authValues.map(isValid)
emailChangedProperty.value = ""
usernameChangedProperty.value = ""
passwordChangedProperty.value = ""
passwordRepeatChangedProperty.value = ""
usernameText = self.prefillUsernameProperty.signal
emailText = self.prefillEmailProperty.signal
passwordText = self.prefillPasswordProperty.signal
passwordRepeatText = self.prefillPasswordRepeatProperty.signal
onePasswordButtonHidden = onePasswordAvailable.signal
.combineLatest(with: authTypeProperty.signal)
.map { (isAvailable, authType) in
return !isAvailable || authType == .none
}
onePasswordFindLogin = onePasswordTappedProperty.signal
let (showNextViewControllerSignal, showNextViewControllerObserver) = Signal<(), Never>.pipe()
self.showNextViewControllerObserver = showNextViewControllerObserver
showNextViewController = Signal.merge(
showNextViewControllerSignal,
self.onSuccessfulLoginProperty.signal
).combineLatest(with: authTypeProperty.signal)
.map({ (_, authType) -> String in
if authType == .login {
return "MainSegue"
} else {
return "SetupSegue"
}
})
(showError, showErrorObserver) = Signal.pipe()
(loadingIndicatorVisibility, loadingIndicatorVisibilityObserver) = Signal<Bool, Never>.pipe()
formVisibility = authTypeProperty.signal.map({ (authType) -> Bool in
return authType != .none
})
beginButtonsVisibility = authTypeProperty.signal.map({ (authType) -> Bool in
return authType == .none
})
backButtonVisibility = authTypeProperty.signal.map({ (authType) -> Bool in
return authType != .none
})
backgroundScrolledToTop = authTypeProperty.signal.map({ (authType) -> Bool in
return authType != .none
})
}
func setDefaultValues() {
}
private let authTypeProperty = MutableProperty<LoginViewAuthType>(LoginViewAuthType.none)
internal func authTypeChanged() {
if authTypeProperty.value == LoginViewAuthType.login {
authTypeProperty.value = LoginViewAuthType.register
} else {
authTypeProperty.value = LoginViewAuthType.login
}
}
func setAuthType(authType: LoginViewAuthType) {
self.authTypeProperty.value = authType
}
private let emailChangedProperty = MutableProperty<String>("")
func emailChanged(email: String?) {
if email != nil {
self.emailChangedProperty.value = email ?? ""
}
}
private let usernameChangedProperty = MutableProperty<String>("")
func usernameChanged(username: String?) {
if username != nil {
self.usernameChangedProperty.value = username ?? ""
}
}
private let passwordChangedProperty = MutableProperty<String>("")
func passwordChanged(password: String?) {
if password != nil {
self.passwordChangedProperty.value = password ?? ""
}
}
private let passwordRepeatChangedProperty = MutableProperty<String>("")
func passwordRepeatChanged(passwordRepeat: String?) {
if passwordRepeat != nil {
self.passwordRepeatChangedProperty.value = passwordRepeat ?? ""
}
}
private let onePasswordAvailable = MutableProperty<Bool>(false)
func onePassword(isAvailable: Bool) {
self.onePasswordAvailable.value = isAvailable
}
private let onePasswordTappedProperty = MutableProperty(())
func onePasswordTapped() {
self.onePasswordTappedProperty.value = ()
}
private let prefillUsernameProperty = MutableProperty<String>("")
private let prefillEmailProperty = MutableProperty<String>("")
private let prefillPasswordProperty = MutableProperty<String>("")
private let prefillPasswordRepeatProperty = MutableProperty<String>("")
public func onePasswordFoundLogin(username: String, password: String) {
self.prefillUsernameProperty.value = username
self.prefillPasswordProperty.value = password
self.prefillPasswordRepeatProperty.value = password
}
private let authValuesProperty: Property<AuthValues?>
func loginButtonPressed() {
guard let authValues = self.authValuesProperty.value else {
return
}
if isValid(authType: authValues.authType,
email: authValues.email,
username: authValues.username,
password: authValues.password,
passwordRepeat: authValues.passwordRepeat) {
self.loadingIndicatorVisibilityObserver.send(value: true)
if authValues.authType == .login {
userRepository.login(username: authValues.username ?? "", password: authValues.password ?? "")
.on(completed: {
self.loadingIndicatorVisibilityObserver.send(value: false)
})
.observeValues { loginResult in
if loginResult != nil {
self.onSuccessfulLogin()
}
}
} else {
userRepository.register(username: authValues.username ?? "",
password: authValues.password ?? "",
confirmPassword: authValues.passwordRepeat ?? "",
email: authValues.email ?? "")
.on(completed: {
self.loadingIndicatorVisibilityObserver.send(value: false)
})
.observeValues { loginResult in
if loginResult != nil {
self.onSuccessfulLogin()
}
}
}
} else {
if authValues.authType == .register && authValues.password != authValues.passwordRepeat {
showErrorObserver.send(value: L10n.Login.passwordConfirmError)
}
}
}
private let googleLoginButtonPressedProperty = MutableProperty(())
func googleLoginButtonPressed() {
guard let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth") else {
return
}
guard let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token") else {
return
}
let keys = HabiticaKeys()
guard let redirectUrl = URL(string: keys.googleRedirectUrl) else {
return
}
let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint, tokenEndpoint: tokenEndpoint)
let request = OIDAuthorizationRequest.init(configuration: configuration,
clientId: keys.googleClient,
scopes: [OIDScopeOpenID, OIDScopeProfile],
redirectURL: redirectUrl,
responseType: OIDResponseTypeCode,
additionalParameters: nil)
// performs authentication request
if let appDelegate = UIApplication.shared.delegate as? HRPGAppDelegate {
guard let viewController = self.viewController else {
return
}
appDelegate.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: viewController, callback: {[weak self] (authState, _) in
if authState != nil {
self?.userRepository.login(userID: "", network: "google", accessToken: authState?.lastTokenResponse?.accessToken ?? "").observeResult { (result) in
switch result {
case .success:
self?.onSuccessfulLogin()
case .failure:
self?.showErrorObserver.send(value: L10n.Login.authenticationError)
}
}
}
})
}
}
private let appleLoginButtonPressedProperty = MutableProperty(())
func appleLoginButtonPressed() {
guard let viewController = self.viewController else {
return
}
if #available(iOS 13.0, *) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = viewController
authorizationController.presentationContextProvider = viewController
authorizationController.performRequests()
}
}
func performExistingAccountSetupFlows() {
// Prepare requests for both Apple ID and password providers.
if #available(iOS 13.0, *) {
guard let viewController = self.viewController else {
return
}
let requests = [ASAuthorizationAppleIDProvider().createRequest(),
ASAuthorizationPasswordProvider().createRequest()]
// Create an authorization controller with the given requests.
let authorizationController = ASAuthorizationController(authorizationRequests: requests)
authorizationController.delegate = viewController
authorizationController.presentationContextProvider = viewController
authorizationController.performRequests()
}
}
func performAppleLogin(identityToken: String, name: String) {
userRepository.loginApple(identityToken: identityToken, name: name).observeResult {[weak self] (result) in
switch result {
case .success:
self?.onSuccessfulLogin()
case .failure:
self?.showErrorObserver.send(value: L10n.Login.authenticationError)
}
}
}
private let onSuccessfulLoginProperty = MutableProperty(())
func onSuccessfulLogin() {
userRepository.retrieveUser().observeCompleted {[weak self] in
self?.onSuccessfulLoginProperty.value = ()
}
}
private let facebookLoginButtonPressedProperty = MutableProperty(())
func facebookLoginButtonPressed() {
let fbManager = LoginManager()
fbManager.logIn(permissions: ["public_profile", "email"], from: viewController) { [weak self] (result, error) in
if error != nil || result?.isCancelled == true {
// If there is an error or the user cancelled login
} else if let userId = result?.token?.userID, let token = result?.token?.tokenString {
self?.userRepository.login(userID: userId, network: "facebook", accessToken: token).observeResult { (result) in
switch result {
case .success:
self?.onSuccessfulLogin()
case .failure:
self?.showErrorObserver.send(value: L10n.Login.authenticationError)
}
}
}
}
}
private weak var viewController: LoginTableViewController?
func setViewController(viewController: LoginTableViewController) {
self.viewController = viewController
}
internal var authTypeButtonTitle: Signal<String, Never>
internal var loginButtonTitle: Signal<String, Never>
internal var socialLoginButtonTitle: Signal<(String) -> String, Never>
internal var usernameFieldTitle: Signal<String, Never>
internal var isFormValid: Signal<Bool, Never>
internal var emailFieldVisibility: Signal<Bool, Never>
internal var passwordRepeatFieldVisibility: Signal<Bool, Never>
internal var passwordFieldReturnButtonIsDone: Signal<Bool, Never>
internal var passwordRepeatFieldReturnButtonIsDone: Signal<Bool, Never>
internal var onePasswordButtonHidden: Signal<Bool, Never>
internal var showError: Signal<String, Never>
internal var showNextViewController: Signal<String, Never>
internal var loadingIndicatorVisibility: Signal<Bool, Never>
internal var onePasswordFindLogin: Signal<(), Never>
internal var arePasswordsSame: Signal<Bool, Never>
internal var formVisibility: Signal<Bool, Never>
internal var beginButtonsVisibility: Signal<Bool, Never>
internal var backButtonVisibility: Signal<Bool, Never>
var backgroundScrolledToTop: Signal<Bool, Never>
internal var emailText: Signal<String, Never>
internal var usernameText: Signal<String, Never>
internal var passwordText: Signal<String, Never>
internal var passwordRepeatText: Signal<String, Never>
private var showNextViewControllerObserver: Signal<(), Never>.Observer
private var showErrorObserver: Signal<String, Never>.Observer
private var loadingIndicatorVisibilityObserver: Signal<Bool, Never>.Observer
internal var inputs: LoginViewModelInputs { return self }
internal var outputs: LoginViewModelOutputs { return self }
var currentAuthType: LoginViewAuthType {
return authTypeProperty.value
}
}
func isValid(authType: LoginViewAuthType, email: String?, username: String?, password: String?, passwordRepeat: String?) -> Bool {
if username?.isEmpty != false || password?.isEmpty != false {
return false
}
if authType == .register {
if !isValidEmail(email: email) {
return false
}
if password?.isEmpty != true && password != passwordRepeat {
return false
}
}
return true
}
func isValidEmail(email: String?) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: email)
}
| gpl-3.0 | 6d31ad42bb42c8c6f35f1d11898d7361 | 38.003891 | 167 | 0.628641 | 5.596873 | false | false | false | false |
CrazyZhangSanFeng/BanTang | BanTang/BanTang/Classes/Home/Model/BTCategoryElement.swift | 1 | 332 | //
// BTCategoryElement.swift
// BanTang
//
// Created by 张灿 on 16/6/6.
// Copyright © 2016年 张灿. All rights reserved.
//
import UIKit
class BTCategoryElement: NSObject {
var index: NSInteger = 0
var title: String = ""
var extend: String = ""
var type: String = ""
var photo: String = ""
}
| apache-2.0 | 00125f23760e07f839075b161ed965a2 | 15.894737 | 46 | 0.604361 | 3.34375 | false | false | false | false |
andresinaka/SwiftCop | SwiftCopExample/ViewController.swift | 1 | 1766 | //
// ViewController.swift
// SwiftCop
//
// Created by Andres on 10/16/15.
// Copyright © 2015 Andres Canal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var validationLabel: UILabel!
@IBOutlet weak var fullNameMessage: UILabel!
@IBOutlet weak var emailMessage: UILabel!
@IBOutlet weak var passwordMessage: UILabel!
@IBOutlet weak var fullName: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var password: UITextField!
let swiftCop = SwiftCop()
override func viewDidLoad() {
super.viewDidLoad()
swiftCop.addSuspect(Suspect(view: self.fullName, sentence: "More Than Two Words Needed"){
return $0.components(separatedBy: " ").filter{$0 != ""}.count >= 2
})
swiftCop.addSuspect(Suspect(view:self.emailTextField, sentence: "Invalid email", trial: Trial.email))
swiftCop.addSuspect(Suspect(view:self.password, sentence: "Minimum 4 Characters", trial: Trial.length(.minimum, 4)))
}
@IBAction func validateFullName(_ sender: UITextField) {
self.fullNameMessage.text = swiftCop.isGuilty(sender)?.verdict()
}
@IBAction func validateEmail(_ sender: UITextField) {
self.emailMessage.text = swiftCop.isGuilty(sender)?.verdict()
}
@IBAction func validatePassword(_ sender: UITextField) {
self.passwordMessage.text = swiftCop.isGuilty(sender)?.verdict()
}
@IBAction func allValid(_ sender: UITextField) {
let nonGultiesMessage = "Everything fine!"
let allGuiltiesMessage = swiftCop.allGuilties().map{ return $0.sentence}.joined(separator: "\n")
self.validationLabel.text = allGuiltiesMessage.count > 0 ? allGuiltiesMessage : nonGultiesMessage
}
@IBAction func hideKeyboard(_ sender: AnyObject) {
self.view.endEditing(true)
}
}
| mit | c7b91d99a6d53bcac53b81aa2cea0caf | 29.964912 | 118 | 0.739943 | 3.631687 | false | false | false | false |
troystribling/BlueCap | Examples/BlueCap/BlueCap/Profiles/ServiceProfilesViewController.swift | 1 | 1822 | //
// ServiceProfilesViewController.swift
// BlueCapUI
//
// Created by Troy Stribling on 6/5/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class ServiceProfilesViewController : ServiceProfilesTableViewController {
struct MainStoryboard {
static let serviceProfileCell = "ServiceProfileCell"
static let serviceCharacteristicProfilesSegue = "ServiceCharacteristicProfiles"
}
override var serviceProfileCell : String {
return MainStoryboard.serviceProfileCell
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.styleNavigationBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Service Profiles"
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue:UIStoryboardSegue, sender:Any!) {
if segue.identifier == MainStoryboard.serviceCharacteristicProfilesSegue {
if let selectedIndex = self.tableView.indexPath(for: sender as! UITableViewCell) {
let tag = Array(self.serviceProfiles.keys)
if let profiles = self.serviceProfiles[tag[selectedIndex.section]] {
let viewController = segue.destination as! ServiceCharacteristicProfilesViewController
viewController.serviceProfile = profiles[selectedIndex.row]
}
}
}
}
}
| mit | aa751e88c9a8eb3ef9ff1490545a33f3 | 30.964912 | 106 | 0.65697 | 5.374631 | false | false | false | false |
linhaosunny/yeehaiyake | 椰海雅客微博/Pods/SnapKit/Source/ConstraintPriority.swift | 115 | 2118 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public struct ConstraintPriority : ExpressibleByFloatLiteral, Equatable {
public typealias FloatLiteralType = Float
public let value: Float
public init(floatLiteral value: Float) {
self.value = value
}
public init(_ value: Float) {
self.value = value
}
public static var required: ConstraintPriority {
return 1000.0
}
public static var high: ConstraintPriority {
return 750.0
}
public static var medium: ConstraintPriority {
#if os(OSX)
return 501.0
#else
return 500.0
#endif
}
public static var low: ConstraintPriority {
return 250.0
}
public static func ==(lhs: ConstraintPriority, rhs: ConstraintPriority) -> Bool {
return lhs.value == rhs.value
}
}
| mit | 8353cf5e2818c8ad3849170e68f4631b | 30.147059 | 85 | 0.677054 | 4.59436 | false | false | false | false |
balazs630/Bad-Jokes | BadJokes/AppDelegate.swift | 1 | 2315 | //
// AppDelegate.swift
// BadJokes
//
// Created by Horváth Balázs on 2017. 07. 18..
// Copyright © 2017. Horváth Balázs. All rights reserved.
//
// swiftlint:disable line_length
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
initUserDefaults()
requestNotificationCenterPermission()
return true
}
}
// MARK: - UserDefaults setup
extension AppDelegate {
private func initUserDefaults() {
guard UserDefaults.standard.object(forKey: UserDefaults.Key.isAppAlreadyLaunchedOnce) == nil else { return }
DefaultSettings.firstTimeLaunchDefaults.forEach {
UserDefaults.standard.set($0.value, forKey: $0.key)
}
}
}
// MARK: UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
private func requestNotificationCenterPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { _, _ in }
UNUserNotificationCenter.current().delegate = self
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let jokeText = response.notification.request.content.body
deeplinkToJokeReader(with: jokeText)
completionHandler()
}
}
// MARK: Deeplinking
extension AppDelegate {
private func deeplinkToJokeReader(with jokeText: String) {
guard let jokeReaderViewController = JokeReaderViewController.instantiate(with: jokeText) else {
return
}
UIApplication.topMostViewController()?.present(jokeReaderViewController, animated: true)
}
}
| apache-2.0 | 322a228ec5f5781354183b831ffab311 | 32.970588 | 129 | 0.684416 | 5.80402 | false | false | false | false |
cohena100/Shimi | Carthage/Checkouts/NSObject-Rx/NSObject+Rx.swift | 1 | 1236 | import Foundation
import RxSwift
import ObjectiveC
public extension NSObject {
fileprivate struct AssociatedKeys {
static var DisposeBag = "rx_disposeBag"
}
fileprivate func doLocked(_ closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
var rx_disposeBag: DisposeBag {
get {
var disposeBag: DisposeBag!
doLocked {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
if let lookup = lookup {
disposeBag = lookup
} else {
let newDisposeBag = DisposeBag()
self.rx_disposeBag = newDisposeBag
disposeBag = newDisposeBag
}
}
return disposeBag
}
set {
doLocked {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
public extension Reactive where Base: NSObject {
var disposeBag: DisposeBag {
get { return base.rx_disposeBag }
set { base.rx_disposeBag = newValue }
}
}
| mit | 1fddc71b6b3072c615e2910f8075a4cf | 27.090909 | 120 | 0.555016 | 5.444934 | false | false | false | false |
sammy0025/SST-Announcer | Announcer Extension/PostInterfaceController.swift | 1 | 1405 | //
// PostInterfaceController.swift
// SST Announcer
//
// Created by Pan Ziyue on 17/12/16.
// Copyright © 2016 FourierIndustries. All rights reserved.
//
import WatchKit
import Foundation
class PostInterfaceController: WKInterfaceController {
@IBOutlet var titleLabel: WKInterfaceLabel!
@IBOutlet var authorLabel: WKInterfaceLabel!
@IBOutlet var dateLabel: WKInterfaceLabel!
@IBOutlet var timeLabel: WKInterfaceLabel!
@IBOutlet var contentLabel: WKInterfaceLabel!
let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "h:mm a"
return df
}()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
if let feed = context as? FeedItem {
titleLabel.setText(feed.title)
authorLabel.setText(feed.author)
dateLabel.setText(feed.date.decodeToTimeAgo())
timeLabel.setText(dateFormatter.string(from: feed.date))
contentLabel.setAttributedText(feed.rawHtmlContent.attributedStringFromHTML)
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| gpl-2.0 | 176a8bf230a4b4c1e7b2f8443e151c45 | 27.08 | 86 | 0.726496 | 4.558442 | false | false | false | false |
nathawes/swift | stdlib/public/core/DiscontiguousSlice.swift | 6 | 6786 | //===--- DiscontiguousSlice.swift -----------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection wrapper that provides access to the elements of a collection,
/// indexed by a set of indices.
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
@frozen
public struct DiscontiguousSlice<Base: Collection> {
/// The collection that the indexed collection wraps.
public var base: Base
/// The set of subranges that are available through this discontiguous slice.
public var subranges: RangeSet<Base.Index>
}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice {
/// A position in an `DiscontiguousSlice`.
@frozen
public struct Index: Comparable {
/// The index of the range that contains `base`.
internal var _rangeOffset: Int
/// The position of this index in the base collection.
public var base: Base.Index
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.base < rhs.base
}
}
}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice.Index: Hashable where Base.Index: Hashable {}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice: Collection {
public typealias SubSequence = Self
public var startIndex: Index {
subranges.isEmpty
? endIndex
: Index(_rangeOffset: 0, base: subranges._ranges[0].lowerBound)
}
public var endIndex: Index {
Index(_rangeOffset: subranges._ranges.endIndex, base: base.endIndex)
}
public func index(after i: Index) -> Index {
let nextIndex = base.index(after: i.base)
if subranges._ranges[i._rangeOffset].contains(nextIndex) {
return Index(_rangeOffset: i._rangeOffset, base: nextIndex)
}
let nextOffset = i._rangeOffset + 1
if nextOffset < subranges._ranges.endIndex {
return Index(
_rangeOffset: nextOffset,
base: subranges._ranges[nextOffset].lowerBound)
} else {
return endIndex
}
}
public subscript(i: Index) -> Base.Element {
base[i.base]
}
public subscript(bounds: Range<Index>) -> DiscontiguousSlice<Base> {
let baseBounds = bounds.lowerBound.base ..< bounds.upperBound.base
let subset = subranges.intersection(RangeSet(baseBounds))
return DiscontiguousSlice<Base>(base: base, subranges: subset)
}
}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice {
public var count: Int {
var c = 0
for range in subranges._ranges {
c += base.distance(from: range.lowerBound, to: range.upperBound)
}
return c
}
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
var result: ContiguousArray<Element> = []
for range in subranges._ranges {
result.append(contentsOf: base[range])
}
return result
}
}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice: BidirectionalCollection
where Base: BidirectionalCollection
{
public func index(before i: Index) -> Index {
_precondition(i != startIndex, "Can't move index before startIndex")
if i == endIndex || i.base == subranges._ranges[i._rangeOffset].lowerBound {
let offset = i._rangeOffset - 1
return Index(
_rangeOffset: offset,
base: base.index(before: subranges._ranges[offset].upperBound))
}
return Index(
_rangeOffset: i._rangeOffset,
base: base.index(before: i.base))
}
}
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension DiscontiguousSlice: MutableCollection where Base: MutableCollection {
public subscript(i: Index) -> Base.Element {
get {
base[i.base]
}
set {
base[i.base] = newValue
}
}
}
// MARK: Subscripts
extension Collection {
/// Accesses a view of this collection with the elements at the given
/// indices.
///
/// - Parameter subranges: The indices of the elements to retrieve from this
/// collection.
/// - Returns: A collection of the elements at the positions in `subranges`.
///
/// - Complexity: O(1)
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
public subscript(subranges: RangeSet<Index>) -> DiscontiguousSlice<Self> {
DiscontiguousSlice(base: self, subranges: subranges)
}
}
extension MutableCollection {
/// Accesses a mutable view of this collection with the elements at the
/// given indices.
///
/// - Parameter subranges: The ranges of the elements to retrieve from this
/// collection.
/// - Returns: A collection of the elements at the positions in `subranges`.
///
/// - Complexity: O(1) to access the elements, O(*m*) to mutate the
/// elements at the positions in `subranges`, where *m* is the number of
/// elements indicated by `subranges`.
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
public subscript(subranges: RangeSet<Index>) -> DiscontiguousSlice<Self> {
get {
DiscontiguousSlice(base: self, subranges: subranges)
}
set {
for i in newValue.indices {
self[i.base] = newValue[i]
}
}
}
}
extension Collection {
/// Returns a collection of the elements in this collection that are not
/// represented by the given range set.
///
/// For example, this code sample finds the indices of all the vowel
/// characters in the string, and then retrieves a collection that omits
/// those characters.
///
/// let str = "The rain in Spain stays mainly in the plain."
/// let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
/// let vowelIndices = str.subranges(where: { vowels.contains($0) })
///
/// let disemvoweled = str.removingSubranges(vowelIndices)
/// print(String(disemvoweled))
/// // Prints "Th rn n Spn stys mnly n th pln."
///
/// - Parameter subranges: A range set representing the indices of the
/// elements to remove.
/// - Returns: A collection of the elements that are not in `subranges`.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
public func removingSubranges(
_ subranges: RangeSet<Index>
) -> DiscontiguousSlice<Self> {
let inversion = subranges._inverted(within: self)
return self[inversion]
}
}
| apache-2.0 | 443ad20eb2a1078668eec7c47e0dfec2 | 31.941748 | 80 | 0.656793 | 4.051343 | false | false | false | false |
xedin/swift | stdlib/public/core/Set.swift | 8 | 56067 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An unordered collection of unique elements.
///
/// You use a set instead of an array when you need to test efficiently for
/// membership and you aren't concerned with the order of the elements in the
/// collection, or when you need to ensure that each element appears only once
/// in a collection.
///
/// You can create a set with any element type that conforms to the `Hashable`
/// protocol. By default, most types in the standard library are hashable,
/// including strings, numeric and Boolean types, enumeration cases without
/// associated values, and even sets themselves.
///
/// Swift makes it as easy to create a new set as to create a new array. Simply
/// assign an array literal to a variable or constant with the `Set` type
/// specified.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.contains("sugar") {
/// print("No thanks, too sweet.")
/// }
/// // Prints "No thanks, too sweet."
///
/// Set Operations
/// ==============
///
/// Sets provide a suite of mathematical set operations. For example, you can
/// efficiently test a set for membership of an element or check its
/// intersection with another set:
///
/// - Use the `contains(_:)` method to test whether a set contains a specific
/// element.
/// - Use the "equal to" operator (`==`) to test whether two sets contain the
/// same elements.
/// - Use the `isSubset(of:)` method to test whether a set contains all the
/// elements of another set or sequence.
/// - Use the `isSuperset(of:)` method to test whether all elements of a set
/// are contained in another set or sequence.
/// - Use the `isStrictSubset(of:)` and `isStrictSuperset(of:)` methods to test
/// whether a set is a subset or superset of, but not equal to, another set.
/// - Use the `isDisjoint(with:)` method to test whether a set has any elements
/// in common with another set.
///
/// You can also combine, exclude, or subtract the elements of two sets:
///
/// - Use the `union(_:)` method to create a new set with the elements of a set
/// and another set or sequence.
/// - Use the `intersection(_:)` method to create a new set with only the
/// elements common to a set and another set or sequence.
/// - Use the `symmetricDifference(_:)` method to create a new set with the
/// elements that are in either a set or another set or sequence, but not in
/// both.
/// - Use the `subtracting(_:)` method to create a new set with the elements of
/// a set that are not also in another set or sequence.
///
/// You can modify a set in place by using these methods' mutating
/// counterparts: `formUnion(_:)`, `formIntersection(_:)`,
/// `formSymmetricDifference(_:)`, and `subtract(_:)`.
///
/// Set operations are not limited to use with other sets. Instead, you can
/// perform set operations with another set, an array, or any other sequence
/// type.
///
/// var primes: Set = [2, 3, 5, 7]
///
/// // Tests whether primes is a subset of a Range<Int>
/// print(primes.isSubset(of: 0..<10))
/// // Prints "true"
///
/// // Performs an intersection with an Array<Int>
/// let favoriteNumbers = [5, 7, 15, 21]
/// print(primes.intersection(favoriteNumbers))
/// // Prints "[5, 7]"
///
/// Sequence and Collection Operations
/// ==================================
///
/// In addition to the `Set` type's set operations, you can use any nonmutating
/// sequence or collection methods with a set.
///
/// if primes.isEmpty {
/// print("No primes!")
/// } else {
/// print("We have \(primes.count) primes.")
/// }
/// // Prints "We have 4 primes."
///
/// let primesSum = primes.reduce(0, +)
/// // 'primesSum' == 17
///
/// let primeStrings = primes.sorted().map(String.init)
/// // 'primeStrings' == ["2", "3", "5", "7"]
///
/// You can iterate through a set's unordered elements with a `for`-`in` loop.
///
/// for number in primes {
/// print(number)
/// }
/// // Prints "5"
/// // Prints "7"
/// // Prints "2"
/// // Prints "3"
///
/// Many sequence and collection operations return an array or a type-erasing
/// collection wrapper instead of a set. To restore efficient set operations,
/// create a new set from the result.
///
/// let morePrimes = primes.union([11, 13, 17, 19])
///
/// let laterPrimes = morePrimes.filter { $0 > 10 }
/// // 'laterPrimes' is of type Array<Int>
///
/// let laterPrimesSet = Set(morePrimes.filter { $0 > 10 })
/// // 'laterPrimesSet' is of type Set<Int>
///
/// Bridging Between Set and NSSet
/// ==============================
///
/// You can bridge between `Set` and `NSSet` using the `as` operator. For
/// bridging to be possible, the `Element` type of a set must be a class, an
/// `@objc` protocol (a protocol imported from Objective-C or marked with the
/// `@objc` attribute), or a type that bridges to a Foundation type.
///
/// Bridging from `Set` to `NSSet` always takes O(1) time and space. When the
/// set's `Element` type is neither a class nor an `@objc` protocol, any
/// required bridging of elements occurs at the first access of each element,
/// so the first operation that uses the contents of the set (for example, a
/// membership test) can take O(*n*).
///
/// Bridging from `NSSet` to `Set` first calls the `copy(with:)` method
/// (`- copyWithZone:` in Objective-C) on the set to get an immutable copy and
/// then performs additional Swift bookkeeping work that takes O(1) time. For
/// instances of `NSSet` that are already immutable, `copy(with:)` returns the
/// same set in constant time; otherwise, the copying performance is
/// unspecified. The instances of `NSSet` and `Set` share buffer using the
/// same copy-on-write optimization that is used when two instances of `Set`
/// share buffer.
@frozen
public struct Set<Element: Hashable> {
@usableFromInline
internal var _variant: _Variant
/// Creates an empty set with preallocated space for at least the specified
/// number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a set's
/// storage buffer when you know how many elements you'll insert into the set
/// after creation.
///
/// - Parameter minimumCapacity: The minimum number of elements that the
/// newly created set should be able to store without reallocating its
/// storage buffer.
public // FIXME(reserveCapacity): Should be inlinable
init(minimumCapacity: Int) {
_variant = _Variant(native: _NativeSet(capacity: minimumCapacity))
}
/// Private initializer.
@inlinable
internal init(_native: __owned _NativeSet<Element>) {
_variant = _Variant(native: _native)
}
#if _runtime(_ObjC)
@inlinable
internal init(_cocoa: __owned __CocoaSet) {
_variant = _Variant(cocoa: _cocoa)
}
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSSet` is immutable;
/// * `Element` is bridged verbatim to Objective-C (i.e.,
/// is a reference type).
@inlinable
public // SPI(Foundation)
init(_immutableCocoaSet: __owned AnyObject) {
_internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self),
"Set can be backed by NSSet _variant only when the member type can be bridged verbatim to Objective-C")
self.init(_cocoa: __CocoaSet(_immutableCocoaSet))
}
#endif
}
extension Set: ExpressibleByArrayLiteral {
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter elements: A variadic list of elements of the new set.
@inlinable
public init(arrayLiteral elements: Element...) {
if elements.isEmpty {
self.init()
return
}
let native = _NativeSet<Element>(capacity: elements.count)
for element in elements {
let (bucket, found) = native.find(element)
if found {
// FIXME: Shouldn't this trap?
continue
}
native._unsafeInsertNew(element, at: bucket)
}
self.init(_native: native)
}
}
extension Set: Sequence {
/// Returns an iterator over the members of the set.
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return _variant.makeIterator()
}
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
///
/// - Complexity: O(1)
@inlinable
public func contains(_ member: Element) -> Bool {
return _variant.contains(member)
}
@inlinable
@inline(__always)
public func _customContainsEquatableElement(_ member: Element) -> Bool? {
return contains(member)
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
// (RangeReplaceableCollection.filter returns Self, but Set isn't an RRC)
extension Set {
/// Returns a new set containing the elements of the set that satisfy the
/// given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
///
/// shortNames.isSubset(of: cast)
/// // true
/// shortNames.contains("Vivien")
/// // false
///
/// - Parameter isIncluded: A closure that takes an element as its argument
/// and returns a Boolean value indicating whether the element should be
/// included in the returned set.
/// - Returns: A set of the elements that `isIncluded` allows.
@inlinable
@available(swift, introduced: 4.0)
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Set {
// FIXME(performance): Eliminate rehashes by using a bitmap.
var result = Set()
for element in self {
if try isIncluded(element) {
result.insert(element)
}
}
return result
}
}
extension Set: Collection {
/// The starting position for iterating members of the set.
///
/// If the set is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
/// The "past the end" position for the set---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the set is empty, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
return _variant.endIndex
}
/// Accesses the member at the given position.
@inlinable
public subscript(position: Index) -> Element {
//FIXME(accessors): Provide a _read
get {
return _variant.element(at: position)
}
}
@inlinable
public func index(after i: Index) -> Index {
return _variant.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
_variant.formIndex(after: &i)
}
// APINAMING: complexity docs are broadly missing in this file.
/// Returns the index of the given element in the set, or `nil` if the
/// element is not a member of the set.
///
/// - Parameter member: An element to search for in the set.
/// - Returns: The index of `member` if it exists in the set; otherwise,
/// `nil`.
///
/// - Complexity: O(1)
@inlinable
public func firstIndex(of member: Element) -> Index? {
return _variant.index(for: member)
}
@inlinable
@inline(__always)
public func _customIndexOfEquatableElement(
_ member: Element
) -> Index?? {
return Optional(firstIndex(of: member))
}
@inlinable
@inline(__always)
public func _customLastIndexOfEquatableElement(
_ member: Element
) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(member)
}
/// The number of elements in the set.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
/// A Boolean value that indicates whether the set is empty.
@inlinable
public var isEmpty: Bool {
return count == 0
}
}
// FIXME: rdar://problem/23549059 (Optimize == for Set)
// Look into initially trying to compare the two sets by directly comparing the
// contents of both buffers in order. If they happen to have the exact same
// ordering we can get the `true` response without ever hashing. If the two
// buffers' contents differ at all then we have to fall back to hashing the
// rest of the elements (but we don't need to hash any prefix that did match).
extension Set: Equatable {
/// Returns a Boolean value indicating whether two sets have equal elements.
///
/// - Parameters:
/// - lhs: A set.
/// - rhs: Another set.
/// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise,
/// `false`.
@inlinable
public static func == (lhs: Set<Element>, rhs: Set<Element>) -> Bool {
#if _runtime(_ObjC)
switch (lhs._variant.isNative, rhs._variant.isNative) {
case (true, true):
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
case (false, false):
return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa)
case (true, false):
return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa)
case (false, true):
return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa)
}
#else
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
#endif
}
}
extension Set: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
// FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue
// Generate a seed from a snapshot of the hasher. This makes members' hash
// values depend on the state of the hasher, which improves hashing
// quality. (E.g., it makes it possible to resolve collisions by passing in
// a different hasher.)
var copy = hasher
let seed = copy._finalize()
var hash = 0
for member in self {
hash ^= member._rawHashValue(seed: seed)
}
hasher.combine(hash)
}
}
extension Set: _HasCustomAnyHashableRepresentation {
public __consuming func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(_box: _SetAnyHashableBox(self))
}
}
internal struct _SetAnyHashableBox<Element: Hashable>: _AnyHashableBox {
internal let _value: Set<Element>
internal let _canonical: Set<AnyHashable>
internal init(_ value: __owned Set<Element>) {
self._value = value
self._canonical = value as Set<AnyHashable>
}
internal var _base: Any {
return _value
}
internal var _canonicalBox: _AnyHashableBox {
return _SetAnyHashableBox<AnyHashable>(_canonical)
}
internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
guard let other = other as? _SetAnyHashableBox<AnyHashable> else {
return nil
}
return _canonical == other._value
}
internal var _hashValue: Int {
return _canonical.hashValue
}
internal func _hash(into hasher: inout Hasher) {
_canonical.hash(into: &hasher)
}
internal func _rawHashValue(_seed: Int) -> Int {
return _canonical._rawHashValue(seed: _seed)
}
internal func _unbox<T: Hashable>() -> T? {
return _value as? T
}
internal func _downCastConditional<T>(
into result: UnsafeMutablePointer<T>
) -> Bool {
guard let value = _value as? T else { return false }
result.initialize(to: value)
return true
}
}
extension Set: SetAlgebra {
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In the following example, a new element is
/// inserted into `classDays`, a set of days of the week. When an existing
/// element is inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
@inlinable
@discardableResult
public mutating func insert(
_ newMember: __owned Element
) -> (inserted: Bool, memberAfterInsert: Element) {
return _variant.insert(newMember)
}
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: An element equal to `newMember` if the set already contained
/// such a member; otherwise, `nil`. In some cases, the returned element
/// may be distinguishable from `newMember` by identity comparison or some
/// other means.
@inlinable
@discardableResult
public mutating func update(with newMember: __owned Element) -> Element? {
return _variant.update(with: newMember)
}
/// Removes the specified element from the set.
///
/// This example removes the element `"sugar"` from a set of ingredients.
///
/// var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// let toRemove = "sugar"
/// if let removed = ingredients.remove(toRemove) {
/// print("The recipe is now \(removed)-free.")
/// }
/// // Prints "The recipe is now sugar-free."
///
/// - Parameter member: The element to remove from the set.
/// - Returns: The value of the `member` parameter if it was a member of the
/// set; otherwise, `nil`.
@inlinable
@discardableResult
public mutating func remove(_ member: Element) -> Element? {
return _variant.remove(member)
}
/// Removes the element at the given index of the set.
///
/// - Parameter position: The index of the member to remove. `position` must
/// be a valid index of the set, and must not be equal to the set's end
/// index.
/// - Returns: The element that was removed from the set.
@inlinable
@discardableResult
public mutating func remove(at position: Index) -> Element {
return _variant.remove(at: position)
}
/// Removes all members from the set.
///
/// - Parameter keepingCapacity: If `true`, the set's buffer capacity is
/// preserved; if `false`, the underlying buffer is released. The
/// default is `false`.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
_variant.removeAll(keepingCapacity: keepCapacity)
}
/// Removes the first element of the set.
///
/// Because a set is not an ordered collection, the "first" element may not
/// be the first element that was added to the set. The set must not be
/// empty.
///
/// - Complexity: Amortized O(1) if the set does not wrap a bridged `NSSet`.
/// If the set wraps a bridged `NSSet`, the performance is unspecified.
///
/// - Returns: A member of the set.
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
_precondition(!isEmpty, "Can't removeFirst from an empty Set")
return remove(at: startIndex)
}
//
// APIs below this comment should be implemented strictly in terms of
// *public* APIs above. `_variant` should not be accessed directly.
//
// This separates concerns for testing. Tests for the following APIs need
// not to concern themselves with testing correctness of behavior of
// underlying buffer (and different variants of it), only correctness of the
// API itself.
//
/// Creates an empty set.
///
/// This is equivalent to initializing with an empty array literal. For
/// example:
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
@inlinable
public init() {
self = Set<Element>(_native: _NativeSet())
}
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, for
/// example, an array or a range.
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// This initializer can also be used to restore set methods after performing
/// sequence operations such as `filter(_:)` or `map(_:)` on a set. For
/// example, after filtering a set of prime numbers to remove any below 10,
/// you can create a new set by using this initializer.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23]
/// let laterPrimes = Set(primes.lazy.filter { $0 > 10 })
/// print(laterPrimes)
/// // Prints "[17, 19, 23, 11, 13]"
///
/// - Parameter sequence: The elements to use as members of the new set.
@inlinable
public init<Source: Sequence>(_ sequence: __owned Source)
where Source.Element == Element {
self.init(minimumCapacity: sequence.underestimatedCount)
if let s = sequence as? Set<Element> {
// If this sequence is actually a native `Set`, then we can quickly
// adopt its native buffer and let COW handle uniquing only
// if necessary.
self._variant = s._variant
} else {
for item in sequence {
insert(item)
}
}
}
/// Returns a Boolean value that indicates whether the set is a subset of the
/// given sequence.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter possibleSuperset: A sequence of elements. `possibleSuperset`
/// must be finite.
/// - Returns: `true` if the set is a subset of `possibleSuperset`;
/// otherwise, `false`.
@inlinable
public func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool
where S.Element == Element {
guard !isEmpty else { return true }
let other = Set(possibleSuperset)
return isSubset(of: other)
}
/// Returns a Boolean value that indicates whether the set is a strict subset
/// of the given sequence.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter possibleStrictSuperset: A sequence of elements.
/// `possibleStrictSuperset` must be finite.
/// - Returns: `true` is the set is strict subset of
/// `possibleStrictSuperset`; otherwise, `false`.
@inlinable
public func isStrictSubset<S: Sequence>(of possibleStrictSuperset: S) -> Bool
where S.Element == Element {
// FIXME: code duplication.
let other = Set(possibleStrictSuperset)
return isStrictSubset(of: other)
}
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given sequence.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter possibleSubset: A sequence of elements. `possibleSubset` must
/// be finite.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
@inlinable
public func isSuperset<S: Sequence>(of possibleSubset: __owned S) -> Bool
where S.Element == Element {
for member in possibleSubset {
if !contains(member) {
return false
}
}
return true
}
/// Returns a Boolean value that indicates whether the set is a strict
/// superset of the given sequence.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter possibleStrictSubset: A sequence of elements.
/// `possibleStrictSubset` must be finite.
/// - Returns: `true` if the set is a strict superset of
/// `possibleStrictSubset`; otherwise, `false`.
@inlinable
public func isStrictSuperset<S: Sequence>(of possibleStrictSubset: S) -> Bool
where S.Element == Element {
let other = Set(possibleStrictSubset)
return other.isStrictSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given sequence.
///
/// In the following example, the `employees` set is disjoint with the
/// elements of the `visitors` array because no name appears in both.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@inlinable
public func isDisjoint<S: Sequence>(with other: S) -> Bool
where S.Element == Element {
return _isDisjoint(with: other)
}
/// Returns a new set with the elements of both this set and the given
/// sequence.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` set and the `visitors` array:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. If `other` contains multiple
/// instances of equivalent elements, only the first instance is kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set with the unique elements of this set and `other`.
@inlinable
public __consuming func union<S: Sequence>(_ other: __owned S) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.formUnion(other)
return newSet
}
/// Inserts the elements of the given sequence into the set.
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept. If `other` contains multiple
/// instances of equivalent elements, only the first instance is kept.
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Diana", "Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formUnion<S: Sequence>(_ other: __owned S)
where S.Element == Element {
for item in other {
insert(item)
}
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given sequence.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Chris", "Diana", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public __consuming func subtracting<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
return self._subtracting(other)
}
@inlinable
internal __consuming func _subtracting<S: Sequence>(
_ other: S
) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.subtract(other)
return newSet
}
/// Removes the elements of the given sequence from the set.
///
/// In the following example, the elements of the `employees` set that are
/// also elements of the `neighbors` array are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Chris", "Diana", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func subtract<S: Sequence>(_ other: S)
where S.Element == Element {
_subtract(other)
}
@inlinable
internal mutating func _subtract<S: Sequence>(_ other: S)
where S.Element == Element {
// If self is empty we don't need to iterate over `other` because there's
// nothing to remove on self.
guard !isEmpty else { return }
for item in other {
remove(item)
}
}
/// Returns a new set with the elements that are common to both this set and
/// the given sequence.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public __consuming func intersection<S: Sequence>(_ other: S) -> Set<Element>
where S.Element == Element {
let otherSet = Set(other)
return intersection(otherSet)
}
/// Removes the elements of the set that aren't also in the given sequence.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formIntersection<S: Sequence>(_ other: S)
where S.Element == Element {
// Because `intersect` needs to both modify and iterate over
// the left-hand side, the index may become invalidated during
// traversal so an intermediate set must be created.
//
// FIXME(performance): perform this operation at a lower level
// to avoid invalidating the index and avoiding a copy.
let result = self.intersection(other)
// The result can only have fewer or the same number of elements.
// If no elements were removed, don't perform a reassignment
// as this may cause an unnecessary uniquing COW.
if result.count != count {
self = result
}
}
/// Returns a new set with the elements that are either in this set or in the
/// given sequence, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
/// - Returns: A new set.
@inlinable
public __consuming func symmetricDifference<S: Sequence>(
_ other: __owned S
) -> Set<Element>
where S.Element == Element {
var newSet = self
newSet.formSymmetricDifference(other)
return newSet
}
/// Replace this set with the elements contained in this set or the given
/// set, but not both.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Bethany"` and `"Eric"` are
/// removed from `employees` while the name `"Forlani"` is added.
///
/// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors = ["Bethany", "Eric", "Forlani"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A sequence of elements. `other` must be finite.
@inlinable
public mutating func formSymmetricDifference<S: Sequence>(
_ other: __owned S)
where S.Element == Element {
let otherSet = Set(other)
formSymmetricDifference(otherSet)
}
}
extension Set: CustomStringConvertible, CustomDebugStringConvertible {
/// A string that represents the contents of the set.
public var description: String {
return _makeCollectionDescription()
}
/// A string that represents the contents of the set, suitable for debugging.
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "Set")
}
}
extension Set {
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: Another set.
@inlinable
public mutating func subtract(_ other: Set<Element>) {
_subtract(other)
}
/// Returns a Boolean value that indicates whether this set is a subset of
/// the given set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
@inlinable
public func isSubset(of other: Set<Element>) -> Bool {
guard self.count <= other.count else { return false }
for member in self {
if !other.contains(member) {
return false
}
}
return true
}
/// Returns a Boolean value that indicates whether this set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
@inlinable
public func isSuperset(of other: Set<Element>) -> Bool {
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether this set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
@inlinable
public func isDisjoint(with other: Set<Element>) -> Bool {
return _isDisjoint(with: other)
}
@inlinable
internal func _isDisjoint<S: Sequence>(with other: S) -> Bool
where S.Element == Element {
guard !isEmpty else { return true }
for member in other {
if contains(member) {
return false
}
}
return true
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@inlinable
public __consuming func subtracting(_ other: Set<Element>) -> Set<Element> {
return self._subtracting(other)
}
/// Returns a Boolean value that indicates whether the set is a strict
/// superset of the given sequence.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict superset of
/// `other`; otherwise, `false`.
@inlinable
public func isStrictSuperset(of other: Set<Element>) -> Bool {
return self.isSuperset(of: other) && self != other
}
/// Returns a Boolean value that indicates whether the set is a strict subset
/// of the given sequence.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter other: Another set.
/// - Returns: `true` if the set is a strict subset of
/// `other`; otherwise, `false`.
@inlinable
public func isStrictSubset(of other: Set<Element>) -> Bool {
return other.isStrictSuperset(of: self)
}
/// Returns a new set with the elements that are common to both this set and
/// the given sequence.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: Another set.
/// - Returns: A new set.
@inlinable
public __consuming func intersection(_ other: Set<Element>) -> Set<Element> {
var newSet = Set<Element>()
for member in self {
if other.contains(member) {
newSet.insert(member)
}
}
return newSet
}
/// Removes the elements of the set that are also in the given sequence and
/// adds the members of the sequence that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and
/// `"Diana"` are removed from `employees` while the names `"Forlani"` and
/// `"Greta"` are added.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"
///
/// - Parameter other: Another set.
@inlinable
public mutating func formSymmetricDifference(_ other: __owned Set<Element>) {
for member in other {
if contains(member) {
remove(member)
} else {
insert(member)
}
}
}
}
extension Set {
/// The position of an element in a set.
@frozen
public struct Index {
// Index for native buffer is efficient. Index for bridged NSSet is
// not, because neither NSEnumerator nor fast enumeration support moving
// backwards. Even if they did, there is another issue: NSEnumerator does
// not support NSCopying, and fast enumeration does not document that it is
// safe to copy the state. So, we cannot implement Index that is a value
// type for bridged NSSet in terms of Cocoa enumeration facilities.
@frozen
@usableFromInline
internal enum _Variant {
case native(_HashTable.Index)
#if _runtime(_ObjC)
case cocoa(__CocoaSet.Index)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
@inline(__always)
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
@inline(__always)
internal init(_native index: _HashTable.Index) {
self.init(_variant: .native(index))
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
internal init(_cocoa index: __owned __CocoaSet.Index) {
self.init(_variant: .cocoa(index))
}
#endif
}
}
extension Set.Index {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
/// Allow the optimizer to consider the surrounding code unreachable if
/// Set<Element> is guaranteed to be native.
@usableFromInline
@_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
@inlinable
@inline(__always)
internal mutating func _isUniquelyReferenced() -> Bool {
defer { _fixLifetime(self) }
var handle = _asCocoa.handleBitPattern
return handle == 0 || _isUnique_native(&handle)
}
#endif
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _HashTable.Index {
switch _variant {
case .native(let nativeIndex):
return nativeIndex
#if _runtime(_ObjC)
case .cocoa:
_preconditionFailure(
"Attempting to access Set elements using an invalid index")
#endif
}
}
#if _runtime(_ObjC)
@usableFromInline
internal var _asCocoa: __CocoaSet.Index {
@_transparent
get {
switch _variant {
case .native:
_preconditionFailure(
"Attempting to access Set elements using an invalid index")
case .cocoa(let cocoaIndex):
return cocoaIndex
}
}
_modify {
guard case .cocoa(var cocoa) = _variant else {
_preconditionFailure(
"Attempting to access Set elements using an invalid index")
}
let dummy = _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0)
_variant = .native(dummy)
defer { _variant = .cocoa(cocoa) }
yield &cocoa
}
}
#endif
}
extension Set.Index: Equatable {
@inlinable
public static func == (
lhs: Set<Element>.Index,
rhs: Set<Element>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative == rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa == rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
}
extension Set.Index: Comparable {
@inlinable
public static func < (
lhs: Set<Element>.Index,
rhs: Set<Element>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative < rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa < rhsCocoa
default:
_preconditionFailure("Comparing indexes from different sets")
#endif
}
}
}
extension Set.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public // FIXME(cocoa-index): Make inlinable
func hash(into hasher: inout Hasher) {
#if _runtime(_ObjC)
guard _isNative else {
hasher.combine(1 as UInt8)
hasher.combine(_asCocoa._offset)
return
}
hasher.combine(0 as UInt8)
hasher.combine(_asNative.bucket.offset)
#else
hasher.combine(_asNative.bucket.offset)
#endif
}
}
extension Set {
/// An iterator over the members of a `Set<Element>`.
@frozen
public struct Iterator {
// Set has a separate IteratorProtocol and Index because of efficiency
// and implementability reasons.
//
// Native sets have efficient indices. Bridged NSSet instances don't.
//
// Even though fast enumeration is not suitable for implementing
// Index, which is multi-pass, it is suitable for implementing a
// IteratorProtocol, which is being consumed as iteration proceeds.
@usableFromInline
@frozen
internal enum _Variant {
case native(_NativeSet<Element>.Iterator)
#if _runtime(_ObjC)
case cocoa(__CocoaSet.Iterator)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
internal init(_native: __owned _NativeSet<Element>.Iterator) {
self.init(_variant: .native(_native))
}
#if _runtime(_ObjC)
@usableFromInline
internal init(_cocoa: __owned __CocoaSet.Iterator) {
self.init(_variant: .cocoa(_cocoa))
}
#endif
}
}
extension Set.Iterator {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
/// Allow the optimizer to consider the surrounding code unreachable if
/// Set<Element> is guaranteed to be native.
@usableFromInline @_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
#endif
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _NativeSet<Element>.Iterator {
get {
switch _variant {
case .native(let nativeIterator):
return nativeIterator
#if _runtime(_ObjC)
case .cocoa:
_internalInvariantFailure("internal error: does not contain a native index")
#endif
}
}
set {
self._variant = .native(newValue)
}
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _asCocoa: __CocoaSet.Iterator {
get {
switch _variant {
case .native:
_internalInvariantFailure("internal error: does not contain a Cocoa index")
case .cocoa(let cocoa):
return cocoa
}
}
}
#endif
}
extension Set.Iterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
@inline(__always)
public mutating func next() -> Element? {
#if _runtime(_ObjC)
guard _isNative else {
guard let cocoaElement = _asCocoa.next() else { return nil }
return _forceBridgeFromObjectiveC(cocoaElement, Element.self)
}
#endif
return _asNative.next()
}
}
extension Set.Iterator: CustomReflectable {
/// A mirror that reflects the iterator.
public var customMirror: Mirror {
return Mirror(
self,
children: EmptyCollection<(label: String?, value: Any)>())
}
}
extension Set: CustomReflectable {
/// A mirror that reflects the set.
public var customMirror: Mirror {
let style = Mirror.DisplayStyle.`set`
return Mirror(self, unlabeledChildren: self, displayStyle: style)
}
}
extension Set {
/// Removes and returns the first element of the set.
///
/// Because a set is not an ordered collection, the "first" element may not
/// be the first element that was added to the set.
///
/// - Returns: A member of the set. If the set is empty, returns `nil`.
@inlinable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
}
/// The total number of elements that the set can contain without
/// allocating new storage.
@inlinable
public var capacity: Int {
return _variant.capacity
}
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to a set, use this
/// method to avoid multiple reallocations. This method ensures that the
/// set has unique, mutable, contiguous storage, with space allocated
/// for at least the requested number of elements.
///
/// Calling the `reserveCapacity(_:)` method on a set with bridged
/// storage triggers a copy to contiguous storage even if the existing
/// storage has room to store `minimumCapacity` elements.
///
/// - Parameter minimumCapacity: The requested number of elements to
/// store.
public // FIXME(reserveCapacity): Should be inlinable
mutating func reserveCapacity(_ minimumCapacity: Int) {
_variant.reserveCapacity(minimumCapacity)
_internalInvariant(self.capacity >= minimumCapacity)
}
}
public typealias SetIndex<Element: Hashable> = Set<Element>.Index
public typealias SetIterator<Element: Hashable> = Set<Element>.Iterator
| apache-2.0 | 17591cc23a7c93fd1c544ad9cf1aaa6f | 33.312729 | 109 | 0.640448 | 4.110785 | false | false | false | false |
orazz/CreditCardForm-iOS | CreditCardForm/Classes/AKMaskFieldUtility.swift | 1 | 3487 | //
// AKMaskFieldUtility.swift
// AKMaskField
// GitHub: https://github.com/artemkrachulov/AKMaskField
//
// Created by Artem Krachulov
// Copyright (c) 2016 Artem Krachulov. All rights reserved.
// Website: http://www.artemkrachulov.com/
//
import UIKit
class AKMaskFieldUtility {
/// [Source](http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index)
class func rangeFromString(_ string: String, nsRange: NSRange) -> Range<String.Index>! {
guard
let from16 = string.utf16.index(string.utf16.startIndex, offsetBy: nsRange.location, limitedBy: string.utf16.endIndex),
let to16 = string.utf16.index(from16, offsetBy: nsRange.length, limitedBy: string.utf16.endIndex),
let from = String.Index(from16, within: string),
let to = String.Index(to16, within: string)
else { return nil }
return from ..< to
/*
let from16 = string.utf16.startIndex.advancedBy(nsRange.location, limit: string.utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: string.utf16.endIndex)
if let from = String.Index(from16, within: string),
let to = String.Index(to16, within: string) {
return from ..< to
}
return nil*/
}
class func substring(_ sourceString: String?, withNSRange range: NSRange) -> String {
guard let sourceString = sourceString else {
return ""
}
#if swift(>=4)
return String(sourceString[rangeFromString(sourceString, nsRange: range)])
#else
return sourceString.substring(with: rangeFromString(sourceString, nsRange: range))
#endif
}
class func replace(_ sourceString: inout String!, withString string: String, inRange range: NSRange) {
sourceString = sourceString.replacingCharacters(in: rangeFromString(sourceString, nsRange: range), with: string)
}
class func replacingOccurrencesOfString(_ string: inout String!, target: String, withString replacement: String) {
string = string.replacingOccurrences(of: target, with: replacement, options: .regularExpression, range: nil)
}
class func maskField(_ maskField: UITextField, moveCaretToPosition position: Int) {
guard let caretPosition = maskField.position(from: maskField.beginningOfDocument, offset: position) else {
return
}
maskField.selectedTextRange = maskField.textRange(from: caretPosition, to: caretPosition)
}
class func matchesInString(_ string: String, pattern: String) -> [NSTextCheckingResult] {
return try!
NSRegularExpression(pattern: pattern, options: .caseInsensitive)
.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.count))
}
class func findIntersection(_ ranges: [NSRange], withRange range: NSRange) -> [NSRange?] {
var intersectRanges = [NSRange?]()
for r in ranges {
var intersectRange: NSRange!
let delta = r.location - range.location
var location, length, tail: Int
if delta <= 0 {
location = range.location
length = range.length
tail = r.length - abs(delta)
} else {
location = r.location
length = r.length
tail = range.length - abs(delta)
}
if tail > 0 && length > 0 {
intersectRange = NSMakeRange(location, min(tail, length))
}
intersectRanges.append(intersectRange)
}
return intersectRanges
}
}
| mit | 40058673afed4cfaa34db420dce53c07 | 33.87 | 127 | 0.671924 | 4.391688 | false | false | false | false |
AcerFeng/SwiftProject | EmojiMachine/EmojiMachine/ViewController.swift | 1 | 2890 | //
// ViewController.swift
// EmojiMachine
//
// Created by lanfeng on 16/11/17.
// Copyright © 2016年 lanfeng. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var emojiPickerView: UIPickerView!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func goButtonDidTouch(_ sender: AnyObject) {
emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 0, animated: true)
emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 1, animated: true)
emojiPickerView.selectRow(Int(arc4random()) % 90 + 3, inComponent: 2, animated: true)
if (dataArray1[emojiPickerView.selectedRow(inComponent: 0)] == dataArray2[emojiPickerView.selectedRow(inComponent: 1)] &&
dataArray1[emojiPickerView.selectedRow(inComponent: 0)] == dataArray3[emojiPickerView.selectedRow(inComponent: 2)]) {
resultLabel.text = "Bingo!"
} else {
resultLabel.text = "💔"
}
}
var imageArray = [String]()
var dataArray1 = [Int]()
var dataArray2 = [Int]()
var dataArray3 = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
imageArray = ["🐶", "🐵", "🦄", "😂", "🎨", "🤖", "🍟", "🐼", "🚖", "🐷"]
for _ in 0 ..< 100 {
dataArray1.append((Int)(arc4random() % 10))
dataArray2.append((Int)(arc4random() % 10))
dataArray3.append((Int)(arc4random() % 10))
}
resultLabel.text = ""
}
}
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
// MARK: -UIPickerViewDelegate
public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100.0
}
public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100.0
}
public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLabel = UILabel()
if component == 0 {
pickerLabel.text = imageArray[(Int)(dataArray1[row])]
} else if component == 1 {
pickerLabel.text = imageArray[(Int)(dataArray2[row])]
} else {
pickerLabel.text = imageArray[(Int)(dataArray3[row])]
}
pickerLabel.font = UIFont(name: "Apple Color Emoji", size: 80)
pickerLabel.textAlignment = NSTextAlignment.center
return pickerLabel
}
// MARK: -UIPickerViewDataSource
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 100
}
}
| apache-2.0 | 8da103c52110062e58873052c9c405b9 | 32.97619 | 139 | 0.613174 | 4.625608 | false | false | false | false |
caiomello/utilities | Sources/Utilities/Extensions/CGSize+Extensions.swift | 1 | 644 | //
// CGSize+Extensions.swift
// Utilities
//
// Created by Caio Mello on 6/2/19.
// Copyright © 2019 Caio Mello. All rights reserved.
//
import UIKit
extension CGSize {
public init(size: CGSize, aspectFitToWidth width: CGFloat) {
self.init()
let scaleFactor = width/size.width
self.width = size.width * scaleFactor
self.height = size.height * scaleFactor
}
public init(size: CGSize, aspectFitToHeight height: CGFloat) {
self.init()
let scaleFactor = height/size.height
self.width = size.width * scaleFactor
self.height = size.height * scaleFactor
}
}
| mit | 2fdbf5efc6ed83c84a7f0dca0b6fdd65 | 21.172414 | 66 | 0.639191 | 3.969136 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK | Example/Tests/OTOrganizationAPITest.swift | 1 | 1707 | //
// OTOrganizationAPITest.swift
// OpenTimeSDK
//
// Created by Josh Woodcock on 3/19/16.
// Copyright © 2016 Connecting Open Time, LLC. All rights reserved.
//
import UIKit
import XCTest
import OpenTimeSDK
class OTOrganizationAPITest : OTAPITest {
func testMyOrganizations() {
let response: OTAPIResponse = TestHelper.getDataResetResponse(testCase: self, scriptNames: ["make_users"], resetCache: true);
// Verify test data was setup correctly.
XCTAssertTrue(response.success, response.message);
if(response.success) {
// Create an expectation to be fulfilled.
let theExpectation = expectation(description: "Get my organizations");
OTOrganizationAPI.getMyOrganizations({ (response: OTGetMyOrganizationsResponse) -> Void in
XCTAssertTrue(response.success);
XCTAssertEqual(1, response.getOrganizations().count);
if(response.success && response.getOrganizations().count == 1){
let organizations = response.getOrganizations();
let organization = organizations[0] as OTDeserializedOrganization;
XCTAssertEqual(1, organization.getOrgID());
XCTAssertEqual("OpenTime", organization.getName());
XCTAssertEqual("https://s3-us-west-2.amazonaws.com/test-opentime-org-images/icon-transparent-filled.png", organization.getLogoURL());
}
theExpectation.fulfill();
});
waitForExpectations(timeout: 5.0, handler:nil);
}
}
}
| mit | fa6726f65277aa16712de3a4306ed5ca | 34.541667 | 153 | 0.603165 | 5.154079 | false | true | false | false |
leeaken/LTMap | LTMap/LTLocationMap/LocationPick/View/LTLocPickHomeView.swift | 1 | 8663 | //
// LTLocPickHomeView.swift
// LTMap
//
// Created by aken on 2017/6/16.
// Copyright © 2017年 LTMap. All rights reserved.
//
import Foundation
class LTLocPickHomeView: UIView {
var selectedPoiModel = LTPoiModel()
var listPickView:LTLocPickListView?
var mapPickView:LTLocPickMapView?
var location:CLLocationCoordinate2D? {
didSet {
listPickView?.location = location
mapPickView?.location = location;
}
}
override var frame:CGRect {
didSet {
super.frame = frame
addViewContrains()
}
}
fileprivate var pickType:MXPickLocationType = .LTPickMix
// 搜索框
let searchResultVC = LTLocationSearchResultVC()
lazy var searchController:UISearchController = { [weak self] in
let controller = UISearchController(searchResultsController: self?.searchResultVC)
controller.searchBar.delegate = self
controller.dimsBackgroundDuringPresentation = true
controller.searchBar.searchBarStyle = .prominent
controller.searchBar.sizeToFit()
controller.hidesNavigationBarDuringPresentation = true
controller.definesPresentationContext = true
controller.searchBar.placeholder = "搜索地点"
controller.delegate = self
return controller
}()
init(frame: CGRect,type:MXPickLocationType) {
super.init(frame: frame)
pickType = type
setupUI()
addViewContrains()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
searchController.view.removeFromSuperview()
}
private func setupUI() {
listPickView = LTLocPickListView(frame: CGRect.zero)
mapPickView = LTLocPickMapView(frame: CGRect.zero)
self.addSubview(searchController.searchBar)
searchResultVC.searchBar = searchController.searchBar
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "取消"
switch pickType {
case .LTPickMix:
self.addSubview(mapPickView!)
self.addSubview(listPickView!)
listPickView?.delegate = self
mapPickView?.delegate = self
searchResultVC.delegate = self
searchResultVC.coordinate = location;
break
case .LTPickList :
self.addSubview(listPickView!)
listPickView?.delegate = self
searchResultVC.delegate = self
searchResultVC.coordinate = location;
break
default:
self.addSubview(mapPickView!)
mapPickView?.delegate = self
searchResultVC.delegate = self
searchResultVC.coordinate = location;
break
}
}
private func addViewContrains() {
switch pickType {
case .LTPickMix:
mapPickView?.frame = CGRect(x: 0, y: searchController.searchBar.frame.maxY,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.MapDefaultHeight)
listPickView?.frame = CGRect(x: 0, y: (mapPickView?.frame.maxY)!,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.TableViewDefaultHeight)
break
case .LTPickList :
listPickView?.frame = CGRect(x: 0, y: searchController.searchBar.frame.maxY,width: UIScreen.main.bounds.size.width, height: self.frame.size.height - 44 - 44 - 20)
break
default:
mapPickView?.frame = CGRect(x: 0, y: searchController.searchBar.frame.maxY,width: UIScreen.main.bounds.size.width, height: self.frame.size.height - 44 - 44 - 20)
break
}
}
func viewController(_ view: UIView) -> UIViewController {
var responder: UIResponder? = view
while !(responder is UIViewController) {
responder = responder?.next
if nil == responder {
break
}
}
return (responder as? UIViewController)!
}
}
extension LTLocPickHomeView:UISearchControllerDelegate,LTLocPickListViewDelegate,LTMapViewDelegate {
/// MARK -- UISearchController delegate
func willPresentSearchController(_ searchController: UISearchController) {
viewController(self).navigationController?.navigationBar.isTranslucent = true;
}
func willDismissSearchController(_ searchController: UISearchController) {
viewController(self).navigationController?.navigationBar.isTranslucent = false;
}
/// MARK -- LTLocPickListView Delegate
func tableViewForPickListViewDidSelectAt(selectedIndex: Int, model: LTPoiModel) {
selectedPoiModel = model
if let location = model.coordinate {
mapPickView?.setRegion(coordinate: location)
}
}
func scrollViewOnPickListViewDidScroll(_ scrollView: UIScrollView) {
if (pickType != .LTPickMix) {
return
}
if scrollView.contentOffset.y > 9.0 {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
[weak self] in
self?.mapPickView?.frame = CGRect(x: 0, y: (self?.searchController.searchBar.frame.maxY)!,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.MapAfterAnimationsDefaultHeight)
self?.listPickView?.frame = CGRect(x: 0, y: (self?.mapPickView?.frame.maxY)!,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.TableViewAfterAnimationsDefaultHeight)
}, completion: { (bol) in
})
}else if scrollView.contentOffset.y <= 0 {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: {
[weak self] in
self?.mapPickView?.frame = CGRect(x: 0, y: (self?.searchController.searchBar.frame.maxY)!,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.MapDefaultHeight)
self?.listPickView?.frame = CGRect(x: 0, y: (self?.mapPickView?.frame.maxY)!,width: UIScreen.main.bounds.size.width, height: LTLocationCommon.TableViewDefaultHeight)
}, completion: { (bol) in
})
}
}
/// MARK -- Map delegate
func mapView(mapView: LTMapView, regionDidChangeAnimated animated: Bool) {
if CLLocationCoordinate2DIsValid(mapView.centerCoordinate!) {
location = mapView.centerCoordinate
}
}
}
/// MARK: -- UISearchBarDelegate
extension LTLocPickHomeView:UISearchBarDelegate {
//点击搜索按钮
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//
// listPickView.resettRequestParameter()
let word = searchBar.text
searchResultVC.coordinate = location
searchResultVC.isKeyboardSearch = true
searchResultVC.searchPlaceWithKeyWord(keyword: word, adCode: "深圳")
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchResultVC.coordinate = location
searchResultVC.isKeyboardSearch = true
searchResultVC.searchPlaceWithKeyWord(keyword: searchText, adCode: "深圳")
}
}
/// MARK -- LTLocationSearchResultVCDelegate
extension LTLocPickHomeView:LTLocationSearchResultVCDelegate {
func tableViewDidSelectAt(selectedIndex:Int,model:LTPoiModel) {
searchController.isActive = false
let searchParam = LTPOISearchAroundArg()
searchParam.city = model.city
searchParam.keyword = model.title
searchParam.location = model.coordinate
listPickView?.searchParam = searchParam
print(selectedIndex)
}
}
| mit | cef9bda17e1d64f0e8ce7e9689e35cea | 28.326531 | 203 | 0.583391 | 5.744171 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Graph/305_Number of Islands II.swift | 1 | 2171 | // 305_Number of Islands II
// https://leetcode.com/problems/number-of-islands-ii
//
// Created by Honghao Zhang on 10/23/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
//
//Example:
//
//Input: m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]
//Output: [1,1,2,3]
//Explanation:
//
//Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).
//
//0 0 0
//0 0 0
//0 0 0
//Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
//
//1 0 0
//0 0 0 Number of islands = 1
//0 0 0
//Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
//
//1 1 0
//0 0 0 Number of islands = 1
//0 0 0
//Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
//
//1 1 0
//0 0 1 Number of islands = 2
//0 0 0
//Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
//
//1 1 0
//0 0 1 Number of islands = 3
//0 1 0
//Follow up:
//
//Can you do it in time complexity O(k log mn), where k is the length of the positions?
//
// 还是求island的个数,不过这次是造岛渐进的过程
// 要求造岛的过程中实时返回岛的个数
import Foundation
class Num305 {
// TODO:
// MARK: - 用Dictionary
// 保存坐标到island_id的一个dict,当新建一个岛的时候
// 检查相邻的坐标有没有existing island。如果有,那么就link这个坐标到这个island
// 特殊情况,如果相邻的坐标对应这不同的island,说明这个点连接了两个或多个island
// 需要更新dict
// 如果没有,说明这是一个新的island
func solution() -> Bool {
return true
}
// MARK: - Union-Find
// 用一个UnionFind动态构造island的count
}
| mit | 422b711ab6b14fe2514fec8900ca7290 | 28.2 | 437 | 0.68177 | 2.988976 | false | false | false | false |
HeMet/DLife | DLife/ViewModels/FeedViewModel.swift | 1 | 1896 | //
// FeedsViewModel.swift
// DLife
//
// Created by Евгений Губин on 12.06.15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import MVVMKit
class FeedViewModel: ViewModel {
var entries = ObservableArray<EntryViewModel>()
var feedToken = FeedToken(category: .Latest, pageSize: 10)
var category = FeedCategory.Latest {
didSet {
feedToken = FeedToken(category: category, pageSize: 10)
loadEntries()
}
}
var onDisposed: ViewModelEventHandler?
func loadEntries() {
if feedToken.category == .Favorite {
loadFavorites()
} else {
loadFromServer()
}
}
func loadFromServer() {
let api = DevsLifeAPI()
let append = feedToken.isUsed
api.getEntries(feedToken) { result in
switch result {
case .OK(let boxedData):
let newVMs = boxedData.value.map { EntryViewModel(entry: $0) }
if append {
self.entries.extend(newVMs)
} else {
self.entries.replaceAll(newVMs)
}
self.onDataChanged?()
case .Error(let error):
println(error)
}
}
}
func loadFavorites() {
if (!feedToken.isUsed) {
let favs = FavoritesManager.sharedInstance.favorites.map { EntryViewModel(entry: $0) }
entries.replaceAll(favs)
feedToken.next()
}
}
func showEntryAtIndex(index: Int) {
let entry = entries[index].entry
GoTo.post(sender: self)(PostViewModel(entry: entry))
}
func showAbout() {
GoTo.about(sender: self)(AboutViewModel())
}
func dispose() {
onDisposed?(self)
}
var onDataChanged: (() -> ())?
} | mit | bc2b06b5a2d4e48c3a4248c0bd860834 | 24.821918 | 98 | 0.54034 | 4.49642 | false | false | false | false |
vicentesuarez/Swift-FlexibleHeightBar | FlexibleHeightBar/FlexibleHeightBar/FlexibleHeightBarSubviewLayoutAttributes.swift | 1 | 8105 | //
// FlexibleHeightBarSubviewLayoutAttributes.swift
// JokeMinder
//
// Modified and converted to swift by Vicente Suarez on 7/31/15.
// Copyright © 2015 Vicente Suarez. All rights reserved.
//
/*
Copyright (c) 2015, Bryan Keller. All rights reserved.
Licensed under the MIT license <http://opensource.org/licenses/MIT>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portionsof 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
/**
The FlexibleHeightBarSubviewLayoutAttributes class is used to define layout attributes (i.e frame, transform, alpha) for subviews of a FlexibleHeightBar.
Note: This class is heavily influenced by UICollectionViewLayoutAttributes.
*/
public class FlexibleHeightBarSubviewLayoutAttributes {
private let boundsAssertionMessage = "Bounds must be set with a (0,0) origin"
public var alpha: CGFloat = 1.0 // Possible values are between 0.0 (transparent) and 1.0 (opaque). The default is 1.0.
public var zIndex = 0.0 // Specifies the item’s position on the z axis.
public var hidden = false
// MARK: - Computed Properties -
/**
The frame rectangle of the item.
The frame rectangle is measured in points and specified in the coordinate system of the collection view. Setting the value of this property also sets the values of the center and size properties.
*/
public var frame: CGRect {
get {
return _frame
}
set(newFrame) {
if _transform.isIdentity && CATransform3DIsIdentity(_transform3D) {
_frame = newFrame
}
_center = CGPoint(x: newFrame.midX, y: newFrame.midY);
_size = CGSize(width: _frame.width, height: _frame.height)
_bounds = CGRect(x: _bounds.minX, y: _bounds.minY, width: _size.width, height: _size.height)
}
}
private var _frame = CGRect.zero
/**
The bounds of the item.
When setting the bounds, the origin of the bounds rectangle must always be at (0, 0). Changing the bounds rectangle also changes the value in the size property to match the new bounds size.
*/
public var bounds: CGRect {
get {
return _bounds
}
set (newBounds) {
assert(newBounds.origin.x == 0.0 && newBounds.origin.y == 0.0, boundsAssertionMessage)
_bounds = newBounds
_size = CGSize(width: _bounds.width, height: _bounds.height)
}
}
private var _bounds = CGRect.zero
/**
The center point of the item.
The center point is specified in the coordinate system of the collection view. Setting the value of this property also updates the origin of the rectangle in the frame property.
*/
public var center: CGPoint {
get {
return _center
}
set (newCenter) {
_center = newCenter;
if _transform.isIdentity && CATransform3DIsIdentity(_transform3D) {
_frame = CGRect(x: newCenter.x - _bounds.midX, y: newCenter.y - _bounds.midY, width: _frame.width, height: _frame.height)
}
}
}
private var _center = CGPoint.zero
/**
The size of the item.
Setting the value of this property also changes the size of the rectangle returned by the frame and bounds properties.
*/
public var size: CGSize {
get {
return _size
}
set (newSize) {
_size = newSize
if _transform.isIdentity && CATransform3DIsIdentity(_transform3D) {
_frame = CGRect(x: _frame.minX, y: _frame.minY, width: newSize.width, height: newSize.height)
}
_bounds = CGRect(x: _bounds.minX, y: _bounds.minY, width: newSize.width, height: newSize.height)
}
}
private var _size = CGSize.zero
/**
The 3D transform of the item.
Assigning a transform other than the identity transform to this property causes the frame property to be set to CGRectNull. Assigning a value also replaces the value in the transform property with an affine version of the 3D transform you specify.
*/
public var transform3D: CATransform3D {
get {
return _transform3D
}
set (newTransform3D) {
_transform3D = newTransform3D
_transform = CGAffineTransform(a: newTransform3D.m11, b: newTransform3D.m12, c: newTransform3D.m21, d: newTransform3D.m22, tx: newTransform3D.m41, ty: newTransform3D.m42)
if !CATransform3DIsIdentity(newTransform3D) {
_frame = CGRect.null;
}
}
}
private var _transform3D = CATransform3DIdentity
/**
The affine transform of the item.
Assigning a transform other than the identity transform to this property causes the frame property to be set to CGRectNull. Assigning a value also replaces the value in the transform3D property with a 3D version of the affine transform you specify.
*/
public var transform: CGAffineTransform {
get {
return _transform
}
set (newTransform) {
_transform = newTransform
_transform3D = CATransform3DMakeAffineTransform(newTransform)
if !newTransform.isIdentity {
_frame = CGRect.null
}
}
}
private var _transform = CGAffineTransform.identity
public var cornerRadius: CGFloat {
get {
return _cornerRadius
}
set (newCornerRadius) {
_cornerRadius = fmax(newCornerRadius, 0.0)
}
}
private var _cornerRadius: CGFloat = 0.0
// MARK: - Initialization -
public init() {
}
/**
A convenience initializer that returns layout attributes with the same property values as the specified layout attributes, or nil of initialization fails.
- Parameter layoutAttributes: The existing layout attributes.
- Returns: Layout attributes with the same property values as the specified layout attributes, or nil of initialization fails.
*/
public convenience init(layoutAttributes: FlexibleHeightBarSubviewLayoutAttributes) {
self.init()
_frame = layoutAttributes.frame
_bounds = layoutAttributes.bounds
_center = layoutAttributes.center
_size = layoutAttributes.size
_transform3D = layoutAttributes.transform3D
_transform = layoutAttributes.transform
alpha = layoutAttributes.alpha
zIndex = layoutAttributes.zIndex
hidden = layoutAttributes.hidden
}
}
extension FlexibleHeightBarSubviewLayoutAttributes: CustomStringConvertible {
public var description: String {
get {
return "FlexibleHeightBarSubviewLayoutAttributes = {\n\talpha: \(alpha)\n\tzIndex: \(zIndex)\n\thidden: \(hidden)\n\tframe: \(frame)\n\tbounds: \(bounds)\n\tcenter: \(center)\n\tsize: \(size)\n\ttransform3D: \(transform3D)\n\ttransform: \(transform)\n}"
}
}
}
| mit | e55f503fa676b7f9f3045c09271cccf4 | 41.197917 | 558 | 0.650704 | 4.788416 | false | false | false | false |
hoddez/MusicTheoryKit | MusicTheoryKit/Scale.swift | 1 | 6289 | //
// File.swift
// MockingBird
//
// Created by Thomas Hoddes on 2015-07-06.
// Copyright (c) 2015 Thomas Hoddes. All rights reserved.
//
public struct Scale {
public let root: Note.Name
public let type: ScaleType
public let preferredAccidental: Note.Accidental
public init(_ root: Note.Name, _ type: ScaleType, preferredAccidental: Note.Accidental = .Sharp) {
self.root = root
self.type = type
self.preferredAccidental = preferredAccidental
}
public func absoluteScale(octave: Int) -> AbsoluteScale {
let rootNote = Note(root, octave)
let rootNoteEqualTemperamentIndex = rootNote.equalTemperamentIndex
let notes = type.steps.map { steps in
return Note(equalTemperamentIndex: rootNoteEqualTemperamentIndex + steps, preferredAccidental: self.preferredAccidental)
}
return AbsoluteScale(notes)
}
public var noteNames: [Note.Name] {
return absoluteScale(0).notes.map { $0.name }
}
}
public struct AbsoluteScale {
private let notes: [Note]
public var root: Note { return notes.first! }
init(_ notes: [Note]) {
self.notes = notes
}
public func triadAtScaleDegree(scaleDegree: ScaleDegree) -> [Note] {
let triadRoot = noteAtScalePosition(ScalePosition(scaleDegree,0))
let triadThird = noteAtScalePosition(ScalePosition(scaleDegree,0).advancedBy(2))
let triadFifth = noteAtScalePosition(ScalePosition(scaleDegree,0).advancedBy(4))
return [triadRoot, triadThird, triadFifth]
}
public func noteAtScalePosition(scalePosition: ScalePosition) -> Note {
let relativeNote = notes[scalePosition.degree.rawValue]
let equalTemperamentIndex = relativeNote.equalTemperamentIndex + scalePosition.octave * 12
return Note(equalTemperamentIndex: equalTemperamentIndex, preferredAccidental: relativeNote.name.accidental)
}
}
public struct ScaleType : CustomStringConvertible, Hashable {
public let steps: [Int]
public let description: String
public init(keyMode: Key.Mode) {
self.steps = keyMode.steps
self.description = keyMode.description
}
public init(steps: [Int], description: String) {
self.steps = steps
self.description = description
}
public var intervalsFromRoot: [Interval] {
return (1..<steps.endIndex).map { index in
return Interval(size: self.steps[index])
}
}
public func intervalForScalePosition(scalePosition: ScalePosition) -> Interval {
return Interval(size: self.steps[scalePosition.degree.rawValue] + 12 * scalePosition.octave)
}
public var melodicIntervals: [MelodicInterval] {
return self.steps.map { MelodicInterval(steps: $0) }
}
public static let Ionian = Major
public static let Dorian = ScaleType(keyMode: Key.Mode.Dorian)
public static let Phrygian = ScaleType(keyMode: Key.Mode.Phrygian)
public static let Lydian = ScaleType(keyMode: Key.Mode.Lydian)
public static let Mixolydian = ScaleType(keyMode: Key.Mode.Mixolydian)
public static let Aeolian = Minor
public static let Locrian = ScaleType(keyMode: Key.Mode.Locrian)
public static let Minor = ScaleType(keyMode: Key.Mode.Minor)
public static let Major = ScaleType(keyMode: Key.Mode.Major)
}
public extension ScaleType {
var hashValue: Int { return description.hashValue }
}
public func ==(left: ScaleType, right: ScaleType) -> Bool {
return left.description == right.description && left.steps == right.steps
}
public struct ScalePosition : Comparable, ForwardIndexType, Hashable, CustomStringConvertible {
let degree: ScaleDegree
let octave: Int
public init(_ degree: ScaleDegree, _ octave: Int) {
self.degree = degree
self.octave = octave
}
var position: Int { return degree.rawValue + octave * 7 }
public func successor() -> ScalePosition {
let newDegree = degree.next()
return ScalePosition(newDegree, newDegree == .First ? octave + 1 : octave)
}
public var hashValue: Int {
return position.hashValue
}
public var description: String {
switch (degree, octave) {
case let (degree, 0):
return degree.description
case (.First, 1):
return "8th"
default:
return "\(degree.description) (+\(octave) Octave)"
}
}
}
public func <=(lhs: ScalePosition, rhs: ScalePosition) -> Bool {
return lhs.position <= rhs.position
}
public func >=(lhs: ScalePosition, rhs: ScalePosition) -> Bool {
return lhs.position >= rhs.position
}
public func >(lhs: ScalePosition, rhs: ScalePosition) -> Bool {
return lhs.position > rhs.position
}
public func <(lhs: ScalePosition, rhs: ScalePosition) -> Bool {
return lhs.position < rhs.position
}
public func ==(lhs: ScalePosition, rhs: ScalePosition) -> Bool {
return lhs.degree == rhs.degree && lhs.octave == rhs.octave
}
public enum ScaleDegree : Int, CustomStringConvertible, Comparable, ForwardIndexType {
case First
case Second
case Third
case Fourth
case Fifth
case Sixth
case Seventh
public var description: String {
switch self {
case .First:
return "Root"
case .Second:
return "2nd"
case .Third:
return "3rd"
case .Fourth:
return "4th"
case .Fifth:
return "5th"
case .Sixth:
return "6th"
case .Seventh:
return "7th"
}
}
public func next() -> ScaleDegree {
return ScaleDegree(rawValue: (rawValue + 1) % 7)!
}
public func successor() -> ScaleDegree {
return next()
}
}
public func <=(lhs: ScaleDegree, rhs: ScaleDegree) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
public func >=(lhs: ScaleDegree, rhs: ScaleDegree) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
public func >(lhs: ScaleDegree, rhs: ScaleDegree) -> Bool {
return lhs.rawValue > rhs.rawValue
}
public func <(lhs: ScaleDegree, rhs: ScaleDegree) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| mit | 3b5f06db19147c23bea2e711f9a41e8f | 29.235577 | 132 | 0.648593 | 4.397902 | false | false | false | false |
zhiquan911/chance_btc_wallet | chance_btc_wallet/chance_btc_wallet/viewcontrollers/wallet/BTCMultiSigTransactionViewController.swift | 1 | 10193 | //
// BTCMultiSigTransactionViewController.swift
// Chance_wallet
//
// Created by Chance on 16/1/28.
// Copyright © 2016年 Chance. All rights reserved.
//
import UIKit
/*
因为本钱包都是P2P的转账交易。
所以待签名的交易单都是只有1个发送方和1个接收方。
以后如果开发批量发送的交易单,将会以另一种界面形式呈现
*/
class BTCMultiSigTransactionViewController: BaseViewController {
// @IBOutlet var labelTransactionHex: UILabel!
@IBOutlet var buttonSign: UIButton!
@IBOutlet var labelTextSender: CHLabelTextField!
@IBOutlet var labelTextReceiver: CHLabelTextField!
@IBOutlet var labelTextSignature: CHLabelTextField!
@IBOutlet var labelTextAmount: CHLabelTextField!
// @IBOutlet var labelTextFees: CHLabelTextField!
var currentAccount: CHBTCAcount!
var multiSigTx: MultiSigTransaction!
var currencyType: CurrencyType = .BTC
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.showMutilSigTxToForm()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 控制器方法
extension BTCMultiSigTransactionViewController {
/**
配置UI
*/
func setupUI() {
self.navigationItem.title = "Contract".localized()
self.labelTextSender.title = "The Sender".localized()
self.labelTextReceiver.title = "The Receiver".localized()
self.labelTextAmount.title = "Transfer Amount".localized() + "(\(self.currencyType.rawValue))"
// self.labelTextFees.title = "Fees".localized() + "(\(self.currencyType.rawValue))"
self.labelTextSignature.title = "Signatures / Required Keys".localized()
self.buttonSign.setTitle("Agree To Sign".localized(), for: .normal)
}
/// 解析多重签名交易协议成显示的表单内容
func showMutilSigTxToForm() {
guard let tx = BTCTransaction(hex: self.multiSigTx.rawTx) else {
//错误提示
return
}
guard let rs = self.multiSigTx.redeemScriptHex.toBTCScript() else {
return
}
switch CHWalletWrapper.selectedBlockchainNetwork {
case .main:
self.labelTextSender.text = rs.scriptHashAddress.string
case .test:
self.labelTextSender.text = rs.scriptHashAddressTestnet.string
}
//转账数量 = 输出方的数量
if tx.outputs.count > 0 {
let output = tx.outputs[0] as! BTCTransactionOutput
self.labelTextAmount.text = output.value.toBTC()
switch CHWalletWrapper.selectedBlockchainNetwork {
case .main:
self.labelTextReceiver.text = output.script.standardAddress.string
case .test:
self.labelTextReceiver.text = BTCPublicKeyAddressTestnet(data: output.script.standardAddress.data)?.string ?? ""
}
}
//签名进度
let signed = self.multiSigTx.keySignatures?.count ?? 0
let required = rs.requiredSignatures
let text = "\(signed) / \(required)"
self.labelTextSignature.text = text
//已签的改为另一个颜色
let attributedStr = NSMutableAttributedString(string: text)
let newRange = NSMakeRange(0, signed.toString().length)
let colorDict = [NSAttributedStringKey.foregroundColor: UIColor(hex: 0xFF230D)]
attributedStr.addAttributes(colorDict, range: newRange)
self.labelTextSignature.textField?.attributedText = attributedStr
}
/**
把之前其他人的签名按顺序解析出来
- parameter sigstring:
- returns:
*/
func getSignArray(_ sigstring: String) -> [Int: Data] {
var dic = [Int: Data]()
let signsArray = sigstring.components(separatedBy: "|")
for signHex in signsArray {
//获取头部的序号
let header = "0x\(signHex.substring(0, length: 2)!)"
let index = signHex.index(signHex.startIndex, offsetBy: 2)
let dataHex = String(signHex[index...])
let seq = strtoul(header,nil,16)
dic[Int(seq)] = BTCDataFromHex(dataHex)
}
return dic
}
/// 把对交易表单输入为i的签名添加有序的多重签名
///
/// - Parameters:
/// - hex: 签名hex
/// - inputIndex: 交易输入位
/// - Returns: 签名后的脚本
func addSignatureByRedeemOrder(hex: String, inputIndex: Int) -> BTCScript {
let allSignData: BTCScript = BTCScript()
//添加脚本第一个命令
_ = allSignData.append(BTCOpcode.OP_0)
//查找自己账户公钥地址在赎回脚本中的位置
let myIndex = self.currentAccount.index(of: BTCScript(hex: self.multiSigTx.redeemScriptHex)!).toString()
//添加签名到自己的位置
var mySignatures = self.multiSigTx.keySignatures![myIndex] ?? [String]()
if !mySignatures.contains(hex) {
mySignatures.append(hex) //除掉重复
}
//同时改变原来的表单结构体内的签名部分,添加当前账户的签名数据和位置
self.multiSigTx.keySignatures![myIndex] = mySignatures
//按顺序合并签名数据
let number = self.multiSigTx.keySignatures!.keys.sorted(by: <)
for n in number {
let sigHex = self.multiSigTx.keySignatures![n]![inputIndex]
_ = allSignData.appendData(BTCDataFromHex(sigHex))
}
return allSignData
}
/**
点击复制
- parameter sender:
*/
@IBAction func handleSignPress(_ sender: AnyObject?) {
let doBlock = {
() -> Void in
//签名HEX
var signatureHexs = [String]()
let tx = BTCTransaction(hex: self.multiSigTx.rawTx)
let redeemScript = BTCScript(hex: self.multiSigTx.redeemScriptHex)
var isComplete = true
for i in 0 ..< tx!.inputs.count {
let txin = tx?.inputs[i] as! BTCTransactionInput
let hashtype = BTCSignatureHashType.BTCSignatureHashTypeAll
//多重签名的地址要用赎回脚本
let hash = try? tx?.signatureHash(for: redeemScript, inputIndex: UInt32(i), hashType: hashtype)
if hash == nil {
SVProgressHUD.showError(withStatus: "Signature error".localized())
} else {
// let sigScript = txin.signatureScript
let key = self.currentAccount.privateKey
let signature = key?.signature(forHash: hash!, hashType: hashtype)
let tmpSinsignatureHex = (signature! as NSData).hex()
signatureHexs.append(tmpSinsignatureHex!) //添加签名到数组
//按赎回脚本的生成顺序一次添加签名
let sigScript = self.addSignatureByRedeemOrder(hex: tmpSinsignatureHex!, inputIndex: i)
txin.signatureScript = sigScript
Log.debug("signatureScript = \(txin.signatureScript)")
//验证交易是否签名完成
do {
let sm = BTCScriptMachine(transaction: tx, inputIndex: UInt32(i))
try sm?.verify(withOutputScript: redeemScript)
txin.signatureScript.appendData(redeemScript?.data)
} catch let error as NSError {
Log.debug("error = \(error.description)")
Log.debug("tx.hex = \(String(describing: tx?.hex))")
//验证不通过,还需要继续签名
isComplete = false
}
}
}
if isComplete {
self.sendTransactionByWebservice(tx!)
} else {
self.gotoSendTransactionHexView(signatureHexs)
}
}
//解锁才能继续操作
CHWalletWrapper.unlock(
vc: self,
complete: {
(flag, error) in
if flag {
doBlock()
} else {
if error != "" {
SVProgressHUD.showError(withStatus: error)
}
}
})
}
/**
进入复制交易文本界面
- parameter tx:
*/
func gotoSendTransactionHexView(_ signatureHex: [String]) {
guard let vc = StoryBoard.wallet.initView(type: BTCSendMultiSigViewController.self) else {
return
}
vc.currentAccount = self.currentAccount
vc.multiSigTx = self.multiSigTx
self.navigationController?.pushViewController(vc, animated: true)
}
/**
调用接口广播交易
- parameter tx:
*/
func sendTransactionByWebservice(_ tx: BTCTransaction) {
SVProgressHUD.show()
let nodeServer = CHWalletWrapper.selectedBlockchainNode.service
nodeServer.sendTransaction(transactionHexString: tx.hex) {
(message, txid) -> Void in
if message.code == ApiResultCode.Success.rawValue {
SVProgressHUD.showSuccess(withStatus: "Transaction successed,waiting confirm".localized())
_ = self.navigationController?.popToRootViewController(animated: true)
} else {
SVProgressHUD.showError(withStatus: message.message)
}
}
}
}
| mit | 87c45007eade775b50b9ec13dfa165b3 | 32.305263 | 128 | 0.557417 | 4.705999 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/Main/Parent/VParentBar.swift | 1 | 5686 | import UIKit
class VParentBar:UIView
{
private weak var controller:CParent!
private weak var buttonHome:VParentBarButton!
private weak var buttonSettings:VParentBarButton!
private weak var buttonStore:VParentBarButton!
private weak var layoutHomeLeft:NSLayoutConstraint!
private let kBorderHeight:CGFloat = 1
private let kButtonsTop:CGFloat = 20
private let kButtonsWidth:CGFloat = 60
init(controller:CParent)
{
super.init(frame:CGRect.zero)
backgroundColor = UIColor.white
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1))
let buttonHome:VParentBarButton = VParentBarButton(
image:#imageLiteral(resourceName: "assetGenericHome"))
buttonHome.isSelected = true
buttonHome.addTarget(
self,
action:#selector(actionHome(sender:)),
for:UIControlEvents.touchUpInside)
self.buttonHome = buttonHome
let buttonSettings:VParentBarButton = VParentBarButton(
image:#imageLiteral(resourceName: "assetGenericSettings"))
buttonSettings.isSelected = false
buttonSettings.addTarget(
self,
action:#selector(actionSettings(sender:)),
for:UIControlEvents.touchUpInside)
self.buttonSettings = buttonSettings
let buttonStore:VParentBarButton = VParentBarButton(
image:#imageLiteral(resourceName: "assetGenericStore"))
buttonStore.isSelected = false
buttonStore.addTarget(
self,
action:#selector(actionStore(sender:)),
for:UIControlEvents.touchUpInside)
self.buttonStore = buttonStore
addSubview(border)
addSubview(buttonStore)
addSubview(buttonSettings)
addSubview(buttonHome)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.topToTop(
view:buttonHome,
toView:self,
constant:kButtonsTop)
NSLayoutConstraint.bottomToBottom(
view:buttonHome,
toView:self)
layoutHomeLeft = NSLayoutConstraint.leftToLeft(
view:buttonHome,
toView:self)
NSLayoutConstraint.width(
view:buttonHome,
constant:kButtonsWidth)
NSLayoutConstraint.topToTop(
view:buttonSettings,
toView:self,
constant:kButtonsTop)
NSLayoutConstraint.bottomToBottom(
view:buttonSettings,
toView:self)
NSLayoutConstraint.leftToLeft(
view:buttonSettings,
toView:self)
NSLayoutConstraint.width(
view:buttonSettings,
constant:kButtonsWidth)
NSLayoutConstraint.topToTop(
view:buttonStore,
toView:self,
constant:kButtonsTop)
NSLayoutConstraint.bottomToBottom(
view:buttonStore,
toView:self)
NSLayoutConstraint.rightToRight(
view:buttonStore,
toView:self)
NSLayoutConstraint.width(
view:buttonStore,
constant:kButtonsWidth)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let remainHome:CGFloat = width - kButtonsWidth
let marginHome:CGFloat = remainHome / 2.0
layoutHomeLeft.constant = marginHome
super.layoutSubviews()
}
//MARK: actions
func actionHome(sender button:UIButton)
{
if !buttonHome.isSelected
{
let transition:CParent.TransitionHorizontal
if buttonSettings.isSelected
{
transition = CParent.TransitionHorizontal.fromRight
}
else
{
transition = CParent.TransitionHorizontal.fromLeft
}
buttonHome.isSelected = true
buttonSettings.isSelected = false
buttonStore.isSelected = false
let controllerHome:CHome = CHome()
controller.slideTo(
horizontal:transition,
controller:controllerHome)
}
}
func actionSettings(sender button:UIButton)
{
if !buttonSettings.isSelected
{
buttonHome.isSelected = false
buttonSettings.isSelected = true
buttonStore.isSelected = false
let controllerSettings:CSettings = CSettings()
controller.slideTo(
horizontal:CParent.TransitionHorizontal.fromLeft,
controller:controllerSettings)
}
}
func actionStore(sender button:UIButton)
{
if !buttonStore.isSelected
{
goStore()
}
}
//MARK: public
func goStore()
{
buttonHome.isSelected = false
buttonSettings.isSelected = false
buttonStore.isSelected = true
let controllerStore:CStore = CStore()
controller.slideTo(
horizontal:CParent.TransitionHorizontal.fromRight,
controller:controllerStore)
}
}
| mit | d642b38e23afa38991fe2b6b08869c3d | 29.084656 | 71 | 0.590573 | 6.036093 | false | false | false | false |
jiamao130/DouYuSwift | DouYuBroad/DouYuBroad/Main/NetworkTools.swift | 1 | 837 | //
// NetworkTools.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/10.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
class func requestData(type: MethodType,URLString: String, parameters: [String: NSString]? = nil,finishedCallback: @escaping (_ result: Any) -> ()){
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error)
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| mit | 83c5a2bbc0f522b6aa0d70869b5d8326 | 24.375 | 152 | 0.591133 | 4.296296 | false | false | false | false |
neoneye/SwiftyFORM | Source/Specification/CharacterSetSpecification.swift | 1 | 6146 | // MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved.
import Foundation
/// Check if a string has no illegal characters.
public class CharacterSetSpecification: Specification {
private let characterSet: CharacterSet
public init(characterSet: CharacterSet) {
self.characterSet = characterSet
}
public static func charactersInString(_ charactersInString: String) -> CharacterSetSpecification {
let cs = CharacterSet(charactersIn: charactersInString)
return CharacterSetSpecification(characterSet: cs)
}
/// Check if all characters are contained in the characterset.
///
/// - parameter candidate: The object to be checked.
///
/// - returns: `true` if the candidate object is a string and all its characters are legal, `false` otherwise.
public func isSatisfiedBy(_ candidate: Any?) -> Bool {
guard let fullString = candidate as? String else { return false }
for character: Character in fullString {
let range: Range<String.Index>? =
String(character).rangeOfCharacter(from: characterSet)
if range == nil {
return false // one or more characters does not satify the characterSet
}
if range!.isEmpty {
return false // one or more characters does not satify the characterSet
}
}
return true // the whole string satisfies the characterSet
}
}
extension CharacterSetSpecification {
public static var alphanumerics: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.alphanumerics)
}
public static var capitalizedLetters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.capitalizedLetters)
}
public static var controlCharacters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.controlCharacters)
}
public static var decimalDigits: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.decimalDigits)
}
public static var decomposables: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.decomposables)
}
public static var illegalCharacters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.illegalCharacters)
}
public static var letters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.letters)
}
public static var lowercaseLetters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.lowercaseLetters)
}
public static var newlines: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.newlines)
}
public static var nonBaseCharacters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.nonBaseCharacters)
}
public static var punctuationCharacters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.punctuationCharacters)
}
public static var symbols: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.symbols)
}
public static var uppercaseLetters: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.uppercaseLetters)
}
public static var urlFragmentAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlFragmentAllowed)
}
public static var urlHostAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlHostAllowed)
}
public static var urlPasswordAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlPasswordAllowed)
}
public static var urlPathAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlPathAllowed)
}
public static var urlQueryAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlQueryAllowed)
}
public static var urlUserAllowed: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.urlUserAllowed)
}
public static var whitespaces: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.whitespaces)
}
public static var whitespacesAndNewlines: CharacterSetSpecification {
CharacterSetSpecification(characterSet: CharacterSet.whitespacesAndNewlines)
}
}
/// - warning:
/// These functions will be removed in the future, starting with SwiftyFORM 2.0.0
extension CharacterSetSpecification {
public static func alphanumericCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.alphanumerics
}
public static func capitalizedLetterCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.capitalizedLetters
}
public static func controlCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.controlCharacters
}
public static func decimalDigitCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.decimalDigits
}
public static func decomposableCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.decomposables
}
public static func illegalCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.illegalCharacters
}
public static func lowercaseLetterCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.lowercaseLetters
}
public static func newlineCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.newlines
}
public static func nonBaseCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.nonBaseCharacters
}
public static func punctuationCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.punctuationCharacters
}
public static func symbolCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.symbols
}
public static func uppercaseLetterCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.uppercaseLetters
}
public static func whitespaceCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.whitespaces
}
public static func whitespaceAndNewlineCharacterSet() -> CharacterSetSpecification {
CharacterSetSpecification.whitespacesAndNewlines
}
}
| mit | e897bb26e3c0f34bdac1f1037b118076 | 36.938272 | 111 | 0.822649 | 5.59745 | false | false | false | false |
PerfectServers/APIDocumentationServer | Sources/APIDocumentationServer/Models/Config.swift | 1 | 928 | //
// Config.swift
// APIDocumentationServer
//
// Created by Jonathan Guthrie on 2017-05-02.
//
//
import StORM
import PostgresStORM
import SwiftRandom
public class Config: PostgresStORM {
public var name = ""
public var val = ""
public static func getVal(_ key: String, _ def: String) -> String {
let this = Config()
do {
try this.get(key)
} catch {
print(error)
}
if this.val.isEmpty {
return def
}
return this.val
}
public static func runSetup() {
do {
let this = Config()
try this.setup()
} catch {
print(error)
}
}
override public func to(_ this: StORMRow) {
name = this.data["name"] as? String ?? ""
val = this.data["val"] as? String ?? ""
}
public func rows() -> [Config] {
var rows = [Config]()
for i in 0..<self.results.rows.count {
let row = Config()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
}
| apache-2.0 | 78babc88346de141a1763d9d2f7e8bb2 | 15.872727 | 68 | 0.599138 | 2.873065 | false | true | false | false |
DasilvaKareem/yum | ios/yum/yum/BaseUser.swift | 1 | 1464 | //
// BaseUser.swift
// yum
//
// Created by Keaton Burleson on 9/9/17.
// Copyright © 2017 poeen. All rights reserved.
//
import Foundation
import Firebase
class BaseUser: NSObject {
private(set) public var ref: DatabaseReference?
private(set) public var actualUser: User?
private(set) public var uid: String!
init(user: User, ref: DatabaseReference) {
self.actualUser = user
self.ref = ref
self.uid = user.uid
}
public func fetchUserType(completion: @escaping (_ userType: BaseUserType) -> Void) {
guard let solidReference = self.ref
else {
return
}
solidReference.child("accounts").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(self.uid) {
solidReference.child("accounts").child(self.uid).observeSingleEvent(of: .value, with: { (snapshot) in
let valueDictionary = snapshot.value as? NSDictionary
if (valueDictionary?["food-truck"] as? Bool ?? false) == true{
completion(.truck)
} else {
completion(.user)
}
})
} else {
solidReference.child("accounts/\(self.uid!)/food-truck").setValue(true)
completion(.user)
}
})
}
}
enum BaseUserType: Int {
case truck = 1
case user = 0
}
| mit | 056d4586d55075d3a879f62c5c73b462 | 28.26 | 117 | 0.55229 | 4.38024 | false | false | false | false |
mownier/photostream | Photostream/Modules/Comment Writer/Module/CommentWriterModule.swift | 1 | 1860 | //
// CommentWriterModule.swift
// Photostream
//
// Created by Mounir Ybanez on 30/11/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
protocol CommentWriterDelegate: BaseModuleDelegate {
func commentWriterDidFinish(with comment: CommentWriterData?)
func keyboardWillMoveUp(with delta: KeyboardFrameDelta)
func keyboardWillMoveDown(with delta: KeyboardFrameDelta)
}
protocol CommentWriterModuleInterface: BaseModuleInterface {
func writeComment(with content: String)
func addKeyboardObserver()
func removeKeyboardObserver()
}
protocol CommentWriterBuilder: BaseModuleBuilder {
func build(root: RootWireframe?, postId: String)
}
class CommentWriterModule: BaseModule, BaseModuleInteractable {
typealias ModuleView = CommentWriterScene
typealias ModuleInteractor = CommentWriterInteractor
typealias ModulePresenter = CommentWriterPresenter
typealias ModuleWireframe = CommentWriterWireframe
var view: ModuleView!
var interactor: ModuleInteractor!
var presenter: ModulePresenter!
var wireframe: ModuleWireframe!
required init(view: ModuleView) {
self.view = view
}
}
extension CommentWriterModule: CommentWriterBuilder {
func build(root: RootWireframe?) {
let service = CommentServiceProvider(session: AuthSession())
interactor = CommentWriterInteractor(service: service)
presenter = CommentWriterPresenter()
wireframe = CommentWriterWireframe(root: root)
interactor.output = presenter
view.presenter = presenter
presenter.interactor = interactor
presenter.view = view
presenter.wireframe = wireframe
}
func build(root: RootWireframe?, postId: String) {
build(root: root)
presenter.postId = postId
}
}
| mit | 2cfaf4b39699101e8469379fb601906a | 27.6 | 68 | 0.717052 | 5.326648 | false | false | false | false |
IsaoTakahashi/iOS-KaraokeSearch | KaraokeSearch/SetListViewController.swift | 1 | 7117 | //
// SetListViewController.swift
// KaraokeSearch
//
// Created by 高橋 勲 on 2015/05/20.
// Copyright (c) 2015年 高橋 勲. All rights reserved.
//
import UIKit
import Foundation
import CoreData
import SugarRecord
import MaterialKit
class SetListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//@IBOutlet weak var favSongTableView: UITableView!
@IBOutlet weak var setListTableView: UITableView!
@IBOutlet weak var filterButton: MKButton!
@IBOutlet weak var addButton: UIBarButtonItem!
var setLists = [SetList]()
func reloadSetLists() {
setLists.removeAll(keepCapacity: false)
let results: SugarRecordResults = SetList.all().sorted(by: "createdAt", ascending: false).find()
for result: AnyObject in results {
let setList = result as! SetList
setLists.append(setList)
}
setListTableView.reloadData()
}
func initializeSearchComponent() {
filterButton.maskEnabled = false
filterButton.ripplePercent = 0.5
filterButton.backgroundAniEnabled = false
filterButton.rippleLocation = .Center
filterButton.tintColor = UIColor.ButtonBKColor()
filterButton.enabled = false
}
func initializeFavSongTableComponent() {
setListTableView.delegate = self
setListTableView.dataSource = self
}
func refreshSearchComponent() {
//self.resultCountLabel.text = "\(self.songs.count)"
//self.sortButton.enabled = self.songs.count > 1
//self.filterButton.enabled = self.sortButton.enabled
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if setLists.count > 0 {
reloadSetLists()
refreshSearchComponent()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initializeSearchComponent()
initializeFavSongTableComponent()
addButton.tintColor = UIColor.whiteColor()
reloadSetLists()
refreshSearchComponent()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func insertSetList(title: String) {
var setList: SetList = SetList.create() as! SetList
setList.id = setLists.count;
setList.title = title
setList.createdAt = NSDate()
setList.updatedAt = NSDate()
let saved: Bool = setList.save()
if saved {
setLists.append(setList)
reloadSetLists()
}
}
func deleteSetList(setList: SetList!) {
setList.beginWriting().delete().endWriting()
}
func openCreateSetListAlert() {
let alert:UIAlertController = UIAlertController(title:"New Set List",
message: "",
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction:UIAlertAction = UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Cancel,
handler:{
(action:UIAlertAction!) -> Void in
println("Cancel")
})
let defaultAction:UIAlertAction = UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default,
handler:{
(action:UIAlertAction!) -> Void in
println("OK")
let textFields:Array<UITextField>? = alert.textFields as! Array<UITextField>?
if textFields != nil {
for textField:UITextField in textFields! {
//各textにアクセス
println(textField.text)
if !textField.text.isEmpty {
self.insertSetList(textField.text)
}
}
}
})
alert.addAction(cancelAction)
alert.addAction(defaultAction)
//textfiledの追加
alert.addTextFieldWithConfigurationHandler({(text:UITextField!) -> Void in
text.placeholder = "SetList Title"
})
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func clickAdd(sender: AnyObject) {
openCreateSetListAlert()
}
// MARK -- tableView
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SetListCell", forIndexPath: indexPath) as! UITableViewCell
//let song = songs[indexPath.row]
//cell.configureCell(song, atIndexPath: indexPath)
cell.textLabel?.text = setLists[indexPath.row].title
cell.textLabel?.textColor = UIColor.CellTextColor()
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return setLists.count
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
// // 編集
// let edit = UITableViewRowAction(style: .Normal, title: "Edit") {
// (action, indexPath) in
//
// self.itemArray[indexPath.row] += "!!"
// self.swipeTable.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// }
//
// edit.backgroundColor = UIColor.greenColor()
// 削除
let del = UITableViewRowAction(style: .Default, title: "Delete") {
(action, indexPath) in
var setList: SetList = self.setLists[indexPath.row]
self.deleteSetList(setList)
self.setLists.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
del.backgroundColor = UIColor.redColor()
// return [edit, del]
return [del]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "showSongInfo") {
}
}
}
| mit | 8ba098a308b390159596bf4fed8952d4 | 31.463303 | 148 | 0.605624 | 5.431312 | false | false | false | false |
alessiobrozzi/firefox-ios | Sync/Synchronizers/Bookmarks/BookmarksDownloader.swift | 2 | 7187 | /* 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 Storage
private let log = Logger.syncLogger
let BookmarksStorageVersion = 2
/**
* This is like a synchronizer, but it downloads records bit by bit, eventually
* notifying that the local storage is up to date with the server contents.
*
* Because batches might be separated over time, it's possible for the server
* state to change between calls. These state changes might include:
*
* 1. New changes arriving. This is fairly routine, but it's worth noting that
* changes might affect existing records that have been batched!
* 2. Wipes. The collection (or the server as a whole) might be deleted. This
* should be accompanied by a change in syncID in meta/global; it's the caller's
* responsibility to detect this.
* 3. A storage format change. This should be unfathomably rare, but if it happens
* we must also be prepared to discard our existing batched data.
* 4. TTL expiry. We need to do better about TTL handling in general, but here
* we might find that a downloaded record is no longer live by the time we
* come to apply it! This doesn't apply to bookmark records, so we will ignore
* it for the moment.
*
* Batch downloading without continuation tokens is achieved as follows:
*
* * A minimum timestamp is established. This starts as zero.
* * A fetch is issued against the server for records changed since that timestamp,
* ordered by modified time ascending, and limited to the batch size.
* * If the batch is complete, we flush it to storage and advance the minimum
* timestamp to just before the newest record in the batch. This ensures that
* a divided set of records with the same modified times will be downloaded
* entirely so long as the set is never larger than the batch size.
* * Iterate until we determine that there are no new records to fetch.
*
* Batch downloading with continuation tokens is much easier:
*
* * A minimum timestamp is established.
* * Make a request with limit=N.
* * Look for an X-Weave-Next-Offset header. Supply that in the next request.
* Also supply X-If-Unmodified-Since to avoid missed modifications.
*
* We do the latter, because we only support Sync 1.5. The use of the offset
* allows us to efficiently process batches, particularly those that contain
* large sets of records with the same timestamp. We still maintain the last
* modified timestamp to allow for resuming a batch in the case of a conflicting
* write, detected via X-I-U-S.
*/
public class BookmarksMirrorer {
private let downloader: BatchingDownloader<BookmarkBasePayload>
private let storage: BookmarkBufferStorage
private let batchSize: Int
private let statsSession: SyncEngineStatsSession
public init(storage: BookmarkBufferStorage, client: Sync15CollectionClient<BookmarkBasePayload>, basePrefs: Prefs, collection: String, statsSession: SyncEngineStatsSession, batchSize: Int=100) {
self.storage = storage
self.downloader = BatchingDownloader(collectionClient: client, basePrefs: basePrefs, collection: collection)
self.batchSize = batchSize
self.statsSession = statsSession
}
// TODO
public func storageFormatDidChange() {
}
// TODO
public func onWipeWasAppliedToStorage() {
}
private func applyRecordsFromBatcher() -> Success {
let retrieved = self.downloader.retrieve()
let invalid = retrieved.filter { !$0.payload.isValid() }
if !invalid.isEmpty {
// There's nothing we can do with invalid input. There's also no point in
// tracking failing GUIDs here yet: if another client reuploads those records
// correctly, we'll encounter them routinely due to a newer timestamp.
// The only improvement we could make is to drop records from the buffer if we
// happen to see a new, invalid one before somehow syncing again, but that's
// unlikely enough that it's not worth doing.
//
// Bug 1258801 tracks recording telemetry for these invalid items, which is
// why we don't simply drop them on the ground at the download stage.
//
// We might also choose to perform certain simple recovery actions here: for example,
// bookmarks with null URIs are clearly invalid, and could be treated as if they
// weren't present on the server, or transparently deleted.
log.warning("Invalid records: \(invalid.map { $0.id }.joined(separator: ", ")).")
}
let mirrorItems = retrieved.flatMap { record -> BookmarkMirrorItem? in
guard record.payload.isValid() else {
return nil
}
return (record.payload as MirrorItemable).toMirrorItem(record.modified)
}
if mirrorItems.isEmpty {
log.debug("Got empty batch.")
return succeed()
}
log.debug("Applying \(mirrorItems.count) downloaded bookmarks.")
return self.storage.applyRecords(mirrorItems)
}
public func go(info: InfoCollections, greenLight: @escaping () -> Bool) -> SyncResult {
if !greenLight() {
log.info("Green light turned red. Stopping mirror operation.")
return deferMaybe(SyncStatus.notStarted(.redLight))
}
log.debug("Downloading up to \(self.batchSize) records.")
return self.downloader.go(info, limit: self.batchSize)
.bind { result in
guard let end = result.successValue else {
log.warning("Got failure: \(result.failureValue!)")
return deferMaybe(result.failureValue!)
}
switch end {
case .complete:
log.info("Done with batched mirroring.")
return self.applyRecordsFromBatcher()
>>> effect(self.downloader.advance)
>>> self.storage.doneApplyingRecordsAfterDownload
>>> always(SyncStatus.completed(self.statsSession.end()))
case .incomplete:
log.debug("Running another batch.")
// This recursion is fine because Deferred always pushes callbacks onto a queue.
return self.applyRecordsFromBatcher()
>>> effect(self.downloader.advance)
>>> { self.go(info: info, greenLight: greenLight) }
case .interrupted:
log.info("Interrupted. Aborting batching this time.")
return deferMaybe(SyncStatus.partial)
case .noNewData:
log.info("No new data. No need to continue batching.")
self.downloader.advance()
return deferMaybe(SyncStatus.completed(self.statsSession.end()))
}
}
}
func advanceNextDownloadTimestampTo(timestamp: Timestamp) {
self.downloader.advanceTimestampTo(timestamp)
}
}
| mpl-2.0 | 494958832e564338592492098cb97fb6 | 45.367742 | 198 | 0.666203 | 4.849528 | false | false | false | false |
benlangmuir/swift | test/SymbolGraph/Symbols/Mixins/DeclarationFragments/Full/NominalTypes.swift | 13 | 7442 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name NominalTypes -emit-module -emit-module-path %t/
// RUN: %target-swift-symbolgraph-extract -module-name NominalTypes -I %t -pretty-print -output-dir %t
// RUN: %FileCheck %s --input-file %t/NominalTypes.symbols.json --check-prefix=STRUCT
// RUN: %FileCheck %s --input-file %t/NominalTypes.symbols.json --check-prefix=CLASS
// RUN: %FileCheck %s --input-file %t/NominalTypes.symbols.json --check-prefix=ENUM
// RUN: %FileCheck %s --input-file %t/NominalTypes.symbols.json --check-prefix=TYPEALIAS
public protocol P {}
@frozen public struct S<T> : P where T: Sequence {}
// STRUCT-LABEL: "precise": "s:12NominalTypes1SV",
// STRUCT: "declarationFragments": [
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "attribute",
// STRUCT-NEXT: "spelling": "@frozen"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": " "
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "keyword",
// STRUCT-NEXT: "spelling": "struct"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": " "
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "identifier",
// STRUCT-NEXT: "spelling": "S"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": "<"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "genericParameter",
// STRUCT-NEXT: "spelling": "T"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": "> "
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "keyword",
// STRUCT-NEXT: "spelling": "where"
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": " "
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "typeIdentifier",
// STRUCT-NEXT: "spelling": "T"
// STRUCT-NEXT: }
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "text",
// STRUCT-NEXT: "spelling": " : "
// STRUCT-NEXT: },
// STRUCT-NEXT: {
// STRUCT-NEXT: "kind": "typeIdentifier",
// STRUCT-NEXT: "spelling": "Sequence",
// STRUCT-NEXT: "preciseIdentifier": "s:ST"
// STRUCT-NEXT: }
// STRUCT-NEXT: ]
public class C<T> where T: Sequence {}
// CLASS-LABEL: "precise": "s:12NominalTypes1CC",
// CLASS: "declarationFragments": [
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "keyword",
// CLASS-NEXT: "spelling": "class"
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "text",
// CLASS-NEXT: "spelling": " "
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "identifier",
// CLASS-NEXT: "spelling": "C"
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "text",
// CLASS-NEXT: "spelling": "<"
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "genericParameter",
// CLASS-NEXT: "spelling": "T"
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "text",
// CLASS-NEXT: "spelling": "> "
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "keyword",
// CLASS-NEXT: "spelling": "where"
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "text",
// CLASS-NEXT: "spelling": " "
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "typeIdentifier",
// CLASS-NEXT: "spelling": "T"
// CLASS-NEXT: }
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "text",
// CLASS-NEXT: "spelling": " : "
// CLASS-NEXT: },
// CLASS-NEXT: {
// CLASS-NEXT: "kind": "typeIdentifier",
// CLASS-NEXT: "spelling": "Sequence",
// CLASS-NEXT: "preciseIdentifier": "s:ST"
// CLASS-NEXT: }
// CLASS-NEXT: ],
public enum E<T> where T: Sequence {}
// ENUM-LABEL: "precise": "s:12NominalTypes1EO",
// ENUM: "declarationFragments": [
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "keyword",
// ENUM-NEXT: "spelling": "enum"
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": " "
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "identifier",
// ENUM-NEXT: "spelling": "E"
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": "<"
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "genericParameter",
// ENUM-NEXT: "spelling": "T"
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": "> "
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "keyword",
// ENUM-NEXT: "spelling": "where"
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": " "
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "typeIdentifier",
// ENUM-NEXT: "spelling": "T"
// ENUM-NEXT: }
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "text",
// ENUM-NEXT: "spelling": " : "
// ENUM-NEXT: },
// ENUM-NEXT: {
// ENUM-NEXT: "kind": "typeIdentifier",
// ENUM-NEXT: "spelling": "Sequence",
// ENUM-NEXT: "preciseIdentifier": "s:ST"
// ENUM-NEXT: }
// ENUM-NEXT: ],
public typealias TA<T> = S<T> where T: Sequence
// TYPEALIAS-LABEL: "precise": "s:12NominalTypes2TAa",
// TYPEALIAS: "declarationFragments": [
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "keyword",
// TYPEALIAS-NEXT: "spelling": "typealias"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": " "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "identifier",
// TYPEALIAS-NEXT: "spelling": "TA"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": "<"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "genericParameter",
// TYPEALIAS-NEXT: "spelling": "T"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": "> = "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "typeIdentifier",
// TYPEALIAS-NEXT: "spelling": "S",
// TYPEALIAS-NEXT: "preciseIdentifier": "s:12NominalTypes1SV"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": "<"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "typeIdentifier",
// TYPEALIAS-NEXT: "spelling": "T"
// TYPEALIAS-NEXT: }
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": "> "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "keyword",
// TYPEALIAS-NEXT: "spelling": "where"
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": " "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "typeIdentifier",
// TYPEALIAS-NEXT: "spelling": "T"
// TYPEALIAS-NEXT: }
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "text",
// TYPEALIAS-NEXT: "spelling": " : "
// TYPEALIAS-NEXT: },
// TYPEALIAS-NEXT: {
// TYPEALIAS-NEXT: "kind": "typeIdentifier",
// TYPEALIAS-NEXT: "spelling": "Sequence",
// TYPEALIAS-NEXT: "preciseIdentifier": "s:ST"
// TYPEALIAS-NEXT: }
// TYPEALIAS-NEXT: ],
| apache-2.0 | 6bb643e0306cb17fbda05cc961fc1fc3 | 30.268908 | 102 | 0.558183 | 2.9357 | false | false | false | false |
accepton/accepton-apple | Pod/Classes/AcceptOnViewController/Views/ChoosePaymentForm/AcceptOnChoosePaymentTypeView.swift | 1 | 15892 | import UIKit
import PassKit
import BUYPaymentButtonPrivate
@objc protocol AcceptOnChoosePaymentTypeViewDelegate {
//Returns the payment method chosen such as 'paypal', 'credit_card', etc.
func choosePaymentTypeWasClicked(name: String)
}
//This view contains a listing of clickable payment types like 'paypal', 'applepay', etc. and sends
//a delegate event when one of them is pressed.
class AcceptOnChoosePaymentTypeView: UIView
{
//-----------------------------------------------------------------------------------------------------
//Properties
//-----------------------------------------------------------------------------------------------------
//List of available payment methods to display. Set when first initialized. Calls down
//to view creation methods
var _paymentMethods: [String]?
var paymentMethods: [String]! {
get { return _paymentMethods! }
set {
_paymentMethods = newValue
//As per apple docs, apple pay must be first
_paymentMethods?.sortInPlace({ (a, b) -> Bool in
if a == "apple_pay" { return true }
return false
})
updatePaymentMethodsInView()
}
}
//Notify the delegate when a payment type was selected
weak var delegate: AcceptOnChoosePaymentTypeViewDelegate?
//All the buttons are stored on a sub-view
var paymentMethodButtonsView: UIView?
var paymentMethodButtonsToName: [UIButton:String]! //Each button is bound to the payment name
var paymentMethodButtons: [UIButton]! //Holds the order of the buttons
var paymentMethodButtonAspectRatios: [Double]! //We need the aspect ratio of the embedded image
//"Select your preffered payment method"
lazy var headerLabel = UILabel()
//-----------------------------------------------------------------------------------------------------
//Constructors, Initializers, and UIView lifecycle
//-----------------------------------------------------------------------------------------------------
override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
required init(coder: NSCoder) {
super.init(coder: coder)!
defaultInit()
}
convenience init() {
self.init(frame: CGRectZero)
}
func defaultInit() {
//Add a header / title label
self.addSubview(headerLabel)
headerLabel.text = "Please select your preferred payment method"
headerLabel.numberOfLines = 2
headerLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
headerLabel.font = UIFont(name: "HelveticaNeue-Light", size: 24)
headerLabel.textAlignment = NSTextAlignment.Center
headerLabel.textColor = UIColor.whiteColor()
}
override func layoutSubviews() {
super.layoutSubviews()
}
var constraintsWereUpdated = false
override func updateConstraints() {
super.updateConstraints()
//Only run custom constraints once
if (constraintsWereUpdated) { return }
constraintsWereUpdated = true
//Put header on the top
headerLabel.snp_makeConstraints { make in
make.top.equalTo(self.snp_top).offset(0)
make.centerX.equalTo(self.snp_centerX)
make.width.equalTo(self.snp_width)
make.height.equalTo(80)
return
}
}
//-----------------------------------------------------------------------------------------------------
//Adding payment buttons if paymentMethods is set
//-----------------------------------------------------------------------------------------------------
func updatePaymentMethodsInView() {
//Remove the old buttons-view if it exists (may have called paymentMethods multiple
//times, but you probably shouldn't have and are doing something wrong)
paymentMethodButtons = []
paymentMethodButtonsToName = [:] //array's hold strong references to the views
paymentMethodButtonAspectRatios = []
paymentMethodButtonsView?.removeFromSuperview()
//Create a new buttons-view
paymentMethodButtonsView = UIView()
self.addSubview(paymentMethodButtonsView!)
paymentMethodButtonsView!.snp_makeConstraints { make in
make.top.equalTo(headerLabel.snp_bottom).offset(10)
make.bottom.equalTo(self.snp_bottom)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
return
}
//Add necessary buttons
for e in paymentMethods {
switch (e) {
case "paypal":
addPaypalButton()
case "credit_card":
addCreditCardButton()
case "apple_pay":
addApplePay()
default:
puts("Warning: Unrecognized payment type for the selector view: \(e)")
}
}
//The addXXX button functions did not actually set constraints
setButtonConstraints()
}
//Called near the end of updatePaymentMethodsInView to set constraints of newly added
//buttons
func setButtonConstraints() {
var lastTop: UIView = self.paymentMethodButtonsView!
let intraButtonVerticalSpace = 10
for (i, e) in paymentMethodButtons.enumerate() {
e.alpha = 0
e.snp_makeConstraints { make in
make.width.lessThanOrEqualTo(self.paymentMethodButtonsView!.snp_width)
//0th lastTop is the container, which we don't need to be equal to
if (i != 0) { make.width.equalTo(lastTop.snp_width) }
make.centerX.equalTo(lastTop.snp_centerX).priority(1000)
if i == 0 {
make.top.equalTo(lastTop.snp_top)
} else {
make.top.equalTo(lastTop.snp_bottom).offset(intraButtonVerticalSpace)
}
make.height.lessThanOrEqualTo(self.paymentMethodButtonsView!.snp_height).multipliedBy(Double(1)/Double(self.paymentMethodButtons.count)).offset(-intraButtonVerticalSpace)
make.width.equalTo(e.snp_height).multipliedBy(Double(self.paymentMethodButtonAspectRatios[i])).priority(1000)
make.width.lessThanOrEqualTo(self.snp_width).multipliedBy(0.8)
}
lastTop = e
}
}
func addPaypalButton() {
let button = AcceptOnPopButton()
paymentMethodButtonsView?.addSubview(button)
let image = AcceptOnBundle.UIImageNamed("checkout_with_paypal")
let imageView = UIImageView(image: image)
button.addSubview(imageView)
imageView.snp_makeConstraints { make in
make.margins.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
return
}
button.innerView = imageView
imageView.contentMode = UIViewContentMode.ScaleAspectFit
paymentMethodButtons.append(button)
paymentMethodButtonsToName[button] = "paypal"
paymentMethodButtonAspectRatios.append(Double(image!.size.width/image!.size.height))
button.addTarget(self, action: "paymentMethodButtonWasClicked:", forControlEvents:.TouchUpInside)
}
func addCreditCardButton() {
let button = AcceptOnPopButton()
paymentMethodButtonsView?.addSubview(button)
let image = AcceptOnBundle.UIImageNamed("checkout_with_credit")
let imageView = UIImageView(image: image)
button.addSubview(imageView)
imageView.snp_makeConstraints { make in
make.margins.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
return
}
button.innerView = imageView
imageView.contentMode = UIViewContentMode.ScaleAspectFit
paymentMethodButtons.append(button)
paymentMethodButtonsToName[button] = "credit_card"
paymentMethodButtonAspectRatios.append(Double(image!.size.width/image!.size.height))
button.addTarget(self, action: "paymentMethodButtonWasClicked:", forControlEvents:.TouchUpInside)
}
func addApplePay() {
// paymentMethodButtonsView?.addSubview(button)
// let image = AcceptOnBundle.UIImageNamed("checkout_with_apple_pay")
// let imageView = UIImageView(image: image)
// button.addSubview(imageView)
// imageView.snp_makeConstraints { make in
// make.margins.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
// return
// }
// button.innerView = imageView
// imageView.contentMode = UIViewContentMode.ScaleAspectFit
//Add an apple-pay button through the vector artwork
let button = AcceptOnPopButton()
let applePayImage = BUYPaymentButton(type: .Plain, style: .Black)
applePayImage.userInteractionEnabled = false
button.addSubview(applePayImage)
button.innerView = applePayImage
paymentMethodButtonsView?.addSubview(button)
paymentMethodButtons.append(button)
paymentMethodButtonsToName[button] = "apple_pay"
paymentMethodButtonAspectRatios.append(2.2)
button.addTarget(self, action: "paymentMethodButtonWasClicked:", forControlEvents:.TouchUpInside)
}
//-----------------------------------------------------------------------------------------------------
//Animation Helpers
//-----------------------------------------------------------------------------------------------------
var hasAnimatedPaymentButtonsIn: Bool = false
func animatePaymentButtonsIn() {
if (hasAnimatedPaymentButtonsIn) { return }
hasAnimatedPaymentButtonsIn = true
//Animate each button in with a slight delay
for (i, e) in paymentMethodButtons.enumerate() {
e.layer.transform = CATransform3DMakeTranslation(0, self.bounds.size.height, 0)
e.alpha = 1
UIView.animateWithDuration(0.8, delay: Double(i)*0.100, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: UIViewAnimationOptions.CurveEaseOut, animations: {
e.layer.transform = CATransform3DIdentity
}, completion: { res in
})
}
}
//Animates a single payment button as 'active' to the bottom and remove all other buttons
var lastExcept: String!
func animateButtonsOutExcept(name: String) {
self.userInteractionEnabled = false
//Retrieve the 'other' buttons that aren't the one selected & the selected button
let otherButtons = paymentMethodButtonsToName.filter {$0.1 != name}
let selectedButton = paymentMethodButtonsToName.filter {$0.1 == name}[0].0
//Animate buttons not selected out left
for (i, e) in otherButtons.enumerate() {
UIView.animateWithDuration(0.8, delay: Double(i)*0.15, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
e.0.alpha = 0
e.0.layer.transform = CATransform3DMakeTranslation(-self.bounds.size.width/8, 0, 0)
}) { res in
}
}
//Animate the header label out top
UIView.animateWithDuration(0.8, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.headerLabel.alpha = 0
self.headerLabel.layer.transform = CATransform3DMakeTranslation(0, -self.bounds.size.height/4, 0)
}) { res in
}
//Animate the selected button to the bottom
UIView.animateWithDuration(0.8, delay: Double(otherButtons.count)*0.3+0.2, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
//We need to adjust the button so that it's exactly half way to the bottom of this view and it's size is equal to some fraction of the total views width
//so first we get the bounds on the view so we can make calculations
let selectedButtonBounds = selectedButton.bounds
//We need to find the scaling factor of this button's width to make it X% of the total width of us (ChoosePaymentForm) because the button can be any size depending
//on the number of buttons that were shown but when the selected button comes up, it should always be the same size regardless of the number of buttons.
let selectedButtonScale = Double(selectedButtonBounds.size.width / self.bounds.size.width) //Will be < 1
//Now let's find the factor we need to scale selectedButtonScale by to yield X%. I.e. Find selectedButtonScale*scaleFactor = xPercent
let xPercent = 0.7
let selectedButtonScaleMultiplier = CGFloat(xPercent / selectedButtonScale)
//First apply the translation and then scale in place
var transform = CATransform3DIdentity
transform = CATransform3DTranslate(transform, 0, selectedButton.superview!.bounds.size.height-selectedButton.layer.position.y, 0)
transform = CATransform3DScale(transform, selectedButtonScaleMultiplier, selectedButtonScaleMultiplier, 1)
selectedButton.layer.transform = transform
}) { res in
}
lastExcept = name
}
//Animate all back in
func animateButtonsIn() {
self.userInteractionEnabled = true
//Retrieve the 'other' buttons that aren't the one selected & the selected button
let otherButtons = paymentMethodButtonsToName.filter {$0.1 != lastExcept}
let button = paymentMethodButtonsToName.filter {$0.1 == lastExcept}[0].0
UIView.animateWithDuration(0.8, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
button.layer.transform = CATransform3DIdentity
button.alpha = 1
}) { res in
}
for (i, e) in otherButtons.enumerate() {
UIView.animateWithDuration(0.8, delay: Double(i)*0.15+0.2, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
e.0.alpha = 1
e.0.layer.transform = CATransform3DIdentity
}) { res in
}
}
UIView.animateWithDuration(0.8, delay: 0.1, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.headerLabel.alpha = 1
self.headerLabel.layer.transform = CATransform3DIdentity
}) { res in
}
}
//-----------------------------------------------------------------------------------------------------
//Signal / Action Handlers
//-----------------------------------------------------------------------------------------------------
//User clicked on a payment method button
func paymentMethodButtonWasClicked(button: UIButton) {
//When we created the buttons, we added the actual UIView as a hash key
//mapping the button to the payment type. e.g. the
//paypal button was mapped to paymentMethodButtons[paypalButton] = "paypal"
if let paymentType = paymentMethodButtonsToName[button] {
delegate?.choosePaymentTypeWasClicked(paymentType)
return
}
puts("Warning: Payment method button was clicked '\(button)' but that wasn't bound to a name")
}
}
| mit | bfec8a7e72e1111730db504d78d22a4f | 45.063768 | 197 | 0.598351 | 5.512314 | false | false | false | false |
zhaobin19918183/zhaobinCode | HTK/HTK/NoteViewController/PhotosSelectView/PhotosSelectView.swift | 1 | 5223 | //
// PhotosSelectView.swift
// HTK
//
// Created by Zhao.bin on 16/6/12.
// Copyright © 2016年 赵斌. All rights reserved.
//
import UIKit
import Photos
class PhotosSelectView: UIView,UICollectionViewDelegate,UICollectionViewDataSource,popViewControllerDelegate
{
@IBOutlet weak var photosCollection: UICollectionView!
@IBOutlet var _photosSelectView: PhotosSelectView!
var photosSelectView = UIViewController()
var photosImageArray = NSMutableArray()
var didselectImageArray = NSMutableArray()
//资源库管理类
var assetsFetchResults = PHFetchResult<AnyObject>()
//保存照片集合
var PHIassets = PHImageManager()
var asset = PHAsset()
var options = PHFetchOptions()
var imageManager = PHImageManager()
var imageArray = NSMutableArray()
var selectedArray = NSMutableArray()
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)!
resetUILayout()
}
func resetUILayout()
{
Bundle.main.loadNibNamed("PhotosSelectView", owner:self,options:nil)
photosCollection.register(UINib(nibName: "PhotosCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCellID")
self.addSubview(_photosSelectView)
}
//MARK: 照片缓存
func photosUserDefaults()
{
assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil) as! PHFetchResult<AnyObject>
if assetsFetchResults.count != 0
{
for index in 1...assetsFetchResults.count
{
asset = assetsFetchResults[index - 1] as! PHAsset
imageManager.requestImage(for: asset, targetSize:PHImageManagerMaximumSize, contentMode: PHImageContentMode.aspectFit, options: nil) { (resultimage, info) in
let imageData = UIImagePNGRepresentation(resultimage!)
let base64String = imageData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue:0))
self.selectedArray.add(base64String)
let data : Data! = try? JSONSerialization.data(withJSONObject: self.selectedArray, options: [])
//NSData转换成NSString打印输出
let str = NSString(data:data, encoding: String.Encoding.utf8.rawValue)
UserDefaults.standard.set(str, forKey: "photos")
}
}
}
}
func popViewControllerPhotosArray(_ photosImageArray : NSMutableArray)
{
self.photosImageArray = photosImageArray
self.photosCollection.reloadData()
}
//MARK:CollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
if self.photosImageArray.count == 0 {
return 1
}
return self.photosImageArray.count + 1
}
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellID", for: indexPath) as? PhotosCollectionViewCell
if cell == nil
{
let nibArray = Bundle.main.loadNibNamed("PhotosCollectionViewCell", owner:self, options:nil) as
cell = nibArray.firstObject as? PhotosCollectionViewCell
}
if self.photosImageArray.count != 0 && (indexPath as NSIndexPath).row < self.photosImageArray.count{
cell?.backgroundImageView.image = self.photosImageArray.object(at: (indexPath as NSIndexPath).row ) as? UIImage
// print(indexPath.row)
cell?.delectButton.isHidden = false
cell?.delectButton.tag = (indexPath as NSIndexPath).row
cell?.delectButton.addTarget(self, action: #selector(PhotosSelectView.deleteImage(_:)), for: UIControlEvents.touchDown)
}
else
{
cell?.backgroundImageView.image = UIImage(named:"jiahao")
cell?.delectButton.isHidden = true
}
return cell!
}
func deleteImage(_ button:UIButton)
{
print(button.tag)
self.photosImageArray.remove(self.photosImageArray[button.tag])
self.photosCollection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
if (indexPath as NSIndexPath).row == self.photosImageArray.count
{
let loginView = PhotosSelectManager()
loginView.delegate = self
loginView.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha:0)
loginView.imageArray = self.photosImageArray
photosSelectView.present(loginView, animated: true, completion: nil)
}
}
}
| gpl-3.0 | c057ea80ac0838bb0d265bd978070685 | 33.932432 | 174 | 0.620696 | 5.459345 | false | false | false | false |
phatblat/realm-cocoa | RealmSwift/List.swift | 1 | 32315 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
extension RLMSwiftCollectionBase: Equatable {
public static func == (lhs: RLMSwiftCollectionBase, rhs: RLMSwiftCollectionBase) -> Bool {
return lhs.isEqual(rhs)
}
}
/**
`List` is the container type in Realm used to define to-many relationships.
Like Swift's `Array`, `List` is a generic type that is parameterized on the type it stores. This can be either an `Object`
subclass or one of the following types: `Bool`, `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`,
`String`, `Data`, `Date`, `Decimal128`, and `ObjectId` (and their optional versions)
Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them
is opened as read-only.
Lists can be filtered and sorted with the same predicates as `Results<Element>`.
Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`.
*/
public final class List<Element: RealmCollectionValue>: RLMSwiftCollectionBase {
// MARK: Properties
/// The Realm which manages the list, or `nil` if the list is unmanaged.
public var realm: Realm? {
return _rlmCollection.realm.map { Realm($0) }
}
/// Indicates if the list can no longer be accessed.
public var isInvalidated: Bool { return _rlmCollection.isInvalidated }
/// Contains the last accessed property names when tracing the key path.
internal var lastAccessedNames: NSMutableArray?
internal var rlmArray: RLMArray<AnyObject> {
_rlmCollection as! RLMArray
}
// MARK: Initializers
/// Creates a `List` that holds Realm model objects of type `Element`.
public override init() {
super.init()
}
internal init(objc rlmArray: RLMArray<AnyObject>) {
super.init(collection: rlmArray)
}
// MARK: Count
/// Returns the number of objects in this List.
public var count: Int { return Int(_rlmCollection.count) }
// MARK: Index Retrieval
/**
Returns the index of an object in the list, or `nil` if the object is not present.
- parameter object: An object to find.
*/
public func index(of object: Element) -> Int? {
return notFoundToNil(index: rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject))
}
/**
Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? {
return notFoundToNil(index: rlmArray.indexOfObject(with: predicate))
}
// MARK: Object Retrieval
/**
Returns the object at the given index (get), or replaces the object at the given index (set).
- warning: You can only set an object during a write transaction.
- parameter index: The index of the object to retrieve or replace.
*/
public subscript(position: Int) -> Element {
get {
if let lastAccessedNames = lastAccessedNames {
return Element._rlmKeyPathRecorder(with: lastAccessedNames)
}
throwForNegativeIndex(position)
return dynamicBridgeCast(fromObjectiveC: _rlmCollection.object(at: UInt(position)))
}
set {
throwForNegativeIndex(position)
rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject)
}
}
/// Returns the first object in the list, or `nil` if the list is empty.
public var first: Element? {
return rlmArray.firstObject().map(dynamicBridgeCast)
}
/// Returns the last object in the list, or `nil` if the list is empty.
public var last: Element? { return rlmArray.lastObject().map(dynamicBridgeCast) }
/**
Returns an array containing the objects in the array at the indexes specified by a given index set.
- warning Throws if an index supplied in the IndexSet is out of bounds.
- parameter indexes: The indexes in the list to select objects from.
*/
public func objects(at indexes: IndexSet) -> [Element] {
guard let r = rlmArray.objects(at: indexes) else {
throwRealmException("Indexes for List are out of bounds.")
}
return r.map(dynamicBridgeCast)
}
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's
objects.
*/
@nonobjc public func value(forKey key: String) -> [AnyObject] {
return rlmArray.value(forKeyPath: key)! as! [AnyObject]
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
@nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] {
return rlmArray.value(forKeyPath: keyPath) as! [AnyObject]
}
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(_ value: Any?, forKey key: String) {
return rlmArray.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the list.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> {
return Results<Element>(_rlmCollection.objects(with: predicate))
}
// MARK: Sorting
/**
Returns a `Results` containing the objects in the list, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing the objects in the list, but sorted.
- warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return Results<Element>(_rlmCollection.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is
empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return _rlmCollection.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list
is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose maximum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return _rlmCollection.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the objects in the list.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T {
return dynamicBridgeCast(fromObjectiveC: _rlmCollection.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<T: AddableType>(ofProperty property: String) -> T? {
return _rlmCollection.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Mutation
/**
Appends the given object to the end of the list.
If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing
the receiver.
- warning: This method may only be called during a write transaction.
- parameter object: An object.
*/
public func append(_ object: Element) {
rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Appends the objects in the given sequence to the end of the list.
- warning: This method may only be called during a write transaction.
*/
public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element {
for obj in objects {
rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject)
}
}
/**
Inserts an object at the given index.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter object: An object.
- parameter index: The index at which to insert the object.
*/
public func insert(_ object: Element, at index: Int) {
throwForNegativeIndex(index)
rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index))
}
/**
Removes an object at the given index. The object is not removed from the Realm that manages it.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter index: The index at which to remove the object.
*/
public func remove(at index: Int) {
throwForNegativeIndex(index)
rlmArray.removeObject(at: UInt(index))
}
/**
Removes all objects from the list. The objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeAll() {
rlmArray.removeAllObjects()
}
/**
Replaces an object at the given index with a new object.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with an invalid index.
- parameter index: The index of the object to be replaced.
- parameter object: An object.
*/
public func replace(index: Int, object: Element) {
throwForNegativeIndex(index)
rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Moves the object at the given source index to the given destination index.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with invalid indices.
- parameter from: The index of the object to be moved.
- parameter to: index to which the object at `from` should be moved.
*/
public func move(from: Int, to: Int) {
throwForNegativeIndex(from)
throwForNegativeIndex(to)
rlmArray.moveObject(at: UInt(from), to: UInt(to))
}
/**
Exchanges the objects in the list at given indices.
- warning: This method may only be called during a write transaction.
- warning: This method will throw an exception if called with invalid indices.
- parameter index1: The index of the object which should replace the object at index `index2`.
- parameter index2: The index of the object which should replace the object at index `index1`.
*/
public func swapAt(_ index1: Int, _ index2: Int) {
throwForNegativeIndex(index1, parameterName: "index1")
throwForNegativeIndex(index2, parameterName: "index2")
rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2))
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
class Person: Object {
@Persisted var dogs: List<Dog>
}
// ...
let dogs = person.dogs
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(on queue: DispatchQueue? = nil,
_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken {
return rlmArray.addNotificationBlock(wrapObserveBlock(block), queue: queue)
}
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
class Person: Object {
@Persisted var dogs: List<Dog>
}
// ...
let dogs = person.dogs
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Person: Object {
@Persisted var dogs: List<Dog>
}
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
@Persisted var toys: List<Toy>
}
// ...
let dogs = person.dogs
let token = dogs.observe(keyPaths: ["name"]) { changes in
switch changes {
case .initial(let dogs):
// ...
case .update:
// This case is hit:
// - after the token is intialized
// - when the name property of an object in the
// collection is modified
// - when an element is inserted or removed
// from the collection.
// This block is not triggered:
// - when a value other than name is modified on
// one of the elements.
case .error:
// ...
}
}
// end of run loop execution context
```
- If the observed key path were `["toys.brand"]`, then any insertion or
deletion to the `toys` list on any of the collection's elements would trigger the block.
Changes to the `brand` value on any `Toy` that is linked to a `Dog` in this
collection will trigger the block. Changes to a value other than `brand` on any `Toy` that
is linked to a `Dog` in this collection would not trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would also trigger a notification.
- If the above example observed the `["toys"]` key path, then any insertion,
deletion, or modification to the `toys` list for any element in the collection
would trigger the block.
Changes to any value on any `Toy` that is linked to a `Dog` in this collection
would *not* trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would still trigger a notification.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(keyPaths: [String]? = nil,
on queue: DispatchQueue? = nil,
_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken {
return rlmArray.addNotificationBlock(wrapObserveBlock(block), keyPaths: keyPaths, queue: queue)
}
// MARK: Frozen Objects
public var isFrozen: Bool {
return _rlmCollection.isFrozen
}
public func freeze() -> List {
return List(objc: rlmArray.freeze())
}
public func thaw() -> List? {
return List(objc: rlmArray.thaw())
}
// swiftlint:disable:next identifier_name
@objc class func _unmanagedCollection() -> RLMArray<AnyObject> {
if let type = Element.self as? ObjectBase.Type {
return RLMArray(objectClassName: type.className())
}
return RLMArray(objectType: Element._rlmType, optional: Element._rlmOptional)
}
/// :nodoc:
@objc public override class func _backingCollectionType() -> AnyClass {
return RLMManagedArray.self
}
// Printable requires a description property defined in Swift (and not obj-c),
// and it has to be defined as override, which can't be done in a
// generic class.
/// Returns a human-readable description of the objects contained in the List.
@objc public override var description: String {
return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
}
@objc private func descriptionWithMaxDepth(_ depth: UInt) -> String {
return RLMDescriptionWithMaxDepth("List", _rlmCollection, depth)
}
}
extension List where Element: MinMaxType {
/**
Returns the minimum (lowest) value in the list, or `nil` if the list is empty.
*/
public func min() -> Element? {
return _rlmCollection.min(ofProperty: "self").map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value in the list, or `nil` if the list is empty.
*/
public func max() -> Element? {
return _rlmCollection.max(ofProperty: "self").map(dynamicBridgeCast)
}
}
extension List where Element: AddableType {
/**
Returns the sum of the values in the list.
*/
public func sum() -> Element {
return sum(ofProperty: "self")
}
/**
Returns the average of the values in the list, or `nil` if the list is empty.
*/
public func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
extension List: RealmCollection {
/// The type of the objects stored within the list.
public typealias ElementType = Element
// MARK: Sequence Support
/// Returns a `RLMIterator` that yields successive elements in the `List`.
public func makeIterator() -> RLMIterator<Element> {
return RLMIterator(collection: _rlmCollection)
}
/**
Replace the given `subRange` of elements with `newElements`.
- parameter subrange: The range of elements to be replaced.
- parameter newElements: The new elements to be inserted into the List.
*/
public func replaceSubrange<C: Collection, R>(_ subrange: R, with newElements: C)
where C.Iterator.Element == Element, R: RangeExpression, List<Element>.Index == R.Bound {
let subrange = subrange.relative(to: self)
for _ in subrange.lowerBound..<subrange.upperBound {
remove(at: subrange.lowerBound)
}
for x in newElements.reversed() {
insert(x, at: subrange.lowerBound)
}
}
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// :nodoc:
public func _observe(_ keyPaths: [String]?,
_ queue: DispatchQueue?,
_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void)
-> NotificationToken {
return rlmArray.addNotificationBlock(wrapObserveBlock(block), keyPaths: keyPaths, queue: queue)
}
}
// MARK: - MutableCollection conformance, range replaceable collection emulation
extension List: MutableCollection {
public typealias SubSequence = Slice<List>
/**
Returns the objects at the given range (get), or replaces the objects at the
given range with new objects (set).
- warning: Objects may only be set during a write transaction.
- parameter index: The index of the object to retrieve or replace.
*/
public subscript(bounds: Range<Int>) -> SubSequence {
get {
return SubSequence(base: self, bounds: bounds)
}
set {
replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue)
}
}
/**
Removes the specified number of objects from the beginning of the list. The
objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeFirst(_ number: Int = 1) {
throwForNegativeIndex(number)
let count = Int(_rlmCollection.count)
guard number <= count else {
throwRealmException("It is not possible to remove more objects (\(number)) from a list"
+ " than it already contains (\(count)).")
}
for _ in 0..<number {
rlmArray.removeObject(at: 0)
}
}
/**
Removes the specified number of objects from the end of the list. The objects
are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeLast(_ number: Int = 1) {
throwForNegativeIndex(number)
let count = Int(_rlmCollection.count)
guard number <= count else {
throwRealmException("It is not possible to remove more objects (\(number)) from a list"
+ " than it already contains (\(count)).")
}
for _ in 0..<number {
rlmArray.removeLastObject()
}
}
/**
Inserts the items in the given collection into the list at the given position.
- warning: This method may only be called during a write transaction.
*/
public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element {
var currentIndex = i
for item in newElements {
insert(item, at: currentIndex)
currentIndex += 1
}
}
/**
Removes objects from the list at the given range.
- warning: This method may only be called during a write transaction.
*/
public func removeSubrange<R>(_ boundsExpression: R) where R: RangeExpression, List<Element>.Index == R.Bound {
let bounds = boundsExpression.relative(to: self)
for _ in bounds {
remove(at: bounds.lowerBound)
}
}
/// :nodoc:
public func remove(atOffsets offsets: IndexSet) {
for offset in offsets.reversed() {
remove(at: offset)
}
}
/// :nodoc:
public func move(fromOffsets offsets: IndexSet, toOffset destination: Int) {
for offset in offsets {
var d = destination
if destination >= count {
d = destination - 1
}
move(from: offset, to: d)
}
}
}
// MARK: - Codable
extension List: Decodable where Element: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
append(try container.decode(Element.self))
}
}
}
extension List: Encodable where Element: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for value in self {
try container.encode(value)
}
}
}
// MARK: - AssistedObjectiveCBridgeable
extension List: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List {
guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() }
return List(objc: objectiveCValue)
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: _rlmCollection, metadata: nil)
}
}
// MARK: Key Path Strings
extension List: PropertyNameConvertible {
var propertyInformation: (key: String, isLegacy: Bool)? {
return (key: rlmArray.propertyKey, isLegacy: rlmArray.isLegacyProperty)
}
}
| apache-2.0 | ebe48f55ca4515d95523a1ff64109169 | 37.654306 | 123 | 0.657156 | 4.811644 | false | false | false | false |
jkolb/Swiftish | Sources/Swiftish/Transform3.swift | 1 | 3093 | /*
The MIT License (MIT)
Copyright (c) 2015-2017 Justin Kolb
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.
*/
public struct Transform3<T: Vectorable> : Hashable, CustomStringConvertible {
public var translation: Vector3<T>
public var rotation: Quaternion<T>
public var scale: Vector3<T>
public init(translation: Vector3<T> = Vector3<T>(), rotation: Quaternion<T> = Quaternion<T>(), scale: Vector3<T> = Vector3<T>(1)) {
self.translation = translation
self.rotation = rotation
self.scale = scale
}
public var isIdentity: Bool {
return !hasTranslation && !hasRotation && !hasScale
}
public var hasScale: Bool {
return scale != Vector3<T>(1)
}
public var hasRotation: Bool {
return rotation != Quaternion<T>()
}
public var hasTranslation: Bool {
return translation != Vector3<T>()
}
public var description: String {
return "{\(translation), \(rotation), \(scale)}"
}
public var inverse: Transform3<T> {
return Transform3<T>(translation: -translation, rotation: Quaternion<T>.conjugate(rotation), scale: 1 / scale)
}
public var matrix: Matrix4x4<T> {
let rs = rotation.matrix * Matrix3x3<T>(scale)
return Matrix4x4<T>(
Vector4<T>(rs[0]),
Vector4<T>(rs[1]),
Vector4<T>(rs[2]),
Vector4<T>(translation, 1)
)
}
public var inverseMatrix: Matrix4x4<T> {
let sri = Matrix3x3<T>(1 / scale) * rotation.matrix.transpose
let ti = sri * -translation
return Matrix4x4<T>(
Vector4<T>(sri[0]),
Vector4<T>(sri[1]),
Vector4<T>(sri[2]),
Vector4<T>(ti, 1)
)
}
public static func +(a: Transform3<T>, b: Transform3<T>) -> Transform3<T> {
return Transform3<T>(
translation: a.rotation * b.translation * a.scale + a.translation,
rotation: a.rotation * b.rotation,
scale: a.scale * b.scale
)
}
}
| mit | a19973be0528d497d86bf3be7a92fd30 | 33.366667 | 135 | 0.640802 | 4.157258 | false | false | false | false |
OscarSwanros/swift | test/IRGen/associated_type_witness.swift | 2 | 11832 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir > %t.ll
// RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll
// RUN: %FileCheck %s < %t.ll
// REQUIRES: CPU=x86_64
protocol P {}
protocol Q {}
protocol Assocked {
associatedtype Assoc : P, Q
}
struct Universal : P, Q {}
// Witness table access functions for Universal : P and Universal : Q.
// CHECK-LABEL: define hidden i8** @_T023associated_type_witness9UniversalVAA1PAAWa()
// CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T023associated_type_witness9UniversalVAA1PAAWP, i32 0, i32 0)
// CHECK-LABEL: define hidden i8** @_T023associated_type_witness9UniversalVAA1QAAWa()
// CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_T023associated_type_witness9UniversalVAA1QAAWP, i32 0, i32 0)
// Witness table for WithUniversal : Assocked.
// GLOBAL-LABEL: @_T023associated_type_witness13WithUniversalVAA8AssockedAAWP = hidden constant [3 x i8*] [
// GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_T023associated_type_witness9UniversalVMa to i8*)
// GLOBAL-SAME: i8* bitcast (i8** ()* @_T023associated_type_witness9UniversalVAA1PAAWa to i8*)
// GLOBAL-SAME: i8* bitcast (i8** ()* @_T023associated_type_witness9UniversalVAA1QAAWa to i8*)
// GLOBAL-SAME: ]
struct WithUniversal : Assocked {
typealias Assoc = Universal
}
// Witness table for GenericWithUniversal : Assocked.
// GLOBAL-LABEL: @_T023associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAWP = hidden constant [3 x i8*] [
// GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_T023associated_type_witness9UniversalVMa to i8*)
// GLOBAL-SAME: i8* bitcast (i8** ()* @_T023associated_type_witness9UniversalVAA1PAAWa to i8*)
// GLOBAL-SAME: i8* bitcast (i8** ()* @_T023associated_type_witness9UniversalVAA1QAAWa to i8*)
// GLOBAL-SAME: ]
struct GenericWithUniversal<T> : Assocked {
typealias Assoc = Universal
}
// Witness table for Fulfilled : Assocked.
// GLOBAL-LABEL: @_T023associated_type_witness9FulfilledVyxGAA8AssockedAAWP = hidden constant [3 x i8*] [
// GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocWt to i8*)
// GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5Assoc_AA1PPWT to i8*)
// GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5Assoc_AA1QPWT to i8*)
// GLOBAL-SAME: ]
struct Fulfilled<T : P & Q> : Assocked {
typealias Assoc = T
}
// Associated type metadata access function for Fulfilled.Assoc.
// CHECK-LABEL: define internal %swift.type* @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocWt(%swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked")
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to %swift.type**
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 2
// CHECK-NEXT: [[T2:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load
// CHECK-NEXT: ret %swift.type* [[T2]]
// Associated type witness table access function for Fulfilled.Assoc : P.
// CHECK-LABEL: define internal i8** @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5Assoc_AA1PPWT(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked")
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8***
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 3
// CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load
// CHECK-NEXT: ret i8** [[T2]]
// Associated type witness table access function for Fulfilled.Assoc : Q.
// CHECK-LABEL: define internal i8** @_T023associated_type_witness9FulfilledVyxGAA8AssockedAA5Assoc_AA1QPWT(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked")
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8***
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4
// CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load
// CHECK-NEXT: ret i8** [[T2]]
struct Pair<T, U> : P, Q {}
// Generic witness table pattern for Computed : Assocked.
// GLOBAL-LABEL: @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWP = hidden constant [3 x i8*] [
// GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAA5AssocWt to i8*)
// GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1PPWT to i8*)
// GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1QPWT to i8*)
// GLOBAL-SAME: ]
// Generic witness table cache for Computed : Assocked.
// GLOBAL-LABEL: @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWG = internal constant %swift.generic_witness_table_cache {
// GLOBAL-SAME: i16 3,
// GLOBAL-SAME: i16 1,
// Relative reference to protocol
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_T023associated_type_witness8AssockedMp to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWG, i32 0, i32 2) to i64)) to i32
// Relative reference to witness table template
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x i8*]* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWP to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWG, i32 0, i32 3) to i64)) to i32),
// No instantiator function
// GLOBAL-SAME: i32 0,
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([16 x i8*]* [[PRIVATE:@.*]] to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAAWG, i32 0, i32 5) to i64)) to i32)
// GLOBAL-SAME: }
// GLOBAL: [[PRIVATE]] = internal global [16 x i8*] zeroinitializer
struct Computed<T, U> : Assocked {
typealias Assoc = Pair<T, U>
}
// Associated type metadata access function for Computed.Assoc.
// CHECK-LABEL: define internal %swift.type* @_T023associated_type_witness8ComputedVyxq_GAA8AssockedAA5AssocWt(%swift.type* %"Computed<T, U>", i8** %"Computed<T, U>.Assocked")
// CHECK: entry:
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** %"Computed<T, U>.Assocked", i32 -1
// CHECK-NEXT: [[CACHE:%.*]] = bitcast i8** [[T0]] to %swift.type**
// CHECK-NEXT: [[CACHE_RESULT:%.*]] = load %swift.type*, %swift.type** [[CACHE]], align 8
// CHECK-NEXT: [[T1:%.*]] = icmp eq %swift.type* [[CACHE_RESULT]], null
// CHECK-NEXT: br i1 [[T1]], label %fetch, label %cont
// CHECK: cont:
// CHECK-NEXT: [[T0:%.*]] = phi %swift.type* [ [[CACHE_RESULT]], %entry ], [ [[FETCH_RESULT:%.*]], %fetch ]
// CHECK-NEXT: ret %swift.type* [[T0]]
// CHECK: fetch:
// CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type**
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 2
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type**
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 3
// CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load
// CHECK-NEXT: [[FETCH_RESULT]] = call %swift.type* @_T023associated_type_witness4PairVMa(%swift.type* [[T]], %swift.type* [[U]])
// CHECK-NEXT: store atomic %swift.type* [[FETCH_RESULT]], %swift.type** [[CACHE]] release, align 8
// CHECK-NEXT: br label %cont
// Witness table instantiation function for Computed : Assocked.
// CHECK-LABEL: define hidden i8** @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWa(%swift.type*)
// CHECK: entry:
// CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG, %swift.type* %0, i8** null)
// CHECK-NEXT: ret i8** [[WTABLE]]
struct PBox<T: P> {}
protocol HasSimpleAssoc {
associatedtype Assoc
}
protocol DerivedFromSimpleAssoc : HasSimpleAssoc {}
// Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc.
// GLOBAL-LABEL: @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWP = hidden constant [1 x i8*] zeroinitializer
// Generic witness table cache for GenericComputed : DerivedFromSimpleAssoc.
// GLOBAL-LABEL: @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG = internal constant %swift.generic_witness_table_cache {
// GLOBAL-SAME: i16 1,
// GLOBAL-SAME: i16 0,
// Relative reference to protocol
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_T023associated_type_witness22DerivedFromSimpleAssocMp to i64),
// Relative reference to witness table template
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x i8*]* @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWP to i64)
// Relative reference to instantiator function
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG, i32 0, i32 4) to i64)) to i32)
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([16 x i8*]* @1 to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWG, i32 0, i32 5) to i64)) to i32)
// GLOBAL-SAME: }
struct GenericComputed<T: P> : DerivedFromSimpleAssoc {
typealias Assoc = PBox<T>
}
// Instantiation function for GenericComputed : DerivedFromSimpleAssoc.
// CHECK-LABEL: define internal void @_T023associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI(i8**, %swift.type*, i8**)
// CHECK: [[T0:%.*]] = call i8** @_T023associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWa(%swift.type* %1)
// CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8*
// CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 0
// CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8
// CHECK-NEXT: ret void
// Witness table instantiation function for GenericComputed : HasSimpleAssoc..
// CHECK-LABEL: define hidden i8** @_T023associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWa(%swift.type*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_T023associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAWG, %swift.type* %0, i8** null)
// CHECK-NEXT: ret i8** %1
protocol HasAssocked {
associatedtype Contents : Assocked
}
struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc {
typealias Assoc = PBox<T.Contents.Assoc>
}
struct UsesVoid : HasSimpleAssoc {
typealias Assoc = ()
}
| apache-2.0 | ae5f6d4680f2896447c29933bb13e0e9 | 66.227273 | 403 | 0.699375 | 3.425594 | false | false | false | false |
OscarSwanros/swift | test/Driver/subcommands.swift | 17 | 1906 | // Check that 'swift' and 'swift repl' invoke the REPL.
//
// REQUIRES: swift_interpreter
//
// RUN: rm -rf %t.dir
// RUN: mkdir -p %t.dir/usr/bin
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t.dir/usr/bin/swift)
// RUN: %t.dir/usr/bin/swift -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
// RUN: %t.dir/usr/bin/swift repl -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-INVOKES-REPL %s
//
// CHECK-SWIFT-INVOKES-REPL: {{.*}}/swift -frontend -repl
// Check that 'swift -', 'swift t.swift', and 'swift /path/to/file' invoke the interpreter
// (for shebang line use). We have to run these since we can't get the driver to
// dump what it is doing and test the argv[1] processing.
//
// RUN: %empty-directory(%t.dir)
// RUN: %empty-directory(%t.dir/subpath)
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/stdin
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/t.swift
// RUN: echo "print(\"exec: \" + #file)" > %t.dir/subpath/build
// RUN: cd %t.dir && %swift_driver_plain - < %t.dir/stdin -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-STDIN-INVOKES-INTERPRETER %s
// CHECK-SWIFT-STDIN-INVOKES-INTERPRETER: exec: <stdin>
// RUN: cd %t.dir && %swift_driver_plain t.swift -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER %s
// CHECK-SWIFT-SUFFIX-INVOKES-INTERPRETER: exec: t.swift
// RUN: cd %t.dir && %swift_driver_plain subpath/build -### 2>&1 | %FileCheck -check-prefix=CHECK-SWIFT-PATH-INVOKES-INTERPRETER %s
// CHECK-SWIFT-PATH-INVOKES-INTERPRETER: exec: subpath/build
// Check that 'swift foo' invokes 'swift-foo'.
//
// RUN: %empty-directory(%t.dir)
// RUN: echo "#!/bin/sh" > %t.dir/swift-foo
// RUN: echo "echo \"exec: \$0\"" >> %t.dir/swift-foo
// RUN: chmod +x %t.dir/swift-foo
// RUN: env PATH=%t.dir %swift_driver_plain foo | %FileCheck -check-prefix=CHECK-SWIFT-SUBCOMMAND %s
// CHECK-SWIFT-SUBCOMMAND: exec: {{.*}}/swift-foo
| apache-2.0 | 4dace4c0b4f46479d3e46c5894171eb2 | 47.871795 | 135 | 0.658972 | 2.879154 | false | false | false | false |
jonnguy/HSTracker | HSTracker/Utility/BoardDamage/BoardCard.swift | 2 | 4212 | //
// BoardCard.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/06/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
class BoardCard: IBoardEntity {
private var _armor = 0
private var _cantAttack = false
private var _damageTaken = 0
private var _durability = 0
private var _frozen = false
private var _health = 0
private var _stdAttack = 0
private(set) var cardId = ""
private(set) var taunt = false
private(set) var charge = false
private(set) var windfury = false
private(set) var cardType = ""
private(set) var name = ""
private(set) var attack = 0
private(set) var health = 0
private(set) var include = false
private(set) var attacksThisTurn = 0
private(set) var exhausted = false
private(set) var zone = ""
init(entity: Entity, active: Bool = true) {
let card = Cards.by(cardId: entity.cardId)
let cardName = card != nil ? card!.name : ""
name = entity.name.isBlank ? cardName : entity.name!
_stdAttack = entity.has(tag: .hide_stats) ? 0 : entity[.atk]
_health = entity.has(tag: .hide_stats) ? 0 : entity[.health]
_armor = entity[.armor]
_durability = entity[.durability]
_damageTaken = entity[.damage]
exhausted = entity[.exhausted] == 1
_cantAttack = entity[.cant_attack] == 1
_frozen = entity[.frozen] == 1
charge = entity[.charge] == 1
windfury = entity[.windfury] == 1
attacksThisTurn = entity[.num_attacks_this_turn]
cardId = entity.cardId
taunt = entity[.taunt] == 1
if let _zone = Zone(rawValue: entity[.zone]) {
zone = "\(_zone)"
}
if let _cardType = CardType(rawValue: entity[.cardtype]) {
cardType = "\(_cardType)"
}
health = calculateHealth(isWeapon: entity.isWeapon)
attack = calculateAttack(active: active, isWeapon: entity.isWeapon)
include = isAbleToAttack(active: active, isWeapon: entity.isWeapon)
}
private func calculateHealth(isWeapon: Bool) -> Int {
return isWeapon ? _durability - _damageTaken : _health + _armor - _damageTaken
}
private func calculateAttack(active: Bool, isWeapon: Bool) -> Int {
// V-07-TR-0N is a special case Mega-Windfury
if !cardId.isBlank && cardId == "GVG_111t" {
return V07TRONAttack(active: active)
}
// for weapons check for windfury and number of hits left
if isWeapon {
if windfury && health >= 2 && attacksThisTurn == 0 {
return _stdAttack * 2
}
}
// for minions with windfury that haven't already attacked, double attack
else if windfury && (!active || attacksThisTurn == 0) {
return _stdAttack * 2
}
return _stdAttack
}
private func isAbleToAttack(active: Bool, isWeapon: Bool) -> Bool {
// TODO: if frozen on turn, may be able to attack next turn
// don't include weapons if an active turn, count Hero instead
if _cantAttack || _frozen || (isWeapon && active) {
return false
}
if !active {
// include everything that can attack if not an active turn
return true
}
if exhausted {
// newly played card could be given charge
return charge && attacksThisTurn == 0
}
// sometimes cards seem to be in wrong zone while in play,
// these cards don't become exhausted, so check attacks.
if zone.lowercased() == "deck" || zone.lowercased() == "hand" {
return (!windfury || attacksThisTurn < 2) && (windfury || attacksThisTurn < 1)
}
return true
}
private func V07TRONAttack(active: Bool) -> Int {
guard active else {
return _stdAttack * 4
}
switch attacksThisTurn {
case 0: return _stdAttack * 4
case 1: return _stdAttack * 3
case 2: return _stdAttack * 2
default: return _stdAttack
}
}
}
| mit | 2a8958a2ea896dd39085be17de01ce4d | 32.959677 | 90 | 0.574448 | 4.470276 | false | false | false | false |
tdkirtland/SwiftStandardLibrary | Sources/LinkedList.swift | 1 | 6214 | //
// LinkedList.swift
// SwiftStandardLibrary
//
// Created by Tyler Kirtland on 9/27/17.
// Copyright © 2017 Tyler Kirtland. All rights reserved.
//
import Foundation
/// A Linked List data structure
public struct LinkedList<Element>: Sequence, ExpressibleByArrayLiteral {
public typealias Iterator = LinkedListIterator<Element>
/// A container for each element in the `LinkedList`
internal class Node<Element> {
/// The next element in the list, `nil` if it is the end of the list
var next: Node<Element>?
/// The previous element in the list, `nil` if is is the beginning of the list
weak var previous: Node<Element>?
/// The value of the current element in the list
var value: Element
/// Initialize a `Node` with a value and previous and next `Node`s if they exist
///
/// - Parameters:
/// - value: The value for the element in the list
/// - previous: The previous `Node` in the list
/// - next: The next `Node` in the list
init(value: Element, previous: Node<Element>? = nil, next: Node<Element>? = nil) {
self.value = value
self.previous = previous
self.next = next
}
}
private var front: Node<Element>?
private var back: Node<Element>?
/// The number of elements in the list
public private(set) var count: Int = 0
/// `true` if there are no elements in the list
public var isEmpty: Bool {
return count == 0
}
/// The first item in the list, `nil` if there are no elements
public var first: Element? {
return front?.value
}
/// The last item in the list, `nil` if there are no elements
public var last: Element? {
return back?.value
}
/// Initializes the list with elements from an array
///
/// - Parameter elements: An array of elements to insert into the list
public init(arrayLiteral elements: Element...) {
for item in elements {
append(item)
}
}
/// Inserts an element at the end of the list
///
/// - Parameter value: The value to insert
public mutating func append(_ value: Element) {
count += 1
let node = Node(value: value)
guard back != nil else {
front = node
back = node
return
}
back?.next = node
node.previous = back
back = node
}
/// Inserts an element at the beginning of the list
///
/// - Parameter value: The value to insert
public mutating func prepend(_ value: Element) {
count += 1
let node = Node(value: value)
guard front != nil else {
front = node
back = node
return
}
node.next = front
front?.previous = node
front = node
}
/// Inserts an element at a given index in the array
///
/// - Parameters:
/// - index: The index to insert the item
/// - value: The value to insert
public mutating func insert(at index: Int, value: Element) {
guard index > 0 else {
prepend(value)
return
}
if index == count {
append(value)
return
}
var node = front
for _ in 0..<(index - 1) {
node = node?.next
}
let newNode = Node(value: value)
let oldNext = node?.next
node?.next = newNode
newNode.previous = node
newNode.next = oldNext
oldNext?.previous = newNode
}
/// Removes the first element in the list
///
/// - Returns: The value of the first element in the list, `nil` if empty
public mutating func removeFirst() -> Element? {
count = Swift.max(count - 1, 0)
let value = front?.value
front = front?.next
return value
}
/// Removes the last element in the list
///
/// - Returns: The value of the last element in the list, `nil` if empty
public mutating func removeLast() -> Element? {
count = Swift.max(count - 1, 0)
let value = back?.value
back = back?.previous
return value
}
/// Removes the element at a given index
///
/// - Parameter index: The index of the element to remove
/// - Returns: The value of the removed element, `nil` if the index does not exist
public mutating func remove(at index: Int) -> Element? {
if index == 0 {
return removeFirst()
} else if index == count - 1 {
return removeLast()
}
var node = front!
for _ in 0..<(index - 1) {
node = node.next!
}
let removingNode = node.next!
node.next = removingNode.next
removingNode.next?.previous = node
count = Swift.max(count - 1, 0)
return removingNode.value
}
/// Removes all elements from the list
public mutating func removeAll() {
count = 0
front = nil
back = nil
}
// MARK: Iterator
/// Creates an iterator for all elements in the list
///
/// - Returns: A `LinkedListIterator` over the elements in the list
public func makeIterator() -> LinkedListIterator<Element> {
return LinkedListIterator<Element>(front)
}
}
public struct LinkedListIterator<Element>: IteratorProtocol {
internal typealias Node = LinkedList<Element>.Node<Element>
private var current: Node?
/// Creates an iterator starting at the given node
///
/// - Parameter node: The start `Node` of the iterator
internal init(_ node: Node?) {
self.current = node
}
/// Fetches the next `Node` in the list
///
/// - Returns: The value of the current `Node` in the list
public mutating func next() -> Element? {
let value = current?.value
current = current?.next
return value
}
}
| mit | d494fce13a249d49edf0c757bdf5bdf7 | 27.113122 | 90 | 0.551585 | 4.703255 | false | false | false | false |
muriarte/swift-semana5 | Hamburguesas/Hamburguesas/Datos.swift | 1 | 1722 | //
// Datos.swift
// Hamburguesas
//
// Created by MARIO R URIARTE ROCHA on 12/6/15.
// Copyright © 2015 MARIO R URIARTE ROCHA. All rights reserved.
//
import Foundation
import UIKit
class ColeccionDePaises {
let paises : [String] = ["México","Uruguay","Suiza","Alemania","Francia","Brasil","Portugal","República Dominicana","Puerto Rico","Cuba","Rusia","Siria","Kazajstan","Chipre","Grecia","Libano","Egipto","Oman","Kenia","Australia"]
func obtenPais()->String {
let idx = Int(arc4random()) % paises.count
return(paises[idx])
}
}
class ColeccionDeHamburguesas {
let hamburguesas : [String] = ["Doble carne doble queso", "La guaira", "Triple queso", "Guacamole burguer","Chicken sandwich", "Meat buster", "Hamburgueseira", "Hot burguer", "Sexy burguer", "Mi Negra burguer", "Hamburguesinski", "Aliba burguer", "Pancontipe", "Burguer island", "Hamburguesopolus", "Burguermix", "Piramiburguer", "Hamburguesas", "Burguertin BurguerTan", "Hamburguer"]
func obtenHamburguesa()->String {
let idx = Int(arc4random()) % hamburguesas.count
return(hamburguesas[idx])
}
}
struct Colores {
let Colores = [UIColor(red: 0.75, green: 0.53, blue: 0.76, alpha: 1.0),
UIColor(red: 0.83, green: 0.62, blue: 0.78, alpha: 1.0),
UIColor(red: 0.80, green: 0.98, blue: 0.96, alpha: 1.0),
UIColor(red: 0.90, green: 0.34, blue: 0.77, alpha: 1.0),
UIColor(red: 0.95, green: 0.67, blue: 0.66, alpha: 1.0),
UIColor(red: 0.65, green: 0.87, blue: 0.87, alpha: 1.0),
UIColor(red: 0.78, green: 0.56, blue: 0.76, alpha: 1.0)]
func obtenColor()->UIColor {
return Colores[Int(arc4random()) % Colores.count]
}
}
| mit | d95a0a743da3e15f2bde063bb7819337 | 36.369565 | 388 | 0.635253 | 2.869783 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Data/Vdv/Model/VdvInterval.swift | 1 | 825 | import Foundation
/**
* Represents a time interval between two bus stops.
*/
class VdvInterval {
var timeGroup: Int
var origin: Int
var destination: Int
init(timeGroup: Int, origin: Int, destination: Int) {
self.timeGroup = timeGroup
self.origin = origin
self.destination = destination
}
}
extension VdvInterval: Hashable {
var hashValue: Int {
var result = timeGroup
result = 31 * result + origin
result = 31 * result + destination
return result
}
public static func ==(lhs: VdvInterval, rhs: VdvInterval) -> Bool {
if lhs.timeGroup != rhs.timeGroup {
return false
}
if lhs.origin != rhs.origin {
return false
}
return lhs.destination == rhs.destination
}
}
| gpl-3.0 | 3b622e07652a55bb9997d3702f35b230 | 20.153846 | 71 | 0.591515 | 4.365079 | false | false | false | false |
acchou/RxGmail | Example/RxGmail/MessagesViewModel.swift | 1 | 1941 | import RxSwift
import RxGmail
struct MessageCell {
var identifier: String
var sender: String
var subject: String
var date: String
}
enum MessagesQueryMode {
case All
case Unread
}
struct MessagesViewModelInputs {
var selectedLabel: Label
var mode: MessagesQueryMode
}
struct MessagesViewModelOutputs {
var messageCells: Observable<[MessageCell]>
}
typealias MessagesViewModelType = (MessagesViewModelInputs) -> MessagesViewModelOutputs
func MessagesViewModel(rxGmail: RxGmail) -> MessagesViewModelType {
return { inputs in
let query = RxGmail.MessageListQuery.query(withUserId: "me")
query.labelIds = [inputs.selectedLabel.identifier]
if case .Unread = inputs.mode {
query.q = "is:unread"
}
// Do the lazy thing and load all message headers every time this view appears. A more production ready implementation would use caching.
let messageCells = rxGmail
.listMessages(query: query) // RxGmail.MessageListResponse
.flatMap {
rxGmail.fetchDetails($0.messages ?? [], detailType: .metadata)
} // [RxGmail.Message] (with all headers)
.flatMap { Observable.from($0) } // RxGmail.Message
.map { message -> MessageCell in
let headers = message.parseHeaders()
return MessageCell(
identifier: message.identifier ?? "",
sender: headers["From"] ?? "",
subject: headers["Subject"] ?? "",
date: headers["Date"] ?? ""
)
} // MessageCell
.toArray() // [MessageCell]
.shareReplay(1)
return MessagesViewModelOutputs(messageCells: messageCells)
}
}
| mit | c76f6a5309cc25b1030ed74cf6ffa19a | 33.660714 | 145 | 0.566203 | 5.361878 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/UI/Sugar/UIDevice+Model.swift | 1 | 737 | import UIKit
public protocol UIDeviceType {
var identifierForVendor: UUID? { get }
var modelCode: String { get }
var systemName: String { get }
var systemVersion: String { get }
var userInterfaceIdiom: UIUserInterfaceIdiom { get }
}
extension UIDevice: UIDeviceType {
public var modelCode: String {
var size: Int = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
}
public extension UIDevice {
static let isPhone = UIDevice().userInterfaceIdiom == .phone
static let isPad = UIDevice().userInterfaceIdiom == .pad
static let isSimulator = Simulator.isRunning
}
| mit | 6eb3a0611ea224057c0eb5eee6ff2c86 | 28.48 | 62 | 0.70692 | 4.309942 | false | false | false | false |
kwkhaw/quick-start-ios-swift | QuickStart-Swift/AppDelegate.swift | 1 | 16135 | import UIKit
/**
Layer App ID from developer.layer.com
*/
let LQSLayerAppIDString = ""
#if arch(i386) || arch(x86_64) // Simulator
// If on simulator set the user ID to Simulator and participant to Device
let LQSCurrentUserID = "Simulator"
let LQSParticipantUserID = "Device"
let LQSInitialMessageText = "Hey Device! This is your friend, Simulator."
#else // Device
// If on device set the user ID to Device and participant to Simulator
let LQSCurrentUserID = "Device"
let LQSParticipantUserID = "Simulator"
let LQSInitialMessageText = "Hey Simulator! This is your friend, Device."
#endif
let LQSParticipant2UserID = "Dashboard"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, LYRClientDelegate {
var window: UIWindow?
var layerClient: LYRClient!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Check if Sample App is using a valid app ID.
if (isValidAppID()) {
// Add support for shake gesture
application.applicationSupportsShakeToEdit = true
// Show a usage the first time the app is launched
showFirstTimeMessage()
// Initializes a LYRClient object
let appID = NSURL(string: LQSLayerAppIDString)
layerClient = LYRClient(appID: appID)
layerClient.delegate = self
layerClient.autodownloadMIMETypes = Set<NSObject>(arrayLiteral: "image/png")
// Connect to Layer
// See "Quick Start - Connect" for more details
// https://developer.layer.com/docs/quick-start/ios#connect
layerClient.connectWithCompletion() { (success: Bool, error: NSError?) in
if !success {
print("Failed to connect to Layer: \(error)")
} else {
self.authenticateLayerWithUserID(LQSCurrentUserID) { (success: Bool, error: NSError?) in
if !success {
print("Failed Authenticating Layer Client with error:\(error)")
} else {
print("successfully authenticated")
}
}
}
}
// Register for push
registerApplicationForPushNotifications(application)
let navigationController: UINavigationController = self.window!.rootViewController as! UINavigationController
let viewController: LQSViewController = navigationController.topViewController as! LQSViewController
viewController.layerClient = layerClient
}
return true
}
// MARK - Push Notification Methods
func registerApplicationForPushNotifications(application: UIApplication) {
// Set up push notifications
// For more information about Push, check out:
// https://developer.layer.com/docs/guides/ios#push-notification
// Register device for iOS8
let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
application.registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Send device token to Layer so Layer can send pushes to this device.
// For more information about Push, check out:
// https://developer.layer.com/docs/guides/ios#push-notification
var error: NSError?
let success: Bool
do {
try layerClient!.updateRemoteNotificationDeviceToken(deviceToken)
success = true
} catch let error1 as NSError {
error = error1
success = false
}
if (success) {
print("Application did register for remote notifications: \(deviceToken)")
} else {
print("Failed updating device token with error: \(error)")
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Get Message from Metadata
// Why never use? var message: LYRMessage = messageFromRemoteNotification(userInfo)
let success = layerClient!.synchronizeWithRemoteNotification(userInfo, completion: { (changes, error) in
if (changes != nil) {
if (changes!.count > 0) {
// Why never use? message = self.messageFromRemoteNotification(userInfo)
completionHandler(UIBackgroundFetchResult.NewData)
} else {
completionHandler(UIBackgroundFetchResult.NoData)
}
} else {
if error != nil {
print("Failed processing push notification with error: \(error)")
completionHandler(UIBackgroundFetchResult.NoData)
} else {
completionHandler(UIBackgroundFetchResult.Failed)
}
}
})
if (success) {
print("Application did complete remote notification sync")
} else {
completionHandler(UIBackgroundFetchResult.NoData)
}
}
func messageFromRemoteNotification(remoteNotification: NSDictionary?) -> LYRMessage {
let LQSPushMessageIdentifierKeyPath = "layer.message_identifier"
let LQSPushAnnouncementIdentifierKeyPath = "layer.announcement_identifier"
// Retrieve message URL from Push Notification
var messageURL = NSURL(string: remoteNotification!.valueForKeyPath(LQSPushMessageIdentifierKeyPath) as! String)
if messageURL == nil {
messageURL = NSURL(string: remoteNotification!.valueForKeyPath(LQSPushAnnouncementIdentifierKeyPath) as! String)
}
// Retrieve LYRMessage from Message URL
let query: LYRQuery = LYRQuery(queryableClass: LYRMessage.self)
query.predicate = LYRPredicate(property: "identifier", predicateOperator: LYRPredicateOperator.IsIn, value: NSSet(object: messageURL!))
var error: NSError?
let messages: NSOrderedSet?
do {
messages = try self.layerClient!.executeQuery(query)
} catch let error1 as NSError {
error = error1
messages = nil
}
if (error == nil) {
print("Query contains \(messages!.count) messages")
let message: LYRMessage = messages!.firstObject as! LYRMessage
let messagePart: LYRMessagePart = message.parts[0] as! LYRMessagePart
print("Pushed Message Contents: \(NSString(data: messagePart.data, encoding: NSUTF8StringEncoding))")
} else {
print("Query failed with error \(error)")
}
return messages!.firstObject as! LYRMessage
}
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:.
}
// MARK - Layer Authentication Methods
func authenticateLayerWithUserID(userID: String, completion: ((success: Bool, error: NSError?) -> Void)) {
if let layerClient = layerClient {
if layerClient.authenticatedUserID != nil {
print("Layer Authenticated as User \(layerClient.authenticatedUserID)")
completion(success: true, error: nil)
return
}
// Authenticate with Layer
// See "Quick Start - Authenticate" for more details
// https://developer.layer.com/docs/quick-start/ios#authenticate
/*
* 1. Request an authentication Nonce from Layer
*/
layerClient.requestAuthenticationNonceWithCompletion() { (nonce: String!, error: NSError!) in
if nonce.isEmpty {
completion(success: false, error: error)
return
}
/*
* 2. Acquire identity Token from Layer Identity Service
*/
self.requestIdentityTokenForUserID(userID, appID: layerClient.appID.absoluteString, nonce: nonce, completion: { (identityToken, error) in
if identityToken.isEmpty {
completion(success: false, error: error)
return
}
/*
* 3. Submit identity token to Layer for validation
*/
layerClient.authenticateWithIdentityToken(identityToken, completion: { (authenticatedUserID, error) in
if !authenticatedUserID.isEmpty {
completion(success: true, error: nil)
print("Layer Authenticated as User: \(authenticatedUserID)")
} else {
completion(success: false, error: error)
}
})
})
}
}
}
func requestIdentityTokenForUserID(userID: String, appID: String, nonce: String, completion: ((identityToken: String, error: NSError?) -> Void)) {
let identityTokenURL = NSURL(string: "https://layer-identity-provider.herokuapp.com/identity_tokens")
let request = NSMutableURLRequest(URL: identityTokenURL!)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let parameters = ["app_id": appID, "user_id": userID, "nonce": nonce]
let requestBody: NSData? = try? NSJSONSerialization.dataWithJSONObject(parameters, options: [])
request.HTTPBody = requestBody
let sessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration)
session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
if error != nil {
completion(identityToken: "", error: error)
return
}
// Deserialize the response
let responseObject: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! NSDictionary
if responseObject.valueForKey("error") == nil {
let identityToken = responseObject["identity_token"] as! String?
let token: String = (identityToken != nil) ? identityToken! : ""
completion(identityToken: token, error: nil);
} else {
let domain = "layer-identity-provider.herokuapp.com"
let code = responseObject["status"] as! Int?
let userInfo = [ NSLocalizedDescriptionKey: "Layer Identity Provider Returned an Error.",
NSLocalizedRecoverySuggestionErrorKey: "There may be a problem with your APPID." ]
let error: NSError = NSError(domain: domain, code: code!, userInfo: userInfo)
completion(identityToken: "", error: error)
}
}).resume()
}
// - MARK LYRClientDelegate Delegate Methods
func layerClient(client: LYRClient, didReceiveAuthenticationChallengeWithNonce nonce: String) {
print("Layer Client did recieve authentication challenge with nonce: \(nonce)")
}
func layerClient(client: LYRClient, didAuthenticateAsUserID userID: String) {
print("Layer Client did recieve authentication nonce")
}
func layerClientDidDeauthenticate(client: LYRClient) {
print("Layer Client did deauthenticate")
}
func layerClient(client: LYRClient, didFinishSynchronizationWithChanges changes: [AnyObject]) {
print("Layer Client did finish sychronization")
}
func layerClient(client: LYRClient, didFailSynchronizationWithError error: NSError) {
print("Layer Client did fail synchronization with error: \(error)")
}
func layerClient(client: LYRClient, willAttemptToConnect attemptNumber: UInt, afterDelay delayInterval: NSTimeInterval, maximumNumberOfAttempts attemptLimit: UInt) {
print("Layer Client will attempt to connect")
}
func layerClientDidConnect(client: LYRClient) {
print("Layer Client did connect")
}
func layerClient(client: LYRClient, didLoseConnectionWithError error: NSError) {
print("Layer Client did lose connection with error: \(error)")
}
func layerClientDidDisconnect(client: LYRClient) {
print("Layer Client did disconnect")
}
// MARK - First Run Notification
func showFirstTimeMessage() {
let LQSApplicationHasLaunchedOnceDefaultsKey = "applicationHasLaunchedOnce"
let standardUserDefaults = NSUserDefaults.standardUserDefaults()
if (!standardUserDefaults.boolForKey(LQSApplicationHasLaunchedOnceDefaultsKey)) {
standardUserDefaults.setBool(true, forKey: LQSApplicationHasLaunchedOnceDefaultsKey)
standardUserDefaults.synchronize()
// This is the first launch ever
let alert: UIAlertView = UIAlertView(title: "Hello!",
message: "This is a very simple example of a chat app using Layer. Launch this app on a Simulator and a Device to start a 1:1 conversation. If you shake the Device the navbar color will change on both the Simulator and Device.",
delegate: self,
cancelButtonTitle: nil)
alert.addButtonWithTitle("Got It!")
alert.show()
}
}
// MARK - Check if Sample App is using a valid app ID.
func isValidAppID() -> Bool {
if LQSLayerAppIDString == "LAYER_APP_ID" {
return false
}
return true
}
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if alertView.buttonTitleAtIndex(buttonIndex) == "Ok" {
abort()
}
}
}
| apache-2.0 | 5296b9cec99f3a31f8c2dc9211b1f801 | 44.968661 | 285 | 0.632724 | 5.820707 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/SectionEditorViewController.swift | 1 | 33328 | @objc(WMFSectionEditorViewControllerDelegate)
protocol SectionEditorViewControllerDelegate: class {
func sectionEditorDidFinishEditing(_ sectionEditor: SectionEditorViewController, withChanges didChange: Bool)
func sectionEditorDidFinishLoadingWikitext(_ sectionEditor: SectionEditorViewController)
}
@objc(WMFSectionEditorViewController)
class SectionEditorViewController: ViewController {
@objc weak var delegate: SectionEditorViewControllerDelegate?
@objc var section: MWKSection?
@objc var selectedTextEditInfo: SelectedTextEditInfo?
@objc var dataStore: MWKDataStore?
private var webView: SectionEditorWebView!
private let sectionFetcher = WikiTextSectionFetcher()
private var inputViewsController: SectionEditorInputViewsController!
private var messagingController: SectionEditorWebViewMessagingController!
private var menuItemsController: SectionEditorMenuItemsController!
private var navigationItemController: SectionEditorNavigationItemController!
lazy var readingThemesControlsViewController: ReadingThemesControlsViewController = {
return ReadingThemesControlsViewController.init(nibName: ReadingThemesControlsViewController.nibName, bundle: nil)
}()
private lazy var focusNavigationView: FocusNavigationView = {
return FocusNavigationView.wmf_viewFromClassNib()
}()
private var webViewTopConstraint: NSLayoutConstraint!
private var didFocusWebViewCompletion: (() -> Void)?
private var needsSelectLastSelection: Bool = false
@objc var editFunnel = EditFunnel.shared
private var isInFindReplaceActionSheetMode = false
private var wikitext: String? {
didSet {
setWikitextToWebViewIfReady()
}
}
private var isCodemirrorReady: Bool = false {
didSet {
setWikitextToWebViewIfReady()
}
}
private let findAndReplaceHeaderTitle = WMFLocalizedString("find-replace-header", value: "Find and replace", comment: "Find and replace header title.")
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.messagingController = SectionEditorWebViewMessagingController()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
init(messagingController: SectionEditorWebViewMessagingController = SectionEditorWebViewMessagingController()) {
self.messagingController = messagingController
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
loadWikitext()
navigationItemController = SectionEditorNavigationItemController(navigationItem: navigationItem)
navigationItemController.delegate = self
configureWebView()
WMFAuthenticationManager.sharedInstance.loginWithSavedCredentials { (_) in }
webView.scrollView.delegate = self
scrollView = webView.scrollView
setupFocusNavigationView()
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectLastSelectionIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
UIMenuController.shared.menuItems = menuItemsController.originalMenuItems
super.viewWillDisappear(animated)
}
@objc func keyboardDidHide() {
inputViewsController.resetFormattingAndStyleSubmenus()
}
private func setupFocusNavigationView() {
let closeAccessibilityText = WMFLocalizedString("find-replace-header-close-accessibility", value: "Close find and replace", comment: "Accessibility label for closing the find and replace view.")
focusNavigationView.configure(titleText: findAndReplaceHeaderTitle, closeButtonAccessibilityText: closeAccessibilityText, traitCollection: traitCollection)
focusNavigationView.isHidden = true
focusNavigationView.delegate = self
focusNavigationView.apply(theme: theme)
focusNavigationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(focusNavigationView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: focusNavigationView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: focusNavigationView.trailingAnchor)
let topConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: focusNavigationView.topAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, topConstraint])
}
private func showFocusNavigationView() {
navigationController?.setNavigationBarHidden(true, animated: false)
webViewTopConstraint.constant = -focusNavigationView.frame.height
focusNavigationView.isHidden = false
}
private func hideFocusNavigationView() {
webViewTopConstraint.constant = 0
focusNavigationView.isHidden = true
navigationController?.setNavigationBarHidden(false, animated: false)
}
private func configureWebView() {
let language = section?.article?.url.wmf_language ?? NSLocale.current.languageCode ?? "en"
let configuration = WKWebViewConfiguration()
let schemeHandler = SchemeHandler.shared
configuration.setURLSchemeHandler(schemeHandler, forURLScheme: schemeHandler.scheme)
let textSizeAdjustment = UserDefaults.wmf.wmf_articleFontSizeMultiplier().intValue
let contentController = WKUserContentController()
messagingController.textSelectionDelegate = self
messagingController.buttonSelectionDelegate = self
messagingController.alertDelegate = self
messagingController.scrollDelegate = self
let languageInfo = MWLanguageInfo(forCode: language)
let isSyntaxHighlighted = UserDefaults.wmf.wmf_IsSyntaxHighlightingEnabled
let setupUserScript = CodemirrorSetupUserScript(language: language, direction: CodemirrorSetupUserScript.CodemirrorDirection(rawValue: languageInfo.dir) ?? .ltr, theme: theme, textSizeAdjustment: textSizeAdjustment, isSyntaxHighlighted: isSyntaxHighlighted) { [weak self] in
self?.isCodemirrorReady = true
}
contentController.addUserScript(setupUserScript)
contentController.add(setupUserScript, name: setupUserScript.messageHandlerName)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.codeMirrorSearchMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.smoothScrollToYOffsetMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.replaceAllCountMessage)
contentController.add(messagingController, name: SectionEditorWebViewMessagingController.Message.Name.didSetWikitextMessage)
configuration.userContentController = contentController
webView = SectionEditorWebView(frame: .zero, configuration: configuration)
webView.navigationDelegate = self
webView.isHidden = true // hidden until wikitext is set
webView.scrollView.keyboardDismissMode = .interactive
inputViewsController = SectionEditorInputViewsController(webView: webView, messagingController: messagingController, findAndReplaceDisplayDelegate: self)
inputViewsController.delegate = self
webView.inputViewsSource = inputViewsController
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: webView.leadingAnchor)
let trailingConstraint = view.trailingAnchor.constraint(equalTo: webView.trailingAnchor)
webViewTopConstraint = view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: webView.topAnchor)
let bottomConstraint = view.bottomAnchor.constraint(equalTo: webView.bottomAnchor)
NSLayoutConstraint.activate([leadingConstraint, trailingConstraint, webViewTopConstraint, bottomConstraint])
if let url = SchemeHandler.FileHandler.appSchemeURL(for: "codemirror/codemirror-index.html", fragment: "top") {
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: WKWebViewLoadAssetsHTMLRequestTimeout)
webView.load(request)
messagingController.webView = webView
menuItemsController = SectionEditorMenuItemsController(messagingController: messagingController)
menuItemsController.delegate = self
webView.menuItemsDataSource = menuItemsController
webView.menuItemsDelegate = menuItemsController
}
}
@objc var shouldFocusWebView = true {
didSet {
guard shouldFocusWebView else {
return
}
logSectionReadyToEdit()
focusWebViewIfReady()
}
}
private var didSetWikitextToWebView: Bool = false {
didSet {
guard shouldFocusWebView else {
return
}
focusWebViewIfReady()
}
}
private func selectLastSelectionIfNeeded() {
guard isCodemirrorReady,
shouldFocusWebView,
didSetWikitextToWebView,
needsSelectLastSelection,
wikitext != nil else {
return
}
messagingController.selectLastSelection()
messagingController.focusWithoutScroll()
needsSelectLastSelection = false
}
private func showCouldNotFindSelectionInWikitextAlert() {
editFunnel.logSectionHighlightToEditError(language: section?.articleLanguage)
let alertTitle = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-title", value:"The text that you selected could not be located", comment:"Title for alert informing user their text selection could not be located in the article wikitext.")
let alertMessage = WMFLocalizedString("edit-menu-item-could-not-find-selection-alert-message", value:"This might be because the text you selected is not editable (eg. article title or infobox titles) or the because of the length of the text that was highlighted", comment:"Description of possible reasons the user text selection could not be located in the article wikitext.")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: CommonStrings.okTitle, style:.default, handler: nil))
present(alert, animated: true, completion: nil)
}
private func setWikitextToWebViewIfReady() {
assert(Thread.isMainThread)
guard isCodemirrorReady, let wikitext = wikitext else {
return
}
setWikitextToWebView(wikitext) { [weak self] (error) in
if let error = error {
assertionFailure(error.localizedDescription)
} else {
DispatchQueue.main.async {
self?.didSetWikitextToWebView = true
if let selectedTextEditInfo = self?.selectedTextEditInfo {
self?.messagingController.highlightAndScrollToText(for: selectedTextEditInfo){ [weak self] (error) in
if let _ = error {
self?.showCouldNotFindSelectionInWikitextAlert()
}
}
}
}
}
}
}
private func focusWebViewIfReady() {
guard didSetWikitextToWebView else {
return
}
webView.isHidden = false
webView.becomeFirstResponder()
messagingController.focus {
assert(Thread.isMainThread)
self.delegate?.sectionEditorDidFinishLoadingWikitext(self)
guard let didFocusWebViewCompletion = self.didFocusWebViewCompletion else {
return
}
didFocusWebViewCompletion()
self.didFocusWebViewCompletion = nil
}
}
func setWikitextToWebView(_ wikitext: String, completionHandler: ((Error?) -> Void)? = nil) {
messagingController.setWikitext(wikitext, completionHandler: completionHandler)
}
private func loadWikitext() {
guard let section = section else {
assertionFailure("Section should be set by now")
return
}
if shouldFocusWebView {
let message = WMFLocalizedString("wikitext-downloading", value: "Loading content...", comment: "Alert text shown when obtaining latest revision of the section being edited")
WMFAlertManager.sharedInstance.showAlert(message, sticky: true, dismissPreviousAlerts: true)
}
sectionFetcher.fetch(section) { (result, error) in
DispatchQueue.main.async {
if let error = error {
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true)
}
return
}
guard
let results = result as? [String: Any],
let revision = results["revision"] as? String
else {
return
}
if let protectionStatus = section.article?.protection,
let allowedGroups = protectionStatus.allowedGroups(forAction: "edit") as? [String],
!allowedGroups.isEmpty {
let message: String
if allowedGroups.contains("autoconfirmed") {
message = WMFLocalizedString("page-protected-autoconfirmed", value: "This page has been semi-protected.", comment: "Brief description of Wikipedia 'autoconfirmed' protection level, shown when editing a page that is protected.")
} else if allowedGroups.contains("sysop") {
message = WMFLocalizedString("page-protected-sysop", value: "This page has been fully protected.", comment: "Brief description of Wikipedia 'sysop' protection level, shown when editing a page that is protected.")
} else {
message = WMFLocalizedString("page-protected-other", value: "This page has been protected to the following levels: %1$@", comment: "Brief description of Wikipedia unknown protection level, shown when editing a page that is protected. %1$@ will refer to a list of protection levels.")
}
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
} else {
self.didFocusWebViewCompletion = {
WMFAlertManager.sharedInstance.dismissAlert()
}
}
self.wikitext = revision
}
}
}
// MARK: - Accessibility
override func accessibilityPerformEscape() -> Bool {
delegate?.sectionEditorDidFinishEditing(self, withChanges: false)
return true
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: nil) { (_) in
self.inputViewsController.didTransitionToNewCollection()
self.focusNavigationView.updateLayout(for: newCollection)
}
}
// MARK: Event logging
private var loggedEditActions: NSMutableSet = []
private func logSectionReadyToEdit() {
guard !loggedEditActions.contains(EditFunnel.Action.ready) else {
return
}
editFunnel.logSectionReadyToEdit(from: editFunnelSource, language: section?.articleLanguage)
loggedEditActions.add(EditFunnel.Action.ready)
}
private var editFunnelSource: EditFunnelSource {
return selectedTextEditInfo == nil ? .pencil : .highlight
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
webView.scrollView.backgroundColor = theme.colors.paperBackground
webView.backgroundColor = theme.colors.paperBackground
messagingController.applyTheme(theme: theme)
inputViewsController.apply(theme: theme)
navigationItemController.apply(theme: theme)
apply(presentationTheme: theme)
focusNavigationView.apply(theme: theme)
}
private var previousContentInset = UIEdgeInsets.zero
override func scrollViewInsetsDidChange() {
super.scrollViewInsetsDidChange()
guard
let newContentInset = scrollView?.contentInset,
newContentInset != previousContentInset
else {
return
}
previousContentInset = newContentInset
messagingController.setAdjustedContentInset(newInset: newContentInset)
}
}
extension SectionEditorViewController: SectionEditorNavigationItemControllerDelegate {
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapProgressButton progressButton: UIBarButtonItem) {
messagingController.getWikitext { [weak self] (result, error) in
guard let self = self else { return }
if let error = error {
assertionFailure(error.localizedDescription)
return
} else if let wikitext = result {
if wikitext != self.wikitext {
guard let vc = EditPreviewViewController.wmf_initialViewControllerFromClassStoryboard() else {
return
}
self.inputViewsController.resetFormattingAndStyleSubmenus()
self.needsSelectLastSelection = true
vc.theme = self.theme
vc.section = self.section
vc.wikitext = wikitext
vc.delegate = self
vc.editFunnel = self.editFunnel
vc.loggedEditActions = self.loggedEditActions
vc.editFunnelSource = self.editFunnelSource
self.navigationController?.pushViewController(vc, animated: true)
} else {
let message = WMFLocalizedString("wikitext-preview-changes-none", value: "No changes were made to be previewed.", comment: "Alert text shown if no changes were made to be previewed.")
WMFAlertManager.sharedInstance.showAlert(message, sticky: false, dismissPreviousAlerts: true)
}
}
}
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapCloseButton closeButton: UIBarButtonItem) {
delegate?.sectionEditorDidFinishEditing(self, withChanges: false)
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapUndoButton undoButton: UIBarButtonItem) {
messagingController.undo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapRedoButton redoButton: UIBarButtonItem) {
messagingController.redo()
}
func sectionEditorNavigationItemController(_ sectionEditorNavigationItemController: SectionEditorNavigationItemController, didTapReadingThemesControlsButton readingThemesControlsButton: UIBarButtonItem) {
webView.resignFirstResponder()
inputViewsController.suppressMenus = true
showReadingThemesControlsPopup(on: self, responder: self, theme: theme)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerTextSelectionDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveTextSelectionChangeMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, isRangeSelected: Bool) {
if isRangeSelected {
menuItemsController.setEditMenuItems()
}
navigationItemController.textSelectionDidChange(isRangeSelected: isRangeSelected)
inputViewsController.textSelectionDidChange(isRangeSelected: isRangeSelected)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerButtonMessageDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveSelectButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
inputViewsController.buttonSelectionDidChange(button: button)
}
func sectionEditorWebViewMessagingControllerDidReceiveDisableButtonMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, button: SectionEditorButton) {
navigationItemController.disableButton(button: button)
inputViewsController.disableButton(button: button)
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerAlertDelegate {
func sectionEditorWebViewMessagingControllerDidReceiveReplaceAllMessage(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, replacedCount: Int) {
let format = WMFLocalizedString("replace-replace-all-results-count", value: "{{PLURAL:%1$d|%1$d item replaced|%1$d items replaced}}", comment: "Alert view label that tells the user how many instances they just replaced via \"Replace all\". %1$d is replaced with the number of instances that were replaced.")
let alertText = String.localizedStringWithFormat(format, replacedCount)
wmf_showAlertWithMessage(alertText)
}
}
extension SectionEditorViewController: FindAndReplaceKeyboardBarDisplayDelegate {
func keyboardBarDidHide(_ keyboardBar: FindAndReplaceKeyboardBar) {
hideFocusNavigationView()
}
func keyboardBarDidShow(_ keyboardBar: FindAndReplaceKeyboardBar) {
showFocusNavigationView()
}
func keyboardBarDidTapReplaceSwitch(_ keyboardBar: FindAndReplaceKeyboardBar) {
let alertController = UIAlertController(title: findAndReplaceHeaderTitle, message: nil, preferredStyle: .actionSheet)
let replaceAllActionTitle = WMFLocalizedString("action-replace-all", value: "Replace all", comment: "Title of the replace all action.")
let replaceActionTitle = WMFLocalizedString("action-replace", value: "Replace", comment: "Title of the replace all action.")
let replaceAction = UIAlertAction(title: replaceActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceSingle)
}
let replaceAllAction = UIAlertAction(title: replaceAllActionTitle, style: .default) { (_) in
self.inputViewsController.updateReplaceType(type: .replaceAll)
}
let cancelAction = UIAlertAction(title: CommonStrings.cancelActionTitle, style: .cancel, handler: nil)
alertController.addAction(replaceAction)
alertController.addAction(replaceAllAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = keyboardBar.replaceSwitchButton
alertController.popoverPresentationController?.sourceRect = keyboardBar.replaceSwitchButton.bounds
isInFindReplaceActionSheetMode = true
present(alertController, animated: true, completion: nil)
}
}
// MARK: - WKNavigationDelegate
extension SectionEditorViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
}
}
// MARK - EditSaveViewControllerDelegate
extension SectionEditorViewController: EditSaveViewControllerDelegate {
func editSaveViewControllerDidSave(_ editSaveViewController: EditSaveViewController) {
delegate?.sectionEditorDidFinishEditing(self, withChanges: true)
}
}
// MARK - EditPreviewViewControllerDelegate
extension SectionEditorViewController: EditPreviewViewControllerDelegate {
func editPreviewViewControllerDidTapNext(_ editPreviewViewController: EditPreviewViewController) {
guard let vc = EditSaveViewController.wmf_initialViewControllerFromClassStoryboard() else {
return
}
vc.section = self.section
vc.wikitext = editPreviewViewController.wikitext
vc.delegate = self
vc.theme = self.theme
vc.editFunnel = self.editFunnel
vc.editFunnelSource = editFunnelSource
vc.loggedEditActions = loggedEditActions
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension SectionEditorViewController: ReadingThemesControlsPresenting {
var shouldPassthroughNavBar: Bool {
return false
}
var showsSyntaxHighlighting: Bool {
return true
}
var readingThemesControlsToolbarItem: UIBarButtonItem {
return self.navigationItemController.readingThemesControlsToolbarItem
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
inputViewsController.suppressMenus = false
}
}
extension SectionEditorViewController: ReadingThemesControlsResponding {
func updateWebViewTextSize(textSize: Int) {
messagingController.scaleBodyText(newSize: String(textSize))
}
func toggleSyntaxHighlighting(_ controller: ReadingThemesControlsViewController) {
messagingController.toggleSyntaxColors()
}
}
extension SectionEditorViewController: FocusNavigationViewDelegate {
func focusNavigationViewDidTapClose(_ focusNavigationView: FocusNavigationView) {
hideFocusNavigationView()
inputViewsController.closeFindAndReplace()
}
}
extension SectionEditorViewController: SectionEditorWebViewMessagingControllerScrollDelegate {
func sectionEditorWebViewMessagingController(_ sectionEditorWebViewMessagingController: SectionEditorWebViewMessagingController, didReceiveScrollMessageWithNewContentOffset newContentOffset: CGPoint) {
guard
presentedViewController == nil,
newContentOffset.x.isFinite,
newContentOffset.y.isFinite
else {
return
}
self.webView.scrollView.setContentOffset(newContentOffset, animated: true)
}
}
extension SectionEditorViewController: SectionEditorInputViewsControllerDelegate {
func sectionEditorInputViewsControllerDidTapMediaInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
let insertMediaViewController = InsertMediaViewController(articleTitle: section?.article?.displaytitle?.wmf_stringByRemovingHTML(), siteURL: section?.article?.url.wmf_site)
insertMediaViewController.delegate = self
insertMediaViewController.apply(theme: theme)
let navigationController = WMFThemeableNavigationController(rootViewController: insertMediaViewController, theme: theme)
navigationController.isNavigationBarHidden = true
present(navigationController, animated: true)
}
func showLinkWizard() {
guard let dataStore = dataStore else {
return
}
messagingController.getLink { link in
guard let link = link else {
assertionFailure("Link button should be disabled")
return
}
let siteURL = self.section?.article?.url.wmf_site
if link.exists {
guard let editLinkViewController = EditLinkViewController(link: link, siteURL: siteURL, dataStore: dataStore) else {
return
}
editLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: editLinkViewController, theme: self.theme)
navigationController.isNavigationBarHidden = true
self.present(navigationController, animated: true)
} else {
let insertLinkViewController = InsertLinkViewController(link: link, siteURL: siteURL, dataStore: dataStore)
insertLinkViewController.delegate = self
let navigationController = WMFThemeableNavigationController(rootViewController: insertLinkViewController, theme: self.theme)
self.present(navigationController, animated: true)
}
}
}
func sectionEditorInputViewsControllerDidTapLinkInsert(_ sectionEditorInputViewsController: SectionEditorInputViewsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: SectionEditorMenuItemsControllerDelegate {
func sectionEditorMenuItemsControllerDidTapLink(_ sectionEditorMenuItemsController: SectionEditorMenuItemsController) {
showLinkWizard()
}
}
extension SectionEditorViewController: EditLinkViewControllerDelegate {
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFinishEditingLink displayText: String?, linkTarget: String) {
messagingController.insertOrEditLink(page: linkTarget, label: displayText)
dismiss(animated: true)
}
func editLinkViewControllerDidRemoveLink(_ editLinkViewController: EditLinkViewController) {
messagingController.removeLink()
dismiss(animated: true)
}
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFailToExtractArticleTitleFromArticleURL articleURL: URL) {
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertLinkViewControllerDelegate {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?) {
messagingController.insertOrEditLink(page: page, label: label)
dismiss(animated: true)
}
}
extension SectionEditorViewController: InsertMediaViewControllerDelegate {
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didTapCloseButton button: UIBarButtonItem) {
dismiss(animated: true)
}
func insertMediaViewController(_ insertMediaViewController: InsertMediaViewController, didPrepareWikitextToInsert wikitext: String) {
dismiss(animated: true)
messagingController.getLineInfo { lineInfo in
guard let lineInfo = lineInfo else {
self.messagingController.replaceSelection(text: wikitext)
return
}
if !lineInfo.hasLineTokens && lineInfo.isAtLineEnd {
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.isAtLineEnd {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
} else if lineInfo.hasLineTokens {
self.messagingController.newlineAndIndent()
self.messagingController.replaceSelection(text: wikitext)
self.messagingController.newlineAndIndent()
} else {
self.messagingController.replaceSelection(text: wikitext)
}
}
}
}
#if (TEST)
//MARK: Helpers for testing
extension SectionEditorViewController {
func openFindAndReplaceForTesting() {
inputViewsController.textFormattingProvidingDidTapFindInPage()
}
var webViewForTesting: WKWebView {
return webView
}
var findAndReplaceViewForTesting: FindAndReplaceKeyboardBar? {
return inputViewsController.findAndReplaceViewForTesting
}
}
#endif
| mit | b49c4271fdc441a3e07af48907625714 | 45.096819 | 384 | 0.704843 | 6.489097 | false | false | false | false |
nextcloud/ios | File Provider Extension/FileProviderExtension+Thumbnail.swift | 1 | 3424 | //
// FileProviderExtension+Thumbnail.swift
// PickerFileProvider
//
// Created by Marino Faggiana on 28/05/18.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import FileProvider
import NextcloudKit
extension FileProviderExtension {
override func fetchThumbnails(for itemIdentifiers: [NSFileProviderItemIdentifier], requestedSize size: CGSize, perThumbnailCompletionHandler: @escaping (NSFileProviderItemIdentifier, Data?, Error?) -> Void, completionHandler: @escaping (Error?) -> Void) -> Progress {
let progress = Progress(totalUnitCount: Int64(itemIdentifiers.count))
var counterProgress: Int64 = 0
for itemIdentifier in itemIdentifiers {
guard let metadata = fileProviderUtility.shared.getTableMetadataFromItemIdentifier(itemIdentifier) else {
counterProgress += 1
if counterProgress == progress.totalUnitCount { completionHandler(nil) }
continue
}
if metadata.hasPreview {
let fileNamePath = CCUtility.returnFileNamePath(fromFileName: metadata.fileName, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, userId: metadata.userId, account: metadata.account)!
let fileNameIconLocalPath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
if let urlBase = metadata.urlBase.urlEncoded,
let fileNamePath = fileNamePath.urlEncoded,
let url = URL(string: "\(urlBase)/index.php/core/preview.png?file=\(fileNamePath)&x=\(size)&y=\(size)&a=1&mode=cover") {
NextcloudKit.shared.getPreview(url: url) { _, data, error in
if error == .success && data != nil {
do {
try data!.write(to: URL(fileURLWithPath: fileNameIconLocalPath), options: .atomic)
} catch { }
perThumbnailCompletionHandler(itemIdentifier, data, nil)
} else {
perThumbnailCompletionHandler(itemIdentifier, nil, NSFileProviderError(.serverUnreachable))
}
counterProgress += 1
if counterProgress == progress.totalUnitCount {
completionHandler(nil)
}
}
}
} else {
counterProgress += 1
if counterProgress == progress.totalUnitCount {
completionHandler(nil)
}
}
}
return progress
}
}
| gpl-3.0 | 15985be5f6e23cd2797a2f9c8aceae17 | 42.329114 | 271 | 0.619048 | 5.290572 | false | false | false | false |
fluidpixel/PlaylistExtender | PlaylistExtender/PlaylistController.swift | 1 | 9516 | //
// PlaylistController.swift
// PlaylistExtender
//
// Created by Lauren Brown on 29/05/2015.
// Copyright (c) 2015 Fluid Pixel. All rights reserved.
//
import UIKit
class PlaylistController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {
var session : SPTSession!
var playlistList : SPTPlaylistList!
var listOfPlaylists = [[String: String]]()
var numberOfPlaylists = 0
var numberOfGrabbedPlaylists = 0
@IBOutlet weak var TableView: UITableView!
let playlistBuilder = PlaylistBuilder()
var currentPlaylist = [String : String]()
var selectedPlaylist : SPTPartialPlaylist?
var currentSelectedRow:NSIndexPath?
var playlistIDArray = [String]()
@IBOutlet weak var amountSlider: UISlider!
@IBOutlet weak var extendPlaylistButton: UIButton!
@IBOutlet weak var extendPlaylistTitle: UILabel!
@IBOutlet weak var extendView: UIView!
@IBOutlet weak var explicitSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
let blur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let effectView = UIVisualEffectView(effect: blur)
effectView.frame = extendView.bounds
extendView.insertSubview(effectView, atIndex:0)
TableView.delegate = self
TableView.dataSource = self
TableView.backgroundColor = UIColor.darkTextColor()
loadPlaylists()
}
override func viewWillAppear(animated: Bool) {
navigationItem.title = "Playlist Extender"
}
func loadPlaylists() {
//change this to web api
playlistBuilder.grabUsersListOfPlaylists(0, thisSession: session) { (result, playlistCount) -> () in
if result.count > 0 {
self.listOfPlaylists = result
self.playlistBuilder.SetPlaylistList(result)
self.currentPlaylist = result[0]
self.numberOfPlaylists = playlistCount
self.numberOfGrabbedPlaylists = self.numberOfGrabbedPlaylists + result.count
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.TableView.reloadData()
})
}else {
print("empty/nil playlist")
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath == currentSelectedRow {
return 104
} else {
return 84
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if listOfPlaylists.count > 0 {
return listOfPlaylists.count
} else {
return 0
}
}
func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
currentPlaylist = listOfPlaylists[indexPath.row]
performSegueWithIdentifier("ShowDetail", sender: self)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Playlist Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PlaylistTableViewCell
cell.backgroundImage.image = UIImage(named: "loginButton")
let playlist = listOfPlaylists[indexPath.row]
if let albumArtwork = playlist["smallestImage"] {
cell.applyImage(NSURL(string: albumArtwork)!)
}
cell.albumName.text = playlist["playlistName"]
if let trackCount = playlist["tracksInPlaylist"] {
cell.trackCount.text = "\(trackCount) tracks"
} else {
cell.trackCount.text = ""
}
cell.detailButton.addTarget(self, action: "detailButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)
cell.detailButton.tag = indexPath.row
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
currentPlaylist = listOfPlaylists[indexPath.row]
if currentSelectedRow == indexPath {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
UIView.animateWithDuration(0.5, animations: {
self.extendView.alpha = 0.0
})
tableView.beginUpdates()
currentSelectedRow = nil
tableView.endUpdates()
return
}
tableView.beginUpdates()
currentSelectedRow = indexPath
tableView.endUpdates()
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell
playlistBuilder.SetPlaylistList(listOfPlaylists)
amountSlider.maximumValue = max(Float(((Int(currentPlaylist["tracksInPlaylist"]!)))!), 20.0)
amountSlider.minimumValue = min(Float(((Int(currentPlaylist["tracksInPlaylist"]!)))!), 10.0)
amountSlider.value = amountSlider.minimumValue
extendPlaylistButton.setTitle("EXTEND by \(Int(amountSlider.value)) Tracks ✚", forState: .Normal)
extendPlaylistTitle.text = currentPlaylist["playlistName"]
UIView.animateWithDuration(0.5, animations: {
self.extendView.alpha = 1.0
})
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//load more playlists if more and user scrolls to the bottom of the screen
if numberOfGrabbedPlaylists == indexPath.row && numberOfGrabbedPlaylists < numberOfPlaylists {
print("Start loading new playlists")
}
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
if let indexPath = currentSelectedRow {
TableView.deselectRowAtIndexPath(indexPath, animated: false)
}
UIView.animateWithDuration(0.5, animations: {
self.extendView.alpha = 0.0
})
TableView.beginUpdates()
currentSelectedRow = nil
TableView.endUpdates()
}
func detailButtonAction (sender: UIButton!) {
// currentPlaylist = playlistList
performSegueWithIdentifier("ShowDetail", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewController = segue.destinationViewController as? PlaylistTableViewController {
navigationItem.title = nil
viewController.playlist = currentPlaylist
viewController.Currentsession = session
viewController.navigationItem.title = currentPlaylist["playlistName"]
}
}
@IBAction func ExtendPlaylistButton(sender: UIButton) {
let message = "Name Your new playlist"
var txt : UITextField?
let alertView = UIAlertController(title: "Playlist Name", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alertView.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
textField.textAlignment = NSTextAlignment.Center
textField.placeholder = self.currentPlaylist["playlistName"]
txt = textField
}
alertView.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alertView.addAction(UIAlertAction(title: "Copy Existing Tracks", style: UIAlertActionStyle.Default, handler: { UIAlertAction -> Void in
self.newPlaylist(txt!.text!, extend: true)
}))
alertView.addAction(UIAlertAction(title: "Brand New Playlist", style: UIAlertActionStyle.Default, handler: { UIAlertAction -> Void in
self.newPlaylist(txt!.text!, extend: false)
}))
self.presentViewController(alertView, animated: true, completion: nil)
}
func newPlaylist (name: String, extend:Bool) {
if self.currentPlaylist["playlistName"] != nil {
let number = Int(self.amountSlider.value)
let defaults = NSUserDefaults.standardUserDefaults()
let explicitFilter = defaults.boolForKey("explicit_filter_preference")
self.playlistBuilder.buildPlaylist(self.currentPlaylist, session: self.session, sizeToIncreaseBy: number, name : name, extendOrBuild: extend, filter : (explicitFilter)) { result in
if result != nil {
self.loadPlaylists()
}
if result == "429" {
self.ShowErrorAlert()
}
}
} else {
print("Please pick a valid playlist")
}
}
@IBAction func OnSliderDragged(sender: UISlider) {
extendPlaylistButton.setTitle("EXTEND by \(Int(sender.value)) Tracks ✚", forState: .Normal)
}
func ShowErrorAlert() {
let alertView = UIAlertController(title: "429 Error", message: "Please try again", preferredStyle: UIAlertControllerStyle.Alert)
alertView.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertView, animated: true, completion: nil)
}
}
| mit | a070b02868e34b36bd01e8924c8b0cd8 | 34.759398 | 192 | 0.640349 | 5.511008 | false | false | false | false |
zcfsmile/Swifter | BasicSyntax/009Dictionary/009Directionary.playground/Contents.swift | 1 | 1100 | //: Playground - noun: a place where people can play
import UIKit
//: 字典
//: Swift 的字典使用Dictionary<Key, Value>定义,其中Key是字典中键的数据类型,Value是字典中对应于这些键所存储值的数据类型。
//: 一个字典的Key类型必须遵循Hashable协议,就像Set的值类型。
//: 我们也可以用[Key: Value]这样简化的形式去创建一个字典类型。
//: 创建字典
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]
var airports: [String: String] = ["YYZ": "Toromto Pearson", "DUB": "Dublin"]
//: 访问和修改字典
airports.count
if airports.isEmpty {
print("empty")
} else {
print("not empty")
}
airports["LHR"] = "Loodon"
airports["LHR"] = "Loodon Heathrow"
if let airportName = airports["DUB"] {
print(airportName)
} else {
print("No airports")
}
airports["APL"] = "Apple Internation"
airports["ApL"] = nil
//: 循环
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportName in airports.values {
print(airportName)
}
| mit | df346e71841c3eabeeac7b66c02da3e8 | 17.367347 | 81 | 0.682222 | 2.990033 | false | false | false | false |
tkremenek/swift | test/ClangImporter/objc_direct.swift | 5 | 1175 | // RUN: %target-swift-frontend-verify -typecheck %s -enable-objc-interop -import-objc-header %S/../Inputs/objc_direct.h
// REQUIRES: objc_interop
var something = Bar() as AnyObject
something.directProperty = 123 // expected-error {{value of type 'AnyObject' has no member 'directProperty'}}
let _ = something.directProperty // expected-error {{value of type 'AnyObject' has no member 'directProperty'}}
something.directProperty2 = 456 // expected-error {{value of type 'AnyObject' has no member 'directProperty2'}}
let _ = something.directProperty2 // expected-error {{value of type 'AnyObject' has no member 'directProperty2'}}
let _ = something.directMethod() // expected-error {{value of type 'AnyObject' has no member 'directMethod'}}
let _ = something.directMethod2() // expected-error {{value of type 'AnyObject' has no member 'directMethod2'}}
class Foo {
// Test that we can use a method with the same name as some `objc_direct` method.
@objc func directProtocolMethod() -> String {
"This is not a direct method."
}
}
var otherthing = Foo() as AnyObject
// We expect no error.
let _ = otherthing.directProtocolMethod()
| apache-2.0 | 12497c172231ce906c571d1884c7fe60 | 42.518519 | 119 | 0.710638 | 3.903654 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/EditRawContentViewController.swift | 1 | 2090 | //
// EditRawContentViewController.swift
// ATests
//
// Created by Radu Costea on 30/05/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
protocol Contained: class {
associatedtype SelfType = Self
static var storyboardName: String { get }
static var storyboardId: String { get }
static func controller() -> SelfType?
}
func storyboardController(storyboard: String, identifier: String) -> UIViewController {
return UIStoryboard(name: storyboard, bundle: nil).instantiateViewControllerWithIdentifier(identifier)
}
class ContainedViewController: UIViewController, Contained {
class var storyboardName: String { return "" }
class var storyboardId: String { return "" }
class func controller() -> ContainedViewController? {
return storyboardController(storyboardName, identifier: storyboardId) as? ContainedViewController
}
}
class EditContentController: ContainedViewController {
typealias SelfType = EditContentController
var editingEnabled: Bool = true
func getContent() -> PFObject? {
return nil
}
override class func controller() -> EditContentController? {
return super.controller() as? EditContentController
}
class func editController(content: PFObject?) -> EditContentController! {
let controllerVC: EditContentController = self.controller()!
controllerVC.loadWith(content)
return controllerVC
}
func loadWith(content: PFObject?) { /* STUB */ }
func startEditing() { /* STUB */ }
}
class EditContentFabric {
class func editController(content: PFObject) -> EditContentController {
if let text = content as? ParseTextContent {
return textController(text)!
}
if let image = content as? ParseImageContent {
return imageController(image)!
}
if let variants = content as? ParseAnswer {
return variantsController(variants)!
}
fatalError("WE cant find a controller")
}
} | mit | 346d3b698cc7c42f7e7ce0b3a1d0c1f4 | 28.857143 | 107 | 0.6764 | 5.30203 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/ActivitityIndicatorView.swift | 1 | 921 | //
// ActivitityIndicatorView.swift
// Podcast
//
// Created by Natasha Armbrust on 11/14/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class LoadingAnimatorUtilities {
static var loadingAnimatorSize: CGFloat = 30
static func createLoadingAnimator() -> NVActivityIndicatorView {
let color: UIColor = .sea
let type: NVActivityIndicatorType = .lineScalePulseOut
let frame = CGRect(x: 0, y: 0, width: loadingAnimatorSize, height: 2/3 * loadingAnimatorSize)
return NVActivityIndicatorView(frame: frame, type: type, color: color, padding: 0)
}
static func createInfiniteScrollAnimator() -> UIActivityIndicatorView {
let view = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: loadingAnimatorSize, height: loadingAnimatorSize))
view.color = .sea
return view
}
}
| mit | 41a555e8a15e2f6ea6da514c217a291c | 31.857143 | 126 | 0.71087 | 4.577114 | false | false | false | false |
ohwutup/ReactiveCocoa | ReactiveCocoaTests/Shared/MKMapViewSpec.swift | 2 | 2173 | import ReactiveSwift
import ReactiveCocoa
import Quick
import Nimble
import enum Result.NoError
import MapKit
@available(tvOS 9.2, *)
class MKMapViewSpec: QuickSpec {
override func spec() {
var mapView: MKMapView!
weak var _mapView: MKMapView?
beforeEach {
mapView = MKMapView(frame: .zero)
_mapView = mapView
}
afterEach {
mapView = nil
// using toEventually(beNil()) here
// since it takes time to release MKMapView
expect(_mapView).toEventually(beNil())
}
it("should accept changes from bindings to its map type") {
expect(mapView.mapType) == MKMapType.standard
let (pipeSignal, observer) = Signal<MKMapType, NoError>.pipe()
mapView.reactive.mapType <~ pipeSignal
observer.send(value: MKMapType.satellite)
expect(mapView.mapType) == MKMapType.satellite
observer.send(value: MKMapType.hybrid)
expect(mapView.mapType) == MKMapType.hybrid
}
it("should accept changes from bindings to its zoom enabled state") {
expect(mapView.isZoomEnabled) == true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
mapView.reactive.isZoomEnabled <~ pipeSignal
observer.send(value: false)
expect(mapView.isZoomEnabled) == false
}
it("should accept changes from bindings to its scroll enabled state") {
expect(mapView.isScrollEnabled) == true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
mapView.reactive.isScrollEnabled <~ pipeSignal
observer.send(value: false)
expect(mapView.isScrollEnabled) == false
}
#if !os(tvOS)
it("should accept changes from bindings to its pitch enabled state") {
expect(mapView.isPitchEnabled) == true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
mapView.reactive.isPitchEnabled <~ pipeSignal
observer.send(value: false)
expect(mapView.isPitchEnabled) == false
}
it("should accept changes from bindings to its rotate enabled state") {
expect(mapView.isRotateEnabled) == true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
mapView.reactive.isRotateEnabled <~ pipeSignal
observer.send(value: false)
expect(mapView.isRotateEnabled) == false
}
#endif
}
}
| mit | c1c1d4ed7d23e92135413706f963418f | 24.267442 | 73 | 0.716061 | 3.880357 | false | false | false | false |
ustwo/videoplayback-ios | VideoPlaybackKit/Interactor/VPKTableViewVideoPlaybackScrollable.swift | 1 | 6311 | //
// VPKScrollingVideoPlaybackInteractor.swift
// DemoVideoPlaybackKit
//
// Created by Sonam on 6/20/17.
// Copyright © 2017 ustwo. All rights reserved.
//
import Foundation
import UIKit
internal enum ScrollDirection {
case up, down, none
}
protocol ScrollInteractor {
func scrollDidHit(targetMidPoint: Int, acceptableOffset: Int, direction: ScrollDirection, tableView: UITableView, view: UIView, cell: UITableViewCell) -> Bool
func scrollDidScrollToTop(_ scrollView: UIScrollView) -> Bool
}
extension ScrollInteractor where Self: UIScrollViewDelegate {
//default implementations
//use within scrollDidScrollDelegate method
func scrollDidScrollToTop(_ scrollView: UIScrollView) -> Bool {
return scrollView.contentOffset.y == 0
}
func scrollDidHit(targetMidPoint: Int, acceptableOffset: Int, direction: ScrollDirection, tableView: UITableView, view: UIView, cell: UITableViewCell) -> Bool {
let minTarget = targetMidPoint - acceptableOffset
let maxTarget = targetMidPoint + acceptableOffset
switch direction {
case .up:
let convertedTopCellFrame = tableView.convert(cell.frame, to: view)
let trackingTopCellYOffset = Int(abs(convertedTopCellFrame.origin.y))
return (minTarget...maxTarget).contains(trackingTopCellYOffset)
case .down:
let convertedBottomCellFrame = tableView.convert(cell.frame, to: view)
let trackingBottomCellYOffset = Int(tableView.frame.height) - Int(abs(convertedBottomCellFrame.origin.y))
return (minTarget...maxTarget).contains(trackingBottomCellYOffset)
case .none:
return false
}
}
}
protocol VPKTableViewVideoPlaybackScrollable: ScrollInteractor {
var tableView: UITableView { get set }
static var scrollAcceptableOffset: Int { get }
func trackVideoViewCellScrolling() //Use with scrollViewDidScroll
func handleAutoplayInTopVideoCell()
}
extension VPKTableViewVideoPlaybackScrollable where Self: UIViewController {
static var scrollAcceptableOffset: Int {
return 5
}
func trackVideoViewCellScrolling() {
let sharedVideoManager = VPKVideoPlaybackManager.shared
//Immediately stop the video player if the user triggers the scroll to top (taps status bar)
if scrollDidScrollToTop(tableView) {
sharedVideoManager.isPlayerPlaying() ? sharedVideoManager.stop(): ()
return
}
//We only care if the video player is playing and we want to stop it as it scrolls off screen
if sharedVideoManager.isPlaying {
//Data structure for potential video cell thats currently playing a video
var playingVideoCellTuple: (indexPath: IndexPath, cell: VPKViewInCellProtocol, direction: ScrollDirection)?
//Determine top or bottom cell in tableview is playing
if let topVisibleIndexPath = tableView.indexPathsForVisibleRows?.first,
let topVideoCell = tableView.cellForRow(at: topVisibleIndexPath) as? VPKViewInCellProtocol {
playingVideoCellTuple = (topVisibleIndexPath, topVideoCell, .up)
} else if let bottomVisibleIndexPath = tableView.indexPathsForVisibleRows?.last,
let bottomVideoCell = tableView.cellForRow(at: bottomVisibleIndexPath) as? VPKViewInCellProtocol {
playingVideoCellTuple = (bottomVisibleIndexPath, bottomVideoCell, .down)
}
guard let cellTuple = playingVideoCellTuple else { return }
//Stop video when it scrolls halfway off screen
guard let videoView = cellTuple.cell.videoView else { return }
let targetMidPoint = Int(abs(videoView.frame.height)/2)
//Determine top or bottom based on direction scrolling and actively playing cell
switch cellTuple {
case (_, let topVideoCell, .up) where topVideoCell.videoView!.playerLayer != nil && scrollDidHit(targetMidPoint: targetMidPoint, acceptableOffset: Self.scrollAcceptableOffset, direction: .up, tableView: tableView, view: view, cell: (topVideoCell as? UITableViewCell)!):
sharedVideoManager.cleanup()
case (_, let bottomVideoCell, .down) where bottomVideoCell.videoView!.playerLayer != nil && scrollDidHit(targetMidPoint: targetMidPoint, acceptableOffset: Self.scrollAcceptableOffset, direction: .down, tableView: tableView, view: view, cell: bottomVideoCell as! UITableViewCell):
sharedVideoManager.cleanup()
default:
break
}
}
}
func handleAutoplayInTopVideoCell() {
//Handle when tableview is at the top
if tableView.contentOffset.y == 0 {
print("table at top")
guard let topIndexPath = tableView.indexPathsForVisibleRows?.first,
let videoCell = tableView.cellForRow(at: topIndexPath) as? VPKViewInCellProtocol else { return }
videoCell.videoView?.didTapView()
return
}
if(!tableView.isDecelerating && !tableView.isDragging) {
tableView.visibleCells.forEach { (cell) in
guard let indexPath = tableView.indexPath(for: cell) else { return }
let cellRect = tableView.rectForRow(at: indexPath)
let superView = tableView.superview
let convertedRect = tableView.convert(cellRect, to: superView)
let intersect = tableView.frame.intersection(convertedRect)
let visibleHeight = intersect.height
print("VISIBLE HEIGHT = \(visibleHeight)")
if visibleHeight > cellRect.height * 0.6 {
//cell is visible more than 60%
guard let videoCell = cell as? VPKViewInCellProtocol else { return }
videoCell.videoView?.didTapView()
print("autoplay cell at \(indexPath.row)")
}
}
}
}
}
| mit | 7c73ef4a38af9c409db96564d55ad937 | 43.125874 | 291 | 0.642631 | 5.574205 | false | false | false | false |
avdwerff/KMLParser | KMLParser/Classes/KML.swift | 1 | 6437 | //
// KMLElement.swift
// KMLParser
//
// Created by Alexander van der Werff on 10/03/2017.
// Copyright © 2017 AvdWerff. All rights reserved.
//
import Foundation
import MapKit
protocol KMLValue {
}
/// KML Box values
struct KMLStringValue: KMLValue {
let value: String
}
struct KMLCoordValue: KMLValue {
let coords: [CLLocationCoordinate2D]
}
struct KMLColorValue: KMLValue {
let value: UIColor
}
struct KMLFloatValue: KMLValue {
let value: CGFloat
}
struct KMLBoolValue: KMLValue {
let value: Bool
}
/// KML Element
enum KMLElement: String {
case
document = "Document",
name = "name",
description = "description",
folder = "Folder",
placemark = "Placemark",
multiGeometry = "MultiGeometry",
styleUrl = "styleUrl",
extendedData = "ExtendedData",
data = "Data",
value = "value",
polygon = "Polygon",
point = "Point",
outerBoundaryIs = "outerBoundaryIs",
linearRing = "LinearRing",
tesselLate = "tessellate",
coordinates = "coordinates",
styleMap = "StyleMap",
lineStyle = "LineStyle",
lineString = "LineString",
color = "color",
width = "width",
style = "Style",
polyStyle = "PolyStyle",
fill = "fill",
outline = "outline",
pair = "Pair",
key = "key",
//extension
circle = "Circle",
//abstract
geometry = "Geometry"
/// Converts KML path to String, delimited with :
static func path(with path: [KMLElement]) -> String {
return path.map{ "\($0)" }.joined(separator: ":")
}
static func isGeometry(element: KMLElement) -> Bool {
switch element {
case .polygon, .linearRing, .point:
return true
default:
return false
}
}
}
///
typealias KMLElementPath = [KMLElement]
/// Geometry
protocol Geometry: KMLValue {
func `is`(a element: KMLElement) -> Bool
}
/// Point
struct Point: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .point
}
let coordinate: CLLocationCoordinate2D
}
struct LinearString: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .lineString
}
let coordinates: [CLLocationCoordinate2D]
}
/// LinearRing
struct LinearRing: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .linearRing
}
let coordinates: [CLLocationCoordinate2D]
}
/// Polygon
struct Circle: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .circle
}
let geo: (center: CLLocationCoordinate2D, radius: CLLocationDistance)
}
/// Polygon
struct Polygon: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .polygon
}
let outerBoundaryIs: LinearRing
var innerBoundaryIs: [LinearRing]
}
/// MultiGeometry
struct MultiGeometry: Geometry {
func `is`(a element: KMLElement) -> Bool {
return element == .multiGeometry
}
var elements: [Geometry]
}
extension MultiGeometry {
init() {
self.elements = []
}
}
/// KML Feature
protocol KMLFeature {
var name: String? { get set }
var description: String? { get set }
func annotation(styles: [KMLStyle]?) -> [MKAnnotation]?
var styleId: String? { get set }
var extendedData: [String: String]? { get set }
}
/// Placemark
struct Placemark: KMLFeature {
var name: String?
var description: String?
var geometry: Geometry?
var styleId: String?
var extendedData: [String: String]?
func annotation(styles: [KMLStyle]?) -> [MKAnnotation]? {
guard let geometry = geometry else { return nil }
if let polygon = geometry as? Polygon {
let poly = KMLPolygon(
coordinates: polygon.outerBoundaryIs.coordinates,
count: polygon.outerBoundaryIs.coordinates.count,
interiorPolygons: nil
)
poly.styles = styles ?? []
poly.title = self.name
poly.subtitle = self.description
poly.extendedData = self.extendedData
return [poly]
} else if let line = geometry as? LinearString {
let polyLine = KMLLineString(coordinates: line.coordinates, count: line.coordinates.count)
polyLine.styles = styles ?? []
polyLine.extendedData = self.extendedData
return [polyLine]
} else if let point = geometry as? Point {
let point = KMLAnnotation(coordinate: point.coordinate, title: self.name ?? "", subtitle: self.description ?? "")
point.extendedData = self.extendedData
return [point]
} else if let circle = geometry as? Circle {
let circleElement = KMLCircle(center: circle.geo.center, radius: circle.geo.radius)
circleElement.styles = styles ?? []
circleElement.title = self.name
circleElement.subtitle = self.description
circleElement.extendedData = self.extendedData
return [circleElement]
} else if let multi = geometry as? MultiGeometry {
return
multi.elements.compactMap({ (element) -> MKAnnotation? in
map(element: element, name: name, description: description, styles: styles, extendedData: extendedData)
})
}
return nil
}
}
func map(element: Geometry, name: String?, description: String?, styles: [KMLStyle]?, extendedData: [String: String]?) -> MKAnnotation? {
if let polygon = element as? Polygon {
let poly = KMLPolygon(coordinates: polygon.outerBoundaryIs.coordinates, count: polygon.outerBoundaryIs.coordinates.count, interiorPolygons: nil)
poly.styles = styles ?? []
poly.title = name
poly.subtitle = description
poly.extendedData = extendedData
return poly
} else if let point = element as? Point {
return KMLAnnotation(coordinate: point.coordinate, title: name ?? "", subtitle: description ?? "")
}
// else if let multi = element as? MultiGeometry {
// return multi.elements.map({ (element) -> MKAnnotation in
//
// })
// }
return nil
}
| mit | 3e0831b99e2e50d9bf96851bc5b480d7 | 26.504274 | 152 | 0.597421 | 4.577525 | false | false | false | false |
Maciej-Matuszewski/GRCalendar | GRCalendar/Classes/macOS/GRCalendarView.swift | 1 | 7977 | //
// GRCalendarView.swift
//
// Created by Maciej Matuszewski on 26.08.2017.
// Copyright © 2017 Maciej Matuszewski. All rights reserved.
//
import Cocoa
open class GRCalendarView: NSView {
fileprivate let scrollView = NSScrollView.init()
fileprivate let collectionView = NSCollectionView.init()
fileprivate let dateProvider: GRCalendarDateProvider
open var delegate: GRCalendarViewDelegate?
fileprivate let overHeader = GRCalendarHeader.init(frame: NSRect.init(origin: CGPoint.zero, size: CGSize.init(width: 400, height: 80)))
public init(startDate: Date, endDate: Date) {
self.dateProvider = GRCalendarDateProvider.init(startDate: startDate, endDate: endDate)
super.init(frame: NSRect.zero)
self.wantsLayer = true
self.layer?.backgroundColor = NSColor.white.cgColor
self.configureLayout()
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func configureLayout() {
self.widthAnchor.constraint(equalToConstant: 400).isActive = true
self.heightAnchor.constraint(greaterThanOrEqualToConstant: 400).isActive = true
let collectionViewLayout = NSCollectionViewFlowLayout.init()
collectionViewLayout.itemSize = NSSize.init(width: 40, height: 40)
collectionViewLayout.sectionInset = EdgeInsets.init(top: 6, left: 16, bottom: 6, right: 16)
self.collectionView.collectionViewLayout = collectionViewLayout
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.isSelectable = true
self.collectionView.register(GRCalendarItem.self, forItemWithIdentifier: "item")
self.collectionView.register(GRCalendarHeader.self, forSupplementaryViewOfKind: NSCollectionElementKindSectionHeader, withIdentifier: "header")
self.collectionView.backgroundColors = [NSColor.clear]
self.scrollView.drawsBackground = false
self.scrollView.documentView = self.collectionView
self.scrollView.automaticallyAdjustsContentInsets = false
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.scrollerInsets.right -= 20
let contentView = self.scrollView.contentView
contentView.postsBoundsChangedNotifications = true
NotificationCenter.default.addObserver(self, selector: #selector(self.collectionViewDidScroll), name: NSNotification.Name.NSViewBoundsDidChange, object: contentView)
self.addSubview(self.scrollView)
self.scrollView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
self.scrollView.widthAnchor.constraint(equalToConstant: 400).isActive = true
self.overHeader.configure("", year: "")
self.overHeader.wantsLayer = true
self.overHeader.layer?.backgroundColor = NSColor.white.cgColor
self.overHeader.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.overHeader)
self.overHeader.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.overHeader.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
self.overHeader.widthAnchor.constraint(equalToConstant: 400).isActive = true
self.overHeader.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
public func select(date: Date) {
let indexPath = self.dateProvider.indexPathFor(date)
self.collectionView(collectionView, didSelectItemsAt: [indexPath])
self.collectionView.selectionIndexPaths.insert(indexPath)
self.collectionView.animator().scrollToItems(at: [indexPath], scrollPosition: NSCollectionViewScrollPosition.centeredVertically)
self.collectionViewDidScroll()
}
public func showToday() {
self.select(date: Date())
}
override open func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
self.perform(#selector(self.showToday), with: nil, afterDelay: 0)
self.perform(#selector(self.collectionViewDidScroll), with: nil, afterDelay: 0.1)
}
@objc private func collectionViewDidScroll() {
let y = self.scrollView.contentView.documentVisibleRect.minY
let sectionHeight: CGFloat = 382
let section = y / sectionHeight
let sizeInSection = y.truncatingRemainder(dividingBy: sectionHeight) / sectionHeight
let indexPath = IndexPath.init(item: 0, section: Int(section))
let headerValues = self.dateProvider.valueForHeaderAt(indexPath)
self.overHeader.configure(headerValues.month, year: headerValues.year)
self.overHeader.alphaValue = sizeInSection < 0.6 ? 1 : 4 - sizeInSection * 5
}
}
extension GRCalendarView: NSCollectionViewDataSource {
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return self.dateProvider.numberOfSections()
}
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
return 42
}
public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let cell = collectionView.makeItem(withIdentifier: "item", for: indexPath) as! GRCalendarItem
let date = self.dateProvider.dateFor(indexPath)
let isSelected = collectionView.selectionIndexPaths.contains(indexPath)
cell.configure(
isSelected ? .selected : self.dateProvider.stateForItem(with: date, indexPath: indexPath),
dayOfMonth: self.dateProvider.dayOfMonthFor(date)
)
return cell
}
public func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> NSView {
let header = collectionView.makeSupplementaryView(ofKind: NSCollectionElementKindSectionHeader, withIdentifier: "header", for: indexPath) as! GRCalendarHeader
let headerValues = self.dateProvider.valueForHeaderAt(indexPath)
header.configure(headerValues.month, year: headerValues.year)
return header
}
}
extension GRCalendarView: NSCollectionViewDelegate{
public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
let indexPath = indexPaths.first ?? IndexPath.init()
guard
let date = self.dateProvider.dateFor(indexPath)
else{
return
}
let currentState = self.dateProvider.stateForItem(with: date, indexPath: indexPath)
if currentState == .outsideMonth {
self.select(date: date)
collectionView.selectionIndexPaths.remove(indexPath)
return
}
let item = collectionView.item(at: indexPath) as? GRCalendarItem
item?.configure(.selected)
self.delegate?.calendarView(self, didSelectItemWith: date)
}
public func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
collectionView.reloadItems(at: indexPaths)
}
}
extension GRCalendarView : NSCollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
return NSSize(width: 400, height: 80)
}
}
public protocol GRCalendarViewDelegate {
func calendarView(_ calendarView: GRCalendarView, didSelectItemWith date: Date?)
}
| mit | 3f060407ec489d56d7727d031beeed84 | 42.824176 | 177 | 0.70988 | 5.440655 | false | false | false | false |
gerdmuller/See-A-Note | See A Note/IntervalsViewController.swift | 1 | 1845 | //
// IntervalsViewController
// See A Note
//
// Created by Gerd Müller on 31.08.15.
// Copyright © 2015 Gerd Müller. All rights reserved.
//
import UIKit
import AVFoundation
class IntervalsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var esDur: [[(line: Int, accidental: AccidentalSymbol)]] =
[[(7, .FLAT)], [(8, .NATURAL)], [(9, .NATURAL)], [(10, .FLAT)],
[(11, .FLAT)], [(12, .NATURAL)], [(13, .NATURAL)], [(14, .FLAT)]]
esDur = [[(2, .FLAT)], [(8, .FLAT)]]
scoreLineView.debugLabel = self.debugLabel
scoreLineView.editButton = self.editButton.subviews[0] as? ScoreEditButton
scoreLineView.scoreClef = .F
scoreLineView.keySignature = .NATURAL
scoreLineView.widthFactor = 2
for ii in esDur.indices {
scoreLineView.setNotesForPosition(esDur[ii], head: .HALF, texts: ["es", "f#"])
scoreLineView.nextPosition()
}
}
@IBOutlet weak var scoreLineView: ScoreLineView!
@IBOutlet weak var editButton: ScoreEditButtonView!
@IBOutlet weak var debugLabel: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func toggleDebug(sender: UIButton) {
scoreLineView.debugColor = !scoreLineView.debugColor
scoreLineView.setNeedsDisplay()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
scoreLineView.setNeedsDisplay()
}
}
| mit | 4af674bf06563316bd52fa15ace26178 | 29.7 | 136 | 0.653637 | 4.735219 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch09/InCellDelegate/InCellTV/ButtonCell.swift | 1 | 1674 | //
// ButtonCell.swift
// InCellDelegate
//
// Created by Tim on 15/11/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
class ButtonCell: UITableViewCell {
var delegate: InCellButtonProtocol?
func didTapButton(sender: AnyObject) {
if let delegate = delegate {
delegate.didTapButtonInCell(self)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let button = UIButton(type: UIButtonType.RoundedRect)
button.tag = 1000
button.setTitle("Tap me!", forState: UIControlState.Normal)
button.sizeToFit()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: "didTapButton:", forControlEvents: UIControlEvents.TouchUpInside)
// button.addTarget(cell, action: "didTapButtonInCell", forControlEvents: UIControlEvents.TouchUpInside)
let vConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterY, relatedBy:
NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)
let hConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0)
self.contentView.addSubview(button)
self.contentView.addConstraints([vConstraint, hConstraint])
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 9d25d9a445ebf84c2367d3a6dfd93499 | 31.803922 | 217 | 0.717872 | 4.891813 | false | false | false | false |
davidozhang/spycodes | Spycodes/Objects/ConsolidatedCategories.swift | 1 | 14174 | import Foundation
class ConsolidatedCategories: NSObject, NSCoding {
static var instance = ConsolidatedCategories()
enum CategoryType: Int {
case defaultCategory = 0
case customCategory = 1
}
fileprivate var allCachedCustomCategories: [CustomCategory]?
fileprivate var selectedCategories = Set<SCWordBank.Category>() // Default categories selected for curated word list
fileprivate var selectedCustomCategories = Set<CustomCategory>() // Custom categories selected for curated word list
// Non-host player synchronization data
fileprivate var synchronizedCategories = [String: Bool]() // Mapping from string category to selected boolean
fileprivate var synchronizedCategoryTypes = [String: Int]() // Mapping from string category to category type
fileprivate var synchronizedWordCounts = [String: Int]() // Mapping from string category to word count
fileprivate var synchronizedEmojis = [String: String]() // Mapping from string category to emoji
// MARK: Coder
func encode(with aCoder: NSCoder) {
self.generateSynchronizedCategories()
aCoder.encode(
self.synchronizedCategories,
forKey: SCConstants.coding.categories.rawValue
)
aCoder.encode(
self.synchronizedWordCounts,
forKey: SCConstants.coding.wordCounts.rawValue
)
aCoder.encode(
self.synchronizedCategoryTypes,
forKey: SCConstants.coding.categoryTypes.rawValue
)
aCoder.encode(
self.synchronizedEmojis,
forKey: SCConstants.coding.emojis.rawValue
)
}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
if aDecoder.containsValue(forKey: SCConstants.coding.categories.rawValue),
let categories = aDecoder.decodeObject(forKey: SCConstants.coding.categories.rawValue) as? [String: Bool] {
self.synchronizedCategories = categories
}
if aDecoder.containsValue(forKey: SCConstants.coding.wordCounts.rawValue),
let wordCounts = aDecoder.decodeObject(forKey: SCConstants.coding.wordCounts.rawValue) as? [String: Int] {
self.synchronizedWordCounts = wordCounts
}
if aDecoder.containsValue(forKey: SCConstants.coding.categoryTypes.rawValue),
let categoryTypes = aDecoder.decodeObject(forKey: SCConstants.coding.categoryTypes.rawValue) as? [String: Int] {
self.synchronizedCategoryTypes = categoryTypes
}
if aDecoder.containsValue(forKey: SCConstants.coding.emojis.rawValue),
let emojis = aDecoder.decodeObject(forKey: SCConstants.coding.emojis.rawValue) as? [String: String] {
self.synchronizedEmojis = emojis
}
}
// MARK: Public
func setSelectedCategories(selectedCategories: Set<SCWordBank.Category>) {
self.selectedCategories = selectedCategories
}
func setSelectedCustomCategories(selectedCategories: Set<CustomCategory>) {
self.selectedCustomCategories = selectedCategories
}
func selectCategory(category: SCWordBank.Category, persistSelectionImmediately: Bool) {
self.selectedCategories.insert(category)
if persistSelectionImmediately {
self.persistSelectedCategoriesIfEnabled()
}
}
func unselectCategory(category: SCWordBank.Category, persistSelectionImmediately: Bool) {
self.selectedCategories.remove(category)
if persistSelectionImmediately {
self.persistSelectedCategoriesIfEnabled()
}
}
func selectCustomCategory(category: CustomCategory, persistSelectionImmediately: Bool) {
self.selectedCustomCategories.insert(category)
if persistSelectionImmediately {
self.persistSelectedCategoriesIfEnabled()
}
}
func unselectCustomCategory(category: CustomCategory, persistSelectionImmediately: Bool) {
self.selectedCustomCategories.remove(category)
if persistSelectionImmediately {
self.persistSelectedCategoriesIfEnabled()
}
}
func updateCustomCategory(originalCategory: CustomCategory, updatedCategory: CustomCategory) {
self.removeCustomCategory(category: originalCategory, persistSelectionImmediately: false)
self.addCustomCategory(category: updatedCategory, persistSelectionImmediately: false)
self.unselectCustomCategory(category: originalCategory, persistSelectionImmediately: false)
self.selectCustomCategory(category: updatedCategory, persistSelectionImmediately: true)
}
func addCustomCategory(category: CustomCategory, persistSelectionImmediately: Bool) {
var allCustomCategories = self.getAllCustomCategories()
allCustomCategories.append(category)
SCLocalStorageManager.instance.saveAllCustomCategories(customCategories: allCustomCategories)
self.selectCustomCategory(category: category, persistSelectionImmediately: persistSelectionImmediately)
self.allCachedCustomCategories?.append(category)
}
func removeCustomCategory(category: CustomCategory, persistSelectionImmediately: Bool) {
let allCustomCategories = self.getAllCustomCategories()
let updatedCustomCategories = allCustomCategories.filter {
$0 != category
}
SCLocalStorageManager.instance.saveAllCustomCategories(customCategories: updatedCustomCategories)
self.unselectCustomCategory(category: category, persistSelectionImmediately: persistSelectionImmediately)
if let allCachedCustomCategories = self.allCachedCustomCategories {
self.allCachedCustomCategories = allCachedCustomCategories.filter {
$0 != category
}
}
}
func selectAllCategories() {
for category in SCWordBank.Category.all {
self.selectCategory(category: category, persistSelectionImmediately: false)
}
for category in self.getAllCustomCategories() {
self.selectCustomCategory(category: category, persistSelectionImmediately: false)
}
self.persistSelectedCategoriesIfEnabled()
}
func resetCategories() {
// Retrieve and set to persistent selections if enabled
if SCLocalStorageManager.instance.isLocalSettingEnabled(.persistentSelection) {
SCLocalStorageManager.instance.retrieveSelectedConsolidatedCategories()
return
}
self.selectAllCategories()
}
func persistSelectedCategoriesIfEnabled() {
if !SCLocalStorageManager.instance.isLocalSettingEnabled(.persistentSelection) {
return
}
SCLocalStorageManager.instance.saveSelectedCategories(selectedCategories: self.getSelectedCategories())
SCLocalStorageManager.instance.saveSelectedCustomCategories(selectedCategories: self.getSelectedCustomCategories())
}
func allCategoriesSelected() -> Bool {
return self.selectedCategories.count + self.selectedCustomCategories.count == self.getConsolidatedCategoriesCount()
}
// Host-side consolidation of category name, word count and emoji information in a tuple array
func getConsolidatedCategoriesInfo() -> [(type: CategoryType, name: String, wordCount: Int, emoji: String?)] {
var result = [(type: CategoryType, name: String, wordCount: Int, emoji: String?)]()
// Default category names
for category in SCWordBank.Category.all {
let name = SCWordBank.getCategoryName(category: category)
let wordCount = SCWordBank.getWordCount(category: category)
let emoji = SCWordBank.getCategoryEmoji(category: category)
result.append(
ConsolidatedCategories.split(tuple: (.defaultCategory, name, wordCount, emoji))
)
}
// Custom category names
for category in ConsolidatedCategories.instance.getAllCustomCategories() {
if let name = category.getName() {
let wordCount = category.getWordCount()
result.append(
ConsolidatedCategories.split(tuple: (.customCategory, name, wordCount, category.getEmoji()))
)
}
}
return result.sorted(by: { t1, t2 in
return t1.name.lowercased() < t2.name.lowercased()
})
}
func getConsolidatedCategoriesCount() -> Int {
return SCWordBank.Category.count + self.getAllCustomCategories().count
}
func getTotalWords() -> Int {
var result = 0
for category in self.selectedCategories {
result += SCWordBank.getWordCount(category: category)
}
for category in self.selectedCustomCategories {
result += category.getWordCount()
}
return result
}
// Integrity check
func getTotalWordsWithNonPersistedExistingCategory(originalCategory: CustomCategory?, newNonPersistedCategory: CustomCategory?) -> Int {
if let originalCategory = originalCategory,
let newNonPersistedCategory = newNonPersistedCategory {
return self.getTotalWordsWithDeletedExistingCategory(deletedCategory: originalCategory) + newNonPersistedCategory.getWordCount()
}
return 0
}
func getTotalWordsWithDeletedExistingCategory(deletedCategory: CustomCategory?) -> Int {
if let deletedCategory = deletedCategory {
return self.getTotalWords() - deletedCategory.getWordCount()
}
return 0
}
// Mirrors the mapping function for default categories in SCWordBank
func getCustomCategoryFromString(string: String?) -> CustomCategory? {
let filtered = self.getAllCustomCategories().filter {
$0.getName()?.lowercased() == string?.lowercased()
}
if filtered.count == 1 {
return filtered[0]
}
return nil
}
func getSelectedCategories() -> Array<SCWordBank.Category> {
return Array(self.selectedCategories)
}
func getSelectedCustomCategories() -> Array<CustomCategory> {
return Array(self.selectedCustomCategories)
}
func generateSynchronizedCategories() {
self.resetSynchronizedInfo()
// Default categories
for category in SCWordBank.Category.all {
let name = SCWordBank.getCategoryName(category: category)
self.synchronizedCategories[name] = self.selectedCategories.contains(category)
self.synchronizedWordCounts[name] = SCWordBank.getWordCount(category: category)
self.synchronizedEmojis[name] = SCWordBank.getCategoryEmoji(category: category)
self.synchronizedCategoryTypes[name] = CategoryType.defaultCategory.rawValue
}
// Custom categories
for category in self.getAllCustomCategories() {
if let name = category.getName() {
self.synchronizedCategories[name] = self.selectedCustomCategories.contains(category)
self.synchronizedWordCounts[name] = category.getWordCount()
self.synchronizedEmojis[name] = category.getEmoji()
self.synchronizedCategoryTypes[name] = CategoryType.customCategory.rawValue
}
}
}
func resetSynchronizedInfo() {
self.synchronizedCategories.removeAll()
self.synchronizedCategoryTypes.removeAll()
self.synchronizedWordCounts.removeAll()
self.synchronizedEmojis.removeAll()
}
func categoryExists(category: String?) -> Bool {
// Null category cannot be valid
guard let category = category else {
return true
}
return SCWordBank.getCategoryFromString(string: category) != nil || self.getCustomCategoryFromString(string: category) != nil
}
func isCategorySelected(category: SCWordBank.Category) -> Bool {
return self.selectedCategories.contains(category)
}
func isCustomCategorySelected(category: CustomCategory) -> Bool {
return self.selectedCustomCategories.contains(category)
}
func reset() {
self.resetCategories()
self.resetSynchronizedInfo()
}
// Non-host methods for synchronized categories
func getSynchronizedCategories() -> [String] {
return Array(self.synchronizedCategories.keys.sorted(
by: { s1, s2 in
s1.lowercased() < s2.lowercased()
}
))
}
func getSynchronizedCategoriesCount() -> Int {
return self.synchronizedCategories.count
}
func isSynchronizedCategoryStringSelected(string: String) -> Bool {
guard let result = self.synchronizedCategories[string] else {
return false
}
return result
}
func getSynchronizedEmojiForCategoryString(string: String) -> String? {
guard let result = self.synchronizedEmojis[string] else {
return nil
}
return result
}
func getSynchronizedCategoryTypeForCategoryString(string: String) -> CategoryType? {
guard let result = self.synchronizedCategoryTypes[string] else {
return nil
}
return CategoryType(rawValue: result)
}
func getSynchronizedWordCountForCategoryString(string: String) -> Int {
guard let result = self.synchronizedWordCounts[string] else {
return 0
}
return result
}
// MARK: Private
fileprivate func getAllCustomCategories() -> [CustomCategory] {
if let allCachedCustomCategories = self.allCachedCustomCategories {
return allCachedCustomCategories
}
let retrievedCustomCategories = SCLocalStorageManager.instance.retrieveAllCustomCategories()
self.allCachedCustomCategories = retrievedCustomCategories
return retrievedCustomCategories
}
fileprivate static func split(tuple: (CategoryType, String, Int, String?)) -> (type: CategoryType, name: String, wordCount: Int, emoji: String?) {
return (tuple.0, tuple.1, tuple.2, tuple.3)
}
}
| mit | 3592ae5dee4331184e0b704124ecae88 | 36.797333 | 150 | 0.684352 | 5.82573 | false | false | false | false |
yunzixun/V2ex-Swift | View/TopicDetailHeaderCell.swift | 1 | 5955 | //
// TopicDetailHeaderCell.swift
// V2ex-Swift
//
// Created by huangfeng on 1/18/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
class TopicDetailHeaderCell: UITableViewCell {
/// 头像
var avatarImageView: UIImageView = {
let imageview = UIImageView();
imageview.contentMode=UIViewContentMode.scaleAspectFit;
imageview.layer.cornerRadius = 3;
imageview.layer.masksToBounds = true;
return imageview
}()
/// 用户名
var userNameLabel: UILabel = {
let label = UILabel();
label.textColor = V2EXColor.colors.v2_TopicListUserNameColor;
label.font=v2Font(14);
return label
}()
/// 日期 和 最后发送人
var dateAndLastPostUserLabel: UILabel = {
let label = UILabel();
label.textColor=V2EXColor.colors.v2_TopicListDateColor;
label.font=v2Font(12);
return label
}()
/// 节点
var nodeNameLabel: UILabel = {
let label = UILabel();
label.textColor = V2EXColor.colors.v2_TopicListDateColor
label.font = v2Font(11)
label.backgroundColor = V2EXColor.colors.v2_NodeBackgroundColor
label.layer.cornerRadius=2;
label.clipsToBounds = true
label.isUserInteractionEnabled = true
return label
}()
/// 帖子标题
var topicTitleLabel: UILabel = {
let label = V2SpacingLabel();
label.textColor = V2EXColor.colors.v2_TopicListTitleColor;
label.font = v2Font(17);
label.numberOfLines = 0;
label.preferredMaxLayoutWidth = SCREEN_WIDTH-24;
return label
}()
/// 装上面定义的那些元素的容器
var contentPanel:UIView = {
let view = UIView()
view.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor
return view
}()
weak var itemModel:TopicDetailModel?
var nodeClickHandler:(() -> Void)?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier);
self.setup();
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup()->Void{
self.selectionStyle = .none
self.backgroundColor=V2EXColor.colors.v2_backgroundColor;
self.contentView.addSubview(self.contentPanel);
self.contentPanel.addSubview(self.avatarImageView);
self.contentPanel.addSubview(self.userNameLabel);
self.contentPanel.addSubview(self.dateAndLastPostUserLabel);
self.contentPanel.addSubview(self.nodeNameLabel)
self.contentPanel.addSubview(self.topicTitleLabel);
self.setupLayout()
//点击用户头像,跳转到用户主页
self.avatarImageView.isUserInteractionEnabled = true
self.userNameLabel.isUserInteractionEnabled = true
var userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailHeaderCell.userNameTap(_:)))
self.avatarImageView.addGestureRecognizer(userNameTap)
userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailHeaderCell.userNameTap(_:)))
self.userNameLabel.addGestureRecognizer(userNameTap)
self.nodeNameLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(nodeClick)))
}
fileprivate func setupLayout(){
self.avatarImageView.snp.makeConstraints{ (make) -> Void in
make.left.top.equalTo(self.contentPanel).offset(12);
make.width.height.equalTo(35);
}
self.userNameLabel.snp.makeConstraints{ (make) -> Void in
make.left.equalTo(self.avatarImageView.snp.right).offset(10);
make.top.equalTo(self.avatarImageView);
}
self.dateAndLastPostUserLabel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.avatarImageView);
make.left.equalTo(self.userNameLabel);
}
self.nodeNameLabel.snp.makeConstraints{ (make) -> Void in
make.centerY.equalTo(self.userNameLabel);
make.right.equalTo(self.contentPanel.snp.right).offset(-10)
make.bottom.equalTo(self.userNameLabel).offset(1);
make.top.equalTo(self.userNameLabel).offset(-1);
}
self.topicTitleLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.avatarImageView.snp.bottom).offset(12);
make.left.equalTo(self.avatarImageView);
make.right.equalTo(self.contentPanel).offset(-12);
}
self.contentPanel.snp.makeConstraints{ (make) -> Void in
make.top.left.right.equalTo(self.contentView);
make.bottom.equalTo(self.topicTitleLabel.snp.bottom).offset(12);
make.bottom.equalTo(self.contentView).offset(SEPARATOR_HEIGHT * -1);
}
}
@objc func nodeClick() {
nodeClickHandler?()
}
@objc func userNameTap(_ sender:UITapGestureRecognizer) {
if let _ = self.itemModel , let username = itemModel?.userName {
let memberViewController = MemberViewController()
memberViewController.username = username
V2Client.sharedInstance.centerNavigation?.pushViewController(memberViewController, animated: true)
}
}
func bind(_ model:TopicDetailModel){
self.itemModel = model
self.userNameLabel.text = model.userName;
self.dateAndLastPostUserLabel.text = model.date
self.topicTitleLabel.text = model.topicTitle;
if let avata = model.avata {
self.avatarImageView.fin_setImageWithUrl(URL(string: "https:" + avata)!, placeholderImage: nil, imageModificationClosure: fin_defaultImageModification())
}
if let node = model.nodeName{
self.nodeNameLabel.text = " " + node + " "
}
}
}
| mit | a1a0720d5a8014d8104f1f70890e8ece | 36.819355 | 165 | 0.649778 | 4.645008 | false | false | false | false |
PayNoMind/iostags | Tags/Scenes/TextEntry/Cells/TagTitleCellVM.swift | 2 | 1008 | //
// TagTitleCellVM.swift
// Tags
//
// Created by Tom Clark on 2018-10-04.
// Copyright © 2018 Fluiddynamics. All rights reserved.
//
import Foundation
class TagTitleCellVM {
private let tag: Tag
init(tag: Tag) {
self.tag = tag
}
}
//import UIKit
//
//class SubTaskCellViewModel {
// private var task: Task
//
// // View Bindings
// private(set)var didChangeText: ((String) -> Void)?
//
// var updateTask: ((Task, String) -> Void)?
//
// var title: String {
// return task.title
// }
//
// init(task: Task) {
// self.task = task
// self.didChangeText = { text in
// let oldTask = self.task
// self.task.title = text
// self.updateTask?(oldTask, text)
// }
// }
//}
//
//extension SubTaskCellViewModel: CellRepresentable {
// static var cellName: String {
// return SubTaskCell.name
// }
//
// func cellSelected() {}
//
// func customizeCell(_ cell: UITableViewCell) {
// let newCell = cell as! SubTaskCell
// newCell.setup(self)
// }
//}
| mit | 972564c73e1a7c4c7e648a6808ca2342 | 17.648148 | 56 | 0.609732 | 3.137072 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/managers/TKRegionManager.swift | 1 | 12596 | //
// TKRegionManager.swift
// TripKit
//
// Created by Adrian Schoenig on 26.09.17.
//
//
import Foundation
import CoreLocation
import MapKit
public extension NSNotification.Name {
static let TKRegionManagerUpdatedRegions = NSNotification.Name(rawValue: "TKRegionManagerRegionsUpdatedNotification")
}
public class TKRegionManager: NSObject {
@objc
public static let shared = TKRegionManager()
@objc
public static let UpdatedRegionsNotification = NSNotification.Name.TKRegionManagerUpdatedRegions
private var response: TKAPI.RegionsResponse? {
didSet {
_requiredForModes = nil
}
}
private var _requiredForModes: [String: [String]]?
private override init() {
super.init()
loadRegionsFromCache()
}
public func loadRegionsFromCache() {
guard let data = TKRegionManager.readLocalCache() else { return }
do {
let response = try JSONDecoder().decode(TKAPI.RegionsResponse.self, from: data)
updateRegions(from: response)
} catch {
assertionFailure()
TKLog.warn("Couldn't load regions from cache: \(error)")
}
}
@objc public var hasRegions: Bool {
return response != nil
}
@objc public var regions: [TKRegion] {
return response?.regions ?? []
}
@objc public var regionsHash: NSNumber? {
if let hashCode = response?.hashCode {
return NSNumber(value: hashCode + 2) // Force update after broken polygons
} else {
return nil;
}
}
}
// MARK: - Updating regions data
extension TKRegionManager {
func updateRegions(from response: TKAPI.RegionsResponse) {
// Silently ignore obviously bad data
guard response.modes != nil, response.regions != nil else {
// This asset isn't valid, due to race conditions
// assert(self.response?.hashCode == response.hashCode)
return
}
self.response = response
if let encoded = try? JSONEncoder().encode(response) {
TKRegionManager.saveToCache(encoded)
}
NotificationCenter.default.post(name: .TKRegionManagerUpdatedRegions, object: self)
}
public static var cacheURL: URL {
let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return urls.first!.appendingPathComponent("regions.json")
}
public static func readLocalCache() -> Data? {
return try? Data(contentsOf: cacheURL)
}
public static func saveToCache(_ data: Data) {
try? data.write(to: cacheURL)
}
}
// MARK: - Getting mode details
extension TKRegionManager {
/// - Parameter mode: The mode identifier for which you want the title
/// - Returns: The localized title as defined by the server
@objc
public func title(forModeIdentifier mode: String) -> String? {
return response?.modes?[mode]?.title
}
/// - Parameter mode: The mode identifier for which you want the title
/// - Returns: The localized subtitle as defined by the server
@objc
public func subtitle(forModeIdentifier mode: String) -> String? {
return response?.modes?[mode]?.subtitle
}
/// - Parameter mode: The mode identifier for which you want the official website URL
/// - Returns: The URL as defined by the server
@objc
public func websiteURL(forModeIdentifier mode: String) -> URL? {
return response?.modes?[mode]?.websiteURL
}
/// - Parameter mode: The mode identifier for which you want the official color
/// - Returns: The color as defined by the server
@objc
public func color(forModeIdentifier mode: String) -> TKColor? {
return response?.modes?[mode]?.color
}
/// - Returns: If specified mode identifier is required and can't get disabled.
@objc
public func modeIdentifierIsRequired(_ mode: String) -> Bool {
return response?.modes?[mode]?.required ?? false
}
/// - Returns: List of modes that this mode implies, i.e., enabling the specified modes should also enable all the returned modes.
@objc(impliedModeIdentifiers:)
public func impliedModes(byModeIdentifer mode: String) -> [String] {
return response?.modes?[mode]?.implies ?? []
}
/// - Returns: List of modes that are dependent on this mode, i.e., disabling this mode should also disable all the returned modes.
@objc(dependentModeIdentifiers:)
public func dependentModeIdentifier(forModeIdentifier mode: String) -> [String] {
return self.requiredForModes[mode] ?? []
}
private var requiredForModes: [String: [String]] {
get {
if let required = _requiredForModes {
return required
}
guard let details = response?.modes else { return [:] }
var result = [String: [String]]()
for (mode, detail) in details {
guard let implies = detail.implies, !implies.isEmpty else { continue }
for impliedMode in implies {
result[impliedMode] = (result[impliedMode] ?? []) + [mode]
}
}
_requiredForModes = result
return result
}
}
func remoteImageName(forModeIdentifier mode: String) -> String? {
return response?.modes?[mode]?.icon
}
public func remoteImageIsTemplate(forModeIdentifier mode: String) -> Bool {
return response?.modes?[mode]?.isTemplate ?? false
}
public func remoteImageIsBranding(forModeIdentifier mode: String) -> Bool {
return response?.modes?[mode]?.isBranding ?? false
}
@objc(imageURLForModeIdentifier:ofIconType:)
public func imageURL(forModeIdentifier mode: String?, iconType: TKStyleModeIconType) -> URL? {
guard
let mode = mode,
let details = response?.modes?[mode]
else { return nil }
var part: String?
switch iconType {
case .mapIcon, .listMainMode, .resolutionIndependent:
part = details.icon
case .vehicle:
part = details.vehicleIcon
case .alert:
part = nil // not supported for modes
@unknown default:
part = nil
}
guard let fileNamePart = part else { return nil }
return TKServer.imageURL(iconFileNamePart: fileNamePart, iconType: iconType)
}
public static func sortedModes(in regions: [TKRegion]) -> [TKRegion.RoutingMode] {
let all = regions.map { $0.routingModes }
return sortedFlattenedModes(all)
}
static func sortedFlattenedModes(_ modes: [[TKRegion.RoutingMode]]) -> [TKRegion.RoutingMode] {
guard let first = modes.first else { return [] }
var added = Set<String>()
added = added.union(first.map { $0.identifier })
var all = first
for group in modes.dropFirst() {
for (index, mode) in group.enumerated() where !added.contains(mode.identifier) {
added.insert(mode.identifier)
if index > 0, let previousIndex = all.firstIndex(of: group[index - 1]) {
all.insert(mode, at: previousIndex + 1)
} else if index == 0 {
all.insert(mode, at: 0)
} else {
assertionFailure("We're merging in sequence here; how come the previous element isn't in the list? Previous is: \(group[index - 1]) from \(group)")
all.append(mode)
}
}
}
// Remove specific modes for which we have the generic one
for mode in all {
let generic = TKTransportMode.genericModeIdentifier(forModeIdentifier: mode.identifier)
if generic != mode.identifier, added.contains(generic) {
added.remove(mode.identifier)
all.removeAll { $0.identifier == mode.identifier }
}
}
return all
}
}
// MARK: - Testing coordinates
extension TKRegionManager {
@objc(coordinateIsPartOfAnyRegion:)
public func coordinateIsPartOfAnyRegion(_ coordinate: CLLocationCoordinate2D) -> Bool {
for region in regions {
if region.contains(coordinate) {
return true
}
}
return false
}
/// Used to check if user can route in that area.
@objc(mapRectIntersectsAnyRegion:)
public func mapRectIntersectsAnyRegion(_ mapRect: MKMapRect) -> Bool {
// TODO: How to handle rect spanning 180th medidian?
for region in regions {
if region.intersects(mapRect) {
return true
}
}
return false
}
}
// MARK: - Getting regions by coordinates, etc.
extension TKRegionManager {
/// - Returns: A matching local region or the shared instance of `TKInternationalRegion` if no local region contains this coordinate region.
@objc(regionContainingCoordinateRegion:)
public func region(containing region: MKCoordinateRegion) -> TKRegion {
return self.region(containing: region.topLeft, region.bottomRight)
}
/// Determines the local (non-international) regions for the coordinate pair
///
/// - Parameters:
/// - start: A valid coordinate
/// - end: Another valid coordinate
/// - Returns: An array of either A) no element (if both coordinates are in the
/// international region), B) one element (if both coordinates are in the
/// the same region, or C) two elements (a local region for the start and
/// one for the end coordinates).
@objc(localRegionsForStart:andEnd:)
public func localRegions(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D) -> [TKRegion] {
let startRegions = localRegions(containing: start)
let endRegions = localRegions(containing: end)
if let intersectingRegion = startRegions.intersection(endRegions).first {
return [intersectingRegion]
} else {
return [startRegions, endRegions].compactMap { $0.first }
}
}
/// - Returns: Local regions that overlap with the provided coordinate region. Can be empty.
@objc(localRegionsOverlappingCoordinateRegion:)
public func localRegions(overlapping region: MKCoordinateRegion) -> [TKRegion] {
let mapRect = MKMapRect.forCoordinateRegion(region)
return regions.filter { $0.intersects(mapRect) }
}
/// - Parameter coordinate: A coordinate
/// - Returns: The local (non-international) regions intersecting with the
/// provided coordinate
@objc(localRegionsContainingCoordinate:)
public func localRegions(containing coordinate: CLLocationCoordinate2D) -> Set<TKRegion> {
guard coordinate.isValid else { return [] }
let containing = regions.filter { $0.contains(coordinate) }
return Set(containing)
}
/// - Parameter name: A region code
/// - Returns: The local (non-international) region matching the provided code
@available(*, deprecated, renamed: "localRegion(code:)")
@objc(localRegionWithName:)
public func localRegion(named name: String) -> TKRegion? {
localRegion(code: name)
}
/// - Parameter code: A region code
/// - Returns: The local (non-international) region matching the provided code
public func localRegion(code: String) -> TKRegion? {
return regions.first { $0.code == code }
}
/// Determines a region (local or international) for the coordinate pair
///
/// - Parameters:
/// - first: A valid coordinate
/// - second: Another valid coordinate
/// - Returns: A local region if both lie within the same or the shared
/// international region instance.
@objc(regionContainingCoordinate:andOther:)
public func region(containing first: CLLocationCoordinate2D, _ second: CLLocationCoordinate2D) -> TKRegion {
let local = localRegions(start: first, end: second)
if local.count == 1 {
return local.first!
} else {
return .international
}
}
/// - Parameter coordinate: A valid coordinate
/// - Returns: The time zone of a matching region for this coordinate. Will
/// return `nil` if the coordinate falls outside any supported region.
@objc(timeZoneForCoordinate:)
public func timeZone(for coordinate: CLLocationCoordinate2D) -> TimeZone? {
return regions.first { $0.contains(coordinate) }?.timeZone
}
/// Find city closest to provided coordinate, in same region
///
/// - Parameter target: Coordinate for which to find closest city
/// - Returns: Nearest City
@objc(cityNearestToCoordinate:)
public func city(nearestTo target: CLLocationCoordinate2D) -> TKRegion.City? {
typealias Match = (TKRegion.City, CLLocationDistance)
let cities = localRegions(containing: target).reduce(into: [TKRegion.City]()) { cities, region in
cities.append(contentsOf: region.cities)
}
let best = cities.reduce(nil) { acc, city -> Match? in
guard let distance = target.distance(from: city.coordinate) else { return acc }
if let existing = acc?.1, existing < distance {
return acc
} else {
return (city, distance)
}
}
return best?.0
}
}
| apache-2.0 | e1a2c92a87c38c87937407db1999db65 | 30.808081 | 157 | 0.675453 | 4.463501 | false | false | false | false |
kinetic-fit/sensors-swift-trainers | Sources/SwiftySensorsTrainers/EliteTrainerService.swift | 1 | 4046 | //
// EliteTrainerService.swift
// SwiftySensorsTrainers
//
// https://github.com/kinetic-fit/sensors-swift-trainers
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import CoreBluetooth
import SwiftySensors
import Signals
/// :nodoc:
open class EliteTrainerService: Service, ServiceProtocol {
public static var uuid: String { return "347B0001-7635-408B-8918-8FF3949CE592" }
public static var characteristicTypes: Dictionary<String, Characteristic.Type> = [
ControlPoint.uuid: ControlPoint.self,
OutOfRange.uuid: OutOfRange.self,
SystemWeight.uuid: SystemWeight.self,
TrainerCapabilities.uuid: TrainerCapabilities.self
]
public var controlPoint: ControlPoint? { return characteristic() }
public var systemWeight: SystemWeight? { return characteristic() }
open class ControlPoint: Characteristic {
public static var uuid: String { return "347B0010-7635-408B-8918-8FF3949CE592" }
public static let writeType = CBCharacteristicWriteType.withResponse
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
// TODO: Needed?
//cbCharacteristic.notify(true)
}
}
open class OutOfRange: Characteristic {
public static var uuid: String { return "347B0011-7635-408B-8918-8FF3949CE592" }
var outOfRange: Bool = false
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
if let oor = EliteTrainerSerializer.readOutOfRangeValue(value) {
outOfRange = oor
}
}
super.valueUpdated()
}
}
open class SystemWeight: Characteristic {
public static var uuid: String { return "347B0018-7635-408B-8918-8FF3949CE592" }
public static let writeType = CBCharacteristicWriteType.withResponse
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
}
}
open class TrainerCapabilities: Characteristic {
public static var uuid: String { return "347B0019-7635-408B-8918-8FF3949CE592" }
public static let writeType = CBCharacteristicWriteType.withResponse
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
}
}
@discardableResult open func setTargetPower(_ watts: UInt16) -> [UInt8] {
let bytes = EliteTrainerSerializer.setTargetPower(watts)
controlPoint?.cbCharacteristic.write(Data(bytes), writeType: ControlPoint.writeType)
return bytes
}
@discardableResult open func setBrakeLevel(_ level: Double) -> [UInt8] {
let bytes = EliteTrainerSerializer.setBrakeLevel(level)
controlPoint?.cbCharacteristic.write(Data(bytes), writeType: ControlPoint.writeType)
return bytes
}
@discardableResult open func setSimulationMode(_ grade: Double, crr: Double, wrc: Double, windSpeedKPH: Double = 0, draftingFactor: Double = 1) -> [UInt8] {
let bytes = EliteTrainerSerializer.setSimulationMode(grade, crr: crr, wrc: wrc, windSpeedKPH: windSpeedKPH, draftingFactor: draftingFactor)
controlPoint?.cbCharacteristic.write(Data(bytes), writeType: ControlPoint.writeType)
return bytes
}
@discardableResult open func setRiderWeight(_ riderKG: UInt8, bikeKG: UInt8) -> [UInt8] {
let bytes = [riderKG, bikeKG]
systemWeight?.cbCharacteristic.write(Data(bytes), writeType: SystemWeight.writeType)
return bytes
}
}
| mit | 58442cac030b47ef9833f523e9e69830 | 34.482456 | 160 | 0.640791 | 4.758824 | false | false | false | false |
justindarc/firefox-ios | Client/Frontend/Browser/UserScriptManager.swift | 2 | 3773 | /* 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 WebKit
class UserScriptManager {
// Scripts can use this to verify the *app* (not JS on the web) is calling into them.
public static let securityToken = UUID()
// Singleton instance.
public static let shared = UserScriptManager()
private let compiledUserScripts: [String : WKUserScript]
private let noImageModeUserScript = WKUserScript(source: "window.__firefox__.NoImageMode.setEnabled(true)", injectionTime: .atDocumentStart, forMainFrameOnly: true)
private let nightModeUserScript = WKUserScript(source: "window.__firefox__.NightMode.setEnabled(true)", injectionTime: .atDocumentStart, forMainFrameOnly: true)
private init() {
var compiledUserScripts: [String : WKUserScript] = [:]
// Cache all of the pre-compiled user scripts so they don't
// need re-fetched from disk for each webview.
[(WKUserScriptInjectionTime.atDocumentStart, mainFrameOnly: false),
(WKUserScriptInjectionTime.atDocumentEnd, mainFrameOnly: false),
(WKUserScriptInjectionTime.atDocumentStart, mainFrameOnly: true),
(WKUserScriptInjectionTime.atDocumentEnd, mainFrameOnly: true)].forEach { arg in
let (injectionTime, mainFrameOnly) = arg
let name = (mainFrameOnly ? "MainFrame" : "AllFrames") + "AtDocument" + (injectionTime == .atDocumentStart ? "Start" : "End")
if let path = Bundle.main.path(forResource: name, ofType: "js"),
let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let wrappedSource = "(function() { const SECURITY_TOKEN = '\(UserScriptManager.securityToken)'; \(source) })()"
let userScript = WKUserScript(source: wrappedSource, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly)
compiledUserScripts[name] = userScript
}
}
self.compiledUserScripts = compiledUserScripts
}
public func injectUserScriptsIntoTab(_ tab: Tab, nightMode: Bool, noImageMode: Bool) {
// Start off by ensuring that any previously-added user scripts are
// removed to prevent the same script from being injected twice.
tab.webView?.configuration.userContentController.removeAllUserScripts()
// Inject all pre-compiled user scripts.
[(WKUserScriptInjectionTime.atDocumentStart, mainFrameOnly: false),
(WKUserScriptInjectionTime.atDocumentEnd, mainFrameOnly: false),
(WKUserScriptInjectionTime.atDocumentStart, mainFrameOnly: true),
(WKUserScriptInjectionTime.atDocumentEnd, mainFrameOnly: true)].forEach { arg in
let (injectionTime, mainFrameOnly) = arg
let name = (mainFrameOnly ? "MainFrame" : "AllFrames") + "AtDocument" + (injectionTime == .atDocumentStart ? "Start" : "End")
if let userScript = compiledUserScripts[name] {
tab.webView?.configuration.userContentController.addUserScript(userScript)
}
}
// If Night Mode is enabled, inject a small user script to ensure
// that it gets enabled immediately when the DOM loads.
if nightMode {
tab.webView?.configuration.userContentController.addUserScript(nightModeUserScript)
}
// If No Image Mode is enabled, inject a small user script to ensure
// that it gets enabled immediately when the DOM loads.
if noImageMode {
tab.webView?.configuration.userContentController.addUserScript(noImageModeUserScript)
}
}
}
| mpl-2.0 | 1d88df002452683b1fe3d7bbbc5ba36f | 52.140845 | 168 | 0.688047 | 5.247566 | false | true | false | false |
PrestonV/ios-cannonball | Cannonball/SignInViewController.swift | 1 | 2731 | //
// Copyright (C) 2014 Twitter, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import TwitterKit
class SignInViewController: UIViewController, UIAlertViewDelegate {
// MARK: Properties
@IBOutlet weak var logoView: UIImageView!
@IBOutlet weak var signInTwitterButton: UIButton!
@IBOutlet weak var signInPhoneButton: UIButton!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Color the logo.
logoView.image = logoView.image?.imageWithRenderingMode(.AlwaysTemplate)
logoView.tintColor = UIColor(red: 0, green: 167/255, blue: 155/255, alpha: 1)
// Decorate the Sign In with Twitter and Phone buttons.
let defaultColor = signInPhoneButton.titleLabel?.textColor
decorateButton(signInTwitterButton, color: UIColor(red: 0.333, green: 0.675, blue: 0.933, alpha: 1))
decorateButton(signInPhoneButton, color: defaultColor!)
// Add custom image to the Sign In with Phone button.
let image = UIImage(named: "Phone")?.imageWithRenderingMode(.AlwaysTemplate)
signInPhoneButton.setImage(image, forState: .Normal)
}
private func navigateToMainAppScreen() {
self.performSegueWithIdentifier("ShowThemeChooser", sender: self)
}
// MARK: IBActions
@IBAction func signInWithTwitter(sender: UIButton) {
Twitter.sharedInstance().logInWithCompletion { (session: TWTRSession!, error: NSError!) -> Void in
if session != nil {
self.navigateToMainAppScreen()
}
}
}
@IBAction func signInWithPhone(sender: UIButton) {
Digits.sharedInstance().authenticateWithCompletion { (session: DGTSession!, error: NSError!) -> Void in
if session != nil {
self.navigateToMainAppScreen()
}
}
}
// MARK: Utilities
private func decorateButton(button: UIButton, color: UIColor) {
// Draw the border around a button.
button.layer.masksToBounds = false
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 2
button.layer.cornerRadius = 6
}
}
| apache-2.0 | b0fefa5f28b5c93120e71c01f13515f0 | 32.716049 | 111 | 0.675943 | 4.708621 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.