repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Vadimkomis/Myclok
Pods/Auth0/Auth0/AuthenticationError.swift
2
5789
// AuthenticationError.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** * Represents an error during a request to Auth0 Authentication API */ public class AuthenticationError: Auth0Error, CustomStringConvertible { /** Additional information about the error - seeAlso: `code` & `description` properties */ public let info: [String: Any] /// Http Status Code of the response public let statusCode: Int /** Creates a Auth0 Auth API error when the request's response is not JSON - parameter string: string representation of the response (or nil) - parameter statusCode: response status code - returns: a newly created AuthenticationError */ public required init(string: String? = nil, statusCode: Int = 0) { self.info = [ "code": string != nil ? nonJSONError : emptyBodyError, "description": string ?? "Empty response body", "statusCode": statusCode ] self.statusCode = statusCode } /** Creates a Auth0 Auth API error from a JSON response - parameter info: JSON response from Auth0 - parameter statusCode: Http Status Code of the Response - returns: a newly created AuthenticationError */ public required init(info: [String: Any], statusCode: Int) { self.statusCode = statusCode self.info = info } /** Auth0 error code if the server returned one or an internal library code (e.g.: when the server could not be reached) */ public var code: String { let code = self.info["error"] ?? self.info["code"] return code as? String ?? unknownError } /** Description of the error - important: You should avoid displaying description to the user, it's meant for debugging only. */ public var description: String { let description = self.info["description"] ?? self.info["error_description"] if let string = description as? String { return string } guard self.code == unknownError else { return "Received error with code \(self.code)" } return "Failed with unknown error \(self.info)" } /// When MFA code is required to authenticate public var isMultifactorRequired: Bool { return self.code == "a0.mfa_required" } /// When MFA is required and the user is not enrolled public var isMultifactorEnrollRequired: Bool { return self.code == "a0.mfa_registration_required" } /// When MFA code sent is invalid or expired public var isMultifactorCodeInvalid: Bool { return self.code == "a0.mfa_invalid_code" } /// When password used for SignUp does not match connection's strength requirements. More info will be available in `info` public var isPasswordNotStrongEnough: Bool { return self.code == "invalid_password" && self.value("name") == "PasswordStrengthError" } /// When password used for SignUp was already used before (Reported when password history feature is enabled). More info will be available in `info` public var isPasswordAlreadyUsed: Bool { return self.code == "invalid_password" && self.value("name") == "PasswordHistoryError" } /// When Auth0 rule returns an error. The message returned by the rull will be in `description` public var isRuleError: Bool { return self.code == "unauthorized" } /// When username and/or password used for authentication are invalid public var isInvalidCredentials: Bool { return self.code == "invalid_user_password" } /// When authenticating with web-based authentication and the resource server denied access per OAuth2 spec public var isAccessDenied: Bool { return self.code == "access_denied" } /// When you reached the maximum amount of request for the API public var isTooManyAttempts: Bool { return self.code == "too_many_attempts" } /** Returns a value from error `info` dictionary - parameter key: key of the value to return - returns: the value of key or nil if cannot be found or is of the wrong type. */ public func value<T>(_ key: String) -> T? { return self.info[key] as? T } } extension AuthenticationError: CustomNSError { public static let infoKey = "com.auth0.authentication.error.info" public static var errorDomain: String { return "com.auth0.authentication" } public var errorCode: Int { return 1 } public var errorUserInfo: [String : Any] { return [ NSLocalizedDescriptionKey: self.description, AuthenticationError.infoKey: self ] } }
mit
fd95ac3349561d3f05803a4f44ee75eb
35.639241
152
0.678528
4.57267
false
false
false
false
seungprk/PenguinJump
PenguinJump/PenguinJump/Shark.swift
1
5605
// // Shark.swift // PenguinJump // // Created by Matthew Tso on 6/10/16. // Copyright © 2016 De Anza. All rights reserved. // import SpriteKit class Shark: SKNode { var face = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_face")!)) var mouth = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_mouth")!)) var faceMask = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_face")!)) var fin = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_fin")!)) var wave = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_wave")!)) var shadow = SKSpriteNode(texture: SKTexture(image: UIImage(named: "shark_shadow")!)) var finMask = SKSpriteNode(color: SKColor.blackColor(), size: CGSizeZero) var didBeginKill = false override init() { super.init() // Face node let faceCropNode = SKCropNode() faceCropNode.maskNode = faceMask faceCropNode.zPosition = 20 mouth.anchorPoint = CGPoint(x: 0.5, y: 0.0) mouth.position.y = -face.size.height / 2 face.addChild(mouth) face.position.y -= face.size.height faceCropNode.addChild(face) addChild(faceCropNode) faceMask.anchorPoint = CGPoint(x: 0.5, y: 0.0) faceMask.position.y -= shadow.size.height / 2 - wave.size.height face.anchorPoint = CGPoint(x: 0.5, y: 0.0) face.position.y -= shadow.size.height / 2 - wave.size.height // Set up sprite nodes shadow.physicsBody = shadowPhysicsBody(shadow.texture!, category: SharkCategory) shadow.alpha = 0.1 shadow.zPosition = -20 wave.zPosition = 10 fin.anchorPoint = CGPoint(x: 0.5, y: 0.0) let offset = wave.size.height * 2 wave.position.x += offset * 2 wave.position.y += offset finMask.size = fin.size finMask.anchorPoint = CGPoint(x: 0.5, y: 0.0) finMask.position.y += offset let finCropNode = SKCropNode() finCropNode.maskNode = finMask finCropNode.zPosition = 10 finCropNode.addChild(fin) addChild(finCropNode) addChild(shadow) addChild(wave) // Begin actions bob() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bob() { let bobDepth = 2.0 let bobDuration = 2.0 let bobUp = SKAction.moveBy(CGVector(dx: 0, dy: bobDepth), duration: bobDuration) let bobDown = SKAction.moveBy(CGVector(dx: 0, dy: -bobDepth), duration: bobDuration) bobUp.timingMode = .EaseInEaseOut bobDown.timingMode = .EaseInEaseOut let bob = SKAction.repeatActionForever(SKAction.sequence([bobUp, bobDown])) finMask.runAction(bob) wave.runAction(bob) let counterBob = SKAction.repeatActionForever(SKAction.sequence([bobDown, bobUp])) fin.runAction(counterBob) shadow.runAction(counterBob) } func beginSwimming() { if (self.scene as! GameScene).gameData.soundEffectsOn as Bool { (scene as! GameScene).lurkingSound?.play() } position.x += 100 swimLeft() } func swimLeft() { let swimLeft = SKAction.moveBy(CGVector(dx: -200, dy: 0), duration: 10.0) swimLeft.timingMode = .EaseInEaseOut self.xScale = 1 runAction(swimLeft, completion: { self.swimRight() }) } func swimRight() { let swimRight = SKAction.moveBy(CGVector(dx: 200, dy: 0), duration: 10.0) swimRight.timingMode = .EaseInEaseOut self.xScale = -1 runAction(swimRight, completion: { self.swimLeft() }) } func kill(blockAfterFaceUp block: (() -> ())?) { let bang = SKLabelNode(text: "!") bang.fontName = "Helvetica Neue Condensed Black" bang.fontSize = 18 bang.fontColor = SKColor.whiteColor() bang.position.y += fin.size.height / 2 addChild(bang) let reactionTime = SKAction.waitForDuration(0.2) let faceMoveUp = SKAction.moveBy(CGVector(dx: 0, dy: face.size.height), duration: 0.5) let faceMoveDown = SKAction.moveBy(CGVector(dx: 0, dy: -face.size.height), duration: 0.5) faceMoveUp.timingMode = .EaseOut faceMoveDown.timingMode = .EaseIn if (scene as! GameScene).gameData.soundEffectsOn as Bool { (scene as! GameScene).alertSound?.play() } removeAllActions() finMask.removeAllActions() wave.removeAllActions() fin.removeAllActions() shadow.removeAllActions() runAction(reactionTime, completion: { if (self.scene as! GameScene).gameData.soundEffectsOn as Bool { (self.scene as! GameScene).sharkSound?.play() } self.fin.runAction(faceMoveDown, completion: { self.wave.removeFromParent() self.fin.removeFromParent() }) self.face.runAction(faceMoveUp, completion: { bang.removeFromParent() self.runAction(reactionTime, completion: { block?() self.face.runAction(faceMoveDown) }) }) }) } }
bsd-2-clause
fe0031f6568ddbdc3bdc32dcb5288471
31.964706
97
0.576374
4.290965
false
false
false
false
shyn/cs193p
Caculator/Caculator/ViewController.swift
1
1889
// // ViewController.swift // Caculator // // Created by deepwind on 4/15/17. // Copyright © 2017 deepwind. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var display: UILabel! @IBOutlet weak var dispplayEvaluation: UILabel! var userIsInTheMiddleOfTyping = false var brain = caculatorBrain() @IBAction func appendDigit(_ sender: UIButton) { let digit = sender.currentTitle! print("digit=\(digit)") if digit != "." || (display.text?.range(of: ".") == nil) { if userIsInTheMiddleOfTyping { display.text = display.text! + digit } else { display.text = digit userIsInTheMiddleOfTyping = true } } } @IBAction func operate(_ sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTyping { enter() } if let result = brain.performOperation(symbol: operation) { displayValue = result } else { displayValue = 0 } } @IBAction func enter() { userIsInTheMiddleOfTyping = false if let result = brain.pushOperand(operand: displayValue) { displayValue = result } else { displayValue = 0 } } @IBAction func clear() { brain.clearOpStack() displayValue = 0 dispplayEvaluation.text = "0" } var displayValue: Double { // using computed property is so elegent! get { // parse string to double and return it return NumberFormatter().number(from: display.text!)!.doubleValue } set { display.text = "\(newValue)" // userIsInTheMiddleOfTyping = false } } }
mit
fd9ee2ff057ad88fabae4ab59c6f6f87
24.513514
77
0.548199
5.088949
false
false
false
false
RevenueCat/purchases-ios
Tests/TestingApps/PurchaseTesterSwiftUI/Shared/Views/Offerings/OfferingDetailView.swift
1
4627
// // OfferingDetailView.swift // PurchaseTester // // Created by Josh Holtz on 2/1/22. // import Foundation import SwiftUI import RevenueCat struct OfferingDetailView: View { let offering: RevenueCat.Offering var body: some View { VStack(alignment: .leading) { List(offering.availablePackages) { package in Section { PackageItem(package: package) } } }.navigationTitle(offering.serverDescription) } struct PackageItem: View { let package: RevenueCat.Package @State private var isEligible: Bool? = nil func checkIntroEligibility() async { guard self.isEligible == nil else { return } let productIdentifier = package.storeProduct.productIdentifier let results = await Purchases.shared.checkTrialOrIntroDiscountEligibility(productIdentifiers: [productIdentifier]) self.isEligible = results[productIdentifier]?.status == .eligible } var body: some View { VStack(alignment: .center) { HStack(alignment: .center) { VStack(alignment: .leading) { Text("**Title:** \(package.storeProduct.localizedTitle)") Text("**Desc:** \(package.storeProduct.localizedDescription)") Text("**Pkg Id:** \(package.identifier)") Text("**Sub Group:** \(package.storeProduct.subscriptionGroupIdentifier ?? "-")") Text("**Package type:** \(package.display)") if let period = package.storeProduct.sk1Product?.subscriptionPeriod?.unit.rawValue { Text("**Sub Period:** \(period)") } else { Text("**Sub Period:** -") } if let isEligible = self.isEligible { Text("**Intro Elig:** \(isEligible ? "yes" : "no")") } else { Text("**Intro Elig:** <loading>") } } Spacer() Text("\(package.storeProduct.localizedPriceString)") } Divider() Text("Buy as Package") .foregroundColor(.blue) .padding(.vertical, 10) .onTapGesture { Task<Void, Never> { await self.purchaseAsPackage() } } Divider() Text("Buy as Product") .foregroundColor(.blue) .padding(.vertical, 10) .onTapGesture { Task<Void, Never> { await self.purchaseAsProduct() } } Divider() NavigationLink(destination: PromoOfferDetailsView(package: package)) { Text("View Promo Offers") .foregroundColor(.blue) .padding(.vertical, 10) } }.task { await self.checkIntroEligibility() } } private func purchaseAsPackage() async { do { let result = try await Purchases.shared.purchase(package: self.package) self.completedPurchase(result) } catch { print("🚀 Failed purchase: 💁‍♂️ - Error: \(error)") } } private func purchaseAsProduct() async { do { let result = try await Purchases.shared.purchase(product: self.package.storeProduct) self.completedPurchase(result) } catch { print("🚀 Purchase failed: 💁‍♂️ - Error: \(error)") } } private func completedPurchase(_ data: PurchaseResultData) { print("🚀 Info 💁‍♂️ - Transaction: \(data.transaction?.description ?? "")") print("🚀 Info 💁‍♂️ - Info: \(data.customerInfo)") print("🚀 Info 💁‍♂️ - User Cancelled: \(data.userCancelled)") } } }
mit
cc0e9490cb2d75128f4801b9e58944bf
34.130769
126
0.446245
5.993438
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01033-swift-declcontext-lookupqualified.swift
11
636
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class a<f : g, g : g where f.f == g> { } protocol g { typealias f } struct c<h : g> : g { typealias e = a<c<h>, f> class d<c>: NSObject { init(b: c) { g) { h } } protocol f { }} struct c<d: Sequence, b where Optional<b> == d.Iterator.Element>
apache-2.0
1c83fbe0b6b9310dfc0a994f6de6f55b
26.652174
78
0.683962
3.117647
false
false
false
false
ImperialCollegeDocWebappGroup/webappProject
webapp/ViewController.swift
1
1633
// // ViewController.swift // webapp // // Created by Shan, Jinyi on 25/05/2015. // Copyright (c) 2015 Shan, Jinyi. All rights reserved. // import UIKit class ViewController: UIViewController { var portNumber = 1111 @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var enterButton: UIButton! @IBOutlet weak var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() enterButton.layer.cornerRadius = 5 logoutButton.layer.cornerRadius = 5 let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.blackColor()] self.navigationController?.navigationBarHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults() let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int if (isLoggedIn != 1) { self.performSegueWithIdentifier("goto_login", sender: self) } else { self.usernameLabel.text = prefs.valueForKey("USERNAME") as! NSString as String } } @IBAction func LogoutTapped(sender: UIButton) { let appDomain = NSBundle.mainBundle().bundleIdentifier NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!) self.performSegueWithIdentifier("goto_login", sender: self) } }
gpl-3.0
625655c3a4a5f198028e12ebf73661c1
28.690909
92
0.65891
5.217252
false
false
false
false
yangyu2010/YYPageView
YYPageView/Classes/YYTitleViewStyle.swift
1
954
// // YYTitleViewStyle.swift // YYPageView // // Created by Young on 2017/4/29. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit public class YYTitleViewStyle { public init() { } /// titleView高度 public var titleViewHeight: CGFloat = 44 /// 默认颜色-必须是RGB格式 public var normalColor: UIColor = UIColor(r: 0, g: 0, b: 0) /// 选中颜色-必须是RGB格式 public var selectColor: UIColor = UIColor(r: 255, g: 127, b: 0) /// 字体 public var fontSize: CGFloat = 15 /// 是否可以滚动 public var isScrollEnble: Bool = false /// 间距 public var itemMargin: CGFloat = 20 /// 是否显示底部横线 public var isShowScrollLine: Bool = false /// 横线高度 public var scrollLineHeight: CGFloat = 2 /// 横线颜色 public var scrollLineColor: UIColor = .orange }
mit
ddc70a2728f094b1e29d09a2aad8474f
18.522727
67
0.589057
3.869369
false
false
false
false
manfengjun/KYMart
Section/Mine/Controller/KYBonusToMoneyViewController.swift
1
3481
// // KYBonusToMoneyViewController.swift // KYMart // // Created by JUN on 2017/7/3. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import IQKeyboardManagerSwift class KYBonusToMoneyViewController: BaseViewController { @IBOutlet weak var codeBgView: UIView! @IBOutlet weak var saveBtn: UIButton! @IBOutlet weak var bonusL: UILabel! @IBOutlet weak var amountT: UITextField! @IBOutlet weak var codeT: UITextField! @IBOutlet weak var infoView: UIView! @IBOutlet weak var headH: NSLayoutConstraint! fileprivate lazy var codeView : PooCodeView = { let codeView = PooCodeView(frame: CGRect(x: 0, y: 0, width: 70, height: 25), andChange: nil) return codeView! }() fileprivate lazy var headView : KYUserInfoView = { let headView = KYUserInfoView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*3/5 + 51 + 51)) headView.userModel = SingleManager.instance.userInfo return headView }() var bonus:String? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.subviews[0].alpha = 0 IQKeyboardManager.sharedManager().enable = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.subviews[0].alpha = 1 IQKeyboardManager.sharedManager().enable = false } override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { setBackButtonInNav() saveBtn.layer.masksToBounds = true saveBtn.layer.cornerRadius = 5.0 codeBgView.addSubview(codeView) bonusL.text = bonus headH.constant = SCREEN_WIDTH*3/5 + 51 infoView.addSubview(headView) headView.titleL.text = "优惠券兑换余额" headView.userModel = SingleManager.instance.userInfo } @IBAction func saveAction(_ sender: UIButton) { if (amountT.text?.isEmpty)! { Toast(content: "金额不能为空") return } let codeText = NSString(string: codeT.text!) let codeStr = NSString(string: codeView.changeString) let params = ["money":amountT.text!] if codeText.caseInsensitiveCompare(codeStr as String).rawValue == 0 { SJBRequestModel.push_fetchBonusToMoneyData(params: params as [String : AnyObject], completion: { (response, status) in if status == 1{ self.Toast(content: "申请成功") self.navigationController?.popViewController(animated: true) } else { self.Toast(content: response as! String) } }) } else { Toast(content: "验证码错误!") } } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0cba8c5b90dd91a6952a312671d9371d
32.647059
130
0.625874
4.72077
false
false
false
false
MiniKeePass/MiniKeePass
MiniKeePass/Password Generator View/CharacterSetsViewController.swift
1
3277
/* * Copyright 2016 Jason Rush and John Flanagan. All rights reserved. * * 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 struct CharacterSet { static let UpperCase = 1 << 0 static let LowerCase = 1 << 1 static let Digits = 1 << 2 static let Minus = 1 << 3 static let Underline = 1 << 4 static let Space = 1 << 5 static let Special = 1 << 6 static let Brackets = 1 << 7 static let Default = (UpperCase | LowerCase | Digits) } class CharacterSetsViewController: UITableViewController { @IBOutlet weak var upperCaseSwitch: UISwitch! @IBOutlet weak var lowerCaseSwitch: UISwitch! @IBOutlet weak var digitsSwitch: UISwitch! @IBOutlet weak var minusSwitch: UISwitch! @IBOutlet weak var underlineSwitch: UISwitch! @IBOutlet weak var spaceSwitch: UISwitch! @IBOutlet weak var specialSwitch: UISwitch! @IBOutlet weak var bracketsSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() let appSettings = AppSettings.sharedInstance() as AppSettings let charSets = appSettings.pwGenCharSets() upperCaseSwitch.isOn = (charSets & CharacterSet.UpperCase) != 0 lowerCaseSwitch.isOn = (charSets & CharacterSet.LowerCase) != 0 digitsSwitch.isOn = (charSets & CharacterSet.Digits) != 0 minusSwitch.isOn = (charSets & CharacterSet.Minus) != 0 underlineSwitch.isOn = (charSets & CharacterSet.Underline) != 0 spaceSwitch.isOn = (charSets & CharacterSet.Space) != 0 specialSwitch.isOn = (charSets & CharacterSet.Special) != 0 bracketsSwitch.isOn = (charSets & CharacterSet.Brackets) != 0 } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) var charSets = 0 if (upperCaseSwitch.isOn) { charSets |= CharacterSet.UpperCase } if (lowerCaseSwitch.isOn) { charSets |= CharacterSet.LowerCase } if (digitsSwitch.isOn) { charSets |= CharacterSet.Digits } if (minusSwitch.isOn) { charSets |= CharacterSet.Minus } if (underlineSwitch.isOn) { charSets |= CharacterSet.Underline } if (spaceSwitch.isOn) { charSets |= CharacterSet.Space } if (specialSwitch.isOn) { charSets |= CharacterSet.Special } if (bracketsSwitch.isOn) { charSets |= CharacterSet.Brackets } let appSettings = AppSettings.sharedInstance() as AppSettings appSettings.setPwGenCharSets(charSets) } }
gpl-3.0
cb7202ed7818f3dd7a3dcbbb0ac3bd6f
35.411111
72
0.649985
4.551389
false
false
false
false
Brightify/DataMapper
Source/Core/Mappable/Mappable.swift
1
1493
// // Mappable.swift // DataMapper // // Created by Filip Dolnik on 21.10.16. // Copyright © 2016 Brightify. All rights reserved. // public typealias SerializableAndDeserializable = Serializable & Deserializable public protocol Mappable: SerializableAndDeserializable { mutating func mapping(_ data: inout MappableData) throws } extension Mappable { public func serialize(to data: inout SerializableData) { mapping(&data) } } extension Mappable { public mutating func mapping(_ data: DeserializableData) throws { var wrapper: MappableData = DeserializableMappableDataWrapper(delegate: data) try mapping(&wrapper) } public func mapping(_ data: inout SerializableData) { do { var wrapper: MappableData = SerializableMappableDataWrapper(delegate: data) var s = self try s.mapping(&wrapper) if let wrapper = wrapper as? SerializableMappableDataWrapper { data = wrapper.delegate } } catch { fatalError("Mapping called for serialization cannot throw exception.") } } } // Mutating function from extension cannot be called on Class instance. extension Mappable where Self: AnyObject { public func mapping(_ data: DeserializableData) throws { var wrapper: MappableData = DeserializableMappableDataWrapper(delegate: data) var s = self try s.mapping(&wrapper) } }
mit
f63f55d8cf4e2c20699d5dc2b9141942
27.150943
87
0.660858
5.040541
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
Playgrounds/hearthstone.playground/Contents.swift
1
4855
// // hearthstone.playground // iOS Networking // // Created by Jarrod Parkes on 09/30/15. // Copyright (c) 2015 Udacity. All rights reserved. // import Foundation /* Path for JSON files bundled with the Playground */ var pathForHearthstoneJSON = NSBundle.mainBundle().pathForResource("hearthstone", ofType: "json") /* Raw JSON data (...simliar to the format you might receive from the network) */ var rawHearthstoneJSON = NSData(contentsOfFile: pathForHearthstoneJSON!) /* Error object */ var parsingHearthstoneError: NSError? = nil /* Parse the data into usable form */ var parsedHearthstoneJSON = try! NSJSONSerialization.JSONObjectWithData(rawHearthstoneJSON!, options: .AllowFragments) as! NSDictionary func parseJSONAsDictionary(dictionary: NSDictionary) { print(dictionary) guard let cards = dictionary["Basic"] as? [[String : AnyObject]] else { print("Could not find value for key: Basic") return } let numberOfFiveDollarMinions = cards.filter { card in guard let minion = card["type"] as? String where minion == "Minion", let cost = card["cost"] as? Int where cost == 5 else { return false } return true }.count print("\(numberOfFiveDollarMinions) minions have a cost of 5") let weaponsOfDurabilityTwo = cards.filter { card in guard let weapon = card["type"] as? String where weapon == "Weapon", let durability = card["durability"] as? Int where durability == 2 else { return false } return true }.count print("\(weaponsOfDurabilityTwo) weapons have a durability of 2") let minionsWithBattleCry = cards.filter { card in guard let minion = card["type"] as? String where minion == "Minion", let text = card["text"] as? String where text.containsString("Battlecry") else { return false } return true }.count print("\(minionsWithBattleCry) minions mention the 'Battlecry' effect in their text") let commonMinions = cards.filter { card in guard let minion = card["type"] as? String where minion == "Minion", let common = card["rarity"] as? String where common == "Common" else { return false } return true } let averageCostOfCommonMinion = Double(commonMinions.reduce(0) { total, card in guard let cost = card["cost"] as? Int else { return total } return total + cost }) / Double(commonMinions.count) print("\(averageCostOfCommonMinion) is the average cost of a common minion.") var totalOfMinions: Double = 0.0 let averageStatsToCostRatioMinions = cards.reduce(0.0) { total, card in guard let minion = card["type"] as? String where minion == "Minion", let cost = card["cost"] as? Double where cost > 0, let attack = card["attack"] as? Double, let health = card["health"] as? Double else { print("Unable to cast as Double") return total } totalOfMinions += 1 return total + ((attack + health) / cost) } / totalOfMinions print("\(averageStatsToCostRatioMinions) is the average stats-to-cost-ratio for all minions.") } parseJSONAsDictionary(parsedHearthstoneJSON) struct Solution { /** Hearthstone Solution You can find the solution playground in the Playgrounds directory of the course repository. Here are some highlights of things we did to solve the problems: Creating Dictionaries with Key Values from an Array Since one of the questions requires us to calculate values based on card rarity, we used an array of known rarity keys to elegantly store calculations into dictionaries: let rarities = ["Free", "Common"] // initialization... for rarity in rarities { numCostForRarityItemsDictionary[rarity] = 0 sumCostForRarityDictionary[rarity] = 0 } Then, later in the code when we parse a card's rarity, we can easily add it to our running totals: guard let rarityForCard = cardDictionary["rarity"] as? String else { print("Cannot find key 'rarityForCard' in \(cardDictionary)") return } numCostForRarityItemsDictionary[rarityForCard]! += 1 sumCostForRarityDictionary[rarityForCard]! += manaCost Creating an Array of Dictionaries Like in the previous exercise, we can use one line to create the array of dictionaries (card dictionaries) as seen in the JSON: guard let arrayOfBasicSetCardDictionaries = parsedHearthstoneJSON["Basic"] as? [[String:AnyObject]] else { print("Cannot find key 'Basic' in \(parsedHearthstoneJSON)") return } */ }
mit
4d6fbd6c5e8887c3d6007c08de296929
35.503759
173
0.649434
4.512082
false
false
false
false
mo3bius/My-Simple-Instagram
My-Simple-Instagram/Networking/Response Parsers/ReponserParser+Comments.swift
1
1472
// // ReponserParser+Comment.swift // My-Simple-Instagram // // Created by Luigi Aiello on 04/11/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import Foundation import SwiftyJSON extension ResponseParser { class Comments { class func parseAndStoreComment(json: JSON, imageId: String) -> Bool { let data = json["data"] guard let commentId = data["id"].string, let commentText = data["text"].string, let creationTime = data["created_time"].string, let userId = data["from"]["id"].string, let username = data["from"]["username"].string, let profilePicture = data["from"]["profile_picture"].string, let fullName = data["from"]["full_name"].string else { print("User parse error") return false } let comment = Comment(commentId: commentId, imageId: imageId, commentText: commentText, creationTime: creationTime, userId: userId, username: username, profilePicture: profilePicture, fullName: fullName) return comment.store(update: true) } } }
mit
4497c9d922e5c8a66a812ba6d7ebaac2
34.02381
78
0.480625
5.657692
false
false
false
false
jeannustre/HomeComics
HomeComics/InterfaceSettingsTableViewController.swift
1
3935
// // InterfaceSettingsTableViewController.swift // HomeComics // // Created by Jean Sarda on 03/05/2017. // Copyright © 2017 Jean Sarda. All rights reserved. // import UIKit import AKPickerView class InterfaceSettingsTableViewController: UITableViewController { @IBOutlet var secondaryColorCell: UITableViewCell! @IBOutlet var primaryColorCell: UITableViewCell! @IBOutlet var booksPerRowCell: HCPickerTableViewCell! let pickerOptions = ["1", "2", "3", "4", "5", "6"] // Number of books per row var defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() self.primaryColorCell.imageView?.image = colorImage //self.primaryColorCell.imageView?.tintColor = UIColor.flatPink() self.secondaryColorCell.imageView?.image = colorImage booksPerRowCell.picker?.delegate = self booksPerRowCell.picker?.dataSource = self let booksPerRowValue = defaults.integer(forKey: "booksPerRow") print("booksPerRowValue : \(booksPerRowValue)") booksPerRowCell.picker?.selectItem(booksPerRowValue - 1) // booksPerRowCell. //print("cell bounds : \(self.booksPerRowCell.bounds.debugDescription)") //print("cell label bounds : \(self.booksPerRowCell.textLabel?.bounds.debugDescription)") //self.booksPerRowCell.addSubview(picker) // self.booksPerRowCell.accessoryView = picker //self.secondaryColorCell.imageView?.tintColor = UIColor.flatTealColorDark() //tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorInset = UIEdgeInsets.zero self.setColors() } override func viewWillAppear(_ animated: Bool) { self.setColors() } private func setColors() { let primaryColorHex = defaults.string(forKey: "primaryColor") let secondaryColorHex = defaults.string(forKey: "secondaryColor") self.primaryColorCell.imageView?.tintColor = UIColor(hexString: primaryColorHex) if secondaryColorHex != "none" { self.secondaryColorCell.imageView?.tintColor = UIColor(hexString: secondaryColorHex) } self.secondaryColorCell.imageView?.tintColor = secondaryColorHex != "none" ? UIColor(hexString: secondaryColorHex) : UIColor.clear } lazy var colorImage: UIImage? = { let image = UIImage(named: "Circle-full") let rendered = image?.withRenderingMode(.alwaysTemplate) return rendered }() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let colorViewController = segue.destination as! ColorPickerTableViewController colorViewController.defaults = defaults if (segue.identifier == "primaryColorPicker") { colorViewController.navigationItem.title = "Primary Color" colorViewController.key = "primaryColor" } if (segue.identifier == "secondaryColorPicker") { colorViewController.navigationItem.title = "Secondary Color" colorViewController.key = "secondaryColor" } } } extension InterfaceSettingsTableViewController: AKPickerViewDataSource { func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int { return pickerOptions.count } func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String { return pickerOptions[item] } } extension InterfaceSettingsTableViewController: AKPickerViewDelegate { func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int) { print("Selected item at \(item)") let numberOfRows = Int(pickerOptions[item]) defaults.set(numberOfRows, forKey: "booksPerRow") } }
gpl-3.0
4e9381ee589d2beb91d187df76d57b16
35.425926
138
0.681495
5.095855
false
false
false
false
Diego5529/tcc-swift3
tcc-swift3/src/model/bean/UserBean.swift
1
5111
// // UserBean.swift // tcc-swift3 // // Created by Diego Oliveira on 05/02/17. // Copyright © 2017 DO. All rights reserved. // import Foundation import CoreData class UserBean : NSObject { var id: Int16 = 0 var user_id: Int16 = 0 var password_confirmation: String? var email: String? var name: String? var password: String? var token: String? var deviseMinPassword = 6 //Dao class func saveUser(context: NSManagedObjectContext, user: UserBean){ let userObj: NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) userObj.setValue(user.id, forKey: "id") userObj.setValue(user.user_id, forKey: "user_id") userObj.setValue(user.name, forKey: "name") userObj.setValue(user.email, forKey: "email") userObj.setValue(user.token, forKey: "token") } class func getMaxUser(context: NSManagedObjectContext) -> Int16 { var idMax = 0 let select = NSFetchRequest<NSFetchRequestResult>(entityName: "User") do { let results = try context.fetch(select) idMax = results.count + 1 }catch{ } return Int16(idMax) } class func getUserByEmail(context: NSManagedObjectContext, email: String) -> UserBean { var user = UserBean() let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "User") fetchRequest.predicate = NSPredicate(format: "email == %@", email.lowercased()) do { let obj = try context.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) if obj.count > 0 { user = UserBean.serializer(object: obj.first as AnyObject) } } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } return user } // class func serializer(object: AnyObject) -> UserBean { let userBean = UserBean() userBean.id = object.value(forKey: "id") as! Int16 userBean.user_id = object.value(forKey: "user_id") as! Int16 userBean.name = object.value(forKey: "name") as? String userBean.email = object.value(forKey: "email") as? String return userBean } // //Validations func validateCreateUser(userEmail: String, userName: String, userPassword: String, userConfirmationPassword: String) -> String{ var message = "" if (userName.isEmpty){ message = "Name can not be empty." } if (message.isEmpty) { message = self.validateLoginUser(userEmail: userEmail, userPassword: userPassword) if (message.isEmpty){ message = validateConfirmationPassword(userPassword: userPassword, userConfirmationPassword: userConfirmationPassword) } } return message } func validateLoginUser(userEmail: String, userPassword: String) -> String { var message = "" message = validateResetPassword(userEmail: userEmail) if (message.isEmpty) { message = validatePassword(userPassword: userPassword) } return message } func validateResetPassword(userEmail: String) -> String { var message = "" if (userEmail.isEmpty){ message = "Email can not be empty." } return message } func validateUpdatePassword(userPassword: String, userConfirmationPassword: String) -> String { var message = "" message = validatePassword(userPassword: userPassword) if message.isEmpty { message = validateConfirmationPassword(userPassword: userPassword, userConfirmationPassword: userConfirmationPassword) } return message } func validatePassword (userPassword: String) -> String { var message = "" if (userPassword.isEmpty){ message = "Password can not be empty." }else if !(userPassword.characters.count >= deviseMinPassword){ message = String.init(format: "Password can not be less than %i characters.", deviseMinPassword) } return message; } func validateConfirmationPassword(userPassword: String, userConfirmationPassword: String) -> String { var message = "" if (userConfirmationPassword.isEmpty){ message = "Confirmation Password can not be empty." }else if !(userConfirmationPassword.characters.count >= deviseMinPassword){ message = String.init(format: "Confirmation Password can not be less than %i characters.", deviseMinPassword) }else if (userPassword != userConfirmationPassword){ message = "can not be different from password" } return message } }
mit
72f6e5596da591424282ae9f697dbdeb
30.54321
134
0.593151
4.985366
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/BorderWaitItem.swift
2
1270
// // BorderWaitItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // 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 RealmSwift class BorderWaitItem: Object { @objc dynamic var id: Int = 0 @objc dynamic var route: Int = 0 @objc dynamic var waitTime: Int = 0 @objc dynamic var name: String = "" @objc dynamic var lane: String = "" @objc dynamic var direction: String = "" @objc dynamic var updated: String = "" @objc dynamic var selected: Bool = false @objc dynamic var delete: Bool = false override static func primaryKey() -> String? { return "id" } }
gpl-3.0
83b821776dead4ebe6bb601f98f6bcec
32.421053
72
0.693701
4.044586
false
false
false
false
curoo/OAuthSwift
OAuthSwift/OAuthSwiftClient.swift
3
9229
// // OAuthSwiftClient.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation import Accounts var dataEncoding: NSStringEncoding = NSUTF8StringEncoding public class OAuthSwiftClient { private(set) public var credential: OAuthSwiftCredential public init(consumerKey: String, consumerSecret: String) { self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret) } public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret) self.credential.consumer_key = consumerKey self.credential.consumer_secret = consumerSecret } public func get(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.request(urlString, method: "GET", parameters: parameters, success: success, failure: failure) } public func post(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.request(urlString, method: "POST", parameters: parameters, success: success, failure: failure) } public func put(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.request(urlString, method: "PUT", parameters: parameters, success: success, failure: failure) } public func delete(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.request(urlString, method: "DELETE", parameters: parameters, success: success, failure: failure) } public func patch(urlString: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.request(urlString, method: "PATCH", parameters: parameters, success: success, failure: failure) } public func request(url: String, method: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { if let request = makeRequest(url, method: method, parameters: parameters) { request.successHandler = success request.failureHandler = failure request.start() } } public func makeRequest(urlString: String, method: String, parameters: Dictionary<String, AnyObject>) -> OAuthSwiftHTTPRequest? { if let url = NSURL(string: urlString) { let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters) request.headers = self.credential.makeHeaders(url, method: method, parameters: parameters) request.dataEncoding = dataEncoding request.encodeParameters = true return request } return nil } public func postImage(urlString: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { self.multiPartRequest(urlString, method: "POST", parameters: parameters, image: image, success: success, failure: failure) } func multiPartRequest(url: String, method: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { if let request = makeRequest(url, method: method, parameters: parameters) { var parmaImage = [String: AnyObject]() parmaImage["media"] = image let boundary = "AS-boundary-\(arc4random())-\(arc4random())" let type = "multipart/form-data; boundary=\(boundary)" let body = self.multiPartBodyFromParams(parmaImage, boundary: boundary) request.HTTPBodyMultipart = body request.contentTypeMultipart = type request.successHandler = success request.failureHandler = failure request.start() } } public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData { let data = NSMutableData() let prefixData = "--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding) let seperData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding) for (key, value) in parameters { var sectionData: NSData? var sectionType: String? var sectionFilename = "" if key == "media" { let multiData = value as! NSData sectionData = multiData sectionType = "image/jpeg" sectionFilename = " filename=\"file\"" } else { sectionData = "\(value)".dataUsingEncoding(NSUTF8StringEncoding) } data.appendData(prefixData!) let sectionDisposition = "Content-Disposition: form-data; name=\"media\";\(sectionFilename)\r\n".dataUsingEncoding(NSUTF8StringEncoding) data.appendData(sectionDisposition!) if let type = sectionType { let contentType = "Content-Type: \(type)\r\n".dataUsingEncoding(NSUTF8StringEncoding) data.appendData(contentType!) } // append data data.appendData(seperData!) data.appendData(sectionData!) data.appendData(seperData!) } data.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) return data } public func postMultiPartRequest(url: String, method: String, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) { if let request = makeRequest(url, method: method, parameters: parameters) { let boundary = "POST-boundary-\(arc4random())-\(arc4random())" let type = "multipart/form-data; boundary=\(boundary)" let body = self.multiDataFromObject(parameters, boundary: boundary) request.HTTPBodyMultipart = body request.contentTypeMultipart = type request.successHandler = success request.failureHandler = failure request.start() } } func multiDataFromObject(object: [String:AnyObject], boundary: String) -> NSData? { let data = NSMutableData() let prefixString = "--\(boundary)\r\n" let prefixData = prefixString.dataUsingEncoding(NSUTF8StringEncoding)! let seperatorString = "\r\n" let seperatorData = seperatorString.dataUsingEncoding(NSUTF8StringEncoding)! for (key, value) in object { var valueData: NSData? let valueType: String = "" let filenameClause = "" let stringValue = "\(value)" valueData = stringValue.dataUsingEncoding(NSUTF8StringEncoding)! if valueData == nil { continue } data.appendData(prefixData) let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding) data.appendData(contentDispositionData!) if let type: String = valueType { let contentTypeString = "Content-Type: \(type)\r\n" let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding) data.appendData(contentTypeData!) } data.appendData(seperatorData) data.appendData(valueData!) data.appendData(seperatorData) } let endingString = "--\(boundary)--\r\n" let endingData = endingString.dataUsingEncoding(NSUTF8StringEncoding)! data.appendData(endingData) return data } @available(*, deprecated=0.4.6, message="Because method moved to OAuthSwiftCredential!") public class func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String { return credential.authorizationHeaderForMethod(method, url: url, parameters: parameters) } @available(*, deprecated=0.4.6, message="Because method moved to OAuthSwiftCredential!") public class func signatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String { return credential.signatureForMethod(method, url: url, parameters: parameters) } }
mit
ba95e3a42a024c03b24eba4a52453963
45.376884
210
0.664861
5.3316
false
false
false
false
Gregsen/okapi
MXStatusMenu/App.swift
1
614
import Cocoa // Visual Parameters let BarWidth: CGFloat = 10.0 let GapBetweenBars: CGFloat = 6.0 let LeftMargin: CGFloat = 5.5 let RightMargin: CGFloat = 5.5 // Update interval in seconds let UpdateInterval = 1.0 /// The maximum throughput per second that is used as the 100% mark for the network load let MaximumNetworkThroughput = Network.Throughput(input: 1_258_291 /* Download: 1,2 MB/s */, output: 133_120 /* Upload: 120 Kb/s */) /// Our app delegate only holds a reference to the StatusController, nothing more class App: NSObject, NSApplicationDelegate { let statusController = StatusController() }
mit
3015a4c4a30151d7f2ec6cf9269005a5
33.111111
132
0.747557
3.886076
false
false
false
false
neoneye/SwiftyFORM
Source/Form/DumpVisitor.swift
1
9917
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import Foundation public class DumpVisitor: FormItemVisitor { private typealias StringToAny = [String: Any?] public init() { } class func dump(_ prettyPrinted: Bool = true, items: [FormItem]) -> Data { var result = [StringToAny]() var rowNumber: Int = 0 for item in items { let dumpVisitor = DumpVisitor() item.accept(visitor: dumpVisitor) var dict = StringToAny() dict["row"] = rowNumber let validateVisitor = ValidateVisitor() item.accept(visitor: validateVisitor) switch validateVisitor.result { case .valid: dict["validate-status"] = "ok" case .hardInvalid(let message): dict["validate-status"] = "hard-invalid" dict["validate-message"] = message case .softInvalid(let message): dict["validate-status"] = "soft-invalid" dict["validate-message"] = message } dict.update(dumpVisitor.dict) result.append(dict) rowNumber += 1 } return JSONHelper.convert(result, prettyPrinted: prettyPrinted) } private var dict = StringToAny() public func visit(object: MetaFormItem) { dict["class"] = "MetaFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["value"] = object.value } public func visit(object: CustomFormItem) { dict["class"] = "CustomFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } public func visit(object: StaticTextFormItem) { dict["class"] = "StaticTextFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["value"] = object.value } public func visit(object: AttributedTextFormItem) { dict["class"] = "AttributedTextFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title?.string dict["value"] = object.value?.string } public func visit(object: TextFieldFormItem) { dict["class"] = "TextFieldFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["value"] = object.value dict["placeholder"] = object.placeholder } public func visit(object: TextViewFormItem) { dict["class"] = "TextViewFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["value"] = object.value } public func visit(object: ViewControllerFormItem) { dict["class"] = "ViewControllerFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title } public func visit(object: OptionPickerFormItem) { dict["class"] = "OptionPickerFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["placeholder"] = object.placeholder dict["value"] = object.selected?.title } public func visit(object: DatePickerFormItem) { dict["class"] = "DatePickerFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["date"] = object.value dict["datePickerMode"] = object.datePickerMode.description dict["locale"] = object.locale dict["minimumDate"] = object.minimumDate dict["maximumDate"] = object.maximumDate dict["minuteInterval"] = object.minuteInterval } public func visit(object: ButtonFormItem) { dict["class"] = "ButtonFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title } public func visit(object: OptionRowFormItem) { dict["class"] = "OptionRowFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["state"] = object.selected } public func visit(object: SwitchFormItem) { dict["class"] = "SwitchFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title dict["value"] = object.value } public func visit(object: StepperFormItem) { dict["class"] = "StepperFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title } public func visit(object: SliderFormItem) { dict["class"] = "SliderFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["value"] = object.value dict["minimumValue"] = object.minimumValue dict["maximumValue"] = object.maximumValue } public func visit(object: PrecisionSliderFormItem) { dict["class"] = "PrecisionSliderFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["value"] = object.value dict["minimumValue"] = object.minimumValue dict["maximumValue"] = object.maximumValue dict["decimalPlaces"] = object.decimalPlaces } public func visit(object: SectionFormItem) { dict["class"] = "SectionFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } public func visit(object: SectionHeaderTitleFormItem) { dict["class"] = "SectionHeaderTitleFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title } public func visit(object: SectionHeaderViewFormItem) { dict["class"] = "SectionHeaderViewFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } public func visit(object: SectionFooterTitleFormItem) { dict["class"] = "SectionFooterTitleFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass dict["title"] = object.title } public func visit(object: SectionFooterViewFormItem) { dict["class"] = "SectionFooterViewFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } public func visit(object: SegmentedControlFormItem) { dict["class"] = "SegmentedControlFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } public func visit(object: PickerViewFormItem) { dict["class"] = "PickerViewFormItem" dict["elementIdentifier"] = object.elementIdentifier dict["styleIdentifier"] = object.styleIdentifier dict["styleClass"] = object.styleClass } } internal struct JSONHelper { /// Convert from a complex object to a simpler json object. /// /// This function is recursive. /// /// - parameter objectOrNil: The complex object to be converted. /// /// - returns: a converted object otherwise NSNull. static func process(_ objectOrNil: Any?) -> Any { guard let object = objectOrNil else { return NSNull() } if object is NSNull { return NSNull() } if let dict = object as? NSDictionary { var result = [String: Any]() for (keyObject, valueObject) in dict { guard let key = keyObject as? String else { print("Expected string for key, skipping key: \(keyObject)") continue } result[key] = process(valueObject) } return result } if let array = object as? NSArray { var result = [Any]() for valueObject in array { let item = process(valueObject) result.append(item) } return result } if let item = object as? String { return item } if let item = object as? Bool { return item } if let item = object as? Int { return item } if let item = object as? UInt { return item } if let item = object as? Float { return item } if let item = object as? Double { return item } if let item = object as? NSNumber { return item } if let item = object as? Date { return item.description } print("skipping unknown item: \(object) \(object.self)") return NSNull() } /// Convert from a complex object to json data. /// /// - parameter unprocessedObject: The complex object to be converted. /// - parameter prettyPrinted: If true then the json is formatted so it's human readable. /// /// - returns: Data object containing json. static func convert(_ unprocessedObject: Any?, prettyPrinted: Bool) -> Data { let object = process(unprocessedObject) if !JSONSerialization.isValidJSONObject(object) { print("the dictionary cannot be serialized to json") return Data() } do { let options: JSONSerialization.WritingOptions = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : [] let data = try JSONSerialization.data(withJSONObject: object, options: options) return data } catch _ { } return Data() } }
mit
0c2c7dd3454aad9c531c3f1946dba279
29.798137
118
0.719472
3.798162
false
false
false
false
kstaring/swift
test/IRGen/c_globals.swift
7
1238
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir | %FileCheck %s import c_layout @inline(never) func blackHole<T>(_ t: T) { } // CHECK: @staticFloat = internal global float 1.700000e+01, align 4 // CHECK: define internal void @doubleTrouble() [[CLANG_FUNC_ATTR:#[0-9]+]] { public func testStaticGlobal() { blackHole(c_layout.staticFloat) doubleTrouble() blackHole(c_layout.staticFloat) } // rdar://problem/21361469 // CHECK: define {{.*}}void @_TF9c_globals17testCaptureGlobalFT_T_() [[SWIFT_FUNC_ATTR:#[0-9]+]] { public func testCaptureGlobal() { var f: Float = 0 var i: CInt = 0 var s: UnsafePointer<CChar>! = nil // CHECK-LABEL: define linkonce_odr hidden void @_TFF9c_globals17testCaptureGlobalFT_T_U_FT_T_{{.*}} { blackHole({ () -> Void in // CHECK: @staticFloat // CHECK: @staticInt // CHECK: @staticString f = c_layout.staticFloat i = c_layout.staticInt s = c_layout.staticString }) // CHECK: {{^}$}} } // CHECK-DAG: attributes [[CLANG_FUNC_ATTR]] = { inlinehint nounwind {{.*}}"no-frame-pointer-elim"="true"{{.*}} // CHECK-DAG: attributes [[SWIFT_FUNC_ATTR]] = { "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf" "target-cpu"
apache-2.0
6f41800bf14626a09af05acd9ece70ae
34.371429
125
0.659935
3.126263
false
true
false
false
shubham01/StyleGuide
Example/StyleGuide/View Themes/TableHeaderFooterTheme.swift
1
1025
// // TableHeaderFooterTheme.swift // StyleGuide // // Created by Shubham Agrawal on 28/10/17. // import Foundation import SwiftyJSON extension StyleGuide { public class TableHeaderFooterTheme: ViewTheme { let textColor: UIColor? let font: UIFont? override init(fromJSON json: JSON) { self.textColor = StyleGuide.getColor(forString: json["textColor"].string) self.font = StyleGuide.parseFont(from: json["font"].string) super.init(fromJSON: json) } } } extension UITableViewHeaderFooterView { override public func apply(theme: String) { if let values: StyleGuide.TableHeaderFooterTheme = StyleGuide.shared.tableHeaderFooterTheme[theme] { self.tintColor = values.tintColor ?? self.tintColor if let font = values.font { self.textLabel?.font = font } if let color = values.textColor { self.textLabel?.textColor = color } } } }
mit
e5d1c0c87ef7c75a1d25818e269a6fda
25.282051
108
0.619512
4.515419
false
false
false
false
russbishop/swift
test/1_stdlib/TestDateInterval.swift
1
6099
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation #if FOUNDATION_XCTEST import XCTest class TestDateIntervalSuper : XCTestCase { } #else import StdlibUnittest class TestDateIntervalSuper { } #endif class TestDateInterval : TestDateIntervalSuper { func dateWithString(_ str: String) -> Date { let formatter = DateFormatter() if #available(iOS 9, *){ formatter.calendar = Calendar(identifier: .gregorian)! }else{ formatter.calendar = Calendar(calendarIdentifier: .gregorian)! } formatter.locale = Locale(localeIdentifier: "en_US") formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" return formatter.date(from: str)! as Date } func test_compareDateIntervals() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration: TimeInterval = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) expectEqual(testInterval2, testInterval1) expectEqual(testInterval1.compare(testInterval2), ComparisonResult.orderedSame) let testInterval3 = DateInterval(start: start, duration: 10000000000.0) expectTrue(testInterval1 < testInterval3) expectTrue(testInterval3 > testInterval1) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") let testInterval4 = DateInterval(start: earlierStart, duration: duration) expectTrue(testInterval4 < testInterval1) expectTrue(testInterval1 > testInterval4) } } func test_isEqualToDateInterval() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval1 = DateInterval(start: start, duration: duration) let testInterval2 = DateInterval(start: start, duration: duration) expectEqual(testInterval1, testInterval2) let testInterval3 = DateInterval(start: start, duration: 100.0) expectNotEqual(testInterval1, testInterval3) } } func test_checkIntersection() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) expectTrue(testInterval1.intersects(testInterval2)) let start3 = dateWithString("2010-10-17 14:49:47 -0700") let end3 = dateWithString("2010-11-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) expectFalse(testInterval1.intersects(testInterval3)) } } func test_validIntersections() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start1 = dateWithString("2010-05-17 14:49:47 -0700") let end1 = dateWithString("2010-08-17 14:49:47 -0700") let testInterval1 = DateInterval(start: start1, end: end1) let start2 = dateWithString("2010-02-17 14:49:47 -0700") let end2 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval2 = DateInterval(start: start2, end: end2) let start3 = dateWithString("2010-05-17 14:49:47 -0700") let end3 = dateWithString("2010-07-17 14:49:47 -0700") let testInterval3 = DateInterval(start: start3, end: end3) let intersection1 = testInterval2.intersection(with: testInterval1) expectNotEmpty(intersection1) expectEqual(testInterval3, intersection1) let intersection2 = testInterval1.intersection(with: testInterval2) expectNotEmpty(intersection2) expectEqual(intersection1, intersection2) } } func test_containsDate() { if #available(iOS 10.10, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { let start = dateWithString("2010-05-17 14:49:47 -0700") let duration = 10000000.0 let testInterval = DateInterval(start: start, duration: duration) let containedDate = dateWithString("2010-05-17 20:49:47 -0700") expectTrue(testInterval.contains(containedDate)) let earlierStart = dateWithString("2009-05-17 14:49:47 -0700") expectFalse(testInterval.contains(earlierStart)) } } } #if !FOUNDATION_XCTEST var DateIntervalTests = TestSuite("TestDateInterval") DateIntervalTests.test("test_compareDateIntervals") { TestDateInterval().test_compareDateIntervals() } DateIntervalTests.test("test_isEqualToDateInterval") { TestDateInterval().test_isEqualToDateInterval() } DateIntervalTests.test("test_checkIntersection") { TestDateInterval().test_checkIntersection() } DateIntervalTests.test("test_validIntersections") { TestDateInterval().test_validIntersections() } runAllTests() #endif
apache-2.0
e3960ca388aabefae9a2646789db2450
41.062069
104
0.622397
4.38777
false
true
false
false
clwm01/RTKitDemo
RCToolsDemo/RCToolsDemo/LabelViewController.swift
2
1138
// // LabelViewController.swift // RCToolsDemo // // Created by Rex Cao on 11/12/15. // Copyright (c) 2015 rexcao. All rights reserved. // import UIKit class LabelViewController: UIViewController { @IBOutlet weak var slider: UISlider! @IBOutlet weak var labelText: UILabel! var defaultFontSize: CGFloat = 17 var defaultSliderValue: CGFloat? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.defaultSliderValue = CGFloat(self.slider.value) self.labelText.layer.borderColor = UIColor.redColor().CGColor self.labelText.layer.borderWidth = 1.0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sliderChange(sender: UISlider) { RTPrint.shareInstance().prt("sliderChange") _ = self.labelText.text let newFontSize = self.defaultFontSize / self.defaultSliderValue! * CGFloat(sender.value) self.labelText.font = UIFont.systemFontOfSize(newFontSize) } }
mit
6d9c391f4a7e9690e409a056cf0efb3b
28.179487
97
0.685413
4.480315
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Profile/Controller/ProfileInforViewController.swift
1
16956
// // ProfileInforViewController.swift // DYZB // // Created by xiudou on 2017/7/9. // Copyright © 2017年 xiudo. All rights reserved. // 我的详情页面 import UIKit import SVProgressHUD import TZImagePickerController let BasicSettingCellIdentifier = "BasicSettingCellIdentifier" let headImageCellHeight : CGFloat = 60 let normalCellHeight : CGFloat = 44 class ProfileInforViewController: BaseViewController { fileprivate var user : User?{ didSet{ guard let user = user else { return } // if let user = user { groups.removeAll() profileInforDataFrameModel = ProfileInforDataFrameModel(user: user) // 第一组 setuoGroupOne(profileInforDataFrameModel) // 第二组 setuoGroupTwo(profileInforDataFrameModel) // 第三组 setuoGroupThree(profileInforDataFrameModel) endAnimation() collectionView.reloadData() // } } } var profileInforDataFrameModel : ProfileInforDataFrameModel! fileprivate lazy var profileInforVM : ProfileInforVM = ProfileInforVM() lazy var groups : [SettingGroup] = [SettingGroup]() lazy var collectionView : UICollectionView = { // 设置layout属性 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: sScreenW, height: 44) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 // 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y:sStatusBarH + sNavatationBarH, width: sScreenW, height: sScreenH - (sStatusBarH + sNavatationBarH)), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor(r: 239, g: 239, b: 239) collectionView.register(BasicSettingCell.self, forCellWithReuseIdentifier: BasicSettingCellIdentifier) return collectionView; }() // MARK:- 生命周期 override func viewDidLoad() { automaticallyAdjustsScrollViewInsets = false baseContentView = collectionView view.addSubview(collectionView) super.viewDidLoad() title = "个人信息" // 请求一下最新数据 setupData() // 接收通知 notificationCenter.addObserver(self, selector: #selector(reLoadProfileInforData), name: NSNotification.Name(rawValue: sNotificationName_ReLoadProfileInforData), object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } deinit { debugLog("ProfileInforViewController -- 销毁") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) debugLog("viewWillAppear") } } // MARK:- 获取数据 extension ProfileInforViewController { fileprivate func setupData(){ profileInforVM.loadProfileInforDatas({ self.user = self.profileInforVM.user }, { (message) in }) { } } } // MARK:- 创建组 extension ProfileInforViewController { fileprivate func setuoGroupOne(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ /// 头像 // 1 创建需要类型的item let avaModel = ArrowImageItem(icon: "", title: "头像", rightImageName: profileInforDataFrameModel.avatarName, VcClass: nil) // 2 计算出item的frame let avaModelFrame = SettingItemFrame(avaModel) // 3 是否需要定义特殊处理(有实现,没有不用实现) avaModel.optionHandler = {[weak self] in // 创建 // preferredStyle 为 ActionSheet let alertController = UIAlertController(title: "上传头像", message: nil, preferredStyle:.actionSheet) // 设置2个UIAlertAction let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let photographAction = UIAlertAction(title: "拍照", style: .default, handler: { (alertAction) in }) let photoAlbumAction = UIAlertAction(title: "从相册选择", style: .default, handler: { (alertAction) in guard let imagePickerVc = TZImagePickerController(maxImagesCount: 1, delegate: self) else { return } imagePickerVc.sortAscendingByModificationDate = false imagePickerVc.photoWidth = 1024.0 imagePickerVc.photoPreviewMaxWidth = 3072.0 self?.navigationController?.present(imagePickerVc, animated: true, completion: nil) }) // 添加到UIAlertController alertController.addAction(cancelAction) alertController.addAction(photoAlbumAction) alertController.addAction(photographAction) // 弹出 self?.present(alertController, animated: true, completion: nil) } avaModel.optionHeight = { return headImageCellHeight } /// 昵称 let nickNameModel = ArrowItem(icon: "", title: "昵称", subtitle: profileInforDataFrameModel.nickname, VcClass: TestViewController.self) let nickNameModelFrame = SettingItemFrame(nickNameModel) /// 性别 let sexModel = ArrowItem(icon: "", title: "性别", subtitle: profileInforDataFrameModel.sexString, VcClass: nil) let sexModelFrame = SettingItemFrame(sexModel) sexModel.optionHandler = {[weak self] in // preferredStyle 为 ActionSheet let alertController = UIAlertController(title: "上传头像", message: nil, preferredStyle:.actionSheet) // 设置2个UIAlertAction let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let womanAction = UIAlertAction(title: "女", style: .default, handler: { (alertAction) in self?.profileInforVM.loadSexProfileInforDatas(sexString: "2", { SVProgressHUD.showSuccess(withStatus: "成功") // 再次请求个人详情的数据 // self?.profileInforVM.loadProfileInforDatas({ // self?.user = self?.profileInforVM.user // }, { (message) in // // }, { // // }) self?.reLoadProfileInforData() }, { (message) in SVProgressHUD.showInfo(withStatus: message) }, { SVProgressHUD.showError(withStatus: "") }) }) let manAction = UIAlertAction(title: "男", style: .default, handler: { (alertAction) in self?.profileInforVM.loadSexProfileInforDatas(sexString: "1", { // 再次请求个人详情的数据 self?.reLoadProfileInforData() // self?.profileInforVM.loadProfileInforDatas({ // self?.user = self?.profileInforVM.user // SVProgressHUD.showSuccess(withStatus: "成功") // }, { (message) in // // }, { // // }) }, { (message) in SVProgressHUD.showInfo(withStatus: message) }, { SVProgressHUD.showError(withStatus: "") }) }) // 添加到UIAlertController alertController.addAction(cancelAction) alertController.addAction(manAction) alertController.addAction(womanAction) // 弹出 self?.present(alertController, animated: true, completion: nil) } /// 生日 let birthDayModel = ArrowItem(icon: "", title: "生日", subtitle: profileInforDataFrameModel.birthdayString, VcClass: nil) let birthDayModelFrame = SettingItemFrame(birthDayModel) birthDayModel.optionHandler = { guard let birthdayString = self.user?.birthday else { return } guard let date = Date.dateFromString("yyyyMMdd", birthdayString) else { return } let showDate = DatePackerView(frame: self.view.bounds, date) showDate.showDatePicker(self.view) showDate.delegate = self } /// 所在地 let locationModel = ArrowItem(icon: "", title: "所在地", subtitle: profileInforDataFrameModel.locationString, VcClass: LocationViewController.self) let locationModelFrame = SettingItemFrame(locationModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [avaModelFrame,nickNameModelFrame,sexModelFrame,birthDayModelFrame,locationModelFrame] groups.append(settingGroup) } fileprivate func setuoGroupTwo(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ let avaModel = ArrowItem(icon: "", title: "实名认证", subtitle: profileInforDataFrameModel.realNameAuthentication, VcClass: nil) let avaModelFrame = SettingItemFrame(avaModel) avaModel.optionHandler = {[weak self] in print("setuoGroupTwo点击了实名认证") } let nickNameModel = ArrowItem(icon: "", title: "密码", subtitle: profileInforDataFrameModel.passWord, VcClass: MyTaskViewController.self) let nickNameModelFrame = SettingItemFrame(nickNameModel) // 如果邮箱有值则不能跳转 没哟值则跳转绑定 var sexModel : SettingItem! if profileInforDataFrameModel.emailString.characters.count > 0{ sexModel = SettingItem(icon: "", title: "邮箱", subTitle: profileInforDataFrameModel.emailString) }else{ sexModel = ArrowItem(icon: "", title: "邮箱", subtitle: profileInforDataFrameModel.emailString, VcClass: TestViewController.self) } let sexModelFrame = SettingItemFrame(sexModel) let birthDayModel = ArrowItem(icon: "", title: "手机", subtitle: profileInforDataFrameModel.mobile_phoneString, VcClass: IPhoneBindingViewController.self) let birthDayModelFrame = SettingItemFrame(birthDayModel) let locationModel = ArrowItem(icon: "", title: "QQ", subtitle: profileInforDataFrameModel.qq, VcClass: BindQQViewController.self) let locationModelFrame = SettingItemFrame(locationModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [avaModelFrame,nickNameModelFrame,sexModelFrame,birthDayModelFrame,locationModelFrame] groups.append(settingGroup) } fileprivate func setuoGroupThree(_ profileInforDataFrameModel : ProfileInforDataFrameModel){ let nickNameModel = SettingItem(icon: "", title: "经验值", subTitle: profileInforDataFrameModel.empiricalValue) let nickNameModelFrame = SettingItemFrame(nickNameModel) let sexModel = SettingItem(icon: "", title: "鱼丸", subTitle: profileInforDataFrameModel.fishBall) let sexModelFrame = SettingItemFrame(sexModel) let birthDayModel = ArrowItem(icon: "", title: "鱼翅", subtitle: profileInforDataFrameModel.fin, VcClass: FishboneRechargeViewController.self) let birthDayModelFrame = SettingItemFrame(birthDayModel) let settingGroup : SettingGroup = SettingGroup() settingGroup.settingGroup = [nickNameModelFrame,sexModelFrame,birthDayModelFrame] groups.append(settingGroup) } } extension ProfileInforViewController { @objc fileprivate func reLoadProfileInforData(){ // 再次请求个人详情的数据 profileInforVM.loadProfileInforDatas({ self.user = self.profileInforVM.user }, { (message) in }, { }) } } // MARK:- UICollectionViewDataSource extension ProfileInforViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ return groups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let group = groups[section] return group.settingGroup.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BasicSettingCellIdentifier, for: indexPath) as! BasicSettingCell let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] cell.settingItemFrame = settingItemFrame return cell } } // MARK:- UICollectionViewDelegateFlowLayout extension ProfileInforViewController : UICollectionViewDelegateFlowLayout { // 组间距 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{ return UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] if settingItemFrame.settingItem.optionHandler != nil { settingItemFrame.settingItem.optionHandler!() }else if settingItemFrame.settingItem is ArrowItem{ let arrowItem = settingItemFrame.settingItem as! ArrowItem guard let desClass = arrowItem.VcClass else { return } guard let desVCType = desClass as? UIViewController.Type else { return } let desVC = desVCType.init() // 修改密码 if desVC is MyTaskViewController{ let desvc = desVC as! MyTaskViewController desvc.open_url = "http://www.douyu.com/api/v1/change_password?client_sys=ios&token=\(TOKEN)&auth=\(AUTH)" } // QQ if desVC is BindQQViewController{ let desvc = desVC as! BindQQViewController desvc.completeButtonValue(completeButtoncallBack: { (isok) in // 刷新页面 self.reLoadProfileInforData() }) } desVC.title = arrowItem.title navigationController?.pushViewController(desVC, animated: true) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ let group = groups[indexPath.section] let settingItemFrame = group.settingGroup[indexPath.item] if settingItemFrame.settingItem.optionHeight != nil { let height = settingItemFrame.settingItem.optionHeight!() return CGSize(width: sScreenW, height: height) } return CGSize(width: sScreenW, height: normalCellHeight) } } // MARK:- TZImagePickerControllerDelegate extension ProfileInforViewController : TZImagePickerControllerDelegate{ func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!){ guard let image = photos.first else { return } guard let imageData = UIImageJPEGRepresentation(image, 0.3) else { return } debugLog(imageData) profileInforVM.loadUpImageProfileInforDatas(imageData: imageData, { }, { (message) in }) { } } } extension ProfileInforViewController : DatePackerViewDelegate { func datePackerView(_ datePackerView: DatePackerView, indexItem: String) { print(indexItem) profileInforVM.loadBirthDayProfileInforDatas(birthDay: indexItem, { self.reLoadProfileInforData() }, { (message) in }) { } } }
mit
991adfba2c8fe20462be57f1875e5fb5
39.002427
199
0.619319
5.047779
false
false
false
false
sarvex/SwiftRecepies
CalendarsEvents/Requesting Permission to Access Calendars/Requesting Permission to Access Calendars/AppDelegate.swift
1
3201
// // AppDelegate.swift // Requesting Permission to Access Calendars // // Created by Vandad Nahavandipoor on 6/24/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import EventKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func extractEventEntityCalendarsOutOfStore(eventStore: EKEventStore){ let calendarTypes = [ "Local", "CalDAV", "Exchange", "Subscription", "Birthday", ] let calendars = eventStore.calendarsForEntityType(EKEntityTypeEvent) as! [EKCalendar] for calendar in calendars{ println("Calendar title = \(calendar.title)") println("Calendar type = \(calendarTypes[Int(calendar.type.value)])") let color = UIColor(CGColor: calendar.CGColor) println("Calendar color = \(color)") if calendar.allowsContentModifications{ println("This calendar allows modifications") } else { println("This calendar does not allow modifications") } println("--------------------------") } } func displayAccessDenied(){ println("Access to the event store is denied.") } func displayAccessRestricted(){ println("Access to the event store is restricted.") } func example1(){ let eventStore = EKEventStore() switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){ case .Authorized: extractEventEntityCalendarsOutOfStore(eventStore) case .Denied: displayAccessDenied() case .NotDetermined: eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {[weak self] (granted: Bool, error: NSError!) -> Void in if granted{ self!.extractEventEntityCalendarsOutOfStore(eventStore) } else { self!.displayAccessDenied() } }) case .Restricted: displayAccessRestricted() } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { example1() self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } }
isc
bc6e8a66a6e647c2853048b9ae09fd34
27.837838
126
0.669791
4.835347
false
false
false
false
EstebanVallejo/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/CustomerCardsViewController.swift
2
3500
// // CustomerCardsViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class CustomerCardsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak private var tableView : UITableView! var loadingView : UILoadingView! var items : [PaymentMethodRow]! var cards : [Card]? var bundle : NSBundle? = MercadoPago.getBundle() var callback : ((selectedCard: Card?) -> Void)? public init(cards: [Card]?, callback: (selectedCard: Card?) -> Void) { super.init(nibName: "CustomerCardsViewController", bundle: bundle) self.cards = cards self.callback = callback } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override public func viewDidLoad() { super.viewDidLoad() self.title = "Medios de pago".localized self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "newCard") self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) self.view.addSubview(self.loadingView) var paymentMethodNib = UINib(nibName: "PaymentMethodTableViewCell", bundle: self.bundle) self.tableView.registerNib(paymentMethodNib, forCellReuseIdentifier: "paymentMethodCell") self.tableView.delegate = self self.tableView.dataSource = self loadCards() } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items == nil ? 0 : items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var pmcell : PaymentMethodTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("paymentMethodCell") as! PaymentMethodTableViewCell let paymentRow : PaymentMethodRow = items[indexPath.row] pmcell.setLabel(paymentRow.label!) pmcell.setImageWithName(paymentRow.icon!) return pmcell } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { callback!(selectedCard: self.cards![indexPath.row]) } public func loadCards() { self.items = [PaymentMethodRow]() for (card) in cards! { var paymentMethodRow = PaymentMethodRow() paymentMethodRow.card = card paymentMethodRow.label = card.paymentMethod!.name + " " + "terminada en".localized + " " + card.lastFourDigits! paymentMethodRow.icon = "icoTc_" + card.paymentMethod!._id self.items.append(paymentMethodRow) } self.tableView.reloadData() self.loadingView.removeFromSuperview() } public func newCard() { callback!(selectedCard: nil) } }
mit
29e0396b88712750729b2f2e95a354d7
36.234043
150
0.676193
5.085756
false
false
false
false
kenwilcox/WeeDate
WeeDate/ChatViewController.swift
1
4712
// // ChatViewController.swift // WeeDate // // Created by Kenneth Wilcox on 7/12/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import Foundation import Parse class ChatViewController: JSQMessagesViewController { var messages: [JSQMessage] = [] var matchID: String? var messageListener: MessageListener? let outgoingBubble = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleBlueColor()) let incomingBubble = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor()) var senderAvatar: UIImage! var recipientAvatar: UIImage! var recipient: User! override func viewDidLoad() { super.viewDidLoad() // collectionView.collectionViewLayout.incomingAvatarViewSize = CGSizeZero // collectionView.collectionViewLayout.outgoingAvatarViewSize = CGSizeZero if let id = matchID { fetchMessages(id, { messages in for m in messages { self.messages.append(JSQMessage(senderId: m.senderID, senderDisplayName: m.senderID, date: m.date, text: m.message)) } self.finishReceivingMessage() }) } } override func viewWillAppear(animated: Bool) { if let id = matchID { messageListener = MessageListener(matchID: id, startDate: NSDate(), callback: { message in self.messages.append(JSQMessage(senderId: message.senderID, senderDisplayName: message.senderID, date: message.date, text: message.message)) self.finishReceivingMessage() }) } } override func viewWillDisappear(animated: Bool) { messageListener?.stop() } override var senderDisplayName: String! { get { return currentUser()!.name } set { super.senderDisplayName = newValue } } override var senderId: String! { get { return currentUser()!.id } set { super.senderId = newValue } } override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! { var data = self.messages[indexPath.row] return data } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! { var data = self.messages[indexPath.row] if data.senderId == PFUser.currentUser()!.objectId { return outgoingBubble } else { return incomingBubble } } override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! { var imgAvatar = JSQMessagesAvatarImage.avatarWithImage( JSQMessagesAvatarImageFactory.circularAvatarImage( UIImage(named: "profile-header"), withDiameter: 60 ) ) if (self.messages[indexPath.row].senderId == self.senderId) { if (self.senderAvatar != nil) { imgAvatar = JSQMessagesAvatarImage.avatarWithImage( JSQMessagesAvatarImageFactory.circularAvatarImage( self.senderAvatar, withDiameter: 60 ) ) } else { currentUser()!.getPhoto({ (image) -> () in self.senderAvatar = image self.updateAvatarImageForIndexPath( indexPath, avatarImage: image) }) } } else { if (self.recipientAvatar != nil) { imgAvatar = JSQMessagesAvatarImage.avatarWithImage( JSQMessagesAvatarImageFactory.circularAvatarImage( self.recipientAvatar, withDiameter: 60 ) ) } else { self.recipient.getPhoto({ (image) -> () in self.updateAvatarImageForIndexPath( indexPath, avatarImage: image) }) } } return imgAvatar } override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) { // let m = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text) // self.messages.append(m) if let id = matchID { saveMessage(id, Message(message: text, senderID: senderId, date: date)) } finishSendingMessage() } func updateAvatarImageForIndexPath( indexPath: NSIndexPath, avatarImage: UIImage) { let cell: JSQMessagesCollectionViewCell = self.collectionView.cellForItemAtIndexPath(indexPath) as! JSQMessagesCollectionViewCell cell.avatarImageView.image = JSQMessagesAvatarImageFactory.circularAvatarImage( avatarImage, withDiameter: 60 ) } }
mit
782204c679345777ca4e722cc0a1a955
33.654412
178
0.712012
5.195149
false
false
false
false
vlribeiro/loja-desafio-ios
LojaDesafio/LojaDesafio/Product.swift
1
1364
// // Product.swift // LojaDesafio // // Created by Vinicius Ribeiro on 29/11/15. // Copyright © 2015 Vinicius Ribeiro. All rights reserved. // import Foundation import RealmSwift import Realm class Product : Object { dynamic var id : Int dynamic var name : String dynamic var productDescription : String dynamic var price : Float dynamic var imageUrl : String required init() { self.id = 0 self.name = String() self.productDescription = String() self.price = 0 self.imageUrl = String() super.init() } init(id : Int, name : String, description : String, price : Float, imageUrl : String) { self.id = id self.name = name self.productDescription = description self.price = price self.imageUrl = imageUrl super.init() } override init(realm: RLMRealm, schema: RLMObjectSchema) { self.id = 0 self.name = String() self.productDescription = String() self.price = 0 self.imageUrl = String() super.init(realm: realm, schema: schema) } override static func primaryKey() -> String? { return "id" } override var description : String { return "Produto -> { id: \(self.id), nome: \(self.name) }" } }
mit
d5b133e4b06e3fb2cee8c00f2977754d
22.929825
91
0.575935
4.354633
false
false
false
false
LeafPlayer/Leaf
Leaf/MicroFramework/MPV/MPV.swift
1
40690
// // MPV.swift // Leaf // // Created by lincolnlaw on 2017/11/15. // Copyright © 2017年 lincolnlaw. All rights reserved. // import Foundation import libmpv import OpenGL.GL import OpenGL.GL3 public final class MPV { public static func clean() { OpenGLContextManager.shared.clean() } public var playingInfo: DI.MediaInfo? { get { return _pQueue.sync { return _playingInfo } } set { _pQueue.sync { _playingInfo = newValue } } } private var _playingInfo: DI.MediaInfo? private var _pQueue = DispatchQueue(label: "MPV.Property.Qeueu") private let _handler: OpaquePointer? private lazy var _initialized = false private lazy var _wakeUpHandler: () -> Void = { } private lazy var _hadLog = false private lazy var _eventQueue: DispatchQueue = DispatchQueue(label: "MPV.Event.Queue") private lazy var _timerQueue: DispatchQueue = DispatchQueue(label: "MPV.Timer.Queue") private lazy var _eof = false private lazy var _timer: RepeatingTimer? = { let t = RepeatingTimer() t.eventHandler = { [weak self] in self?.timerCallback() } return t }() private lazy var _fileLoaded = false private var _state: DI.PlayerState = .stopped public private(set) var state: DI.PlayerState { get { return _pQueue.sync { return _state } } set { _pQueue.sync { _state = newValue } eventHandler(.state) print("state: changed to \(state)") } } // public private(set) var playing = false /** This ticket will be increased each time before a new task being submitted to `backgroundQueue`. Each task holds a copy of ticket value at creation, so that a previous task will perceive and quit early if new tasks is awaiting. **See also**: `autoLoadFilesInCurrentFolder(ticket:)` */ private var backgroundQueueTicket = 0 /// A dispatch queue for auto load feature. let backgroundQueue: DispatchQueue = DispatchQueue(label: "IINAPlayerCoreTask") let thumbnailQueue: DispatchQueue = DispatchQueue(label: "IINAPlayerCoreThumbnailTask") private var _geometry: Geometry? public var geometry: Geometry? { guard let value = _geometry else { let geometry = stringOpt(for: Option.window(.geometry)) ?? "" // guard option value guard geometry.isEmpty == false else { return nil } // match the string, replace empty group by nil let captures: [String?] = Regex.geometry.captures(in: geometry).map { $0.isEmpty ? nil : $0 } // guard matches guard captures.count == 10 else { return nil } // return struct _geometry = Geometry(x: captures[7], y: captures[9], w: captures[2], h: captures[4], xSign: captures[6], ySign: captures[8]) return _geometry } return value } public lazy var eventHandler: (Event) -> Void = { _ in } public var openGLCallback: () -> Void = { } public var openGLQueue = DispatchQueue(label: "mpv.opengl") public private(set) var openglContext: OpaquePointer? = nil let observeProperties: [String: mpv_format] = [ Property.trackList(.count).rawValue: MPV_FORMAT_INT64, Property.vf.rawValue: MPV_FORMAT_NONE, Property.af.rawValue: MPV_FORMAT_NONE, Property.chapter.rawValue: MPV_FORMAT_INT64, Option.trackSelection(.vid).rawValue: MPV_FORMAT_INT64, Option.trackSelection(.aid).rawValue: MPV_FORMAT_INT64, Option.trackSelection(.sid).rawValue: MPV_FORMAT_INT64, Option.playbackControl(.pause).rawValue: MPV_FORMAT_FLAG, Option.video(.deinterlace).rawValue: MPV_FORMAT_FLAG, Option.audio(.mute).rawValue: MPV_FORMAT_FLAG, Option.audio(.volume).rawValue: MPV_FORMAT_DOUBLE, Option.audio(.audioDelay).rawValue: MPV_FORMAT_DOUBLE, Option.playbackControl(.speed).rawValue: MPV_FORMAT_DOUBLE, Option.subtitles(.subDelay).rawValue: MPV_FORMAT_DOUBLE, Option.subtitles(.subScale).rawValue: MPV_FORMAT_DOUBLE, Option.subtitles(.subPos).rawValue: MPV_FORMAT_DOUBLE, Option.equalizer(.contrast).rawValue: MPV_FORMAT_INT64, Option.equalizer(.brightness).rawValue: MPV_FORMAT_INT64, Option.equalizer(.gamma).rawValue: MPV_FORMAT_INT64, Option.equalizer(.hue).rawValue: MPV_FORMAT_INT64, Option.equalizer(.saturation).rawValue: MPV_FORMAT_INT64, Option.window(.fullscreen).rawValue: MPV_FORMAT_FLAG, Option.window(.ontop).rawValue: MPV_FORMAT_FLAG, Option.window(.windowScale).rawValue: MPV_FORMAT_DOUBLE ] deinit { _timer = nil } public init() { let handler = mpv_create() _handler = mpv_create_client(handler, UUID().uuidString) } public func initialize() { guard let mpv = _handler else { return } do { try mpv_initialize(mpv).checkError() _initialized = true try setStringOption(value: ExOptValue.openglcb.rawValue, for: Option.video(.vo)).checkError() try setStringOption(value: ExOptValue.yes.rawValue, for: Option.window(.keepaspect)).checkError() try setStringOption(value: ExOptValue.auto.rawValue, for: Option.video(.openglHwdecInterop)).checkError() } catch { print(error) } guard let cb = mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB) else { return } let context = OpaquePointer(cb) openglContext = context let openglCallback: mpv_opengl_cb_get_proc_address_fn = { (ctx, name) -> UnsafeMutableRawPointer? in let symbolName: CFString = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII) guard let addr = CFBundleGetFunctionPointerForName(CFBundleGetBundleWithIdentifier(CFStringCreateCopy(kCFAllocatorDefault, "com.apple.opengl" as CFString!)), symbolName) else { // Utility.fatal("Cannot get OpenGL function pointer!") fatalError("Cannot get OpenGL function pointer!") } return addr } mpv_opengl_cb_init_gl(context, nil, openglCallback, nil) // Set the callback that notifies you when a new video frame is available, or requires a redraw. let callback: mpv_opengl_cb_update_fn = { ctx in guard let sself = ctx?.to(object: MPV.self) else { return } sself.openGLCallback() } mpv_opengl_cb_set_update_callback(context, callback, UnsafeMutableRawPointer.from(object: self)) OpenGLContextManager.shared.add(ctx: openglContext) } public func setOption(for key: Preference.Property) { let opts = key.mpvOption() guard opts.count != 0, let value = key.value() else { return } for opt in opts { setOption(value: value, for: opt) } } public func setOption(value: PreferenceValueCompatible, for key: Option) { guard let mpv = _handler else { return } let name = key.rawValue var result: Int32 = 0 if let string = value.stringValue { result = setStringOption(value: string, for: key) } else if let bool = value.boolValue { result = setBoolOption(value: bool, for: key) } else if let int = value.intValue { result = setIntOption(value: int, for: key) } else if let double = value.doubleValue { result = setDoubleOption(value: double, for: key) } else if let color = value.colorValue { result = mpv_set_option_string(mpv, name, color) // Random error here (perhaps a Swift or mpv one), so set it twice // 「没有什么是 set 不了的;如果有,那就 set 两次」 if result < 0 { result = mpv_set_option_string(mpv, name, color) } } if result < 0 { print("mpv error[\(result)]:\(String(cString: mpv_error_string(result))) for key:\(key.rawValue), value: \(value)") } } public func setProperty(value: PreferenceValueCompatible, for key: Property) { guard let mpv = _handler else { return } let name = key.rawValue var result: Int32 = 0 if let string = value.stringValue { result = mpv_set_property_string(mpv, name, string) } else if let bool = value.boolValue { var data = bool ? 1 : 0 result = mpv_set_property(mpv, name, MPV_FORMAT_FLAG, &data) } else if let int = value.intValue { var value = Int64(int) result = mpv_set_property(mpv, name, MPV_FORMAT_INT64, &value) } else if var double = value.doubleValue { result = mpv_set_property(mpv, name, MPV_FORMAT_DOUBLE, &double) } if result < 0 { print("mpv error[\(result)]:\(String(cString: mpv_error_string(result))) for key:\(key)") } } @discardableResult public func setStringRaw(value: String, for key: String) -> Int32 { var p = value return setOption(value: &p, for: key, format: MPV_FORMAT_STRING) } @discardableResult public func setStringExOption(value: String, for key: ExOptKey) -> Int32 { var p = value return setOption(value: &p, for: key.rawValue, format: MPV_FORMAT_STRING) } @discardableResult public func setStringOption(value: String, for key: Option) -> Int32 { guard let mpv = _handler else { return 0 } let name = key.rawValue if _initialized { return mpv_set_property_string(mpv, name, value) } else { return mpv_set_option_string(mpv, name, value) } } @discardableResult public func setBoolOption(value: Bool, for key: Option) -> Int32 { guard let mpv = _handler else { return 0 } let name = key.rawValue if _initialized { var data = value ? 1 : 0 return mpv_set_property(mpv, name, MPV_FORMAT_FLAG, &data) } else { return mpv_set_option_string(mpv, name, value.mpvString) } } @discardableResult public func setIntOption(value: Int, for key: Option) -> Int32 { var data = Int64(value) return setOption(value: &data, for: key.rawValue, format: MPV_FORMAT_INT64) } @discardableResult public func setDoubleOption(value: Double, for key: Option) -> Int32 { var double = value return setOption(value: &double, for: key.rawValue, format: MPV_FORMAT_DOUBLE) } @discardableResult public func setOption(value: UnsafeMutableRawPointer!, for key: String, format: mpv_format) -> Int32{ guard let mpv = _handler else { return 0 } let name = key if _initialized { return mpv_set_property(mpv, name, format, value) } else { return mpv_set_option(mpv, name, format, value) } } @discardableResult public func enabledLog(level: LogLevel) -> Int32 { guard let mpv = _handler else { return 0 } return mpv_request_log_messages(mpv, level.rawValue) } @discardableResult public func enabledTickEvent() -> Int32 { guard let mpv = _handler else { return 0 } return mpv_request_event(mpv, MPV_EVENT_TICK, 1) } public func enabledWakeUpCallback() { guard let mpv = _handler else { return } let info = UnsafeMutableRawPointer.from(object: self) mpv_set_wakeup_callback(mpv, { (ctx) in guard let sself = ctx?.to(object: MPV.self) else { return } sself.readEvents() }, info) } public func enabledObserveProperties() { guard let mpv = _handler else { return } do { for (key, value) in observeProperties { var name = key.cString(using: .utf8)! let hash = UInt64(abs(key.hashValue)) try mpv_observe_property(mpv, hash, &name, value).checkError() } } catch { print(error) } } public func unobserveProperties() { guard let mpv = _handler else { return } do { for (key, _) in observeProperties { let hash = UInt64(abs(key.hashValue)) try mpv_unobserve_property(mpv, hash).checkError() } } catch { print(error) } } public func retrieveWaittingEvent() -> UnsafeMutablePointer<mpv_event>? { guard let mpv = _handler else { return nil } return mpv_wait_event(mpv, 0) } public func destory() { guard let mpv = _handler else { return } openGLCallback = { } OpenGLContextManager.shared.removePlayingWindow() mpv_detach_destroy(mpv) // mpv_terminate_destroy(mpv) // opengl must be uninit before call this } public func loadfile(url: String, mode: MPV.Command.LoadFileMode = .replace) throws { timerPaused() _eof = false let info = DI.MediaInfo(url: url) playingInfo = info state = .loading try command(.loadfile(mode, url)).checkError() if let title = string(for: .mediaTitle) { info.title = title } // guard var copy = url.cString(using: .utf8) else { return } // var real: UnsafeMutablePointer<Int8>? = nil // let rv = realpath(&copy, nil) // if let r = rv { // let realP = String(cString: r) // print(realP) // } } public func removeCurrentFileFromPlayList() { guard let index = int(for: .playlistPos) else { return } command(.playlistRemove("\(index)")) } @discardableResult private func command(_ command: Command) -> Int32 { guard let mpv = _handler else { return -1 } let strArgs = command.commands var cargs = strArgs.map { $0.flatMap { UnsafePointer<Int8>(strdup($0)) } } let returnValue = mpv_command(mpv, &cargs) for ptr in cargs { free(UnsafeMutablePointer(mutating: ptr)) } return returnValue } public func initOpenGLCB() -> UnsafeMutableRawPointer? { // Get opengl-cb context. guard let mpv = _handler else { return nil } return mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB) } public func togglePlayPause(play: Bool? = nil) { var isPaused = state.isPlaying == false if let p = play { isPaused = !p } else { isPaused = !isPaused } setBoolOption(value: isPaused, for: Option.playbackControl(.pause)) } public func fullScreen(enabled: Bool) { setBoolOption(value: enabled, for: Option.window(.fullscreen)) } public func stop() { eventHandler = { _ in } _eventQueue.suspend() state = .stopped command(.stop) } public func playlistClear() { command(.playlistClear) } public func quit() { // if let ctx = openglContext { mpv_opengl_cb_uninit_gl(ctx) } command(.quit) } public func enableLog() { guard _hadLog == false else { return } _hadLog = true let token = UUID().uuidString var rawTime = time_t() time(&rawTime) var timeinfo = tm() localtime_r(&rawTime, &timeinfo) var curTime = timeval() gettimeofday(&curTime, nil) let milliseconds = curTime.tv_usec / 1000 let logFileName = String(format: "%d-%d-%d-%02d-%02d-%03d_%@.log", arguments: [Int(timeinfo.tm_year) + 1900, Int(timeinfo.tm_mon + 1), Int(timeinfo.tm_mday), Int(timeinfo.tm_hour), Int(timeinfo.tm_min), Int(milliseconds), token]) let path = Preference.logDirURL.appendingPathComponent(logFileName).path try? setStringOption(value: path, for: .programBehavior(.logFile)).checkError() } public func savePlaybackPosition() { command(.writeWatchLaterConfig) } public func title() -> String? { return string(for: Property.mediaTitle) } public var netRotate: Int { return videoParamsRotate - videoRotate } public var videoParamsRotate: Int { return int(for: MPV.Property.videoParams(.rotate)) ?? 0 } public var videoRotate: Int { return intOpt(for: MPV.Option.video(.videoRotate)) ?? 0 } @discardableResult public func draw(fbo: Int32, width: Int32, heihgt: Int32) -> Bool { guard let ctx = openglContext else { return false } return mpv_opengl_cb_draw(ctx, fbo, width, heihgt) == MPV_ERROR_SUCCESS.rawValue } public func reportFlip() { guard let ctx = openglContext else { return } mpv_opengl_cb_report_flip(ctx, 0) } public func updatePlayerList() { guard let info = playingInfo, let count = int(for: .playlistCount) else { return } info.playlist.removeAll() for index in 0..<count { guard let filename = string(for: .playlist(.nFilename(index))), let isCurrent = bool(for: .playlist(.nCurrent(index))), let isPlaying = bool(for: .playlist(.nPlaying(index))) else { continue } let title = string(for: .playlist(.nTitle(index))) let playlistItem = DI.MediaInfo.PlaylistItem(filename: filename, isCurrent: isCurrent, isPlaying: isPlaying, title: title) info.playlist.append(playlistItem) } } public func updateChapters() { guard let info = playingInfo, let count = int(for: .chapterList(.count) ), count > 0 else { return } info.chapters.removeAll() for index in 0..<count { guard let title = string(for: .chapterList(.nTitle(index))), let startTime = double(for: .chapterList(.nTime(index))) else { continue } let chapter = DI.MediaInfo.Chapter(title: title, startTime: startTime, index: index) info.chapters.append(chapter) } } public func playPlaylist(at index: Int) { guard let info = playingInfo, let item = info.playlist[le_safe: index] else { return } info.playingListIndex = index try? loadfile(url: item.filename) } public func playChapter(at index: Int) { guard let info = playingInfo, let item = info.chapters[le_safe: index] else { return } info.playingChapterIndex = index if state.isPaused { togglePlayPause(play: true) } command(MPV.Command.seek(.absolute, item.time, nil)) if state.isPaused { togglePlayPause(play: true) } } public func seekRelative(second: Double, extra: MPV.Command.SeekModeExtra? = nil) { seek(to: second, mode: .relative, extra: extra) } public func seekAbsolute(second: Double) { seek(to: second, mode: .relative, extra: .exact) } public func seekPecentage(percent: Double, forceExact: Bool) { guard let info = playingInfo else { return } var percent = percent // mpv will play next file automatically when seek to EOF. // the following workaround will constrain the max seek position to (video length - 1) s. // however, it still won't work for videos with large keyframe interval. let duration = info.duration let maxPercent = (duration - 1) / duration * 100 percent = percent.constrain(min: 0, max: maxPercent) let useExact = forceExact ? true : Pref.isUseExactSeek let mode: MPV.Command.SeekMode = .absolutePercent let extra: MPV.Command.SeekModeExtra? = useExact ? .exact : nil seek(to: percent, mode: mode, extra: extra) } private func seek(to value: Double, mode: MPV.Command.SeekMode, extra: MPV.Command.SeekModeExtra? = nil) { command(.seek(mode, value, extra)) } } // MARK: - Timer tick private extension MPV { func timerPaused() { _timer?.suspend() } func timerResume() { _timer?.resume() } func timerCallback() { if let pos = double(for: .timePos) { playingInfo?.increasePlayPos(to: pos) } } } // MARK: - Get Set private extension MPV { func int(for name: Property) -> Int? { return get(property: name.rawValue) } func intOpt(for name: Option) -> Int? { return get(property: name.rawValue) } func double(for name: Property) -> Double? { return get(property: name.rawValue) } func bool(for name: Property) -> Bool? { return get(property: name.rawValue) } func string(for name: Property) -> String? { return get(property: name.rawValue) } func stringOpt(for name: Option) -> String? { return get(property: name.rawValue) } func get<T>(property: String) -> T? { guard let mpv = _handler else { return nil } let name = property let typeString = "\(type(of: T.self))" if typeString.contains("String") { if let raw = mpv_get_property_string(mpv, name) { let value = String(cString: raw) as? T mpv_free(raw) return value } } else if typeString.contains("Int") { var data = Int64() mpv_get_property(mpv, name, MPV_FORMAT_INT64, &data) return Int(data) as? T } else if typeString.contains("Bool") { var data = Int64() mpv_get_property(mpv, name, MPV_FORMAT_FLAG, &data) let value = data > 0 return value as? T } else if typeString.contains("Double") { var data = Double() mpv_get_property(mpv, name, MPV_FORMAT_DOUBLE, &data) return Double(data) as? T } return nil } func get<T: PreferenceValueCompatible, U: RawRepresentable>(property: U) -> T? where U.RawValue == String { return get(property: property.rawValue) } } extension MPV { private func readEvents() { _eventQueue.async { while true { let event = self.retrieveWaittingEvent() // Do not deal with mpv-event-none if event?.pointee.event_id == MPV_EVENT_NONE { break } self.handleEvent(event) } } } private func handleEvent(_ value: UnsafePointer<mpv_event>?) { guard let event = value else { return } let eventId = event.pointee.event_id enum Event { case shutdown case log(String) case propertyChange } switch eventId { case MPV_EVENT_SHUTDOWN: print("MPV_EVENT_SHUTDOWN") // let quitByMPV = !player.isMpvTerminated // if quitByMPV { // NSApp.terminate(nil) // } else { // mpv.destory() // _mpv = nil // } case MPV_EVENT_LOG_MESSAGE: let dataOpaquePtr = OpaquePointer(event.pointee.data) let msg = UnsafeMutablePointer<mpv_event_log_message>(dataOpaquePtr)?.pointee guard let prefix = msg?.prefix, let level = msg?.level, let text = msg?.text else { return } let message = String(cString: text) if let loglevel = LogLevel(rawValue: String(cString: level)) { switch loglevel { case .error: state = .error(message) case .v: if message.contains("EOF reached.") { _eof = true } default: break } print("MPV log: [\(String(cString: prefix))] \(loglevel.rawValue): \(message)") } case MPV_EVENT_PROPERTY_CHANGE: print("MPV_EVENT_PROPERTY_CHANGE") let dataOpaquePtr = OpaquePointer(event.pointee.data) guard let property = UnsafePointer<mpv_event_property>(dataOpaquePtr)?.pointee else { return } let propertyName = String(cString: property.name) handlePropertyChange(propertyName, property) case MPV_EVENT_AUDIO_RECONFIG: print("MPV_EVENT_AUDIO_RECONFIG") case MPV_EVENT_VIDEO_RECONFIG: onVideoReconfig() case MPV_EVENT_START_FILE: onFileStarted() // player.info.isIdle = false // guard getString(Property.path) != nil else { break } // player.fileStarted() // player.sendOSD(.fileStart(player.info.currentURL?.lastPathComponent ?? "-")) case MPV_EVENT_FILE_LOADED: onFileLoaded() case MPV_EVENT_SEEK: print("MPV_EVENT_SEEK") playingInfo?.isSeeking = true // player.info.isSeeking = true // if needRecordSeekTime { // recordedSeekStartTime = CACurrentMediaTime() // } // player.syncUI(.time) // let osdText = (player.info.videoPosition?.stringRepresentation ?? Constants.String.videoTimePlaceholder) + " / " + // (player.info.videoDuration?.stringRepresentation ?? Constants.String.videoTimePlaceholder) // let percentage = (player.info.videoPosition / player.info.videoDuration) ?? 1 // player.sendOSD(.seek(osdText, percentage)) case MPV_EVENT_PLAYBACK_RESTART: print("MPV_EVENT_PLAYBACK_RESTART") playingInfo?.isSeeking = false if let pos = double(for: .timePos) { playingInfo?.playPosition = pos } // player.info.isIdle = false // player.info.isSeeking = false // if needRecordSeekTime { // recordedSeekTimeListener?(CACurrentMediaTime() - recordedSeekStartTime) // recordedSeekTimeListener = nil // } // player.playbackRestarted() // player.syncUI(.time) case MPV_EVENT_END_FILE: print("MPV_EVENT_END_FILE") state = .stopped // if receive end-file when loading file, might be error // wait for idle // if player.info.fileLoading { // receivedEndFileWhileLoading = true // } else { // player.info.shouldAutoLoadFiles = false // } case MPV_EVENT_IDLE: print("MPV_EVENT_IDLE") state = .stopped // if receivedEndFileWhileLoading && player.info.fileLoading { // player.errorOpeningFileAndCloseMainWindow() // player.info.fileLoading = false // player.info.currentURL = nil // player.info.isNetworkResource = false // } // player.info.isIdle = true // if fileLoaded { // fileLoaded = false // player.closeMainWindow() // } // receivedEndFileWhileLoading = false break default: // let eventName = String(cString: mpv_event_name(eventId)) // Utility.log("MPV event (unhandled): \(eventName)") break } } private func onVideoReconfig() { // If loading file, video reconfig can return 0 width and height guard let info = playingInfo, info.loading == false, var w = int(for: .dwidth), var h = int(for: .dheight) else { return } if info.rotation == 90 || info.rotation == 270 { swap(&w, &h) } let fw = CGFloat(w) let fh = CGFloat(h) guard fw != info.displaySize?.width || fh != info.displaySize?.height else { return } if fw == 0, fh == 0, bool(for: .coreIdle) == true { return } info.displaySize = CGSize(width: fw, height: fh) eventHandler(.videoReconfig) } private func onFileLoaded() { self.togglePlayPause(play: false) if let duration = double(for: .duration) { playingInfo?.duration = duration } if let width = int(for: .width), let height = int(for: .height) { playingInfo?.videoSize = CGSize(width: width, height: height) } timerResume() _fileLoaded = true playingInfo?.loading = false DispatchQueue.main.async { self.updatePlayerList() self.updateChapters() if Pref.isPauseWhenOpen == false { self.togglePlayPause(play: true) } } } func onFileStarted() { guard var info = playingInfo else { return } info.isIdle = false guard let path = string(for: Property.path) else { return } info.justStartedFile = true info.disableOSDForFileLoading = true info.resourceType = .unknown info.currentURL = path.contains("://") ? URL(string: path) : URL(fileURLWithPath: path) // Auto load backgroundQueueTicket += 1 let shouldAutoLoadFiles = info.shouldAutoLoadFiles let currentTicket = backgroundQueueTicket backgroundQueue.async { // add files in same folder if shouldAutoLoadFiles { // self.autoLoadFilesInCurrentFolder(ticket: currentTicket) } // auto load matched subtitles // if let matchedSubs = self.info.matchedSubs[path] { // for sub in matchedSubs { // guard currentTicket == self.backgroundQueueTicket else { return } // self.loadExternalSubFile(sub) // } // // set sub to the first one // guard currentTicket == self.backgroundQueueTicket, self.mpv.mpv != nil else { return } // self.setTrack(1, forType: .sub) // } } } private func handlePropertyChange(_ name: String, _ property: mpv_event_property) { print("handlePropertyChange: \(name), property:\(property)") switch name { case Property.videoParams(.videoParams).rawValue: break // onVideoParamsChange(UnsafePointer<mpv_node_list>(OpaquePointer(property.data))) case Option.TrackSelection.vid.rawValue: break // let data = getInt(Option.TrackSelection.vid) // player.info.vid = Int(data) // let currTrack = player.info.currentTrack(.video) ?? .noneVideoTrack // player.sendOSD(.track(currTrack)) // DispatchQueue.main.async { // self.player.mainWindow.quickSettingView.reloadVideoData() // } case Option.TrackSelection.aid.rawValue: break // let data = getInt(Option.TrackSelection.aid) // player.info.aid = Int(data) // let currTrack = player.info.currentTrack(.audio) ?? .noneAudioTrack // player.sendOSD(.track(currTrack)) // DispatchQueue.main.async { // self.player.mainWindow.quickSettingView.reloadAudioData() // } case Option.TrackSelection.sid.rawValue: break // let data = getInt(Option.TrackSelection.sid) // player.info.sid = Int(data) // let currTrack = player.info.currentTrack(.sub) ?? .noneSubTrack // player.sendOSD(.track(currTrack)) // DispatchQueue.main.async { // self.player.mainWindow.quickSettingView.reloadSubtitleData() // } case Option.PlaybackControl.pause.rawValue: let isPaused = property.data.assumingMemoryBound(to: Bool.self).pointee _pQueue.sync { if isPaused { _state = .paused } else { _state = .playing } } if _eof == true { seekAbsolute(second: 0) timerPaused() _eof = false } // if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { // if player.info.isPaused != data { // player.sendOSD(data ? .pause : .resume) // player.info.isPaused = data // } // if player.mainWindow.isWindowLoaded { // if Preference.bool(for: .alwaysFloatOnTop) { // DispatchQueue.main.async { // self.player.mainWindow.setWindowFloatingOnTop(!data) // } // } // } // } // player.syncUI(.playButton) case Property.chapter.rawValue: break // player.syncUI(.time) // player.syncUI(.chapterList) case Option.Video.deinterlace.rawValue: break // if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { // // this property will fire a change event at file start // if player.info.deinterlace != data { // player.sendOSD(.deinterlace(data)) // player.info.deinterlace = data // } // } case Option.Audio.mute.rawValue: break // player.syncUI(.muteButton) // if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { // player.info.isMuted = data // player.sendOSD(data ? OSDMessage.mute : OSDMessage.unMute) // } case Option.Audio.volume.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // player.info.volume = data // player.syncUI(.volume) // player.sendOSD(.volume(Int(data))) // } case Option.Audio.audioDelay.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // player.info.audioDelay = data // player.sendOSD(.audioDelay(data)) // } case Option.Subtitles.subDelay.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // player.info.subDelay = data // player.sendOSD(.subDelay(data)) // } case Option.Subtitles.subScale.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // let displayValue = data >= 1 ? data : -1/data // let truncated = round(displayValue * 100) / 100 // player.sendOSD(.subScale(truncated)) // } case Option.Subtitles.subPos.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // player.sendOSD(.subPos(data)) // } case Option.PlaybackControl.speed.rawValue: break // if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { // player.sendOSD(.speed(data)) // } case Option.Equalizer.contrast.rawValue: break // if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { // let intData = Int(data) // player.info.contrast = intData // player.sendOSD(.contrast(intData)) // } case Option.Equalizer.hue.rawValue: break // if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { // let intData = Int(data) // player.info.hue = intData // player.sendOSD(.hue(intData)) // } case Option.Equalizer.brightness.rawValue: break // if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { // let intData = Int(data) // player.info.brightness = intData // player.sendOSD(.brightness(intData)) // } case Option.Equalizer.gamma.rawValue: break // if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { // let intData = Int(data) // player.info.gamma = intData // player.sendOSD(.gamma(intData)) // } case Option.Equalizer.saturation.rawValue: break // if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { // let intData = Int(data) // player.info.saturation = intData // player.sendOSD(.saturation(intData)) // } // following properties may change before file loaded case Property.playlistCount.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.playlistChanged)) case Property.trackList(.count).rawValue: break // player.trackListChanged() // NotificationCenter.default.post(Notification(name: Constants.Noti.tracklistChanged)) case Property.vf.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.vfChanged)) case Property.af.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.afChanged)) case Option.Window.fullscreen.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.fsChanged)) case Option.Window.ontop.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.ontopChanged)) case Option.Window.windowScale.rawValue: break // NotificationCenter.default.post(Notification(name: Constants.Noti.windowScaleChanged)) default: // Utility.log("MPV property changed (unhandled): \(name)") break } } } // MARK: - enums extension MPV { public enum Event { case videoReconfig, state } public enum ActionError: Error { case error(String) } public enum ExOptKey: String { case config case watchLaterDirectory = "watch-later-directory" } public enum ExOptValue: String { case yes, no, auto, openglcb = "opengl-cb" } public enum LogLevel: String { case no //- disable absolutely all messages case fatal //- critical/aborting errors case error //- simple errors case warn //- possible problems case info //- informational message case v //- noisy informational message case debug //- very noisy technical information case trace //- extremely noisy } public struct Geometry { public var x: String?, y: String?, w: String?, h: String?, xSign: String?, ySign: String? } } private final class OpenGLContextManager { static let shared = OpenGLContextManager() private var _playingWindowCount = 0 private var _contexts: [OpaquePointer?] = [] func add(ctx: OpaquePointer?) { _playingWindowCount += 1 _contexts.append(ctx) } func clean() { guard _contexts.count > 0 else { return } for item in _contexts { guard let ctx = item else { continue } mpv_opengl_cb_set_update_callback(ctx, nil, nil) mpv_opengl_cb_uninit_gl(ctx) } print("clean opengl context") _contexts = [] } func removePlayingWindow() { _playingWindowCount -= 1 if _playingWindowCount == 0 { clean() } } }
gpl-3.0
c5ef9b906eac214c6e9bc7a13593a983
39.406561
237
0.568353
4.414531
false
false
false
false
zerozheng/zhibo
Source/Network/RTMPType.swift
1
12240
// // RTMPType.swift // zhiboApp // // Created by zero on 17/2/23. // Copyright © 2017年 zero. All rights reserved. // import Foundation let RTMPScheme: String = "rtmp" let RTMPDefaultPort: Int = 1935 let RTMPBufferSize: Int = 4096 let RTMPSignatureSize: Int = 1536 /** * Chunk类型 * * 0 表示messageHeader信息齐全 * 1 表示messageHeader使用跟上一次相同msgStreamId * 2 表示messageHeader跟上一次仅时间戳不一样 * 3 表示messageHeader跟上一次的一样 */ struct RTMPChunkType: RawRepresentable { var rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static var type_00 = {return RTMPChunkType(rawValue: 0x0)}() static var type_01 = {return RTMPChunkType(rawValue: 0x40)}() static var type_10 = {return RTMPChunkType(rawValue: 0x80)}() static var type_11 = {return RTMPChunkType(rawValue: 0xC0)}() } /** * CSID * * 0 表示BasicHeader 占2个字节 * 1 表示BasicHeader 占3个字节 * 2 表示该chunk是控制信息/命令信息 * 3~(2^16+2^6-1) 为自定义id */ struct RTMPChunkStreamId: RawRepresentable { var rawValue: UInt8 init(rawValue: UInt8) { self.rawValue = rawValue } static var csid_0 = {return RTMPChunkStreamId(rawValue: 0x0)}() static var csid_1 = {return RTMPChunkStreamId(rawValue: 0x1)}() static var csid_2 = {return RTMPChunkStreamId(rawValue: 0x2)}() } class RTMPChunk { var chunkType: RTMPChunkType var timeStamp: TimeInterval var msgLength: Int var msgTypeId: Int var msgStreamId: Int init(chunkType: RTMPChunkType, timeStamp: TimeInterval, msgLenght: Int, msgTypeId: Int, msgStreamId: Int) { self.chunkType = chunkType self.timeStamp = timeStamp self.msgLength = msgLenght self.msgTypeId = msgTypeId self.msgStreamId = msgStreamId //litte-endian } } struct RTMPMessage { private(set) var timeStamp: TimeInterval private(set) var msgLength: Int private(set) var msgTypeId: Int private(set) var msgStreamId: Int //litte-endian private(set) var data: Data } /// RTMP消息类型 /// /// - 用户控制消息 /// - **userControl**: The client or the server sends this message to notify the peer about the user control events. This message carries Event type(2 bytes) and Event data. /// - also see: **UserControlEventType** /// - 协议控制消息 /// - **chunkSize**: This message is used to notify the peer of a new maximum chunk size, which is maintained independently for each direction. The payload is 4-byte length (32bit). The first bit must be zero, and the rest of 31 bit represent the chunk size to set. /// - **abortMsg**: This message is used to notify the peer, which is waiting for chunks to complete a message, to discard the partially received message over a chunk stream. the payload is 4 bytes and represent the ID of the discarded stream. /// - **acknowledgement**: This message is sent by client or server to notify the peer after receiving bytes equal to the window size. The payload is 4 bytes and holds the number of bytes received so far. /// - **windowAcknowledgementSize**: This message is used by client or server to inform the peer of the window size to use between sending acknowledgments. The payload is 4 bytes and represent the size of the window. /// - **peerBandwidth**: This message is sent by client or server to limit the output bandwidth of its peer. The peer receiving this message limits ith output bandwidth by limiting the amount of sent bu unacknowledged data to the window size indicated in this message. The peer receiving this message should respond with a Window Acknowledgment Size message if the window size is different from the last one sent to the sender of this message. The payload is 5 bytes. The first 4 bytes represent the window size, and the next 1 byte represent the type of limit. The limit type is one of the following values: /// - 0: Hard. The peer should limit its output bandwidth to the indicated window size. /// - 1: Soft. The peer should limit its output to the window indicated in this message or the limit already in effect, whichever is smaller. /// - 2: Dynamic. If the previous limit type was hard, treat this message as though is was marked hard, otherwise ignore this message. enum MessageType: Int { case chunkSize = 1 case abortMsg = 2 case acknowledgement = 3 case userControl = 4 case windowAcknowledgementSize = 5 case peerBandwidth = 6 case audio = 8 case vedio = 9 case afm3CommandMsg = 17 case afm0CommandMsg = 20 case afm3DataMsg = 15 case afm0DataMsg = 18 case afm3SharedObjectMsg = 16 case afm0SharedObjectMsg = 19 case aggregate = 22 } /// 用户控制消息的事件类型 /// /// - **streamBegin**: The server sends this event to notify the client that a stream has become functional and can be used for communication. By default, this event is sent on ID 0 after the application connect command is successfully received from the client. The event data is 4-byte and represents the stream ID of the stream that became functional. /// - **streamEOF**: The server sends this event to notify the client that the playback of data is over as requested on this stream. No more data is sent without issuing additional commands. The client discards the messages received for the stream. The 4 bytes of event data represent the ID of the stream on which playback has ended. /// - **streamDry**: The server sends this event to notify the client that there is no more data on the stream. If the server does not detect any message for a time period, it can notify the subscribed clients that the stream is dry. The 4 bytes of event data represent the stream ID of the dry stream. /// - **setBufferLength**: The client sends this event to inform the server of the buffer size (in milliseconds) that is used to buffer any data coming over a stream. This event is sent before the server starts processing the stream. The first 4 bytes of the event data represent the stream ID and the next 4 bytes represent the buffer length, in milliseconds. /// - **streamIsRecorded**: The server sends this event to notify the client that the stream is a recorded stream. The 4 bytes event data represent the stream ID of the recorded stream. /// - **pingRequest**: The server sends this event to test whether the client is reachable. Event data is a 4-byte timestamp, representing the local server time when the server dispatched the command. The client responds with PingResponse on receiving MsgPingRequest. /// - **pingResponse**: The client sends this event to the server in response to the ping request. The event data is a 4-byte timestamp, which was received with the PingRequest request. enum UserControlEventType: Int { case streamBegin = 0 case streamEOF = 1 case streamDry = 2 case setBufferLength = 3 case streamIsRecorded = 4 case pingRequest = 6 case pingResponse = 7 } enum CommandType: String { //netconnection case connect = "connect" case call = "call" case close = "close" case createStream = "createStream" //netstream case play = "play" case play2 = "play2" case deleteStream = "deleteStream" case closeStream = "closeStream" case receiveAudio = "receiveAudio" case receiveVideo = "receiveVideo" case publish = "publish" case seek = "seek" case pause = "pause" } // MARK: Connect Command About struct ConnectCommandObjectName: RawRepresentable { typealias RawValue = String private(set) var rawValue: RawValue init(rawValue: RawValue) { self.rawValue = rawValue } static var app: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "app") } static var flashver: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "flashver") } static var swfUrl: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "swfUrl") } static var tcUrl: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "tcUrl") } static var fpad: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "tcUrl") } static var audioCodecs: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "audioCodecs") } static var videoCodecs: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "audioCodecs") } static var videoFunction: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "videoFunction") } static var pageUrl: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "pageUrl") } static var objectEncoding: ConnectCommandObjectName { return ConnectCommandObjectName.init(rawValue: "objectEncoding") } } typealias CCOName = ConnectCommandObjectName enum AudioCodecsType: Int { case none = 0x0001 case adpcm = 0x0002 case mp3 = 0x0004 case intel = 0x0008 case unused = 0x0010 case nelly8 = 0x0020 case nelly = 0x0040 case g711a = 0x0080 case g711u = 0x0100 case nelly16 = 0x0200 case aac = 0x0400 case speex = 0x0800 case all = 0x0fff } enum VideoCodecsType: Int { case unused = 0x0001 case jpeg = 0x0002 case sorenson = 0x0004 case homebrew = 0x0008 case vp6 = 0x0010 case vp6alpha = 0x0020 case homebrewv = 0x0040 case h264 = 0x0080 case all = 0x00ff } enum VideoFunctionType: Int { case seek = 1 } enum EncodingType: Int { case amf0 = 0 case amf3 = 3 } class RTMPCommandMessage { private(set) var commandName: CommandType private(set) var transactionId: Int private(set) var commandObject: [String:AFM0Encoder]? private(set) var optionalUserArguments: [String:AFM0Encoder]? init(commandName: CommandType, transactionId: Int, commandObject: [String:AFM0Encoder]?, optionalUserArguments: [String:AFM0Encoder]?) { self.commandName = commandName self.transactionId = transactionId self.commandObject = commandObject self.optionalUserArguments = optionalUserArguments } func buffer() -> Data? { var data: Data = Data() do { try commandName.rawValue.append(to: &data) } catch { if error is RTMPError { print((error as! RTMPError).errorDescription) }else{ print("unknown error happen") } return nil } do { try transactionId.append(to: &data) } catch { if error is RTMPError { print((error as! RTMPError).errorDescription) }else{ print("unknown error happen") } return nil } do { try commandObject?.append(to: &data) } catch { if error is RTMPError { print((error as! RTMPError).errorDescription) }else{ print("unknown error happen") } return nil } do { try optionalUserArguments?.append(to: &data) } catch { if error is RTMPError { print((error as! RTMPError).errorDescription) }else{ print("unknown error happen") } return nil } return data } } enum AFM0DataType: UInt8 { case number = 0 case boolean = 1 case string = 2 case object = 3 case movieClip = 4 /* reserved, not used */ case null = 5 case undefined = 6 case reference = 7 case arrayEMCA = 8 case objectEnd = 9 case arrayStrict = 10 case date = 11 case longString = 12 case unsupported = 13 case recordSet = 14 /* reserved, not used */ case xml = 15 case typedObject = 16 case avmPlus = 17 /* switch to AMF3 */ case invalid = 0xff }
mit
0cb3b66321e9ee798a88f6e7c4930a53
34.636095
610
0.678788
4.204188
false
false
false
false
Yurssoft/QuickFile
QuickFile/Views/YSToolbarView.swift
1
2304
// // YSToolbarView.swift // YSGGP // // Created by Yurii Boiko on 10/4/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit import CoreGraphics protocol YSToolbarViewDelegate: class { func selectAllButtonTapped(toolbar: YSToolbarView) func downloadButtonTapped(toolbar: YSToolbarView) func deleteButtonTapped(toolbar: YSToolbarView) } @IBDesignable class YSToolbarView: UIView { var view: UIView! @IBOutlet weak var selectAllButton: UIButton! @IBOutlet weak var downloadButton: UIButton! @IBOutlet weak var deleteButton: UIButton! weak var ysToolbarDelegate: YSToolbarViewDelegate? @IBInspectable var selectAllButtonText: String? { get { return selectAllButton.titleLabel?.text } set(text) { selectAllButton.setTitle(text, for: .normal) } } @IBInspectable var downloadButtonImage: UIImage? { get { return downloadButton.imageView?.image } set(image) { downloadButton.setImage(image, for: .normal) } } @IBAction func selectAllTapped(_ sender: UIButton) { logDefault(.View, .Info, "") ysToolbarDelegate?.selectAllButtonTapped(toolbar: self) } @IBAction func downloadTapped(_ sender: UIButton) { logDefault(.View, .Info, "") ysToolbarDelegate?.downloadButtonTapped(toolbar: self) } @IBAction func deleteTapped(_ sender: UIButton) { logDefault(.View, .Info, "") ysToolbarDelegate?.deleteButtonTapped(toolbar: self) } override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { view = loadViewFromNib() view.frame = bounds view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] addSubview(view) } func loadViewFromNib() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: YSToolbarView.nameOfClass, bundle: bundle) guard let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView else { return UIView() } return view } }
mit
ac43ff0b66948941d6e1fc53280d8ef3
27.085366
110
0.648719
4.578529
false
false
false
false
orchely/ColorThiefSwift
Example/ColorThiefSwiftExample/ViewController.swift
2
3327
// // ViewController.swift // ColorThiefSample // // Created by Kazuki Ohara on 2017/02/12. // Copyright © 2019 Kazuki Ohara. All rights reserved. // // License // ------- // MIT License // https://github.com/yamoridon/ColorThiefSwift/blob/master/LICENSE import UIKit import ColorThiefSwift class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var button: UIButton! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var colorLabel: UILabel! @IBOutlet weak var colorView: UIView! @IBOutlet var paletteLabels: [UILabel]! @IBOutlet var paletteViews: [UIView]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonTapped(_ sender: UIButton) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .photoLibrary present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) picker.dismiss(animated: true, completion: nil) guard let image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage else { return } imageView.image = image DispatchQueue.global(qos: .default).async { guard let colors = ColorThief.getPalette(from: image, colorCount: 10, quality: 1, ignoreWhite: true) else { return } let start = Date() guard let dominantColor = ColorThief.getColor(from: image) else { return } let elapsed = -start.timeIntervalSinceNow NSLog("time for getColorFromImage: \(Int(elapsed * 1000.0))ms") DispatchQueue.main.async { [weak self] in for i in 0 ..< 9 { if i < colors.count { let color = colors[i] self?.paletteViews[i].backgroundColor = color.makeUIColor() self?.paletteLabels[i].text = "getPalette[\(i)] R\(color.r) G\(color.g) B\(color.b)" } else { self?.paletteViews[i].backgroundColor = UIColor.white self?.paletteLabels[i].text = "-" } } self?.colorView.backgroundColor = dominantColor.makeUIColor() self?.colorLabel.text = "getColor R\(dominantColor.r) G\(dominantColor.g) B\(dominantColor.b)" } } } } fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)}) } fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
mit
33c89e2ccbb22d554ed74f25cf6719e1
39.072289
148
0.642814
4.920118
false
false
false
false
TMTBO/TTAMusicPlayer
TTAMusicPlayer/TTAMusicPlayer/Classes/Player/Controllers/PlayerViewController.swift
1
6107
// // PlayerViewController.swift // MusicPlayer // // Created by ys on 16/11/22. // Copyright © 2016年 YS. All rights reserved. // import UIKit import MediaPlayer // MARK: - LifeCycle class PlayerViewController: BaseViewController{ var music : MPMediaItem? { didSet { configMusicInfo() } } var playerView : PlayerView? var bgImageView : UIImageView? var titleLabel : UILabel? var navBgView : UIVisualEffectView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.contentMode = .scaleAspectFill view.layer.masksToBounds = true playMusic() PlayerManager.shared.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: false) let playingMusic = PlayerManager.shared.musics[PlayerManager.shared.playingIndex] music = music == playingMusic ? music : playingMusic } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } deinit { print("PlayerViewController deinit") } } // MARK: - UI extension PlayerViewController { override func setupUI() { playerView = PlayerView(frame: view.bounds) playerView?.delegate = self self.view.addSubview(playerView!) configNavcBar() } func configNavcBar() { // bgView let blur = UIBlurEffect(style: .light) navBgView = UIVisualEffectView(effect: blur) navBgView?.backgroundColor = UIColor.clear // lineView let lineView = UIView(frame: CGRect(x: 0, y: 64, width: kSCREEN_WIDTH, height: 1.0 / kSCREEN_SCALE)) lineView.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) // titleView titleLabel = UILabel() titleLabel?.numberOfLines = 0 titleLabel?.textAlignment = .center configNavcTitle(with: .black) // add view.addSubview(navBgView!) view.addSubview(backButton!) view.addSubview(titleLabel!) view.addSubview(lineView) // layout navBgView?.snp.makeConstraints { (make) in make.top.left.right.equalTo(view) make.height.equalTo(64) } titleLabel?.snp.makeConstraints({ (make) in make.centerX.equalTo(view) make.top.equalTo(28) }) backButton?.snp.makeConstraints({ (make) in make.left.equalTo(view).offset(12 * kSCALEP) make.top.equalTo(view).offset(26) }) } func configNavcTitle(with color : UIColor) { guard let currentMusic = music else { titleLabel?.text = "Music" titleLabel?.font = UIFont.boldSystemFont(ofSize: 17) titleLabel?.sizeToFit() return } let nameAttributeString = NSMutableAttributedString(string: (currentMusic.title ?? "音乐") + "\n", attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15), NSForegroundColorAttributeName : color]) let singerAttributeString = NSMutableAttributedString(string: currentMusic.artist ?? "专集", attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 12), NSForegroundColorAttributeName : color]) nameAttributeString.append(singerAttributeString) titleLabel?.attributedText = nameAttributeString titleLabel?.sizeToFit() } func configMusicInfo() { // background let bgImage = music?.artwork?.image(at: view.bounds.size) let realBgImage = bgImage == nil ? #imageLiteral(resourceName: "cm2_default_play_bg") : bgImage view.layer.contents = realBgImage?.cgImage let point = CGPoint(x: view.center.x, y: 32) let color = bgImage?.tta_pickColor(from: point) playerView?.configIconImageView(with: bgImage ?? #imageLiteral(resourceName: "cm2_default_cover_play")) // title configNavcTitle(with: color ?? .black) } } // MARK: - Player Control extension PlayerViewController { /// 播放 func playMusic() { if let newMusic = music { PlayerManager.shared.play(music : newMusic) } else { // 从用户偏好设置中读取上次播放信息 let musicURL = PlayerManager.shared.readNowPlayingMusicInfo() PlayerManager.shared.play(musicURL : musicURL) } playerView?.updateDurationTime() } /// 暂停 func pauseMusic() { PlayerManager.shared.pause() } /// 下一曲 func nextMusic() { PlayerManager.shared.next() } /// 上一曲 func previousMusic() { PlayerManager.shared.previous() } } // MARK: - PlayerViewDelegate extension PlayerViewController : PlayerViewDelegate { func playerView(_ playerView: PlayerView, play: UIButton) { playMusic() } func playerView(_ playerView: PlayerView, pause: UIButton) { pauseMusic() } func playerView(_ playerView: PlayerView, next: UIButton) { nextMusic() } func playerView(_ playerView: PlayerView, preview: UIButton) { previousMusic() } } // MARK: - PlayerManagerDelegate extension PlayerViewController : PlayerManagerDelegate { func playerManager(_ playerManager: PlayerManager, playingMusic: MPMediaItem) { self.music = playingMusic } func playerManagerUpdateProgressAndTime(_ playerManager: PlayerManager) { playerView?.updateProgressAndTime() } func playerManager(_ playerManager: PlayerManager, conrtolMusicIconAnimation isPause: Bool) { if isPause { playerView?.stopIconImageViewAnmation() } else { playerView?.startIconImageViewAnmation() } } }
mit
c8034cfb2dfecd683a1ccf32e98c411a
31.148936
215
0.632528
4.808274
false
false
false
false
sp71/SnapLayout
Example/SnapLayout_ExampleTests/SnapManagerTests.swift
1
14565
// // SnapManagerTests.swift // SnapLayout // // Created by Satinder Singh on 3/30/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import XCTest import SnapLayout /// Tests SnapManager class SnapManagerTests: BaseTestCase { /// Test Snap Manager Constructor func testSnapManagerConstructor() { let topConstant = CGFloat(0) let leadingConstant = CGFloat(8) let bottomConstant = CGFloat(16) let trailingConstant = CGFloat(24) let widthConstant = CGFloat(32) let heightConstant = CGFloat(64) let centerXConstant = CGFloat(0) let centerYConstant = CGFloat(0) let snapManager = childView.snap(top: topConstant, leading: leadingConstant, bottom: bottomConstant, trailing: trailingConstant, width: widthConstant, height: heightConstant, centerX: centerXConstant, centerY: centerYConstant) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertNotNil(snapManager.trailing) XCTAssertEqual(snapManager.trailing!.constant, trailingConstant) XCTAssertNotNil(snapManager.width) XCTAssertEqual(snapManager.width!.constant, widthConstant) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.height!.constant, heightConstant) XCTAssertNotNil(snapManager.centerX) XCTAssertEqual(snapManager.centerX!.constant, centerXConstant) XCTAssertNotNil(snapManager.centerY) XCTAssertEqual(snapManager.centerY!.constant, centerYConstant) } /// Test Snap Manager Constructor with a view who does not have a superview func testSnapManagerConstructorWithoutSuperView() { let widthConstant = CGFloat(32) let heightConstant = CGFloat(64) let snapManager = view.snap(width: widthConstant, height: heightConstant) XCTAssertEqual(view.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNotNil(snapManager.width) XCTAssertEqual(snapManager.width!.constant, widthConstant) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.height!.constant, heightConstant) XCTAssertNil(snapManager.top) XCTAssertNil(snapManager.leading) XCTAssertNil(snapManager.bottom) XCTAssertNil(snapManager.trailing) XCTAssertNil(snapManager.centerX) XCTAssertNil(snapManager.centerY) } /// Test Snap Manager Constructor where a error would occur through logging func testSnapManagerConstructorError() { let snapManager = view.snap(trailing: 0) XCTAssertEqual(view.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNil(snapManager.top) XCTAssertNil(snapManager.leading) XCTAssertNil(snapManager.bottom) XCTAssertNil(snapManager.trailing) XCTAssertNil(snapManager.width) XCTAssertNil(snapManager.height) XCTAssertNil(snapManager.centerX) XCTAssertNil(snapManager.centerY) } /// Test Snap Manager Constructor with view argument func testSnapManagerConstructorWithSnapConfigErrorForNotSharingSameViewHeirarchy() { let containerViewSubview = UIView() let otherView = UIView() let containerView = UIView() containerView.addSubview(containerViewSubview) containerView.addSubview(otherView) let snapManager = containerViewSubview.snap(to: otherView, config: .zero) XCTAssertEqual(containerViewSubview.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, 0) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.leading!.constant, 0) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.bottom!.constant, 0) XCTAssertNotNil(snapManager.trailing) XCTAssertEqual(snapManager.trailing!.constant, 0) XCTAssertNil(snapManager.width) XCTAssertNil(snapManager.height) XCTAssertNil(snapManager.centerX) XCTAssertNil(snapManager.centerY) } /// Test Snap Manager Constructor with a config parameter func testSnapManagerConstructorWithSnapConfig() { let topConstant = CGFloat(0) let leadingConstant = CGFloat(8) let bottomConstant = CGFloat(16) let trailingConstant = CGFloat(24) let widthConstant = CGFloat(32) let heightConstant = CGFloat(64) let centerXConstant = CGFloat(0) let centerYConstant = CGFloat(0) let snapConfig = SnapConfig(top: topConstant, leading: leadingConstant, bottom: bottomConstant, trailing: trailingConstant, width: widthConstant, height: heightConstant, centerX: centerXConstant, centerY: centerYConstant) let snapManager = childView.snap(config: snapConfig) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertNotNil(snapManager.trailing) XCTAssertEqual(snapManager.trailing!.constant, trailingConstant) XCTAssertNotNil(snapManager.width) XCTAssertEqual(snapManager.width!.constant, widthConstant) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.height!.constant, heightConstant) XCTAssertNotNil(snapManager.centerX) XCTAssertEqual(snapManager.centerX!.constant, centerXConstant) XCTAssertNotNil(snapManager.centerY) XCTAssertEqual(snapManager.centerY!.constant, centerYConstant) } /// Test Snap Manager Config Constructor when used with chaining. /// Ensures SnapManager information is not lost during chaining func testSnapManagerConfigChainConstructor() { let topConstant = CGFloat(0) let leadingConstant = CGFloat(8) let bottomConstant = CGFloat(16) let trailingConstant = CGFloat(24) let widthConstant = CGFloat(32) let heightConstant = CGFloat(64) let centerXConstant = CGFloat(0) let centerYConstant = CGFloat(0) let snapConfig = SnapConfig(top: topConstant, leading: leadingConstant, bottom: bottomConstant, trailing: trailingConstant, width: widthConstant, height: heightConstant) let centerConfig = SnapConfig(centerX: centerXConstant, centerY: centerYConstant) let snapManager = childView.snap(config: snapConfig) .snap(config: centerConfig) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertNotNil(snapManager.trailing) XCTAssertEqual(snapManager.trailing!.constant, trailingConstant) XCTAssertNotNil(snapManager.width) XCTAssertEqual(snapManager.width!.constant, widthConstant) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.height!.constant, heightConstant) XCTAssertNotNil(snapManager.centerX) XCTAssertEqual(snapManager.centerX!.constant, centerXConstant) XCTAssertNotNil(snapManager.centerY) XCTAssertEqual(snapManager.centerY!.constant, centerYConstant) } /// Tests Snap Manager width during chaining func testSnapManagerWidthConstructor() { let topConstant = CGFloat(10) let widthMultiplier = CGFloat(0.5) let snapManager = childView.snap(top: topConstant).snapWidth(to: parentView, multiplier: widthMultiplier) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertNotNil(snapManager.width) XCTAssertEqual(snapManager.width!.multiplier, widthMultiplier) XCTAssertEqual(snapManager.width!.constant, 0) } /// Tests Snap Manager height during chaining func testSnapManagerHeightConstructor() { let topConstant = CGFloat(10) let heightMultiplier = CGFloat(0.5) let snapManager = childView.snap(top: topConstant).snapHeight(to: parentView, multiplier: heightMultiplier) XCTAssertNotNil(snapManager.top) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.height!.multiplier, heightMultiplier) XCTAssertEqual(snapManager.height!.constant, 0) } /// Tests Snap Manager Size during chaining func testSnapManagerSizeConstructor() { let bottomConstant = CGFloat(10) let size = CGSize(width: 30, height: 40) let snapManager = childView.snap(bottom: bottomConstant).snap(size: size) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertNotNil(snapManager.bottom) XCTAssertNotNil(snapManager.width) XCTAssertNotNil(snapManager.height) XCTAssertEqual(snapManager.bottom!.isActive, true) XCTAssertEqual(snapManager.width!.isActive, true) XCTAssertEqual(snapManager.height!.isActive, true) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertEqual(snapManager.width!.constant, size.width) XCTAssertEqual(snapManager.height!.constant, size.height) XCTAssertEqual(snapManager.width!.multiplier, 1.0) XCTAssertEqual(snapManager.height!.multiplier, 1.0) } /// Tests Snap Manager Trailing View during chaining func testSnapManagerTrailingViewConstructor() { let bottomConstant = CGFloat(10) let trailingConstant = CGFloat(8) let snapManager = childView.snap(bottom: bottomConstant).snap(trailingView: childView2, constant: trailingConstant) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertEqual(childView2.translatesAutoresizingMaskIntoConstraints, true) XCTAssertNotNil(snapManager.trailing) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.trailing!.isActive, true) XCTAssertEqual(snapManager.bottom!.isActive, true) XCTAssertEqual(snapManager.trailing!.constant, trailingConstant) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertEqual(snapManager.trailing!.multiplier, 1.0) XCTAssertEqual(snapManager.bottom!.multiplier, 1.0) } /// Tests Snap Manager Leading View during chaining func testSnapLeadingView() { let bottomConstant = CGFloat(10) let leadingConstant = CGFloat(8) let snapManager = childView.snap(bottom: bottomConstant).snap(leadingView: childView2, constant: leadingConstant) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertEqual(childView2.translatesAutoresizingMaskIntoConstraints, true) XCTAssertNotNil(snapManager.leading) XCTAssertNotNil(snapManager.bottom) XCTAssertEqual(snapManager.leading!.isActive, true) XCTAssertEqual(snapManager.bottom!.isActive, true) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertEqual(snapManager.leading!.multiplier, 1.0) XCTAssertEqual(snapManager.bottom!.multiplier, 1.0) } /// Tests Snap Manager Bottom View during chaining func testSnapBottomView() { let leadingConstant = CGFloat(8) let bottomConstant = CGFloat(10) let snapManager = childView.snap(leading: leadingConstant).snap(bottomView: childView2, constant: bottomConstant) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertEqual(childView2.translatesAutoresizingMaskIntoConstraints, true) XCTAssertNotNil(snapManager.bottom) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.bottom!.isActive, true) XCTAssertEqual(snapManager.leading!.isActive, true) XCTAssertEqual(snapManager.bottom!.constant, bottomConstant) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertEqual(snapManager.bottom!.multiplier, 1.0) XCTAssertEqual(snapManager.leading!.multiplier, 1.0) } /// Tests Snap Manager Top View during chaining func testSnapTopView() { let leadingConstant = CGFloat(8) let topConstant = CGFloat(8) let snapManager = childView.snap(leading: leadingConstant).snap(topView: childView2, constant: topConstant) XCTAssertEqual(childView.translatesAutoresizingMaskIntoConstraints, false) XCTAssertEqual(childView2.translatesAutoresizingMaskIntoConstraints, true) XCTAssertNotNil(snapManager.top) XCTAssertNotNil(snapManager.leading) XCTAssertEqual(snapManager.top!.isActive, true) XCTAssertEqual(snapManager.leading!.isActive, true) XCTAssertEqual(snapManager.top!.constant, topConstant) XCTAssertEqual(snapManager.leading!.constant, leadingConstant) XCTAssertEqual(snapManager.top!.multiplier, 1.0) XCTAssertEqual(snapManager.leading!.multiplier, 1.0) } }
mit
06724cf4a4de91da8e2ff3514da54486
48.037037
123
0.696031
5.502078
false
true
false
false
hodinkee/iris
Iris/SigningOptions.swift
1
983
// // SigningOptions.swift // Iris // // Created by Jonathan Baker on 11/11/15. // Copyright © 2015 HODINKEE. All rights reserved. // public struct SigningOptions { // MARK: - Properties /// The host pertaining to an Imgix source. /// /// Example: `hodinkee.imgix.net` public var host: String /// The alphanumeric "Secure URL Token" pertaining to an Imgix source. /// /// Example: `hodinkee.imgix.net` public var token: String /// Controls whether or not to use HTTPS when requesting the image. public var secure: Bool // MARK: - Initializers public init(host: String, token: String, secure: Bool = true) { self.host = host self.token = token self.secure = secure } } extension SigningOptions: Equatable { public static func == (lhs: SigningOptions, rhs: SigningOptions) -> Bool { return (lhs.host == rhs.host) && (lhs.token == rhs.token) && (lhs.secure == rhs.secure) } }
mit
dc7e9f7910f6349ef57da18feb746842
23.55
95
0.627291
3.677903
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV2/Models/RuntimeResponseGenericRuntimeResponseTypeOption.swift
1
2356
/** * (C) Copyright IBM Corp. 2020, 2021. * * 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 /** RuntimeResponseGenericRuntimeResponseTypeOption. Enums with an associated value of RuntimeResponseGenericRuntimeResponseTypeOption: RuntimeResponseGeneric */ public struct RuntimeResponseGenericRuntimeResponseTypeOption: Codable, Equatable { /** The preferred type of control to display. */ public enum Preference: String { case dropdown = "dropdown" case button = "button" } /** The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. */ public var responseType: String /** The title or introductory text to show before the response. */ public var title: String /** The description to show with the the response. */ public var description: String? /** The preferred type of control to display. */ public var preference: String? /** An array of objects describing the options from which the user can choose. */ public var options: [DialogNodeOutputOptionsElement] /** An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. */ public var channels: [ResponseGenericChannel]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case responseType = "response_type" case title = "title" case description = "description" case preference = "preference" case options = "options" case channels = "channels" } }
apache-2.0
660164df13f8a3cc57dc57f9ec5c7dd2
29.597403
114
0.693124
4.759596
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/ExplicitACLRule.swift
1
6718
import Foundation import SourceKittenFramework private typealias SourceKittenElement = [String: SourceKitRepresentable] public struct ExplicitACLRule: OptInRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "explicit_acl", name: "Explicit ACL", description: "All declarations should specify Access Control Level keywords explicitly.", kind: .idiomatic, nonTriggeringExamples: [ "internal enum A {}\n", "public final class B {}\n", "private struct C {}\n", "internal enum A {\n internal enum B {}\n}", "internal final class Foo {}", "internal\nclass Foo { private let bar = 5 }", "internal func a() { let a = }\n", "private func a() { func innerFunction() { } }", "private enum Foo { enum Bar { } }", "private struct C { let d = 5 }", "internal protocol A {\n func b()\n}", "internal protocol A {\n var b: Int\n}", "internal class A { deinit {} }" ], triggeringExamples: [ "enum A {}\n", "final class B {}\n", "internal struct C { let d = 5 }\n", "public struct C { let d = 5 }\n", "func a() {}\n", "internal let a = 0\nfunc b() {}\n" ] ) private func findAllExplicitInternalTokens(in file: File) -> [NSRange] { let contents = file.contents.bridge() return file.match(pattern: "internal", with: [.attributeBuiltin]).compactMap { contents.NSRangeToByteRange(start: $0.location, length: $0.length) } } private func offsetOfElements(from elements: [SourceKittenElement], in file: File, thatAreNotInRanges ranges: [NSRange]) -> [Int] { return elements.compactMap { element in guard let typeOffset = element.offset else { return nil } // find the last "internal" token before the type guard let previousInternalByteRange = lastInternalByteRange(before: typeOffset, in: ranges) else { return typeOffset } // the "internal" token correspond to the type if there're only // attributeBuiltin (`final` for example) tokens between them let length = typeOffset - previousInternalByteRange.location let range = NSRange(location: previousInternalByteRange.location, length: length) let internalDoesntBelongToType = Set(file.syntaxMap.kinds(inByteRange: range)) != [.attributeBuiltin] return internalDoesntBelongToType ? typeOffset : nil } } public func validate(file: File) -> [StyleViolation] { let implicitAndExplicitInternalElements = internalTypeElements(in: file.structure.dictionary) guard !implicitAndExplicitInternalElements.isEmpty else { return [] } let explicitInternalRanges = findAllExplicitInternalTokens(in: file) let violations = offsetOfElements(from: implicitAndExplicitInternalElements, in: file, thatAreNotInRanges: explicitInternalRanges) return violations.map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: $0)) } } private func lastInternalByteRange(before typeOffset: Int, in ranges: [NSRange]) -> NSRange? { let firstPartition = ranges.prefix(while: { typeOffset > $0.location }) return firstPartition.last } private func internalTypeElements(in element: SourceKittenElement) -> [SourceKittenElement] { return element.substructure.flatMap { element -> [SourceKittenElement] in guard let elementKind = element.kind.flatMap(SwiftDeclarationKind.init(rawValue:)) else { return [] } let isDeinit = elementKind == .functionMethodInstance && element.name == "deinit" guard !isDeinit else { return [] } let internalTypeElementsInSubstructure = elementKind.childsAreExemptFromACL ? [] : internalTypeElements(in: element) if element.accessibility.flatMap(AccessControlLevel.init(identifier:)) == .internal { return internalTypeElementsInSubstructure + [element] } return internalTypeElementsInSubstructure } } } private extension SwiftDeclarationKind { var childsAreExemptFromACL: Bool { switch self { case .`associatedtype`, .enumcase, .enumelement, .functionAccessorAddress, .functionAccessorDidset, .functionAccessorGetter, .functionAccessorMutableaddress, .functionAccessorSetter, .functionAccessorWillset, .genericTypeParam, .module, .precedenceGroup, .varLocal, .varParameter, .varClass, .varGlobal, .varInstance, .varStatic, .`typealias`, .functionConstructor, .functionDestructor, .functionFree, .functionMethodClass, .functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix, .functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .`protocol`: return true case .`class`, .`enum`, .`extension`, .`extensionClass`, .`extensionEnum`, .extensionProtocol, .extensionStruct, .`struct`: return false } } var shouldContainExplicitACL: Bool { switch self { case .`associatedtype`, .enumcase, .enumelement, .functionAccessorAddress, .functionAccessorDidset, .functionAccessorGetter, .functionAccessorMutableaddress, .functionAccessorSetter, .functionAccessorWillset, .functionDestructor, .genericTypeParam, .module, .precedenceGroup, .varLocal, .varParameter: return false case .`class`, .`enum`, .`extension`, .`extensionClass`, .`extensionEnum`, .extensionProtocol, .extensionStruct, .functionConstructor, .functionFree, .functionMethodClass, .functionMethodInstance, .functionMethodStatic, .functionOperator, .functionOperatorInfix, .functionOperatorPostfix, .functionOperatorPrefix, .functionSubscript, .`protocol`, .`struct`, .`typealias`, .varClass, .varGlobal, .varInstance, .varStatic: return true } } }
mit
828cb904ccac26682adfb7ba2e23e19d
42.908497
113
0.621911
5.043544
false
false
false
false
dclelland/DirectedPanGestureRecognizer
DirectedPanDemo/DirectedPanDemo/ViewController.swift
1
5127
// // ViewController.swift // DirectedPanDemo // // Created by Daniel Clelland on 11/04/16. // Copyright © 2016 Daniel Clelland. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var panGestureRecognizer: DirectedPanGestureRecognizer! @IBOutlet weak var translationLabel: UILabel! @IBOutlet weak var velocityLabel: UILabel! @IBOutlet weak var arrowLabel: UILabel! @IBOutlet weak var directionSegmentedControl: UISegmentedControl! @IBOutlet weak var minimumTranslationLabel: UILabel! @IBOutlet weak var minimumTranslationSlider: UISlider! @IBOutlet weak var minimumVelocityLabel: UILabel! @IBOutlet weak var minimumVelocitySlider: UISlider! // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() updateView() } // MARK: View state func updateView() { let currentDirection = direction(forIndex: directionSegmentedControl.selectedSegmentIndex)! let translationText = String(format: "%.2f", panGestureRecognizer.translation()) let velocityText = String(format: "%.2f", panGestureRecognizer.velocity()) translationLabel.text = "Translation: " + translationText velocityLabel.text = "Velocity: " + velocityText let translationColor = panGestureRecognizer.translation() < panGestureRecognizer.minimumTranslation ? UIColor.red : UIColor.green let velocityColor = panGestureRecognizer.velocity() < panGestureRecognizer.minimumVelocity ? UIColor.red : UIColor.green translationLabel.backgroundColor = translationColor velocityLabel.backgroundColor = velocityColor let arrowText = arrow(forDirection: currentDirection) arrowLabel.text = arrowText let minimumTranslationText = String(format: "%.2f", panGestureRecognizer.minimumTranslation) let minimumVelocityText = String(format: "%.2f", panGestureRecognizer.minimumVelocity) minimumTranslationLabel.text = "Minimum translation: " + minimumTranslationText minimumVelocityLabel.text = "Minimum velocity: " + minimumVelocityText } // MARK: Actions @IBAction func directionSegmentedControlDidChangeValue(_ segmentedControl: UISegmentedControl) { updateView() } @IBAction func minimumTranslationSliderDidChangeValue(_ slider: UISlider) { panGestureRecognizer.minimumTranslation = minimumTranslation(forValue: slider.value) updateView() } @IBAction func minimumVelocitySliderDidChangeValue(_ slider: UISlider) { panGestureRecognizer.minimumVelocity = minimumVelocity(forValue: slider.value) updateView() } } // MARK: - Gesture recognizer delegate extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { switch gestureRecognizer { case let panGestureRecognizer as DirectedPanGestureRecognizer where panGestureRecognizer == self.panGestureRecognizer: return panGestureRecognizer.direction == direction(forIndex: directionSegmentedControl.selectedSegmentIndex)! default: return true } } } // MARK: - Directed pan gesture recognizer delegate extension ViewController: DirectedPanGestureRecognizerDelegate { func directedPanGestureRecognizer(didStart gestureRecognizer: DirectedPanGestureRecognizer) { arrowLabel.backgroundColor = .clear updateView() } func directedPanGestureRecognizer(didUpdate gestureRecognizer: DirectedPanGestureRecognizer) { arrowLabel.backgroundColor = .clear updateView() } func directedPanGestureRecognizer(didCancel gestureRecognizer: DirectedPanGestureRecognizer) { arrowLabel.backgroundColor = .red updateView() } func directedPanGestureRecognizer(didFinish gestureRecognizer: DirectedPanGestureRecognizer) { arrowLabel.backgroundColor = .green updateView() } } // MARK: - Private helpers private extension ViewController { func direction(forIndex index: Int) -> DirectedPanGestureRecognizer.Direction? { switch index { case 0: return .up case 1: return .left case 2: return .down case 3: return .right default: return nil } } func minimumTranslation(forValue value: Float) -> CGFloat { return CGFloat(value) * view.frame.width } func minimumVelocity(forValue value: Float) -> CGFloat { return CGFloat(value) * view.frame.width } func arrow(forDirection direction: DirectedPanGestureRecognizer.Direction) -> String { switch direction { case .up: return "↑" case .left: return "←" case .down: return "↓" case .right: return "→" } } }
mit
fbb128f344fcd1f7f42594d49dba94bd
30.592593
137
0.67585
5.674058
false
false
false
false
RobotRebels/Kratos2
Kratos2/Kratos2/DetailViewController.swift
1
1153
// // DetailViewController.swift // Kratos2 // // Created by Denis Alekseychuk on 22.05.17. // Copyright © 2017 RobotRebles. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailTableView: UITableView? @IBOutlet weak var shortTextLabel: UILabel? var acronymShortForm: String = "" var acronymLongForm: String = "" var acronymDescription: String = "" var acronymsData: [Acronym] = [] var detailAcronymsData: [Acronym] = [] override func viewDidLoad() { super.viewDidLoad() for acronym in acronymsData { if acronym.short == acronymShortForm { detailAcronymsData.append(acronym) } } navigationController?.navigationBar.tintColor = Global.mainApplicationActiveColor shortTextLabel?.text = acronymShortForm detailTableView?.tableFooterView = UIView() detailTableView?.reloadData() } override func viewDidLayoutSubviews() { detailTableView?.setContentOffset(CGPoint.zero, animated:false) } }
mit
c626d405b618c009b72d4b552513f330
25.790698
89
0.644097
4.860759
false
false
false
false
sdhzwm/BaiSI-Swift-
BaiSi/BaiSi/Classes/Essence(精华)/Model/WMWordToip.swift
1
1847
// // WMWordToip.swift // BaiSi // // Created by 王蒙 on 15/8/1. // Copyright © 2015年 wm. All rights reserved. // import UIKit class WMWordToip: NSObject { /** 名称 */ var name:String /** 头像 */ var profile_image:String /** 发帖时间 */ var create_time:String /** 文字内容 */ var text:String /** 顶的数量 */ var ding:Int /** 踩的数量 */ var cai:Int /** 转发的数量 */ var repost:Int /** 评论的数量 */ var comment:Int /**新浪微博*/ var sina_v:String /**帖子的类型*/ var type:Int init(dictionary: [String: AnyObject]) { name = dictionary["name"] as! String profile_image = dictionary["profile_image"] as! String create_time = dictionary["create_time"] as! String text = dictionary["text"] as! String let dingStr = dictionary["ding"] as! String ding = Int(dingStr)! let caiStr = dictionary["cai"] as! String cai = Int(caiStr)! let repostStr = dictionary["repost"] as! String repost = Int(repostStr)! if let commentStr = dictionary["comment"] as? String{ comment = Int(commentStr)! }else{ comment = 0 } let typeStr = dictionary["type"] as! String type = Int(typeStr)! if let sina_vStr = dictionary["sina_v"] as? String{ sina_v = sina_vStr }else{ sina_v = "0" } } static func worfToipResults(results: [[String : AnyObject]]) -> [WMWordToip] { var wordToip = [WMWordToip]() for result in results { wordToip.append(WMWordToip(dictionary: result)) } return wordToip } }
apache-2.0
7b2926d8fd757d6e22b0fa62878d2f30
21.589744
82
0.514756
3.83878
false
false
false
false
STShenZhaoliang/iOS2017
framework/Swift_WKWebView/Swift_WKWebView/WKWebViewController.swift
1
5029
// // WKWebViewController.swift // Swift_WKWebView // // Created by 沈兆良 on 2017/2/23. // Copyright © 2017年 沈兆良. All rights reserved. // import UIKit import WebKit class WKWebViewController: UIViewController { // MARK: - --- interface 接口 var webView : WKWebView = { let configuration = WKWebViewConfiguration() configuration.userContentController = WKUserContentController() let preferences = WKPreferences() preferences.javaScriptEnabled = true preferences.minimumFontSize = 30.0 configuration.preferences = preferences let webView = WKWebView.init(frame: UIScreen.main.bounds, configuration: configuration) let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html")!) webView.loadFileURL(url, allowingReadAccessTo: url) return webView }() // MARK: - --- lift cycle 生命周期 --- override func viewDidLoad() { super.viewDidLoad() title = "Swift_WKWebView拦截URL" navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .cancel, target: self, action:#selector(goBack)) view.addSubview(webView) webView.uiDelegate = self webView.navigationDelegate = self } // MARK: - --- delegate 视图委托 --- // MARK: - --- event response 事件相应 --- func goBack() { webView.goBack() } func getLocation() { let jsStr = "setLocation('广东省深圳市福田区')" webView.evaluateJavaScript(jsStr) { (result: Any?, error: Error?) in // print(result as! String, error!) } } func share(htmlUrl : URL) { let tempDic = dictionaryQueryWithURL(htmlUrl: htmlUrl) let title = tempDic["title"] let content = tempDic["content"] let url = tempDic["url"] let jsStr = "shareResult(" + "'\(title)'" + "'\(content)'" + "'\(url)'" + ")" webView.evaluateJavaScript(jsStr) { (result :Any?, error: Error?) in print(result as! String, error!) } } func changeBGColor(htmlUrl : URL) { let tempDic = dictionaryQueryWithURL(htmlUrl: htmlUrl) let r: CGFloat = CGFloat(Float(tempDic["r"]!)!) let g: CGFloat = CGFloat(Float(tempDic["g"]!)!) let b: CGFloat = CGFloat(Float(tempDic["b"]!)!) let a: CGFloat = CGFloat(Float(tempDic["a"]!)!) view.backgroundColor = UIColor.init(red: r, green: g, blue: b, alpha: a) } func payAction(htmlUrl : URL) { let jsStr = "payResult('支付成功')" webView.evaluateJavaScript(jsStr) { (result :Any?, error: Error?) in // print(result as! String, error!) } } func shakeAction() { } // MARK: - --- private methods 私有方法 --- func dictionaryQueryWithURL(htmlUrl url : URL) -> Dictionary<String, String> { let components = url.query?.components(separatedBy: "&") var tempDic = Dictionary<String, String>() for string in components! { let dicArray = string.components(separatedBy: "=") if dicArray.count > 1 { tempDic.updateValue(dicArray[1].removingPercentEncoding!, forKey: dicArray[0]) } } return tempDic } // MARK: - --- setters 属性 --- // MARK: - --- getters 属性 --- } extension WKWebViewController: WKNavigationDelegate, WKUIDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let scheme = navigationAction.request.url?.scheme let url = navigationAction.request.url if scheme == "staction" { switch url?.host ?? "" { case "scanClick": print(self) case "getLocation": print(self) getLocation() case "setColor": print(self) changeBGColor(htmlUrl: url!) case "payAction": payAction(htmlUrl: url!) print(self) case "shake": print(self) shakeAction() case "goBack": print(self) goBack() default:break } decisionHandler(WKNavigationActionPolicy.cancel) }else { decisionHandler(WKNavigationActionPolicy.allow) } } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertVC = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction.init(title: "知道了", style: .cancel, handler: { (alert :UIAlertAction) in completionHandler() })) present(alertVC, animated: true, completion: nil) } }
mit
52e2ceef2751e9803cd9df3f6646d22d
30.202532
170
0.592901
4.655335
false
false
false
false
mapsme/omim
iphone/Maps/Core/DeepLink/Strategies/DeepLinkSubscriptionStrategy.swift
5
1248
class DeepLinkSubscriptionStrategy: IDeepLinkHandlerStrategy { var deeplinkURL: DeepLinkURL private var data: DeepLinkSubscriptionData init(url: DeepLinkURL, data: DeepLinkSubscriptionData) { self.deeplinkURL = url self.data = data } func execute() { guard let mapViewController = MapViewController.shared() else { return; } guard let type: SubscriptionGroupType = SubscriptionGroupType(serverId: data.groups) else { LOG(.error, "Groups is wrong: \(deeplinkURL.url)"); return } mapViewController.dismiss(animated: false, completion: nil) mapViewController.navigationController?.popToRootViewController(animated: false) let subscriptionViewController = SubscriptionViewBuilder.build(type: type, parentViewController: mapViewController, source: kStatDeeplink, successDialog: .goToCatalog, completion: nil) mapViewController.present(subscriptionViewController, animated: true, completion: nil) sendStatisticsOnSuccess(type: kStatSubscription) } }
apache-2.0
e482e0ae26bd238b2ea36b7bf3f98094
43.571429
97
0.626603
6.117647
false
false
false
false
andrewlowson/Visiocast
Visucast/AboutViewController.swift
1
2454
// // AboutViewController.swift // Visucast // // Created by Andrew Lowson on 19/07/2015. // Copyright (c) 2015 Andrew Lowson. All rights reserved. // import UIKit class AboutViewController: UIViewController { @IBOutlet weak var AboutTabBarItem: UITabBarItem! @IBOutlet weak var aboutParagraph: UITextView! @IBOutlet weak var imageLogoView = UIImageView() // @IBOutlet weak var dictateButton: UIButton! { // didSet{ // let image = UIImage(named: "microphoneIcon") as UIImage! // let dictateButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton // dictateButton.setImage(image, forState: .Normal) // dictateButton.setTitle("Dictate", forState: .Normal) // } // } @IBOutlet weak var scrollView: UIScrollView! { didSet { aboutParagraph.text = "Welcome to Visiocast. \n \nVisiocast is a Podcast application built for people who are visually impaired. \nThere is a global button at the top for you to dictate commands, like 'Download The Empire Podcast' or 'search for Back to Work.' \n \nVisiocast started as a Software Development Masters project out of the University of Glasgow in the summer of 2015.\n \nContact:\nAndrew Lowson: [email protected] \nChuan Chen: [email protected]" } } var image: UIImage? { get { return imageLogoView?.image } set { imageLogoView?.image = newValue } } // layout items override func viewDidLoad() { super.viewDidLoad() self.aboutParagraph.editable = false // Do any additional setup after loading the view. //let logoImage = UIImage(named: "glasgowLogo") _ = UIImage(named: "glasgowLogo") view.addSubview(self.imageLogoView!) scrollView.addSubview(aboutParagraph) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } var aspectRatioConstraint: NSLayoutConstraint? { willSet { if let existingConstraint = aspectRatioConstraint { view.removeConstraint(existingConstraint) } } didSet { if let newConstraint = aspectRatioConstraint { view.addConstraint(newConstraint) } } } } extension UIImage { var aspectRatio: CGFloat { return size.height != 0 ? size.width / size.height : 0 } }
gpl-2.0
93e12a39b933db3f520c57316898dd76
34.057143
481
0.644254
4.437613
false
false
false
false
Guidebook/HideShowPasswordTextField
Example/HideShowPasswordTextFieldExample/HideShowPasswordTextFieldExample/ViewController.swift
1
1677
// // ViewController.swift // HideShowPasswordTextFieldExample // // Created by Mike Sprague on 5/2/16. // Copyright © 2016 Guidebook. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var passwordTextField: HideShowPasswordTextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setupPasswordTextField() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: HideShowPasswordTextFieldDelegate // Implementing this delegate is entirely optional. // It's useful when you want to show the user that their password is valid. extension ViewController: HideShowPasswordTextFieldDelegate { func isValidPassword(_ password: String) -> Bool { return password.count > 7 } } // MARK: Private helpers extension ViewController { private func setupPasswordTextField() { passwordTextField.passwordDelegate = self passwordTextField.borderStyle = .none passwordTextField.clearButtonMode = .whileEditing passwordTextField.layer.borderWidth = 0.5 passwordTextField.layer.borderColor = UIColor(red: 220/255.0, green: 220/255.0, blue: 220/255.0, alpha: 1.0).cgColor passwordTextField.borderStyle = UITextField.BorderStyle.none passwordTextField.clipsToBounds = true passwordTextField.layer.cornerRadius = 0 passwordTextField.rightView?.tintColor = UIColor(red: 0.204, green: 0.624, blue: 0.847, alpha: 1) } }
mit
fbdce5a63e5d17ac1ec47ea549727147
33.204082
124
0.710621
4.843931
false
false
false
false
qinting513/SwiftNote
youtube/YouTube/Model/User.swift
1
2282
// // Profile.swift // YouTube // // Created by Haik Aslanyan on 7/11/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // import Foundation import UIKit class User { //MARK: Properties let name: String let profilePic: UIImage let backgroundImage: UIImage let playlists: Array<Playlist> //MARK: Methods class func fetchProfile(link: URL, completition: @escaping ((User) -> Void)) { UIApplication.shared.isNetworkActivityIndicatorVisible = true let _ = URLSession.shared.dataTask(with: link) { (data, response, error) in if error == nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] let name = json["name"] as! String let profilePic = UIImage.contentOfURL(link: (json["profilePic"] as! String)) let backgroundImage = UIImage.contentOfURL(link: (json["backgroundImage"] as! String)) var playlists = [Playlist]() let list = json["playlists"] as! [[String : AnyObject]] for item in list { let numberOfItems = item["numberOfVideos"] as! Int let title = item["title"] as! String let pic = UIImage.contentOfURL(link: item["pic"] as! String) let playlistItem = Playlist.init(pic: pic, title: title, numberOfVideos: numberOfItems) playlists.append(playlistItem) } let user = User.init(name: name, profilePic: profilePic, backgroundImage: backgroundImage, playlists: playlists) completition(user) } catch _ { showNotification() } } else { showNotification() } }.resume() } //MARK: Inits init(name: String, profilePic: UIImage, backgroundImage: UIImage, playlists: Array<Playlist>) { self.profilePic = profilePic self.backgroundImage = backgroundImage self.playlists = playlists self.name = name } }
apache-2.0
1c464980afef61d65ec484b321d05373
37.016667
132
0.548444
5.172336
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/DataStructure/Other/List.swift
1
6808
// // List.swift // DataStructure // // Created by 朱双泉 on 08/01/2018. // Copyright © 2018 Castie!. All rights reserved. // import Foundation class List1<Element: Comparable> { private var capacity: Int = 0 private lazy var length: Int = 0 private lazy var list: [Element] = [Element]() init(_ listCapacity: Int = 16) { capacity = listCapacity } func clear() { length = 0 } func isEmpty() -> Bool { return length == 0 ? true : false } func size() -> Int { return length } func getElement(loc index: Int) -> Element? { if index < 0 || index >= capacity || length == 0 { return nil } return list[index] } func locate(of element: Element) -> Int { for i in 0..<length { if list[i] == element { return i } } return -1 } func prior(of element: Element) -> Element? { let temp = locate(of: element) if temp == -1 { return nil } else { if temp == 0 { return nil } else { return list[temp - 1] } } } func next(of element: Element) -> Element? { let temp = locate(of: element) if temp == -1 { return nil } else { if temp == length - 1 { return nil } else { return list[temp + 1] } } } @discardableResult func insert(loc index: Int, element: Element) -> Bool { if index < 0 || index > length { return false } list.append(element) for i in (index..<length).reversed() { list[i + 1] = list[i] } list[index] = element length += 1 return true } @discardableResult func delete(loc index: Int) -> Element? { if index < 0 || index >= length { return nil } for i in (index + 1)..<length { list[i - 1] = list[i] } length -= 1 return list[index] } func traverse() { print("︵") for i in 0..<length { print(list[i]) } print("︶") } } class List2<Element: Hashable> { private var head: Node<Element> private lazy var length: Int = 0 init() { head = Node() head.data = nil head.next = nil } func clear() { var node = head.next while node != nil { let temp = node?.next node = nil node = temp } head.next = nil } func isEmpty() -> Bool { return length == 0 ? true : false } func size() -> Int { return length } func getElement(loc index: Int) -> Node<Element>? { if index < 0 || index >= length { return nil } var currentNode = head for _ in 0...index { guard let node = currentNode.next else { continue } currentNode = node } let node = Node<Element>() node.data = currentNode.data return node } func locate(of node: Node<Element>) -> Int { var currentNode = head var count = 0 while currentNode.next != nil { currentNode = currentNode.next! if currentNode.data == node.data { return count } count += 1 } return -1 } func prior(of node: Node<Element>) -> Node<Element>? { var currentNode = head var tempNode: Node<Element>? = nil while currentNode.next != nil { tempNode = currentNode currentNode = currentNode.next! if currentNode.data == node.data { guard let tempNode = tempNode else { continue } if tempNode == head { return nil } let node = Node<Element>() node.data = tempNode.data return node } } return nil } func next(of node: Node<Element>) -> Node<Element>? { var currentNode = head while currentNode.next != nil { currentNode = currentNode.next! if currentNode.data == node.data { if currentNode.next == nil { return nil } guard let data = currentNode.next?.data else { continue } let node = Node<Element>() node.data = data return node } } return nil } @discardableResult func insert(loc index: Int, node: Node<Element>) -> Bool { if index < 0 || index >= length { return false } var currentNode = head for _ in 0..<index { guard let nextNode = currentNode.next else { continue } currentNode = nextNode } let newNode = Node<Element>() newNode.data = node.data newNode.next = currentNode.next currentNode.next = newNode length += 1 return true } @discardableResult func delete(loc index: Int) -> Node<Element>? { if index < 0 || index >= length { return nil } var currentNode = head var currentNodeBefore: Node<Element>? = nil for _ in 0...index { currentNodeBefore = currentNode guard let nextNode = currentNode.next else { continue } currentNode = nextNode } currentNodeBefore?.next = currentNode.next let node = Node<Element>() node.data = currentNode.data length -= 1 return node } @discardableResult func insertHead(node: Node<Element>) -> Bool { let temp = head.next let newNode = Node<Element>() newNode.data = node.data head.next = newNode newNode.next = temp length += 1 return true } @discardableResult func insertTail(node: Node<Element>) -> Bool { var currentNode = head while currentNode.next != nil { currentNode = currentNode.next! } let newNode = Node<Element>() newNode.data = node.data newNode.next = nil currentNode.next = newNode length += 1 return true } func traverse() { print("︵") var currentNode = head while currentNode.next != nil { currentNode = currentNode.next! currentNode.printNode() } print("︶") } }
mit
539f176e6b082fe86ba03d2fcd891abc
24.441948
81
0.478434
4.763675
false
false
false
false
divljiboy/IOSChatApp
Quick-Chat/Pods/Swinject/Sources/ObjectScope.swift
1
1833
// // ObjectScope.swift // Swinject // // Created by Yoichi Tagaya on 7/24/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // /// A configuration how an instance provided by a `Container` is shared in the system. /// The configuration is ignored if it is applied to a value type. public protocol ObjectScopeProtocol: AnyObject { /// Used to create `InstanceStorage` to persist an instance for single service. /// Will be invoked once for each service registered in given scope. func makeStorage() -> InstanceStorage } /// Basic implementation of `ObjectScopeProtocol`. public class ObjectScope: ObjectScopeProtocol, CustomStringConvertible { public private(set) var description: String private var storageFactory: () -> InstanceStorage private let parent: ObjectScopeProtocol? /// Instantiates an `ObjectScope` with storage factory and description. /// - Parameters: /// - storageFactory: Closure for creating an `InstanceStorage` /// - description: Description of object scope for `CustomStringConvertible` implementation /// - parent: If provided, its storage will be composed with the result of `storageFactory` public init( storageFactory: @escaping () -> InstanceStorage, description: String = "", parent: ObjectScopeProtocol? = nil ) { self.storageFactory = storageFactory self.description = description self.parent = parent } /// Will invoke and return the result of `storageFactory` closure provided during initialisation. public func makeStorage() -> InstanceStorage { if let parent = parent { return CompositeStorage([storageFactory(), parent.makeStorage()]) } else { return storageFactory() } } }
mit
72705bf389954dd30f6c78c440321bfc
37.166667
109
0.684498
5.160563
false
false
false
false
ruslanskorb/CoreStore
Sources/Internals.DiffableDataSourceSnapshot.swift
1
18886
// // Internals.DiffableDataSourceSnapshot.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if canImport(UIKit) || canImport(AppKit) import CoreData #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit #endif // MARK: - Internals extension Internals { // MARK: - DiffableDataSourceSnapshot // Implementation based on https://github.com/ra1028/DiffableDataSources internal struct DiffableDataSourceSnapshot: DiffableDataSourceSnapshotProtocol { // MARK: Internal init(sections: [NSFetchedResultsSectionInfo]) { self.structure = .init(sections: sections) } var sections: [Section] { get { return self.structure.sections } set { self.structure.sections = newValue } } // MARK: DiffableDataSourceSnapshotProtocol init() { self.structure = .init() } var numberOfItems: Int { return self.structure.allItemIDs.count } var numberOfSections: Int { return self.structure.allSectionIDs.count } var sectionIdentifiers: [String] { return self.structure.allSectionIDs } var itemIdentifiers: [NSManagedObjectID] { return self.structure.allItemIDs } func numberOfItems(inSection identifier: String) -> Int { return self.itemIdentifiers(inSection: identifier).count } func itemIdentifiers(inSection identifier: String) -> [NSManagedObjectID] { return self.structure.items(in: identifier) } func sectionIdentifier(containingItem identifier: NSManagedObjectID) -> String? { return self.structure.section(containing: identifier) } func indexOfItem(_ identifier: NSManagedObjectID) -> Int? { return self.structure.allItemIDs.firstIndex(of: identifier) } func indexOfSection(_ identifier: String) -> Int? { return self.structure.allSectionIDs.firstIndex(of: identifier) } mutating func appendItems(_ identifiers: [NSManagedObjectID], toSection sectionIdentifier: String?) { self.structure.append(itemIDs: identifiers, to: sectionIdentifier) } mutating func insertItems(_ identifiers: [NSManagedObjectID], beforeItem beforeIdentifier: NSManagedObjectID) { self.structure.insert(itemIDs: identifiers, before: beforeIdentifier) } mutating func insertItems(_ identifiers: [NSManagedObjectID], afterItem afterIdentifier: NSManagedObjectID) { self.structure.insert(itemIDs: identifiers, after: afterIdentifier) } mutating func deleteItems(_ identifiers: [NSManagedObjectID]) { self.structure.remove(itemIDs: identifiers) } mutating func deleteAllItems() { self.structure.removeAllItems() } mutating func moveItem(_ identifier: NSManagedObjectID, beforeItem toIdentifier: NSManagedObjectID) { self.structure.move(itemID: identifier, before: toIdentifier) } mutating func moveItem(_ identifier: NSManagedObjectID, afterItem toIdentifier: NSManagedObjectID) { self.structure.move(itemID: identifier, after: toIdentifier) } mutating func reloadItems(_ identifiers: [NSManagedObjectID]) { self.structure.update(itemIDs: identifiers) } mutating func appendSections(_ identifiers: [String]) { self.structure.append(sectionIDs: identifiers) } mutating func insertSections(_ identifiers: [String], beforeSection toIdentifier: String) { self.structure.insert(sectionIDs: identifiers, before: toIdentifier) } mutating func insertSections(_ identifiers: [String], afterSection toIdentifier: String) { self.structure.insert(sectionIDs: identifiers, after: toIdentifier) } mutating func deleteSections(_ identifiers: [String]) { self.structure.remove(sectionIDs: identifiers) } mutating func moveSection(_ identifier: String, beforeSection toIdentifier: String) { self.structure.move(sectionID: identifier, before: toIdentifier) } mutating func moveSection(_ identifier: String, afterSection toIdentifier: String) { self.structure.move(sectionID: identifier, after: toIdentifier) } mutating func reloadSections(_ identifiers: [String]) { self.structure.update(sectionIDs: identifiers) } // MARK: Private private var structure: BackingStructure // MARK: - Section internal struct Section: DifferentiableSection, Equatable { var isReloaded: Bool init(differenceIdentifier: String, items: [Item] = [], isReloaded: Bool = false) { self.differenceIdentifier = differenceIdentifier self.elements = items self.isReloaded = isReloaded } // MARK: Differentiable let differenceIdentifier: String func isContentEqual(to source: Section) -> Bool { return !self.isReloaded && self.differenceIdentifier == source.differenceIdentifier } // MARK: DifferentiableSection var elements: [Item] = [] init<S: Sequence>(source: Section, elements: S) where S.Element == Item { self.init( differenceIdentifier: source.differenceIdentifier, items: Array(elements), isReloaded: source.isReloaded ) } } // MARK: - Item internal struct Item: Differentiable, Equatable { var isReloaded: Bool init(differenceIdentifier: NSManagedObjectID, isReloaded: Bool = false) { self.differenceIdentifier = differenceIdentifier self.isReloaded = isReloaded } // MARK: Differentiable let differenceIdentifier: NSManagedObjectID func isContentEqual(to source: Item) -> Bool { return !self.isReloaded && self.differenceIdentifier == source.differenceIdentifier } } // MARK: - BackingStructure fileprivate struct BackingStructure { // MARK: Internal var sections: [Section] init() { self.sections = [] } init(sections: [NSFetchedResultsSectionInfo]) { self.sections = sections.map { Section( differenceIdentifier: $0.name, items: $0.objects? .compactMap({ ($0 as? NSManagedObject)?.objectID }) .map({ Item(differenceIdentifier: $0) }) ?? [] ) } } var allSectionIDs: [String] { return self.sections.map({ $0.differenceIdentifier }) } var allItemIDs: [NSManagedObjectID] { return self.sections.lazy.flatMap({ $0.elements }).map({ $0.differenceIdentifier }) } func items(in sectionID: String) -> [NSManagedObjectID] { guard let sectionIndex = self.sectionIndex(of: sectionID) else { Internals.abort("Section \"\(sectionID)\" does not exist") } return self.sections[sectionIndex].elements.map({ $0.differenceIdentifier }) } func section(containing itemID: NSManagedObjectID) -> String? { return self.itemPositionMap()[itemID]?.section.differenceIdentifier } mutating func append(itemIDs: [NSManagedObjectID], to sectionID: String?) { let index: Array<Section>.Index if let sectionID = sectionID { guard let sectionIndex = self.sectionIndex(of: sectionID) else { Internals.abort("Section \"\(sectionID)\" does not exist") } index = sectionIndex } else { let section = self.sections guard !section.isEmpty else { Internals.abort("No sections exist") } index = section.index(before: section.endIndex) } let items = itemIDs.lazy.map({ Item(differenceIdentifier: $0) }) self.sections[index].elements.append(contentsOf: items) } mutating func insert(itemIDs: [NSManagedObjectID], before beforeItemID: NSManagedObjectID) { guard let itemPosition = self.itemPositionMap()[beforeItemID] else { Internals.abort("Item \(beforeItemID) does not exist") } let items = itemIDs.lazy.map({ Item(differenceIdentifier: $0) }) self.sections[itemPosition.sectionIndex].elements .insert(contentsOf: items, at: itemPosition.itemRelativeIndex) } mutating func insert(itemIDs: [NSManagedObjectID], after afterItemID: NSManagedObjectID) { guard let itemPosition = self.itemPositionMap()[afterItemID] else { Internals.abort("Item \(afterItemID) does not exist") } let itemIndex = self.sections[itemPosition.sectionIndex].elements .index(after: itemPosition.itemRelativeIndex) let items = itemIDs.lazy.map({ Item(differenceIdentifier: $0) }) self.sections[itemPosition.sectionIndex].elements .insert(contentsOf: items, at: itemIndex) } mutating func remove(itemIDs: [NSManagedObjectID]) { let itemPositionMap = self.itemPositionMap() var removeIndexSetMap: [Int: IndexSet] = [:] for itemID in itemIDs { guard let itemPosition = itemPositionMap[itemID] else { continue } removeIndexSetMap[itemPosition.sectionIndex, default: []] .insert(itemPosition.itemRelativeIndex) } for (sectionIndex, removeIndexSet) in removeIndexSetMap { for range in removeIndexSet.rangeView.reversed() { self.sections[sectionIndex].elements.removeSubrange(range) } } } mutating func removeAllItems() { for sectionIndex in self.sections.indices { self.sections[sectionIndex].elements.removeAll() } } mutating func move(itemID: NSManagedObjectID, before beforeItemID: NSManagedObjectID) { guard let removed = self.remove(itemID: itemID) else { Internals.abort("Item \(itemID) does not exist") } guard let itemPosition = self.itemPositionMap()[beforeItemID] else { Internals.abort("Item \(beforeItemID) does not exist") } self.sections[itemPosition.sectionIndex].elements .insert(removed, at: itemPosition.itemRelativeIndex) } mutating func move(itemID: NSManagedObjectID, after afterItemID: NSManagedObjectID) { guard let removed = self.remove(itemID: itemID) else { Internals.abort("Item \(itemID) does not exist") } guard let itemPosition = self.itemPositionMap()[afterItemID] else { Internals.abort("Item \(afterItemID) does not exist") } let itemIndex = self.sections[itemPosition.sectionIndex].elements .index(after: itemPosition.itemRelativeIndex) self.sections[itemPosition.sectionIndex].elements .insert(removed, at: itemIndex) } mutating func update<S: Sequence>(itemIDs: S) where S.Element == NSManagedObjectID { let itemPositionMap = self.itemPositionMap() for itemID in itemIDs { guard let itemPosition = itemPositionMap[itemID] else { continue } self.sections[itemPosition.sectionIndex] .elements[itemPosition.itemRelativeIndex].isReloaded = true } } mutating func append(sectionIDs: [String]) { let newSections = sectionIDs.lazy.map({ Section(differenceIdentifier: $0) }) self.sections.append(contentsOf: newSections) } mutating func insert(sectionIDs: [String], before beforeSectionID: String) { guard let sectionIndex = self.sectionIndex(of: beforeSectionID) else { Internals.abort("Section \"\(beforeSectionID)\" does not exist") } let newSections = sectionIDs.lazy.map({ Section(differenceIdentifier: $0) }) self.sections.insert(contentsOf: newSections, at: sectionIndex) } mutating func insert(sectionIDs: [String], after afterSectionID: String) { guard let beforeIndex = self.sectionIndex(of: afterSectionID) else { Internals.abort("Section \"\(afterSectionID)\" does not exist") } let sectionIndex = self.sections.index(after: beforeIndex) let newSections = sectionIDs.lazy.map({ Section(differenceIdentifier: $0) }) self.sections.insert(contentsOf: newSections, at: sectionIndex) } mutating func remove(sectionIDs: [String]) { for sectionID in sectionIDs { self.remove(sectionID: sectionID) } } mutating func move(sectionID: String, before beforeSectionID: String) { guard let removed = self.remove(sectionID: sectionID) else { Internals.abort("Section \"\(sectionID)\" does not exist") } guard let sectionIndex = self.sectionIndex(of: beforeSectionID) else { Internals.abort("Section \"\(beforeSectionID)\" does not exist") } self.sections.insert(removed, at: sectionIndex) } mutating func move(sectionID: String, after afterSectionID: String) { guard let removed = self.remove(sectionID: sectionID) else { Internals.abort("Section \"\(sectionID)\" does not exist") } guard let beforeIndex = self.sectionIndex(of: afterSectionID) else { Internals.abort("Section \"\(afterSectionID)\" does not exist") } let sectionIndex = self.sections.index(after: beforeIndex) self.sections.insert(removed, at: sectionIndex) } mutating func update<S: Sequence>(sectionIDs: S) where S.Element == String { for sectionID in sectionIDs { guard let sectionIndex = self.sectionIndex(of: sectionID) else { continue } self.sections[sectionIndex].isReloaded = true } } // MARK: Private private func sectionIndex(of sectionID: String) -> Array<Section>.Index? { return self.sections.firstIndex(where: { $0.differenceIdentifier == sectionID }) } @discardableResult private mutating func remove(itemID: NSManagedObjectID) -> Item? { guard let itemPosition = self.itemPositionMap()[itemID] else { return nil } return self.sections[itemPosition.sectionIndex].elements .remove(at: itemPosition.itemRelativeIndex) } @discardableResult private mutating func remove(sectionID: String) -> Section? { guard let sectionIndex = self.sectionIndex(of: sectionID) else { return nil } return self.sections.remove(at: sectionIndex) } private func itemPositionMap() -> [NSManagedObjectID: ItemPosition] { return self.sections.enumerated().reduce(into: [:]) { result, section in for (itemRelativeIndex, item) in section.element.elements.enumerated() { result[item.differenceIdentifier] = ItemPosition( item: item, itemRelativeIndex: itemRelativeIndex, section: section.element, sectionIndex: section.offset ) } } } // MARK: - ItemPosition fileprivate struct ItemPosition { let item: Item let itemRelativeIndex: Int let section: Section let sectionIndex: Int } } } } #endif
mit
3ca176d679d6084cd7593dbd2c370aa8
32.073555
119
0.568864
5.693398
false
false
false
false
Burning-Man-Earth/iBurn-iOS
PlayaGeocoder/PlayaGeocoder/PlayaGeocoder.swift
1
4245
// // PlayaGeocoder.swift // iBurn // // Created by Chris Ballinger on 8/5/18. // Copyright © 2018 Burning Man Earth. All rights reserved. // import Foundation import CoreLocation import JavaScriptCore public final class PlayaGeocoder: NSObject { // MARK: - Properties @objc public static let shared = PlayaGeocoder() private let context = JSContext() private let queue = DispatchQueue(label: "Geocoder Queue") // MARK: - Init public override init() { super.init() setupContext() } // MARK: - Public API /// WARN: This function may block during initialization @objc public func syncForwardLookup(_ address: String) -> CLLocationCoordinate2D { var coordinate = kCLLocationCoordinate2DInvalid queue.sync { coordinate = self.forwardLookup(address) } return coordinate } /// WARN: This function may block during initialization @objc public func syncReverseLookup(_ coordinate: CLLocationCoordinate2D) -> String? { var address: String? queue.sync { address = self.reverseLookup(coordinate) } return address } @objc public func asyncForwardLookup(_ address: String, completionQueue: DispatchQueue = DispatchQueue.main, completion: @escaping (CLLocationCoordinate2D)->Void) { queue.async { let coordinate = self.forwardLookup(address) completionQueue.async { completion(coordinate) } } } @objc public func asyncReverseLookup(_ coordinate: CLLocationCoordinate2D, completionQueue: DispatchQueue = DispatchQueue.main, completion: @escaping (String?)->Void) { queue.async { let address = self.reverseLookup(coordinate) completionQueue.async { completion(address) } } } } private extension PlayaGeocoder { func setupContext() { context?.exceptionHandler = { (context, exception) in if let exception = exception { NSLog("Geocoder exception: \(exception)") } } guard let path = Bundle(for: PlayaGeocoder.self).path(forResource: "bundle", ofType: "js"), let file = try? String(contentsOfFile: path) else { return } let _ = context?.evaluateScript("var window = this") let _ = context?.evaluateScript(file) let _ = context?.evaluateScript("var geocoder = prepare()") } /// Call this only on internal queue func reverseLookup(_ coordinate: CLLocationCoordinate2D) -> String? { guard CLLocationCoordinate2DIsValid(coordinate), let result = self.context?.evaluateScript("reverseGeocode(geocoder, \(coordinate.latitude), \(coordinate.longitude))"), result.isString, let string = result.toString() else { return nil } return string } /// Call this only on internal queue func forwardLookup(_ address: String) -> CLLocationCoordinate2D { guard let result = self.context?.evaluateScript("forwardGeocode(geocoder, \"\(address)\")"), let dict = result.toDictionary(), let geometry = dict["geometry"] as? [AnyHashable: Any], let coordinates = geometry["coordinates"] else { return kCLLocationCoordinate2DInvalid } var coordinatesArray: [Double] = [] if let coordinates = coordinates as? [Double] { coordinatesArray = coordinates } else if let coordinates = coordinates as? [[Double]], let first = coordinates.first { coordinatesArray = first } var coordinate = kCLLocationCoordinate2DInvalid if let latitude = coordinatesArray.last, let longitude = coordinatesArray.first, latitude != 0, longitude != 0 { coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } return coordinate } }
mpl-2.0
a2112b76d092b69d38609f4de59eea02
33.786885
131
0.592601
5.324969
false
false
false
false
radex/swift-compiler-crashes
crashes-fuzzing/19579-clang-astreader-readattributes.swift
1
2495
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct A { } struct B<T>() as a struct d<T where I.= c protocol a { let i { f protocol b { class B<T where I.b { let start = [Void{ struct d<ff where H.h = e func a! func a protocol a! protocol a : A<T : A { typealias e protocol a { protocol a class B<T where k.b : P { } struct S<ff where I.h : a println(array: let i { f protocol b { struct B<T : e { (true as a<T : S<T where g.= c let start = c (true as a protocol b : A<f : A? { struct B<Int>(a" class a" } struct A { } func a func ^(array: struct B<T where g.= i{ () as a (a<f : A { func a! let i { f let start = f protocol B : a let end = i{ func a println(array: struct d<T : P { let a : A { println() as String) { struct B<T>() { struct S<T where B : A<T where S protocol b { } } () { struct A { typealias e protocol B : A { let end = [Void{ let i { f protocol b : e { func a" let start = f println() { struct d<T where B : T where k.= f protocol a" func a let g = i{ let i { f struct S<ff where B : b { let end = e? func a! func a" class A? { protocol a { } let a : e { let start = f protocol a" struct S<Int>: a" protocol a let end = f protocol a<f : S<f : P { } func a! } } protocol b : A? { let start = [Void{ struct d<T>(array: (true as String) as String) { struct S<T where g.b { let end = c protocol b { protocol B : A? { struct B<Int>() { struct A { typealias e? println(true as String) { } typealias e class A<T where I.= [Void{ protocol B : T where B : A<T where I.h : B<T where B : e { println(true as String) { struct A { () { } struct A { class a" struct B<T where H.h : S<T where S struct d<T where I.= e? struct A { struct B<T : S protocol a" struct d<f : T where H.= i{ let g = i{ let i { f protocol B : A<T where I.h = e struct d<ff where B : S protocol b { class A? { class a struct S func ^(true as String) as String) { class A? { let g = f struct d<Int>: A? { class a class B<Int>(a" func a! struct d<T where I.b { (array: } let start = f } println() { struct B<T : A { struct d<T where S<f : T : a let end = [Void{ func a<T where H.b { (a! let end = [Void{ } func ^(true as a let a { struct B<T where H.b : A { let i { f } class A<T : e { protocol B : a<T where H.b { let start = c typealias e? let i { f (array: class A? { func a } println(true as a! } struct d<T where S<T where k.h : a<T where H.= f } } } let g = c func a" struct A { protocol
mit
44afa2f7674865b9ff24d810973e92c9
13.676471
87
0.619238
2.453294
false
false
false
false
FuzzyHobbit/bitcoin-swift
BitcoinSwiftTests/OSKeyChainSecureDataStoreTests.swift
2
1029
// // OSKeyChainSecureDataStoreTests.swift // BitcoinSwift // // Created by Kevin Greene on 1/29/15. // Copyright (c) 2015 DoubleSha. All rights reserved. // import BitcoinSwift import XCTest class OSKeyChainSecureDataStoreTests: XCTestCase { let key = "key" var secureDataStore = OSKeyChainSecureDataStore(service: "com.BitcoinSwift.test") override func setUp() { super.setUp() if secureDataStore.dataForKey(key) != nil { secureDataStore.deleteDataForKey(key) } } override func tearDown() { if secureDataStore.dataForKey(key) != nil { secureDataStore.deleteDataForKey(key) } super.tearDown() } func testStoreSecureData() { let bytes: [UInt8] = [0x00, 0x01, 0x02, 0x03] let data = SecureData(bytes: bytes, length: UInt(bytes.count)) XCTAssertTrue(secureDataStore.saveData(data, forKey: key)) XCTAssertEqual(secureDataStore.dataForKey(key)!, data) secureDataStore.deleteDataForKey(key) XCTAssertTrue(secureDataStore.dataForKey(key) == nil) } }
apache-2.0
1b4f9f6f671ef4ebba51acb83fa85340
25.384615
83
0.712342
3.839552
false
true
false
false
gyro-n/PaymentsIos
GyronPayments/Classes/Models/Common.swift
1
3780
// // PaymentError.swift // GyronPayments // // Created by Ye David on 11/1/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation /** The AmountWithCurrency class stores information about the amount and its currency. */ open class AmountWithCurrency: BaseModel { public var amount: Float public var currency: String /** Initializes the Charge object */ override public init() { amount = 0 currency = "" } /** Maps the values from a hash map object into the TransactionToken. */ override open func mapFromObject(map: ResponseData) { amount = map["amount"] as? Float ?? 0 currency = map["currency"] as? String ?? "" } } /** The InvoiceChargeFee class stores information about the charge volume and fee involved. */ open class InvoiceChargeFee: BaseModel { public var chargeVolume: Float public var chargeInvoiceFee: Float override public init() { chargeVolume = 0 chargeInvoiceFee = 0 } override open func mapFromObject(map: ResponseData) { chargeVolume = map["charge_volume"] as? Float ?? 0 chargeInvoiceFee = map["charge_invoice_fee"] as? Float ?? 0 } } /** The ContactInfo class stores information about how to contact a particular person. */ open class ContactInfo: BaseModel, RequestDataDelegate { public var name: String? public var companyName: String? public var phoneNumber: PhoneNumber? public var line1: String? public var line2: String? public var city: String? public var state: String? public var country: String? public var zip: String? /** Initializes the Charge object */ override public init() { name = nil companyName = nil phoneNumber = nil line1 = nil line2 = nil city = nil state = nil country = nil zip = nil } /** Maps the values from a hash map object into the TransactionToken. */ override open func mapFromObject(map: ResponseData) { name = map["name"] as? String companyName = map["company_name"] as? String phoneNumber = map["phone_number"] as? PhoneNumber line1 = map["line1"] as? String line2 = map["line2"] as? String city = map["city"] as? String state = map["state"] as? String country = map["country"] as? String zip = map["zip"] as? String } public func convertToMap() -> RequestData { return convertToRequestData() } } /** The PhoneNumber struct stores information about the phone number. */ public struct PhoneNumber { public var countryCode: String? public var localNumber: String? } /** The PaymentError struct stores information about an error generated from the request. */ public struct PaymentError { public var name: String public var code: Int public var details: String? } /** The Metadata typealias stands in for a [String:AnyObject] hash */ public typealias Metadata = [String:AnyObject] /** The ProcessingMode enum contains a list of processing modes. */ public enum ProcessingMode: String { case test = "test" case live = "live" case liveTest = "live_test" } /** The PaymentSystemEvent enum contains a list of payment system webhook events. */ public enum PaymentSystemEvent: String { case chargeFinished = "charge_finished" case subscriptionPayment = "subscription_payment" case subscriptionFailure = "subscription_failure" case subscriptionCancelled = "subscription_cancelled" case refundFinished = "refund_finished" case transferFinalized = "transfer_finalized" case cancelFinished = "cancel_finished" }
mit
efa4591a321d732f693e7eabf07ddb19
25.243056
88
0.653347
4.440658
false
false
false
false
EyreFree/UICountingLabel
Example/EFCountingLabel/ViewControllers/CustomTableViewController.swift
2
4254
// // CustomTableViewController.swift // EFCountingLabel // // Created by Kirow on 2019-05-26. // // Copyright (c) 2017 EyreFree <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import EFCountingLabel struct CounterCellModel { let counter: EFCounter init(from: CGFloat, to: CGFloat, duration: TimeInterval, function: EFTiming = EFTimingFunction.linear) { self.counter = EFCounter() self.counter.timingFunction = function self.counter.countFrom(from, to: to, withDuration: duration) } } class CountingTableViewCell: UITableViewCell { weak var counter: EFCounter? func setCounter(_ model: CounterCellModel, formatter: NumberFormatter) { //unbind counter from cell if let current = self.counter { current.updateBlock = nil } if let from = formatter.string(from: NSNumber(value: Int(model.counter.fromValue))), let to = formatter.string(from: NSNumber(value: Int(model.counter.toValue))) { textLabel?.text = "Count from \(from) to \(to)" } //bind new counter model.counter.updateBlock = { [unowned self] value in self.detailTextLabel?.text = formatter.string(from: NSNumber(value: Int(value))) } counter = model.counter } } class CustomTableViewController: UIViewController { @IBOutlet weak var tableView: UITableView! lazy var formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.groupingSeparator = "." formatter.usesGroupingSeparator = true formatter.groupingSize = 3 return formatter }() var dataSource: [CounterCellModel] = [] override func viewDidLoad() { super.viewDidLoad() remakeDataSource() tableView.reloadData() } @IBAction func didClickRefresh(_ sender: UIBarButtonItem) { remakeDataSource() tableView.reloadData() } private func remakeDataSource() { dataSource.forEach({ $0.counter.invalidate() }) dataSource.removeAll() var prevValue: CGFloat = 0 for i in 1...12 { let from = prevValue let to = pow(10, CGFloat(i)) let model = CounterCellModel(from: from, to: to, duration: 60) dataSource.append(model) prevValue = to } } deinit { dataSource.forEach({ $0.counter.invalidate() }) } } extension CustomTableViewController: UITableViewDelegate, UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "CountingTableViewCell") as? CountingTableViewCell else { fatalError() } let model = dataSource[indexPath.row] cell.setCounter(model, formatter: formatter) return cell } }
gpl-2.0
50b9dbf8caac606042fbe96de7a1759d
33.306452
128
0.66126
4.834091
false
false
false
false
at-internet/atinternet-ios-objc-sdk
Tracker/TrackerTests/TrackerTests.swift
1
30987
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // TrackerTests.swift // import UIKit import XCTest class TrackerTests: XCTestCase, ATTrackerDelegate { /* Implémentation des méthodes du TrackerDelegate */ func didCallPartner(response: String, semaphore: dispatch_semaphore_t) { if (response == "OK") { callbackCalled = true } } func warningDidOccur(message: String) { if (message == "OK") { callbackCalled = true } } func errorDidOccur(message: String) { if (message == "OK") { callbackCalled = true } } func sendDidEnd(status: ATHitStatus, message: String) { if (message == "OK" && status == ATHitStatus.Success) { callbackCalled = true } } func saveDidEnd(message: String) { callbackCalled = true } func buildDidEnd(status: ATHitStatus, message: String) { if (message == "OK" && status == ATHitStatus.Success) { callbackCalled = true } } func trackerNeedsFirstLaunchApproval(message: String) { if (message == "OK") { callbackCalled = true } } // Instance du tracker let tracker = ATTracker() let nbPersistentParameters = 15 // Variables références var callbackCalled = false let mess = "OK" let stat = ATHitStatus.Success let myConf = NSDictionary( objects: ["ctlog", "ctlogs", "ctdomain", "ctpixelpath", "ctsite", "ctsecure", "ctidentifier", "ctplugin", "ctbgtask", "ctstorage"], forKeys: ["log", "logSSL", "domain", "pixelPath", "site", "secure", "identifier", "plugins", "enableBackgroundTask", "storage"]) let anotherConf = NSDictionary( objects: ["tata", "yoyo"], forKeys: ["log", "logSSL"]) let opts = ATParamOption() override func setUp() { super.setUp() tracker.delegate = self callbackCalled = false tracker.buffer = ATBuffer(tracker: tracker) opts.persistent = true } override func tearDown() { super.tearDown() } // On vérifie que qu'il est possible d'instancier plusieurs fois Tracker func testMultiInstance() { let tracker1 = ATTracker() let tracker2 = ATTracker() XCTAssert(tracker1 !== tracker2, "tracker1 et tracker2 ne doivent pas pointer vers la même référence") } /* On vérifie si l'appel des différents callbacks est effectué correctement */ func testDidCallPartner() { let semaphore: dispatch_semaphore_t = dispatch_semaphore_create(0) tracker.delegate?.didCallPartner(mess, semaphore: semaphore) XCTAssert(callbackCalled, "Le callback doit être appelé et la réponse doit être 'OK'") } func testWarningDidOccur() { tracker.delegate?.warningDidOccur(mess) XCTAssert(callbackCalled, "Le callback doit être appelé et le message doit être 'OK'") } func testErrorDidOccur() { tracker.delegate?.errorDidOccur(mess) XCTAssert(callbackCalled, "Le callback doit être appelé et le message doit être 'OK'") } func testSendDidEnd() { tracker.delegate?.sendDidEnd(stat, message: mess) XCTAssert(callbackCalled, "Le callback doit être appelé avec le status 'Success' et le message 'OK'") } func testBuildDidEnd() { tracker.delegate?.buildDidEnd(stat, message: mess) XCTAssert(callbackCalled, "Le callback doit être appelé avec le status 'Success' et le message 'OK'") } func testTrackerNeedsFirstLaunchApproval() { tracker.delegate?.trackerNeedsFirstLaunchApproval(mess) XCTAssert(callbackCalled, "Le callback doit être appelé et le message doit être 'OK'") } /* On teste toutes les surcharges de setParameter */ func testsetParameterInt() { tracker.setIntParam("test", value: 2) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam XCTAssertEqual(param.value() as String, "2", "Le paramètre doit avoir la valeur 2") } func testsetParameterIntWithOptions() { tracker.setIntParam("test", value: 2, options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterFloat() { let val: Float = 3.14 tracker.setFloatParam("test", value: val) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam let result = ((param.value() as String) == val.description) XCTAssert(result, "Le paramètre doit avoir la valeur 3.14 (float)") } func testsetParameterFloatWithOptions() { let val: Float = 3.14 tracker.setFloatParam("test", value: val, options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterDouble() { let val: Double = 3.14 tracker.setDoubleParam("test", value: val) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam let result = ((param.value() as String) == val.description) XCTAssert(result, "Le paramètre doit avoir la valeur 3.14 (double)") } func testsetParameterDoubleWithOptions() { let val: Double = 3.14 tracker.setDoubleParam("test", value: val, options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterBool() { tracker.setBooleanParam("test", value: true) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam XCTAssertEqual(param.value() as String, "true", "Le paramètre doit avoir la valeur true") } func testsetParameterBoolWithOptions() { tracker.setBooleanParam("test", value: true, options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterString() { tracker.setStringParam("test", value: "home") XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam XCTAssertEqual(param.value() as String, "home", "Le paramètre doit avoir la valeur \"home\"") } func testsetParameterStringWithOptions() { tracker.setStringParam("test", value: "home", options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterArray() { tracker.setArrayParam("test", value: ["toto", true]) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let array = (tracker.buffer.volatileParameters[0] as! ATParam).value() XCTAssert(array == "toto,true", "Le paramètre doit avoir la valeur [\"toto\", true]") } func testsetParameterArrayWithOptions() { tracker.setArrayParam("test", value: ["toto", true], options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterDictionary() { tracker.setDictionaryParam("test", value: ["toto": true, "tata": "hello"]) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let dict: [String: AnyObject] = (tracker.buffer.volatileParameters[0] as! ATParam).value().parseJSONString! as! [String : AnyObject] XCTAssert(dict["toto"] as! Bool == true, "La clé toto doit avoir pour valeur 1") XCTAssert(dict["tata"] as! String == "hello", "La clé tata doit avoir pour valeur hello") } func testsetParameterDictionaryWithOptions() { tracker.setDictionaryParam("test", value: ["toto": true, "tata": "hello"], options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } func testsetParameterClosure() { let closure = { () -> String! in return "hello" } tracker.setClosureParam("test", value: closure) XCTAssertEqual(tracker.buffer.volatileParameters.count, 1, "La collection des paramètres volatiles doit contenir un objet") let param = tracker.buffer.volatileParameters[0] as! ATParam XCTAssertEqual(param.value(), "hello", "Le paramètre doit avoir la valeur \"hello\"") } func testsetParameterClosureWithOptions() { let closure = { () -> String! in return "hello" } tracker.setClosureParam("test", value: closure, options: opts) XCTAssertEqual(tracker.buffer.volatileParameters.count, 0, "La collection des paramètres volatiles doit être vide") XCTAssertEqual(tracker.buffer.persistentParameters.count, nbPersistentParameters, "La collection des paramètres persitants doit contenir un objet") } /* Vérification du paramètrage de la configuration du tracker */ func testSetFullConfiguration() { let expectation = expectationWithDescription("test") tracker.setConfig(anotherConf as [NSObject : AnyObject], override: true, completionHandler: nil) let configurationOperation = NSBlockOperation(block: { XCTAssertEqual(self.tracker.configuration.parameters.count, self.anotherConf.count, "La configuration complète du tracker n'est pas correcte") expectation.fulfill() }) ATTrackerQueue.sharedInstance().queue.addOperation(configurationOperation) waitForExpectationsWithTimeout(10, handler: nil) } func testSetLogConfiguration() { let expectation = expectationWithDescription("test") tracker.setLog("logtest", completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["log"] as! String == "logtest", "Le nouveau log est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetSecuredLogConfiguration() { let expectation = expectationWithDescription("test") tracker.setSecuredLog("logstest", completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["logSSL"] as! String == "logstest", "Le nouveau log sécurisé est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetSiteIdConfiguration() { let expectation = expectationWithDescription("test") tracker.setSiteId(123456, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["site"] as! String == "123456", "Le nouveau site est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetDomainConfiguration() { let expectation = expectationWithDescription("test") tracker.setDomain("newdomain.com", completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["domain"] as! String == "newdomain.com", "Le nouveau domaine est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetOfflineModeConfiguration() { let expectation = expectationWithDescription("test") tracker.setOfflineMode(.Never, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["storage"] as! String == "never", "Le nouveau mode offline est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetPluginsConfiguration() { let expectation = expectationWithDescription("test") tracker.setPlugins([NSNumber(int: ATPluginKey.Nuggad.rawValue),NSNumber(int: ATPluginKey.TvTracking.rawValue)], completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["plugins"] as! String == "nuggad,tvtracking", "Les nouveaux plugins sont incorrects") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetSecureModeConfiguration() { let expectation = expectationWithDescription("test") tracker.setSecureModeEnabled(true, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["secure"] as! String == "true", "Le nouveau mode securise est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetIdentifierConfiguration() { let expectation = expectationWithDescription("test") tracker.setIdentifierType(.ATIDFV, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["identifier"] as! String == "idfv", "Le nouvel identifiant est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetHashUserIdModeConfiguration() { let expectation = expectationWithDescription("test") tracker.setHashUserIdEnabled(true, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["hashUserId"] as! String == "true", "Le nouveau hashage est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetPixelPathConfiguration() { let expectation = expectationWithDescription("test") tracker.setPixelPath("/toto.xiti", completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["pixelPath"] as! String == "/toto.xiti", "Le nouveau pixel path est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetPersistIdentifiedVisitorConfiguration() { let expectation = expectationWithDescription("test") tracker.setPersistentIdentifiedVisitorEnabled(true, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["persistIdentifiedVisitor"] as! String == "true", "Le nouveau mode de persistence est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetTVTUrlConfiguration() { let expectation = expectationWithDescription("test") tracker.setTvTrackingUrl("test.com", completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["tvtURL"] as! String == "test.com", "La nouvelle tvtURL est incorrecte") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetTVTVisitDurationConfiguration() { let expectation = expectationWithDescription("test") tracker.setTvTrackingVisitDuration(20, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["tvtVisitDuration"] as! String == "20", "La nouvelle tvtVisitDuration est incorrecte") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetTVTSpotValidityTimeConfiguration() { let expectation = expectationWithDescription("test") tracker.setTvTrackingSpotValidityTime(4, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["tvtSpotValidityTime"] as! String == "4", "Le nouveau tvtSpotValidityTime est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetEnabledBGTaskConfiguration() { let expectation = expectationWithDescription("test") tracker.setBackgroundTaskEnabled(true, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["enableBackgroundTask"] as! String == "true", "Le nouveau mode de background task est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetCampaignLastPersistenceConfiguration() { let expectation = expectationWithDescription("test") tracker.setCampaignLastPersistenceEnabled(false, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["campaignLastPersistence"] as! String == "false", "Le nouveau mode de persistence est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetCampaignLifetimeConfiguration() { let expectation = expectationWithDescription("test") tracker.setCampaignLifetime(54, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["campaignLifetime"] as! String == "54", "Le nouveau campaignLifetime est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetSessionBackgroundDurationConfiguration() { let expectation = expectationWithDescription("test") tracker.setSessionBackgroundDuration(54, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["sessionBackgroundDuration"] as! String == "54", "Le nouveau sessionBackgroundDuration est incorrect") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testReplaceSomeConfiguration() { let expectation = expectationWithDescription("test") tracker.setConfig(anotherConf as [NSObject : AnyObject], override: false, completionHandler: { (isSet) -> Void in XCTAssert(self.tracker.configuration.parameters["log"] as! String == "tata", "La configuration complète du tracker n'est pas correcte") expectation.fulfill() }) waitForExpectationsWithTimeout(10, handler: nil) } func testSetKeyConfiguration() { let expectation = expectationWithDescription("test") tracker.setConfig("macle", value: "mavaleur", completionHandler: nil) let configurationOperation = NSBlockOperation(block: { XCTAssertTrue(self.tracker.configuration.parameters["macle"] as! String == "mavaleur", "La clé de configuration du tracker n'est pas correcte") expectation.fulfill() }) ATTrackerQueue.sharedInstance().queue.addOperation(configurationOperation) waitForExpectationsWithTimeout(10, handler: nil) } func testSetConfigKeyReadOnly() { let expectation = expectationWithDescription("test") let refCount = self.tracker.configuration.parameters.count tracker.setConfig("atreadonlytest", value: "test", completionHandler: nil) let configurationOperation = NSBlockOperation(block: { let newCount = self.tracker.configuration.parameters.count XCTAssertTrue(newCount == refCount, "La clé de configuration du tracker ne doit pas existée") expectation.fulfill() }) ATTrackerQueue.sharedInstance().queue.addOperation(configurationOperation) waitForExpectationsWithTimeout(10, handler: nil) } /* Vérification de la gestion de la surcharge des paramètres */ func testSetVolatileParameterNotReadOnly() { tracker.setClosureParam("cle", value: {"valeurOriginale"}) let refCount = tracker.buffer.volatileParameters.count let refValue = (tracker.buffer.volatileParameters[0] as! ATParam).value() tracker.setClosureParam("cle", value: {"valeurModifiee"}) let newCount = tracker.buffer.volatileParameters.count let newValue = (tracker.buffer.volatileParameters[0] as! ATParam).value() XCTAssertEqual(refCount, newCount, "Le nombre de paramètres dans la collection volatile doit être identique") XCTAssertTrue(refValue != newValue, "La valeur du paramètre dans la collection volatile pour la même clé doit changer") } func testSetPersistentParameterNotReadOnly() { let opt = ATParamOption() opt.persistent = true tracker.setClosureParam("cle", value: {"valeurOriginale"}, options: opt) let refCount = tracker.buffer.persistentParameters.count let refValue = (tracker.buffer.persistentParameters[refCount - 1] as! ATParam).value() tracker.setClosureParam("cle", value: {"valeurModifiee"}) let newCount = tracker.buffer.persistentParameters.count let newValue = (tracker.buffer.persistentParameters[refCount - 1] as! ATParam).value() XCTAssertEqual(refCount, newCount, "Le nombre de paramètres dans la collection persistante doit être identique") XCTAssertTrue(refValue != newValue, "La valeur du paramètre dans la collection persistante pour la même clé doit changer") } func testSetParameterReadOnly() { let opt = ATParamOption() opt.persistent = true let refCount = tracker.buffer.persistentParameters.count let refValue = (tracker.buffer.persistentParameters[0] as! ATParam).value() let refKey = tracker.buffer.persistentParameters[0].key tracker.setStringParam(refKey, value: "123", options: opt) let newKey = tracker.buffer.persistentParameters[0].key let newCount = tracker.buffer.persistentParameters.count let newValue = (tracker.buffer.persistentParameters[0] as! ATParam).value() XCTAssertEqual(refCount, newCount, "Le nombre de paramètres dans la collection persistante doit être identique") XCTAssertTrue(refValue == newValue, "La valeur du paramètre dans la collection persistante pour la même clé ne doit pas changer") XCTAssertTrue(refKey == newKey, "la clé pour l'index donnée de la collection persistante ne doit pas changer") } func testDefaultDoNotTrack() { let builder = ATBuilder(tracker: self.tracker, volatileParameters: self.tracker.buffer.volatileParameters as [AnyObject], persistentParameters: self.tracker.buffer.persistentParameters as [AnyObject]) let hits = builder.build() let url = NSURL(string: hits[0] as! String) _ = [String: String]() let urlComponents = url?.absoluteString!.componentsSeparatedByString("&") for component in urlComponents! as [String] { let pairComponents = component.componentsSeparatedByString("=") if(pairComponents[0] == "idclient") { XCTAssert(pairComponents[1] != "opt-out".percentEncodedString, "le paramètre idclient doit être différent d'opt-out") } } } func testDoNotTrack() { ATTracker.setDoNotTrack(true); let builder = ATBuilder(tracker: self.tracker, volatileParameters: tracker.buffer.volatileParameters as [AnyObject], persistentParameters: tracker.buffer.persistentParameters as [AnyObject]) let hits = builder.build() let url = NSURL(string: hits[0] as! String) _ = [String: String]() let urlComponents = url?.absoluteString!.componentsSeparatedByString("&") for component in urlComponents! as [String] { let pairComponents = component.componentsSeparatedByString("=") if(pairComponents[0] == "idclient") { XCTAssert(pairComponents[1] == "opt-out", "le paramètre idclient doit être égal à opt-out") } } ATTracker.setDoNotTrack(false); } func testHashUserId() { let expectation = expectationWithDescription("test") self.tracker.setConfig("hashUserId", value: "true", completionHandler: nil) let configurationOperation = NSBlockOperation(block: { self.tracker.setStringParam("idclient", value: "coucou") let builder = ATBuilder(tracker: self.tracker, volatileParameters: self.tracker.buffer.volatileParameters as [AnyObject], persistentParameters: self.tracker.buffer.persistentParameters as [AnyObject]) let hits = builder.build() let url = NSURL(string: hits[0] as! String) _ = [String: String]() let urlComponents = url?.absoluteString!.componentsSeparatedByString("&") for component in urlComponents! as [String] { let pairComponents = component.componentsSeparatedByString("=") if(pairComponents[0] == "idclient") { XCTAssert(pairComponents[1] == "1edd758910e96f4c7f7426ce8daf82c1a97dda4bfb165855e2b47a43021bddef".percentEncodedString, "le paramètre idclient doit être égal à 1edd758910e96f4c7f7426ce8daf82c1a97dda4bfb165855e2b47a43021bddef") expectation.fulfill() } } }) ATTrackerQueue.sharedInstance().queue.addOperation(configurationOperation) waitForExpectationsWithTimeout(10, handler: nil) self.tracker.setConfig("hashUserId", value: "false", completionHandler: nil) } func testNoHashUserId() { let expectation = expectationWithDescription("test") self.tracker.setConfig("hashUserId", value: "false", completionHandler: nil) let configurationOperation = NSBlockOperation(block: { self.tracker.setStringParam("idclient", value: "coucou") let builder = ATBuilder(tracker: self.tracker, volatileParameters: self.tracker.buffer.volatileParameters as [AnyObject], persistentParameters: self.tracker.buffer.persistentParameters as [AnyObject]) let hits = builder.build() let url = NSURL(string: hits[0] as! String) _ = [String: String]() let urlComponents = url?.absoluteString!.componentsSeparatedByString("&") for component in urlComponents! as [String] { let pairComponents = component.componentsSeparatedByString("=") if(pairComponents[0] == "idclient") { XCTAssert(pairComponents[1] == "coucou".percentEncodedString, "le paramètre idclient doit être égal à coucou") expectation.fulfill() } } }) ATTrackerQueue.sharedInstance().queue.addOperation(configurationOperation) waitForExpectationsWithTimeout(10, handler: nil) } func testUnsetParam() { let refCount = tracker.buffer.volatileParameters.count tracker.setStringParam("toto", value: "tata") tracker.unsetParam("toto") let newCount = tracker.buffer.volatileParameters.count XCTAssertTrue(refCount == newCount, "Le nombre d'éléments ne doit pas avoir changé") } }
mit
6ff3ca7be9c73b0825cd125ac82527b6
44.197657
246
0.666116
4.816664
false
true
false
false
naebada-dev/swift
language-guide/Tests/language-guideTests/collectiontypes/ArrayTests.swift
1
3793
import XCTest class ArrayTests: XCTestCase { override func setUp() { super.setUp(); print("############################"); } override func tearDown() { print("############################"); super.tearDown(); } /* array는 같은 타입의 값을 순서대로 저장한다. 같은 값이 다른 위치에서 여러 번 나타날 수 있다. */ func testArrayCreation() { // 정규 구문 let full = Array<Int>() print(full) // 간편 구문 let shorthand = [Int]() print(shorthand) } func testArrayEmpty() { // Int 타입으로 추론됨 var someInts = [Int]() print("someInts1 is of type [Int] \(someInts.count) items.") someInts.append(3) someInts.append(4) print("\(someInts.count)") someInts = [] // empty print("\(someInts.count)") } func testArrayWithDefaultValue() { // 기본값을 가진 배열 생성 let threeDoubles = Array(repeating: 0.0, count: 3) print(threeDoubles) } func testArrayWithAddingOtherArray() { let threeDoubles = Array(repeating: 0.0, count: 3) let anotherThreeDoubles = Array(repeating: 2.5, count: 3) // + 을 이용하여 이미 있는 배열을 이용하여 생성할 수 있다(타입이 호환되어야 함). let sixDoubles = threeDoubles + anotherThreeDoubles print(sixDoubles) } func testArrayCreationWithLiteral() { // literal을 이용하여 생성할 수 있다. let shoppingList: [String] = ["Eggs", "Milk"] print(shoppingList) // 타입이 추론이 되어 [String]을 생략할 수 있다. let shoppingList1 = ["Eggs", "Milk"] print(shoppingList1) } func testArrayAccessingAndModifying() { var shoppingList = ["Eggs", "Milk"] print("The shopping list contains \(shoppingList.count) items.") // empty인지 확인 if shoppingList.isEmpty { print("The shopping list is empty.") } else { print("The shopping list is not empty.") } // 배열 요소 추가 shoppingList.append("Flour") shoppingList += ["Baking Powder"] shoppingList += ["Chocolate Spread", "Cheese", "Butter"] print("The shopping list contains \(shoppingList.count) items.") // 배열 요소 접근 let firstItem = shoppingList[0] print("The first Item is \(firstItem).") // 배열 요소 변경 shoppingList[0] = "Six eggs" print("The first Item is \(shoppingList[0]).") print("\norigin shopping list") for i in shoppingList { print("The shopping list item is \(i)") } print("\nreplace 4...6 shopping list") shoppingList[4...6] = ["Bananas", "Apples"] for i in shoppingList { print("The shopping list item is \(i)") } shoppingList.insert("Maple Syrup", at: 0) print("The first Item is \(shoppingList[0]).") // 배열 요소 제거 _ = shoppingList.remove(at: 0) print("The first Item is \(shoppingList[0]).") _ = shoppingList.removeLast() for i in shoppingList { print("The shopping list item is \(i)") } } func testArrayIteration() { // 값과 index가 필요한 경우 let arr = ["A", "B"] for (index, value) in arr.enumerated() { print("\(index) \(value)") } } }
apache-2.0
e31c54abb90100c72ac4215cc676affd
26.031008
72
0.501577
4.112028
false
true
false
false
kyouko-taiga/anzen
Sources/AnzenIR/AIRInstruction.swift
1
9190
import AST import Utils /// An AIR instruction. public protocol AIRInstruction { /// The text description of the instruction. var instDescription: String { get } } /// A sequence of instructions. public class InstructionBlock: Sequence { /// The label of the block. public let label: String /// The function in which the block's defined. public unowned var function: AIRFunction /// The instructions of the block. public var instructions: [AIRInstruction] = [] public init(label: String, function: AIRFunction) { self.label = label self.function = function } public func nextRegisterID() -> Int { return function.nextRegisterID() } public func makeIterator() -> Array<AIRInstruction>.Iterator { return instructions.makeIterator() } public var description: String { return instructions.map({ $0.instDescription }).joined(separator: "\n") } } /// An object allocation. public struct AllocInst: AIRInstruction, AIRRegister { /// The type of the allocated object. public let type: AIRType /// The ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = alloc \(type)" } } /// A reference allocation. public struct MakeRefInst: AIRInstruction, AIRRegister { /// The type of the allocated reference. public let type: AIRType /// The ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = make_ref \(type)" } } /// An unsafe cast. public struct UnsafeCastInst: AIRInstruction, AIRRegister { /// The operand of the case expression. public let operand: AIRValue /// The type to which the operand shall be casted. public let type: AIRType /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = unsafe_cast \(operand.valueDescription) to \(type)" } } /// Extracts a reference from an aggregate data structure. /// /// - Note: /// This intruction only extracts references that are part of the storage of the source (i.e. it /// doesn't handle computed properties). public struct ExtractInst: AIRInstruction, AIRRegister { /// The instance from which the extraction is performed. public let source: AIRRegister /// The index of the reference to extract. public let index: Int /// The type of the extracted member. public let type: AIRType /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = extract \(source.valueDescription), \(index)" } } /// A reference identity check. public struct RefEqInst: AIRInstruction, AIRRegister { /// The left operand. public let lhs: AIRValue /// The right operand. public let rhs: AIRValue /// The type of the instruction's result. public let type: AIRType = .bool /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = ref_eq \(lhs.valueDescription), \(rhs.valueDescription)" } } /// A negated reference identity check. public struct RefNeInst: AIRInstruction, AIRRegister { /// The left operand. public let lhs: AIRValue /// The right operand. public let rhs: AIRValue /// The type of the instruction's result. public let type: AIRType = .bool /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { return "%\(id) = ref_ne \(lhs.valueDescription), \(rhs.valueDescription)" } } /// A function application. public struct ApplyInst: AIRInstruction, AIRRegister { /// The callee being applied. public let callee: AIRValue /// The arguments to which the callee is applied. public let arguments: [AIRValue] /// The type of the application's result. public let type: AIRType /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? internal init( callee: AIRValue, arguments: [AIRValue], type: AIRType, id: Int, debugInfo: DebugInfo?) { self.callee = callee self.arguments = arguments self.type = type self.id = id self.debugInfo = debugInfo } public var valueDescription: String { return "%\(id)" } public var instDescription: String { let args = arguments .map({ $0.valueDescription }) .joined(separator: ", ") return "%\(id) = apply \(callee.valueDescription), \(args)" } } /// A function's partial application. /// /// A partial application keeps a reference to another function as well as a partial sequence of /// arguments. When applied, the backing function is called with the stored arguments first, /// followed by those that are provided additionally. public struct PartialApplyInst: AIRInstruction, AIRRegister { /// The function being partially applied. public let function: AIRFunction /// The arguments to which the function is partially applied. public let arguments: [AIRValue] /// The type of the partial application's result. public let type: AIRType /// Thie ID of the register. public let id: Int /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var valueDescription: String { return "%\(id)" } public var instDescription: String { let args = arguments .map({ $0.valueDescription }) .joined(separator: ", ") return "%\(id) = partial_apply \(function.valueDescription), \(args)" } } /// A function return public struct ReturnInst: AIRInstruction { /// The return value. public let value: AIRValue? public var instDescription: String { if let value = value?.valueDescription { return "ret \(value)" } else { return "ret" } } } /// A copy assignment. public struct CopyInst: AIRInstruction { /// The assignmnent's right operand. public let source: AIRValue /// The assignmnent's left operand. public let target: AIRRegister /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "copy \(source.valueDescription), \(target.valueDescription)" } } /// A move assignment. public struct MoveInst: AIRInstruction { /// The assignmnent's right operand. public let source: AIRValue /// The assignmnent's left operand. public let target: AIRRegister /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "move \(source.valueDescription), \(target.valueDescription)" } } /// An aliasing assignment. public struct BindInst: AIRInstruction { /// The assignmnent's right operand. public let source: AIRValue /// The assignmnent's left operand. public let target: AIRRegister /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "bind \(source.valueDescription), \(target.valueDescription)" } } /// A drop instruction. public struct DropInst: AIRInstruction { /// The value being dropped. public let value: MakeRefInst /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "drop \(value.valueDescription)" } } /// A conditional jump instruction. public struct BranchInst: AIRInstruction { /// The conditional expression's condition. public let condition: AIRValue /// The label to which jump if the condition holds. public let thenLabel: String /// The label to which jump if the condition doesn't hold. public let elseLabel: String /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "branch \(condition.valueDescription), \(thenLabel), \(elseLabel)" } } /// An unconditional jump instruction. public struct JumpInst: AIRInstruction { /// The label to which jump. public let label: String /// The debug information associated with this instruction. public let debugInfo: DebugInfo? public var instDescription: String { return "jump \(label)" } }
apache-2.0
8f74fa3ed5c20b05a3dd803d0ca75451
24.598886
98
0.701523
4.386635
false
false
false
false
migue1s/habitica-ios
HabitRPG/TableviewCells/ChallengeTableViewCell.swift
2
1884
// // ChallengeTableViewCell.swift // Habitica // // Created by Phillip Thelen on 23/02/2017. // Copyright © 2017 Phillip Thelen. All rights reserved. // import UIKit class ChallengeTableViewCell: UITableViewCell { @IBOutlet weak private var prizeLabel: UILabel! @IBOutlet weak private var nameLabel: UILabel! @IBOutlet weak private var groupLabel: UILabel! @IBOutlet weak private var leaderLabel: UILabel! @IBOutlet weak private var memberCountLabel: UILabel! @IBOutlet weak private var officialBadge: PillView! @IBOutlet weak private var participatingBadge: PillView! @IBOutlet weak private var officialParticipatingSpacing: NSLayoutConstraint! @IBOutlet weak private var badgesOffset: NSLayoutConstraint! @IBOutlet weak private var badgesHeight: NSLayoutConstraint! func setChallenge(_ challenge: Challenge) { self.prizeLabel.text = challenge.prize?.stringValue self.nameLabel.text = challenge.name?.unicodeEmoji self.groupLabel.text = challenge.group?.name.unicodeEmoji if let leaderName = challenge.leaderName { self.leaderLabel.text = "By \(leaderName.unicodeEmoji)".localized } self.memberCountLabel.text = challenge.memberCount?.stringValue let official = challenge.official?.boolValue ?? false self.officialBadge.isHidden = !official if official { officialParticipatingSpacing.constant = 8 } else { officialParticipatingSpacing.constant = 0 } self.participatingBadge.isHidden = challenge.user == nil if self.officialBadge.isHidden && self.participatingBadge.isHidden { self.badgesHeight.constant = 0 self.badgesOffset.constant = 0 } else { self.badgesHeight.constant = 22 self.badgesOffset.constant = 8 } } }
gpl-3.0
aac46436d688978857b0c5cf35610f85
34.528302
80
0.693574
4.719298
false
false
false
false
haaakon/Indus-Valley
IndusValley/AlternativeNamesManager.swift
1
1033
// // AlternativeNamesManager.swift // Indus Valley // // Created by Håkon Bogen on 20/04/15. // Copyright (c) 2015 haaakon. All rights reserved. // import Foundation private let _alternativeNamesManagerManagerSharedInstance = AlternativeNamesManager() // TODO Make a binary search tree for quick lookup class AlternativeNamesManager { class var sharedManager: AlternativeNamesManager { return _alternativeNamesManagerManagerSharedInstance } // lazy var massNames: [String : [String]]? = { // let bundle = NSBundle(forClass: self.dynamicType) // let path = bundle.pathForResource("MassAlternativeNames", ofType: "json") // let data = NSData(contentsOfFile: path!) // var error : NSError? // let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &error) as? [String : [String]] // // if let error = error { // return nil // } // // return jsonDictionary // }() }
mit
538eadc60a369b5f62861737ce66112b
27.694444
161
0.675388
4.229508
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/VideoViewController.swift
1
4348
// // VideoViewController.swift // Sublime // // Created by Eular on 2/19/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import AVKit import AVFoundation class VideoViewController: UIViewController { let popupMenu = PopupMenu() var curFile: File! var player: AVPlayer! var playerLayer: AVPlayerLayer! var isPlay: Bool { return player?.rate == 1.0 } var isFullScreen: Bool = false { didSet { navigationController?.setNavigationBarHidden(isFullScreen, animated: true) tabBarController?.tabBar.hidden = isFullScreen playerTimeView.show = isFullScreen && !isPlay } } let pauseView = UIView() var pauseViewFrame: CGRect { if isFullScreen { return CGRectMake((view.width - 200) / 2, (view.height - 200) / 2, 200, 200) } else { return CGRectMake(0, (view.height - 200) / 2, view.width, 200) } } var playerTimeView: VideoPlayerTimeView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constant.CapeCod title = curFile.name // 设置分享菜单 navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: popupMenu, action: #selector(popupMenu.showUp)) popupMenu.controller = self popupMenu.itemsToShare = [curFile.url] player = AVPlayer(URL: curFile.url) playerLayer = AVPlayerLayer(player: player) playerLayer.frame = self.view.frame playerLayer.frame.size.height -= Constant.NavigationBarOffset self.view.layer.addSublayer(playerLayer) let oneTap = UITapGestureRecognizer(target: self, action: #selector(self.handleOneTapGesture(_:))) pauseView.frame = pauseViewFrame pauseView.frame.size.height -= Constant.NavigationBarOffset pauseView.addGestureRecognizer(oneTap) view.addSubview(pauseView) let doubleTap = UITapGestureRecognizer(target: self, action: #selector(self.handleDoubleTapGesture(_:))) doubleTap.numberOfTapsRequired = 2 view.addGestureRecognizer(doubleTap) playerTimeView = VideoPlayerTimeView(frame: CGRectMake( 0, view.width, view.height, 30)) view.addSubview(playerTimeView) let lastPlayTime = Global.Database.doubleForKey("video-\(curFile.name.md5)") player.seekToTime(CMTimeMakeWithSeconds(lastPlayTime, 600)) player.play() } func handleOneTapGesture(sender: UITapGestureRecognizer) { if isPlay { player.pause() } else { player.play() } let playerItem = player.currentItem! playerTimeView.setTime(playerItem.currentTime().seconds, totalTime: playerItem.duration.seconds) playerTimeView.show = isFullScreen && !isPlay } func handleDoubleTapGesture(sender: UITapGestureRecognizer) { isFullScreen = !isFullScreen if isFullScreen { UIDevice.currentDevice().setValue(UIInterfaceOrientation.LandscapeLeft.rawValue, forKey: "orientation") } else { UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") tabBarController?.tabBar.hidden = true } playerLayer.frame = self.view.bounds pauseView.frame = pauseViewFrame } override func viewWillDisappear(animated: Bool) { player.pause() let key = "video-\(curFile.name.md5)" let playerItem = player.currentItem! if CMTimeGetSeconds(playerItem.duration - playerItem.currentTime()) < 0.1 { Global.Database.setDouble(0, forKey: key) } else { Global.Database.setDouble(playerItem.currentTime().seconds, forKey: key) } } override func shouldAutorotate() -> Bool { return true } } // let player = AVPlayer(URL: curFile.url) // let playerController = AVPlayerViewController() // playerController.player = player // self.addChildViewController(playerController) // self.view.addSubview(playerController.view) // playerController.view.frame = CGRectMake(0, 200, 320, 200) // player.play()
gpl-3.0
397f4564f3c8e4d9dcac0b624ff94be8
34.252033
145
0.644521
4.88726
false
false
false
false
hughbe/swift
stdlib/public/core/StringCore.swift
2
24485
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// The core implementation of a highly-optimizable String that /// can store both ASCII and UTF-16, and can wrap native Swift /// _StringBuffer or NSString instances. /// /// Usage note: when elements are 8 bits wide, this code may /// dereference one past the end of the byte array that it owns, so /// make sure that storage is allocated! You want a null terminator /// anyway, so it shouldn't be a burden. // // Implementation note: We try hard to avoid branches in this code, so // for example we use integer math to avoid switching on the element // size with the ternary operator. This is also the cause of the // extra element requirement for 8 bit elements. See the // implementation of subscript(Int) -> UTF16.CodeUnit below for details. @_fixed_layout public struct _StringCore { //===--------------------------------------------------------------------===// // Internals public var _baseAddress: UnsafeMutableRawPointer? var _countAndFlags: UInt public var _owner: AnyObject? /// (private) create the implementation of a string from its component parts. init( baseAddress: UnsafeMutableRawPointer?, _countAndFlags: UInt, owner: AnyObject? ) { self._baseAddress = baseAddress self._countAndFlags = _countAndFlags self._owner = owner _invariantCheck() } func _invariantCheck() { // Note: this code is intentionally #if'ed out. It unconditionally // accesses lazily initialized globals, and thus it is a performance burden // in non-checked builds. #if INTERNAL_CHECKS_ENABLED _sanityCheck(count >= 0) if _baseAddress == nil { #if _runtime(_ObjC) _sanityCheck(hasCocoaBuffer, "Only opaque cocoa strings may have a null base pointer") #endif _sanityCheck(elementWidth == 2, "Opaque cocoa strings should have an elementWidth of 2") } else if _baseAddress == _emptyStringBase { _sanityCheck(!hasCocoaBuffer) _sanityCheck(count == 0, "Empty string storage with non-zero count") _sanityCheck(_owner == nil, "String pointing at empty storage has owner") } else if let buffer = nativeBuffer { _sanityCheck(!hasCocoaBuffer) _sanityCheck(elementWidth == buffer.elementWidth, "_StringCore elementWidth doesn't match its buffer's") _sanityCheck(_baseAddress! >= buffer.start) _sanityCheck(_baseAddress! <= buffer.usedEnd) _sanityCheck(_pointer(toElementAt: count) <= buffer.usedEnd) } #endif } /// Bitmask for the count part of `_countAndFlags`. var _countMask: UInt { return UInt.max &>> 2 } /// Bitmask for the flags part of `_countAndFlags`. var _flagMask: UInt { return ~_countMask } /// Value by which to multiply a 2nd byte fetched in order to /// assemble a UTF-16 code unit from our contiguous storage. If we /// store ASCII, this will be zero. Otherwise, it will be 0x100. var _highByteMultiplier: UTF16.CodeUnit { return UTF16.CodeUnit(elementShift) &<< 8 } /// Returns a pointer to the Nth element of contiguous /// storage. Caveats: The string must have contiguous storage; the /// element may be 1 or 2 bytes wide, depending on elementWidth; the /// result may be null if the string is empty. func _pointer(toElementAt n: Int) -> UnsafeMutableRawPointer { _sanityCheck(hasContiguousStorage && n >= 0 && n <= count) return _baseAddress! + (n &<< elementShift) } static func _copyElements( _ srcStart: UnsafeMutableRawPointer, srcElementWidth: Int, dstStart: UnsafeMutableRawPointer, dstElementWidth: Int, count: Int ) { // Copy the old stuff into the new storage if _fastPath(srcElementWidth == dstElementWidth) { // No change in storage width; we can use memcpy _memcpy( dest: dstStart, src: srcStart, size: UInt(count &<< (srcElementWidth - 1))) } else if srcElementWidth < dstElementWidth { // Widening ASCII to UTF-16; we need to copy the bytes manually var dest = dstStart.assumingMemoryBound(to: UTF16.CodeUnit.self) var src = srcStart.assumingMemoryBound(to: UTF8.CodeUnit.self) let srcEnd = src + count while src != srcEnd { dest.pointee = UTF16.CodeUnit(src.pointee) dest += 1 src += 1 } } else { // Narrowing UTF-16 to ASCII; we need to copy the bytes manually var dest = dstStart.assumingMemoryBound(to: UTF8.CodeUnit.self) var src = srcStart.assumingMemoryBound(to: UTF16.CodeUnit.self) let srcEnd = src + count while src != srcEnd { dest.pointee = UTF8.CodeUnit(src.pointee) dest += 1 src += 1 } } } //===--------------------------------------------------------------------===// // Initialization public init( baseAddress: UnsafeMutableRawPointer?, count: Int, elementShift: Int, hasCocoaBuffer: Bool, owner: AnyObject? ) { _sanityCheck(elementShift == 0 || elementShift == 1) self._baseAddress = baseAddress self._countAndFlags = (UInt(extendingOrTruncating: elementShift) &<< (UInt.bitWidth - 1)) | ((hasCocoaBuffer ? 1 : 0) &<< (UInt.bitWidth - 2)) | UInt(extendingOrTruncating: count) self._owner = owner _sanityCheck(UInt(count) & _flagMask == (0 as UInt), "String too long to represent") _invariantCheck() } /// Create a _StringCore that covers the entire length of the _StringBuffer. init(_ buffer: _StringBuffer) { self = _StringCore( baseAddress: buffer.start, count: buffer.usedCount, elementShift: buffer.elementShift, hasCocoaBuffer: false, owner: buffer._anyObject ) } /// Create the implementation of an empty string. /// /// - Note: There is no null terminator in an empty string. public init() { self._baseAddress = _emptyStringBase self._countAndFlags = 0 self._owner = nil _invariantCheck() } //===--------------------------------------------------------------------===// // Properties /// The number of elements stored /// - Complexity: O(1). public var count: Int { get { return Int(_countAndFlags & _countMask) } set(newValue) { _sanityCheck(UInt(newValue) & _flagMask == 0) _countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue) } } /// Left shift amount to apply to an offset N so that when /// added to a UnsafeMutableRawPointer, it traverses N elements. var elementShift: Int { return Int(_countAndFlags &>> (UInt.bitWidth - 1)) } /// The number of bytes per element. /// /// If the string does not have an ASCII buffer available (including the case /// when we don't have a utf16 buffer) then it equals 2. public var elementWidth: Int { return elementShift &+ 1 } public var hasContiguousStorage: Bool { #if _runtime(_ObjC) return _fastPath(_baseAddress != nil) #else return true #endif } /// Are we using an `NSString` for storage? public var hasCocoaBuffer: Bool { return Int((_countAndFlags &<< 1)._value) < 0 } public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> { _sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII") return _baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self) } /// True iff a contiguous ASCII buffer available. public var isASCII: Bool { return elementWidth == 1 } public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { _sanityCheck( count == 0 || elementWidth == 2, "String does not contain contiguous UTF-16") return _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self) } public var asciiBuffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>? { if elementWidth != 1 { return nil } return UnsafeMutableBufferPointer(start: startASCII, count: count) } /// the native _StringBuffer, if any, or `nil`. public var nativeBuffer: _StringBuffer? { if !hasCocoaBuffer { return _owner.map { unsafeBitCast($0, to: _StringBuffer.self) } } return nil } #if _runtime(_ObjC) /// the Cocoa String buffer, if any, or `nil`. public var cocoaBuffer: _CocoaString? { if hasCocoaBuffer { return _owner } return nil } #endif //===--------------------------------------------------------------------===// // slicing /// Returns the given sub-`_StringCore`. public subscript(bounds: Range<Int>) -> _StringCore { _precondition( bounds.lowerBound >= 0, "subscript: subrange start precedes String start") _precondition( bounds.upperBound <= count, "subscript: subrange extends past String end") let newCount = bounds.upperBound - bounds.lowerBound _sanityCheck(UInt(newCount) & _flagMask == 0) if hasContiguousStorage { return _StringCore( baseAddress: _pointer(toElementAt: bounds.lowerBound), _countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount), owner: _owner) } #if _runtime(_ObjC) return _cocoaStringSlice(self, bounds) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } /// Get the Nth UTF-16 Code Unit stored. @_versioned func _nthContiguous(_ position: Int) -> UTF16.CodeUnit { let p = UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue) // Always dereference two bytes, but when elements are 8 bits we // multiply the high byte by 0. // FIXME(performance): use masking instead of multiplication. #if _endian(little) return UTF16.CodeUnit(p.pointee) + UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier #else return _highByteMultiplier == 0 ? UTF16.CodeUnit(p.pointee) : UTF16.CodeUnit((p + 1).pointee) + UTF16.CodeUnit(p.pointee) * _highByteMultiplier #endif } /// Get the Nth UTF-16 Code Unit stored. public subscript(position: Int) -> UTF16.CodeUnit { @inline(__always) get { _precondition( position >= 0, "subscript: index precedes String start") _precondition( position <= count, "subscript: index points past String end") if _fastPath(_baseAddress != nil) { return _nthContiguous(position) } #if _runtime(_ObjC) return _cocoaStringSubscript(self, position) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } } var _unmanagedASCII : UnsafeBufferPointer<Unicode.ASCII.CodeUnit>? { @inline(__always) get { guard _fastPath(_baseAddress != nil && elementWidth == 1) else { return nil } return UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound( to: Unicode.ASCII.CodeUnit.self), count: count ) } } var _unmanagedUTF16 : UnsafeBufferPointer<UTF16.CodeUnit>? { @inline(__always) get { guard _fastPath(_baseAddress != nil && elementWidth != 1) else { return nil } return UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self), count: count ) } } /// Write the string, in the given encoding, to output. func encode<Encoding: Unicode.Encoding>( _ encoding: Encoding.Type, into processCodeUnit: (Encoding.CodeUnit) -> Void) { defer { _fixLifetime(self) } if let bytes = _unmanagedASCII { if encoding == Unicode.ASCII.self || encoding == Unicode.UTF8.self || encoding == Unicode.UTF16.self || encoding == Unicode.UTF32.self { bytes.forEach { processCodeUnit(Encoding.CodeUnit(extendingOrTruncating: $0)) } } else { // TODO: be sure tests exercise this code path. for b in bytes { Encoding._encode( Unicode.Scalar(_unchecked: UInt32(b))).forEach(processCodeUnit) } } } else if let content = _unmanagedUTF16 { var i = content.makeIterator() Unicode.UTF16.ForwardParser._parse(&i) { Encoding._transcode($0, from: UTF16.self).forEach(processCodeUnit) } } else if hasCocoaBuffer { #if _runtime(_ObjC) _StringCore( _cocoaStringToContiguous( source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0) ).encode(encoding, into: processCodeUnit) #else _sanityCheckFailure("encode: non-native string without objc runtime") #endif } } /// Attempt to claim unused capacity in the String's existing /// native buffer, if any. Return zero and a pointer to the claimed /// storage if successful. Otherwise, returns a suggested new /// capacity and a null pointer. /// /// - Note: If successful, effectively appends garbage to the String /// until it has newSize UTF-16 code units; you must immediately copy /// valid UTF-16 into that storage. /// /// - Note: If unsuccessful because of insufficient space in an /// existing buffer, the suggested new capacity will at least double /// the existing buffer's storage. @inline(__always) mutating func _claimCapacity( _ newSize: Int, minElementWidth: Int) -> (Int, UnsafeMutableRawPointer?) { if _fastPath( (nativeBuffer != nil) && elementWidth >= minElementWidth && isKnownUniquelyReferenced(&_owner) ) { var buffer = nativeBuffer! // In order to grow the substring in place, this _StringCore should point // at the substring at the end of a _StringBuffer. Otherwise, some other // String is using parts of the buffer beyond our last byte. let usedStart = _pointer(toElementAt:0) let usedEnd = _pointer(toElementAt:count) // Attempt to claim unused capacity in the buffer if _fastPath(buffer.start == _baseAddress && newSize <= buffer.capacity) { buffer.usedEnd = buffer.start + (newSize &<< elementShift) count = newSize return (0, usedEnd) } else if newSize > buffer.capacity { // Growth failed because of insufficient storage; double the size return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil) } } return (newSize, nil) } /// Ensure that this String references a _StringBuffer having /// a capacity of at least newSize elements of at least the given width. /// Effectively appends garbage to the String until it has newSize /// UTF-16 code units. Returns a pointer to the garbage code units; /// you must immediately copy valid data into that storage. @inline(__always) mutating func _growBuffer( _ newSize: Int, minElementWidth: Int ) -> UnsafeMutableRawPointer { let (newCapacity, existingStorage) = _claimCapacity(newSize, minElementWidth: minElementWidth) if _fastPath(existingStorage != nil) { return existingStorage! } let oldCount = count _copyInPlace( newSize: newSize, newCapacity: newCapacity, minElementWidth: minElementWidth) return _pointer(toElementAt:oldCount) } /// Replace the storage of self with a native _StringBuffer having a /// capacity of at least newCapacity elements of at least the given /// width. Effectively appends garbage to the String until it has /// newSize UTF-16 code units. mutating func _copyInPlace( newSize: Int, newCapacity: Int, minElementWidth: Int ) { _sanityCheck(newCapacity >= newSize) let oldCount = count // Allocate storage. let newElementWidth = minElementWidth >= elementWidth ? minElementWidth : isRepresentableAsASCII() ? 1 : 2 let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize, elementWidth: newElementWidth) if hasContiguousStorage { _StringCore._copyElements( _baseAddress!, srcElementWidth: elementWidth, dstStart: UnsafeMutableRawPointer(newStorage.start), dstElementWidth: newElementWidth, count: oldCount) } else { #if _runtime(_ObjC) // Opaque cocoa buffers might not store ASCII, so assert that // we've allocated for 2-byte elements. // FIXME: can we get Cocoa to tell us quickly that an opaque // string is ASCII? Do we care much about that edge case? _sanityCheck(newStorage.elementShift == 1) _cocoaStringReadAll(cocoaBuffer!, newStorage.start.assumingMemoryBound(to: UTF16.CodeUnit.self)) #else _sanityCheckFailure("_copyInPlace: non-native string without objc runtime") #endif } self = _StringCore(newStorage) } /// Append `c` to `self`. /// /// - Complexity: O(1) when amortized over repeated appends of equal /// character values. mutating func append(_ c: Unicode.Scalar) { let width = UTF16.width(c) append( width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value), width == 2 ? UTF16.trailSurrogate(c) : nil ) } /// Append `u` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(_ u: UTF16.CodeUnit) { append(u, nil) } mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) { _invariantCheck() let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2 let utf16Width = u1 == nil ? 1 : 2 let destination = _growBuffer( count + utf16Width, minElementWidth: minBytesPerCodeUnit) if _fastPath(elementWidth == 1) { _sanityCheck(_pointer(toElementAt:count) == destination + 1) destination.assumingMemoryBound(to: UTF8.CodeUnit.self)[0] = UTF8.CodeUnit(u0) } else { let destination16 = destination.assumingMemoryBound(to: UTF16.CodeUnit.self) destination16[0] = u0 if u1 != nil { destination16[1] = u1! } } _invariantCheck() } @inline(never) mutating func append(_ rhs: _StringCore) { _invariantCheck() let minElementWidth = elementWidth >= rhs.elementWidth ? elementWidth : rhs.isRepresentableAsASCII() ? 1 : 2 let destination = _growBuffer( count + rhs.count, minElementWidth: minElementWidth) if _fastPath(rhs.hasContiguousStorage) { _StringCore._copyElements( rhs._baseAddress!, srcElementWidth: rhs.elementWidth, dstStart: destination, dstElementWidth:elementWidth, count: rhs.count) } else { #if _runtime(_ObjC) _sanityCheck(elementWidth == 2) _cocoaStringReadAll(rhs.cocoaBuffer!, destination.assumingMemoryBound(to: UTF16.CodeUnit.self)) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } _invariantCheck() } /// Returns `true` iff the contents of this string can be /// represented as pure ASCII. /// /// - Complexity: O(*n*) in the worst case. func isRepresentableAsASCII() -> Bool { if _slowPath(!hasContiguousStorage) { return false } if _fastPath(elementWidth == 1) { return true } let unsafeBuffer = UnsafeBufferPointer( start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self), count: count) return !unsafeBuffer.contains { $0 > 0x7f } } } extension _StringCore : RandomAccessCollection { public typealias Indices = CountableRange<Int> public // @testable var startIndex: Int { return 0 } public // @testable var endIndex: Int { return count } } extension _StringCore : RangeReplaceableCollection { /// Replace the elements within `bounds` with `newElements`. /// /// - Complexity: O(`bounds.count`) if `bounds.upperBound /// == self.endIndex` and `newElements.isEmpty`, O(*n*) otherwise. public mutating func replaceSubrange<C>( _ bounds: Range<Int>, with newElements: C ) where C : Collection, C.Element == UTF16.CodeUnit { _precondition( bounds.lowerBound >= 0, "replaceSubrange: subrange start precedes String start") _precondition( bounds.upperBound <= count, "replaceSubrange: subrange extends past String end") let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1 let replacementCount = numericCast(newElements.count) as Int let replacedCount = bounds.count let tailCount = count - bounds.upperBound let growth = replacementCount - replacedCount let newCount = count + growth // Successfully claiming capacity only ensures that we can modify // the newly-claimed storage without observably mutating other // strings, i.e., when we're appending. Already-used characters // can only be mutated when we have a unique reference to the // buffer. let appending = bounds.lowerBound == endIndex let existingStorage = !hasCocoaBuffer && ( appending || isKnownUniquelyReferenced(&_owner) ) ? _claimCapacity(newCount, minElementWidth: width).1 : nil if _fastPath(existingStorage != nil) { let rangeStart = _pointer(toElementAt:bounds.lowerBound) let tailStart = rangeStart + (replacedCount &<< elementShift) if growth > 0 { (tailStart + (growth &<< elementShift)).copyBytes( from: tailStart, count: tailCount &<< elementShift) } if _fastPath(elementWidth == 1) { var dst = rangeStart.assumingMemoryBound(to: UTF8.CodeUnit.self) for u in newElements { dst.pointee = UInt8(extendingOrTruncating: u) dst += 1 } } else { var dst = rangeStart.assumingMemoryBound(to: UTF16.CodeUnit.self) for u in newElements { dst.pointee = u dst += 1 } } if growth < 0 { (tailStart + (growth &<< elementShift)).copyBytes( from: tailStart, count: tailCount &<< elementShift) } } else { var r = _StringCore( _StringBuffer( capacity: newCount, initialSize: 0, elementWidth: width == 1 ? 1 : isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1 : 2 )) r.append(contentsOf: self[0..<bounds.lowerBound]) r.append(contentsOf: newElements) r.append(contentsOf: self[bounds.upperBound..<count]) self = r } } public mutating func reserveCapacity(_ n: Int) { if _fastPath(!hasCocoaBuffer) { if _fastPath(isKnownUniquelyReferenced(&_owner)) { let bounds: Range<UnsafeRawPointer> = UnsafeRawPointer(_pointer(toElementAt:0)) ..< UnsafeRawPointer(_pointer(toElementAt:count)) if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) { return } } } _copyInPlace( newSize: count, newCapacity: Swift.max(count, n), minElementWidth: 1) } public mutating func append<S : Sequence>(contentsOf s: S) where S.Element == UTF16.CodeUnit { var width = elementWidth if width == 1 { if let hasNonAscii = s._preprocessingPass({ s.contains { $0 > 0x7f } }) { width = hasNonAscii ? 2 : 1 } } let growth = s.underestimatedCount var iter = s.makeIterator() if _fastPath(growth > 0) { let newSize = count + growth let destination = _growBuffer(newSize, minElementWidth: width) if elementWidth == 1 { let destination8 = destination.assumingMemoryBound(to: UTF8.CodeUnit.self) for i in 0..<growth { destination8[i] = UTF8.CodeUnit(iter.next()!) } } else { let destination16 = destination.assumingMemoryBound(to: UTF16.CodeUnit.self) for i in 0..<growth { destination16[i] = iter.next()! } } } // Append any remaining elements for u in IteratorSequence(iter) { self.append(u) } } } // Used to support a tighter invariant: all strings with contiguous // storage have a non-NULL base address. var _emptyStringStorage: UInt32 = 0 var _emptyStringBase: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.addressof(&_emptyStringStorage)) }
apache-2.0
c7f01e77432d5a28b89dcd0ea5c35471
30.840052
147
0.639371
4.564691
false
false
false
false
yakirlee/Extersion
Helpers/String+Crypto.swift
1
8140
// // String+Crypto.swift // TSWeChat // // Created by Hilen on 2/19/16. // Copyright © 2016 Hilen. All rights reserved. // // https://github.com/onevcat/Kingfisher/blob/master/Sources/String%2BMD5.swift import Foundation extension String { var MD5String: String { if let data = dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))) let MD5Data = MD5Calculator.calculate() let MD5String = NSMutableString() for c in MD5Data { MD5String.appendFormat("%02x", c) } return MD5String as String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) let valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T), totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } protocol HashProtocol { var message: Array<UInt8> { get } /** Common part for hash calculation. Prepare header data. */ func prepare(len: Int) -> Array<UInt8> } extension HashProtocol { func prepare(len: Int) -> Array<UInt8> { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array<UInt8>(count: counter, repeatedValue: 0) return tmpMessage } } // func anyGenerator is renamed to AnyGenerator in Swift 2.2, // until then it's just dirty hack for linux (because swift >= 2.2 is available for Linux) private func CS_AnyGenerator<Element>(body: () -> Element?) -> AnyGenerator<Element> { #if os(Linux) return AnyGenerator(body: body) #else return AnyGenerator(body: body) #endif } func toUInt32Array(slice: ArraySlice<UInt8>) -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in slice.startIndex.stride(to: slice.endIndex, by: sizeof(UInt32)) { let d0 = UInt32(slice[idx.advancedBy(3)]) << 24 let d1 = UInt32(slice[idx.advancedBy(2)]) << 16 let d2 = UInt32(slice[idx.advancedBy(1)]) << 8 let d3 = UInt32(slice[idx]) let val: UInt32 = d0 | d1 | d2 | d3 result.append(val) } return result } struct BytesSequence: SequenceType { let chunkSize: Int let data: [UInt8] func generate() -> AnyGenerator<ArraySlice<UInt8>> { var offset: Int = 0 return CS_AnyGenerator { let end = min(self.chunkSize, self.data.count - offset) let result = self.data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } } func rotateLeft(value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5: HashProtocol { static let size = 16 // 128 / 8 let message: [UInt8] init (_ message: [UInt8]) { self.message = message } /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> [UInt8] { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // hash values var hh = hashes // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reverse() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)] } return result } }
mit
902cf9af5a3e546db0f2caabc301fea4
31.146245
133
0.538055
3.52383
false
false
false
false
codeOfRobin/Components-Personal
Sources/SingleSelectSearchViewController.swift
1
2517
// // SingleSelectSearchViewController.swift // SearchableComponent // // Created by Robin Malhotra on 30/08/17. // Copyright © 2017 Robin Malhotra. All rights reserved. // import AsyncDisplayKit import RxSwift public class SingleSelectSearchViewController<ViewModel: Equatable>: SingleSelectViewController<ViewModel> { let searchClosure: (ViewModel, String) -> Bool public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(dataSource: DiffableDataSourceAdapter<ViewModel>, title: String, searchClosure: @escaping (ViewModel, String) -> Bool, onSelecting: @escaping ((ViewModel) -> ())) { self.searchClosure = searchClosure super.init(dataSource: dataSource, title: title, onSelecting: onSelecting) } public override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { let searchDataObservable = PublishSubject<[ViewModel]>() let searchDataSource = DiffableDataSourceAdapter<ViewModel>.init(dataObservable: searchDataObservable.asObservable(), nodeClosure: dataSource.nodeClosure) let resultsController = SingleSelectViewController(dataSource: searchDataSource, title: title ?? "", onSelecting: { (result) in super.onSelecting(result) if let parent = self.parent { parent.dismiss(animated: true, completion: nil) } else { self.dismiss(animated: true, completion: nil) } }) let searchController = UISearchController(searchResultsController: resultsController) self.definesPresentationContext = true self.navigationItem.searchController = searchController self.navigationItem.hidesSearchBarWhenScrolling = false Observable.combineLatest(searchController.searchBar.rx.text, dataSource.dataVariable.asObservable()).map { [weak self] text, viewModels -> [ViewModel] in guard let text = text else { return []} let array = viewModels.filter { return self?.searchClosure($0, text) ?? false } return array }.bind(to: searchDataObservable).disposed(by: disposeBag) } else { // Fallback on earlier versions } // Do any additional setup after loading the view. self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: FrameworkImage.close, style: .plain, target: self, action: #selector(closeButtonPressed)) // Do any additional setup after loading the view. } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
c9babd9f60f8cc6f106fa8bdd6717662
36.552239
177
0.746025
4.383275
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ColorPixel/RGB/ARGB64ColorPixel.swift
1
1857
// // ARGB64ColorPixel.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct ARGB64ColorPixel: _RGBColorPixel { public var a: UInt16 public var r: UInt16 public var g: UInt16 public var b: UInt16 @inlinable @inline(__always) public init(red: UInt16, green: UInt16, blue: UInt16, opacity: UInt16 = 0xFFFF) { self.a = opacity self.r = red self.g = green self.b = blue } @inlinable @inline(__always) public init(_ hex: UInt64) { self.a = UInt16((hex >> 48) & 0xFFFF) self.r = UInt16((hex >> 32) & 0xFFFF) self.g = UInt16((hex >> 16) & 0xFFFF) self.b = UInt16(hex & 0xFFFF) } }
mit
a78bb74b4b81f0a95f7e2379b112f974
35.411765
85
0.679052
3.942675
false
false
false
false
iOS-Swift-Developers/Swift
基础语法/字符和字符串/main.swift
1
1547
// // main.swift // 字符和字符串 // // Created by 韩俊强 on 2017/6/1. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* 字符: OC: char charValue = 'a'; */ var charVlaue1: Character = "a" /* Swift和OC字符不一样 1.Swift是用双引号 2.Swift中的字符类型和OC也不一样, OC中的字符占一个字节, 因为它自包含ASCII表中的字符, 而Swift中的字符除了可以存储ASCII表中的字符还可以存储unicode字符 例如中文: OC:char charValue = '韩' Swift: var charValue: Character = "韩" // 正确 OC的字符是遵守ASCII标准的,Swift的字符是遵守unicode标准的, 所以可以存放实际上所有国家的字符(大部分) */ var charValue2: Character = "韩" //正确 /* 注意:双引号中只能放一个字符, 如下是错误写法 var charValue: Character = "abc" */ /* 字符串: 字符是单个字符的集合, 字符串十多个字符的集合, 想要存放多个字符需要使用字符串 C: char *stringValue = "ab" char stringStr = "ab" OC: NSString *stringArr = "ab"; */ var stringValue1 = "ab" /* C语言中的字符串是以\0结尾的,例如: char *sringValue = "abc\0def" printf("%s", stringValue); 打印结果为: abc OC语言中的字符串也是以\0结尾的, 例如: NSString *StringValue = @"abc\0def"; printf("%@", stringValue); 打印结果为: abc */ var stringValue2 = "abc\0def" print(stringValue2) // 打印结果为:abcdef // 从此可以看出Swift中的字符串和C语言/OC语言中的字符串是不一样的
mit
1f6240df4ce8a6bb9e08d1d532c3fc6b
14.969231
93
0.710019
2.408353
false
false
false
false
GenerallyHelpfulSoftware/Scalar2D
Colour/Sources/CGColor+ColourParser.swift
1
5725
// // CGColor+ColorParser.swift // Scalar2D // // Created by Glenn Howes on 10/8/16. // Copyright © 2016-2019 Generally Helpful Software. All rights reserved. // // // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // 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) || os(OSX) || os(watchOS) import Foundation import CoreGraphics public extension Colour { /// the CGColor described by this color or nil if can't be created var nativeColour: CGColor? { switch self { case .clear: let components = [CGFloat(0.0), 0.0] let colorSpace = CGColorSpaceCreateDeviceGray() return CGColor(colorSpace: colorSpace, components: components) case .rgb(let red, let green, let blue, _): let colorSpace = CGColorSpaceCreateDeviceRGB() let components = [red, green, blue, 1.0] return CGColor(colorSpace: colorSpace, components: components) case .device_rgb(let red, let green, let blue, _): let components = [red, green, blue, 1.0] let colorSpace = CGColorSpaceCreateDeviceRGB() return CGColor(colorSpace: colorSpace, components: components) case .device_gray(let gray, _): let components = [gray, 1.0] let colorSpace = CGColorSpaceCreateDeviceGray() return CGColor(colorSpace: colorSpace, components: components) case .device_cmyk(let cyan, let magenta, let yellow, let black, _): let components = [cyan, magenta, yellow, black, 1.0] let colorSpace = CGColorSpaceCreateDeviceCMYK() return CGColor(colorSpace: colorSpace, components: components) case .icc(let profileName, let components, _): switch profileName { case "p3": if let colorSpace = CGColorSpace(name: CGColorSpace.displayP3) { var withAlphaComponents = components if withAlphaComponents.count == 3 { withAlphaComponents.append(1.0) } return CGColor(colorSpace: colorSpace, components: withAlphaComponents) } default: return nil } case .placeholder(_): return nil case .transparent(let aColour, let alpha): guard let cgColor = aColour.nativeColour else { return nil } return cgColor.copy(alpha: alpha) } return nil } func toCGColorWithColorContext(_ colorContext: ColorContext? = nil) ->CGColor? { guard let cgColor = self.nativeColour else { var result: CGColor? = nil if let context = colorContext , case .icc(let name, let components, _) = self { if let profileData = context.profileNamed(name: name) { if #available(OSX 10.12, iOS 10, *) { guard let colorSpace = CGColorSpace(iccData: profileData as CFData) else { return nil // } result = CGColor(colorSpace: colorSpace, components: components) } else { return nil // Fallback on earlier versions } } } return result } return cgColor } } extension CGColor { static public let standaloneParsers = [ AnyColourParser(RGBColourParser()), AnyColourParser(WebColourParser()), AnyColourParser(HexColourParser()), AnyColourParser(DeviceRGBColourParser()), AnyColourParser(DeviceGrayColourParser()), AnyColourParser(DeviceCYMKColourParser()), AnyColourParser(ICCColourParser()) ] static public func from(string: String, colorContext: ColorContext? = nil) -> CGColor? { if let aColorDefinition = ((try? CGColor.standaloneParsers.parseString(source: string, colorContext: nil)) as Colour??) { return aColorDefinition?.nativeColour } return nil } } #endif
mit
818bbabdcf951f77166fe0579ccf0964
37.938776
128
0.563767
5.256198
false
false
false
false
lkzhao/Hero
LegacyExamples/Examples/BuiltInTransition/AnimationSelectTableViewController.swift
1
4164
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Hero import ChameleonFramework class AnimationSelectHeaderCell: UITableViewCell { @IBOutlet weak var backButton: UIButton! @IBOutlet weak var heroLogo: TemplateImageView! @IBOutlet weak var promptLabel: UILabel! } class AnimationSelectTableViewController: UITableViewController { var animations: [HeroDefaultAnimationType] = [ .push(direction: .left), .pull(direction: .left), .slide(direction: .left), .zoomSlide(direction: .left), .cover(direction: .up), .uncover(direction: .up), .pageIn(direction: .left), .pageOut(direction: .left), .fade, .zoom, .zoomOut, .none ] var labelColor: UIColor! override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.randomFlat labelColor = UIColor(contrastingBlackOrWhiteColorOn: tableView.backgroundColor!, isFlat: true) let screenEdgePanGR = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handlePan(gr:))) screenEdgePanGR.edges = .left view.addGestureRecognizer(screenEdgePanGR) } @objc func handlePan(gr: UIPanGestureRecognizer) { switch gr.state { case .began: dismiss(animated: true, completion: nil) case .changed: let progress = gr.translation(in: nil).x / view.bounds.width Hero.shared.update(progress) default: if (gr.translation(in: nil).x + gr.velocity(in: nil).x) / view.bounds.width > 0.5 { Hero.shared.finish() } else { Hero.shared.cancel() } } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : animations.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let header = tableView.dequeueReusableCell(withIdentifier: "header", for: indexPath) as! AnimationSelectHeaderCell header.heroLogo.tintColor = labelColor header.promptLabel.textColor = labelColor header.backButton.tintColor = labelColor return header } let cell = tableView.dequeueReusableCell(withIdentifier: "item", for: indexPath) cell.textLabel!.text = animations[indexPath.item].label cell.textLabel!.textColor = labelColor return cell } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath.section == 0 ? nil : indexPath } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = self.storyboard!.instantiateViewController(withIdentifier: "animationSelect") vc.hero.modalAnimationType = animations[indexPath.item] hero.replaceViewController(with: vc) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return indexPath.section == 0 ? 300 : 44 } }
mit
72c8f044ff72ea5138def850e277c987
35.849558
120
0.725024
4.521173
false
false
false
false
mohamede1945/quran-ios
BatchDownloader/DownloadBatchDataController.swift
2
13333
// // DownloadBatchDataController.swift // Quran // // Created by Mohamed Afifi on 4/29/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import VFoundation func describe(_ task: URLSessionTask) -> String { return "\(task.taskIdentifier) " + ((task.originalRequest?.url?.absoluteString ?? task.currentRequest?.url?.absoluteString) ?? "") } class DownloadBatchDataController { private let maxSimultaneousDownloads: Int private let persistence: DownloadsPersistence var session: URLSession? weak var cancellable: NetworkResponseCancellable? private var runningDownloads: [Int: DownloadResponse] = [:] private var batchesByIds: [Int64: DownloadBatchResponse] = [:] init(maxSimultaneousDownloads: Int, persistence: DownloadsPersistence) { self.maxSimultaneousDownloads = maxSimultaneousDownloads self.persistence = persistence } func getOnGoingDownloads() -> [Int64: DownloadBatchResponse] { // make sure we set the cancellable // as we could load the requests before the cancellable is set for (_, batch) in batchesByIds { batch.cancellable = cancellable } return batchesByIds } func downloadResponse(for task: URLSessionTask) -> DownloadResponse? { // get from running if let response = runningDownloads[task.taskIdentifier] { return response } // get from pending CLog("Didn't find a running task", describe(task), "will search in pending tasks") for (_, batch) in batchesByIds { for response in batch.responses where response.download.taskId == task.taskIdentifier { CLog("Found task in pending tasks") runningDownloads[task.taskIdentifier] = response response.task = task return response } } CLog("Didn't find the task in pending tasks") return nil } func download(_ batchRequest: DownloadBatchRequest) throws -> DownloadBatchResponse { CLog("Batching \(batchRequest.requests.count) to download.") // save to persistence let batch = try persistence.insert(batch: batchRequest) // create the response let response = createResponse(forBatch: batch) batchesByIds[batch.id] = response // start pending downloads if needed try startPendingTasksIfNeeded() return response } func loadBatchesFromPersistence() throws { let batches = try persistence.retrieveAll() CLog("Loading \(batches.count) from persistence") for batch in batches { let response = createResponse(forBatch: batch) batchesByIds[batch.id] = response } } private func createResponse(forBatch batch: DownloadBatch) -> DownloadBatchResponse { var responses: [DownloadResponse] = [] for download in batch.downloads { // create the response let response = DownloadResponse(download: download, progress: QProgress(totalUnitCount: 1)) response.promise.catch { _ in // ignore all errors } // if completed, then show that // if it is running, add it to running tasks if download.status == .completed { response.progress.completedUnitCount = 1 response.fulfill() } else if let taskId = download.taskId { runningDownloads[taskId] = response } responses.append(response) } // create batch response let response = DownloadBatchResponse(batchId: batch.id, responses: responses, cancellable: cancellable) return response } func setRunningTasks(_ tasks: [URLSessionTask]) throws { guard !tasks.isEmpty else { return } // load the models from persistence if not loaded yet if batchesByIds.isEmpty { try loadBatchesFromPersistence() } let previouslyDownloading = batchesByIds .flatMap { $1.responses } .filter { $0.download.taskId != nil } .flatGroup { $0.download.taskId ?? 0 } // associate tasks with downloads for task in tasks { if let response = previouslyDownloading[task.taskIdentifier] { runningDownloads[task.taskIdentifier] = response response.task = task CLog("Associating download with a DownloadTask:", describe(task)) } else { CLog("Cancelling DownloadTask: ", describe(task)) // cancel the task task.cancel() } } // remove downloads that doesn't have tasks from being running for (_, response) in previouslyDownloading where response.task == nil { response.download.taskId = nil // don't save it as it doesn't matter response.download.status = .pending CLog("From downloading to pending", response.download.request.url) } // start pending tasks if needed try startPendingTasksIfNeeded() } private func removeCompletedDownloadsAndNotify() throws { // complete fulfilled/rejected batches var batchesToDelete: [Int64] = [] let batches = batchesByIds for (id, batch) in batches { var state = State.completed for response in batch.responses { if let error = response.promise.error { state.fail(error) } else if response.promise.isPending { state.bePending() // we won't break since we might have another one failed } } // if finished successfully or failed if state.isFinished { batchesByIds[id] = nil batchesToDelete.append(id) // if successful if state.isCompleted { // fulfill it batch.fulfill() CLog("Batch \(batch.batchId) completed successfully") } else if state.isFailed { // if failed // cancel any on-going downloads cancelOngoingResponses(for: batch) // get the error if it is not cancelled let cancelledError = URLError(.cancelled) let error = state.errorOtherThan(cancelledError as NSError) ?? cancelledError // reject it anyway batch.reject(error) CLog("Batch \(batch.batchId) rejected with error: \(error)") } } } if !batchesToDelete.isEmpty { // delete the completed batches try persistence.delete(batchIds: batchesToDelete) } } private func startPendingTasksIfNeeded() throws { // if we have a session guard let session = session else { return } // and there are empty slots to use for downloading guard runningDownloads.count < maxSimultaneousDownloads else { return } // and there are things to download guard !batchesByIds.isEmpty else { return } let emptySlots = maxSimultaneousDownloads - runningDownloads.count // sort the batches by id let batches = batchesByIds.sorted { $0.key < $1.key } var downloads: [(task: URLSessionDownloadTask, response: DownloadResponse)] = [] for (_, batch) in batches { for download in batch.responses { guard download.task == nil else { continue } // create the download task let task = session.downloadTask(with: download.download.request) download.task = task download.download.taskId = task.taskIdentifier download.download.status = .downloading downloads.append((task, download)) // if all slots are filled, exist if downloads.count >= emptySlots { break } } // if all slots are filled, exist if downloads.count >= emptySlots { break } } // continue if there are data guard !downloads.isEmpty else { return } let message = "Enqueuing \(downloads.count) to download on empty channels." if downloads.count == 1 { CLog(message) } else { log(message) } // updated downloads do { try persistence.update(downloads: downloads.map { $0.response.download }) } catch { // roll back for download in downloads { download.response.task = nil download.response.download.status = .pending download.response.download.taskId = nil } for download in downloads { download.task.cancel() } // rethrow throw error } // set them to be running for download in downloads { runningDownloads[download.task.taskIdentifier] = download.response } // start the tasks for download in downloads { download.task.resume() } } func downloadCompleted(_ response: DownloadResponse) throws { try update(response, to: .completed) // fulfill response.fulfill() responseIsDone(response) // clean up the model try removeCompletedDownloadsAndNotify() // start pending tasks if needed try startPendingTasksIfNeeded() } func downloadFailed(_ response: DownloadResponse, with error: Error) throws { if response.promise.isPending { response.reject(error) } responseIsDone(response) // clean up the model try removeCompletedDownloadsAndNotify() // start pending tasks if needed try startPendingTasksIfNeeded() } func cancel(batch: DownloadBatchResponse) throws { // cancel any on-going downloads cancelOngoingResponses(for: batch) // clean up the model try removeCompletedDownloadsAndNotify() // start pending tasks if needed try startPendingTasksIfNeeded() } private func cancelOngoingResponses(for batch: DownloadBatchResponse) { for response in batch.responses { if response.promise.isPending { response.reject(URLError(.cancelled)) } responseIsDone(response) response.task?.cancel() } } private func update(_ response: DownloadResponse, to status: Download.Status) throws { let oldStatus = response.download.status response.download.status = status do { try persistence.update(url: response.download.request.url, newStatus: status) } catch { // roll back response.download.status = oldStatus // rethrow throw error } } private func responseIsDone(_ response: DownloadResponse) { if let id = response.task?.taskIdentifier { runningDownloads[id] = nil } } } private enum State { case completed; case failed([Error]); case pending mutating func fail(_ error: Error) { switch self { case .failed(var errors): errors.append(error) self = .failed(errors) default: self = .failed([error]) } } mutating func bePending() { switch self { case .completed: self = .pending default: break } } var isFinished: Bool { switch self { case .completed: return true case .failed: return true default: return false } } var isCompleted: Bool { switch self { case .completed: return true default: return false } } var isFailed: Bool { switch self { case .failed: return true default: return false } } func errorOtherThan(_ error: NSError) -> Error? { switch self { case .failed(let errors): for failedError in errors as [NSError] { if failedError.domain != error.domain || failedError.code == error.code { return failedError } } return nil default: return nil } } }
gpl-3.0
bf9e64dc0bd42c37ebe022c904b174ac
31.519512
134
0.58014
5.249213
false
false
false
false
panadaW/MyNews
MyWb完善首页数据/MyWb/Class/Controllers/Home/PhotoViewCotroller/PhoneChoseCell.swift
1
4910
// // PhoneChoseCell.swift // MyWb // // Created by 王明申 on 15/10/20. // Copyright © 2015年 晨曦的Mac. All rights reserved. // import UIKit import SDWebImage class PhoneChoseCell: UICollectionViewCell { var imageURL:NSURL? { didSet { indicator.startAnimating() // 重设布局 resetphoneScrollView() self.phoneImageView.sd_setImageWithURL(self.imageURL) { (image, _, _, _) -> Void in self.indicator.stopAnimating() if self.phoneImageView.image == nil { print("没有获取图像") return } // 加载图片 self.setUpLocation() } } } // 重新布局 func resetphoneScrollView() { // 重新设置图片的形变 phoneImageView.transform = CGAffineTransformIdentity phoneScrollView.contentInset = UIEdgeInsetsZero phoneScrollView.contentOffset = CGPointZero phoneScrollView.contentSize = CGSizeZero } // 设置图片位置 func setUpLocation() { let s = self.setUpSizeOfPhoneImageview(phoneImageView.image!) // 长微博 if s.height < phoneScrollView.bounds.height { // 让图片垂直居中 let y = (phoneScrollView.bounds.height - s.height) * 0.5 phoneImageView.frame = CGRect(origin: CGPointZero, size: s) phoneScrollView.contentInset = UIEdgeInsetsMake(y, 0, y, 0) } else { phoneImageView.frame = CGRect(origin: CGPointZero, size: s) // 让图片超出范围可以滚动 phoneScrollView.contentSize = s } // 短微博 } // 设置图片尺寸 func setUpSizeOfPhoneImageview(image: UIImage)->CGSize { // 图像高宽比 let scale = image.size.height / image.size.width let h = scale * phoneScrollView.bounds.width return CGSizeMake(phoneScrollView.bounds.width, h) } override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUpUI() { // 添加控件 contentView.addSubview(phoneScrollView) phoneScrollView.addSubview(phoneImageView) contentView.addSubview(indicator) // phoneScrollView.backgroundColor = UIColor.redColor() // 设置布局 phoneScrollView.translatesAutoresizingMaskIntoConstraints = false indicator.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": phoneScrollView])) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv": phoneScrollView])) contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)) //设置phoneScrollView的属性 prepareForphoneScrollView() layoutIfNeeded() } private func prepareForphoneScrollView() { // 设置代理 phoneScrollView.delegate = self // 设置缩放比例 phoneScrollView.maximumZoomScale = 2.0 phoneScrollView.minimumZoomScale = 0.5 } //懒记在scrollview控件 lazy var phoneScrollView = UIScrollView() // 懒加载imageview控件 lazy var phoneImageView = UIImageView() // 懒加载网络加载图标 lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) } extension PhoneChoseCell: UIScrollViewDelegate { func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return phoneImageView } // 图片完成缩放后,让其居中显示 func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { // var offx = (phoneScrollView.bounds.width - view!.frame.width) * 0.5 offx = offx > 0 ? offx : 0 var offy = (phoneScrollView.bounds.height - view!.frame.height) * 0.5 offy = offy > 0 ? offy : 0 phoneScrollView.contentInset = UIEdgeInsets(top: offy, left: offx, bottom: 0, right: 0) } func scrollViewDidScroll(scrollView: UIScrollView) { } }
mit
1db2ff4857cb9ef5f3c12af2f81ef66f
36.176
232
0.650312
4.679758
false
false
false
false
fireflyexperience/Eki
Eki/Group.swift
1
2244
// // Group.swift // Eki // // Created by Jeremy Marchand on 20/10/2014. // Copyright (c) 2014 Jérémy Marchand. All rights reserved. // import Foundation /** A wrapper for Grand Central Dispatch Group */ public class Group { private var group = dispatch_group_create() public var queue:Queue = Queue.UserInitiated public init(queue:Queue = Queue.Background) { self.queue = queue } public convenience init(tasks:[Task]) { self.init() async(tasks) } //MARK: Dispatch public func async(block:() -> Void) -> Group { return async(queue + block) } public func async(task:Task) -> Group { dispatch_group_async(group, task.queue.dispatchQueue, task.dispatchBlock) return self } public func async(blocks:[() -> Void]) -> Group { async(blocks.map{ self.queue + $0 }) return self } public func async(tasks:[Task]) -> Group { for task in tasks { async(task) } return self } //MARK: - Manually public func enter() { dispatch_group_enter(group) } public func leave() { dispatch_group_leave(group) } //MARK: Others public func notify(block:() -> Void) -> Group { return notify(queue + block) } public func notify(task:Task) -> Group { dispatch_group_notify(group,task.queue.dispatchQueue, task.dispatchBlock) return self } public func wait(time:NSTimeInterval? = nil) -> Bool { return dispatch_group_wait(group, dispatch_time_t(timeInterval: time)) == 0 } } // MARK: Equatable extension Group: Equatable { } public func ==(lhs: Group, rhs: Group) -> Bool { return lhs.group.isEqual(rhs.group) } //MARK: Operator public func <<< (g:Group,block:() -> Void) -> Group { return g.async(block) } public func <<< (g:Group,task:Task) -> Group { return g.async(task) } public func <<< (g:Group,blocks:[() -> Void]) -> Group { return g.async(blocks) } public func <<< (g:Group,tasks:[Task]) -> Group { return g.async(tasks) } public postfix func ++ (group: Group) { group.enter() } public postfix func -- (group: Group) { group.leave() }
mit
abdfc9912ff87174b96492c52a4b357d
22.354167
83
0.594558
3.724252
false
false
false
false
Driftt/drift-sdk-ios
Drift/Managers/UserManager.swift
2
1887
// // UserManager.swift // Drift // // Created by Eoin O'Connell on 17/08/2016. // Copyright © 2016 Drift. All rights reserved. // import UIKit class UserManager { static let sharedInstance: UserManager = UserManager() var completionDict: [Int64: [((_ user: User?) -> ())]] = [:] var userCache: [Int64: (User)] = [:] func userMetaDataForUserId(_ userId: Int64, completion: @escaping (_ user: User?) -> ()) { if let user = userCache[userId] { completion(user) }else if let user = DriftDataStore.sharedInstance.embed?.users.filter({$0.userId == userId}).first { completion(user) }else{ if let completionArr = completionDict[userId] { completionDict[userId] = completionArr + [completion] }else{ completionDict[userId] = [completion] DriftAPIManager.getUser(userId, orgId: DriftDataStore.sharedInstance.embed!.orgId, authToken: DriftDataStore.sharedInstance.auth!.accessToken, completion: { (result) -> () in switch result { case .success(let users): for user in users { self.userCache[user.userId ?? userId] = user self.executeCompletions(userId, user: user) } case .failure(_): self.executeCompletions(userId, user: nil) } }) } } } func executeCompletions(_ userId: Int64, user : User?) { if let completions = self.completionDict[userId] { for completion in completions { completion(user) } } completionDict[userId] = nil } }
mit
2adcc1527bb49983e4fcb75266b76faf
32.678571
190
0.510604
4.924282
false
false
false
false
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/RunLoop/RunLoop/RunLoop.swift
111
2629
//===--- RunLoop.swift ----------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Boilerplate public protocol SettledType { var isHome:Bool {get} } public protocol RunLoopType : NonStrictEquatable { init() func semaphore() -> SemaphoreType func semaphore(value:Int) -> SemaphoreType /// tries to execute before other tasks func urgent(task:SafeTask) func execute(task:SafeTask) func execute(delay:Timeout, task:SafeTask) // commented until @autoclosure is resolved in Swift 3.0 //func sync<ReturnType>(@autoclosure(escaping) task:() throws -> ReturnType) rethrows -> ReturnType func sync<ReturnType>(task:() throws -> ReturnType) rethrows -> ReturnType var native:Any {get} static var main:RunLoopType {get} } public protocol RunnableRunLoopType : RunLoopType { func run(timeout:Timeout, once:Bool) -> Bool func run(until:NSDate, once:Bool) -> Bool func stop() /// protected loop stop shout take to effect while this flag is set /// false by default var protected:Bool {get set} } public extension RunnableRunLoopType { func run(timeout:Timeout = .Infinity, once:Bool = false) -> Bool { return self.run(timeout.timeSinceNow(), once: once) } func run(until:NSDate) -> Bool { return self.run(until, once: false) } } #if os(Linux) #if dispatch #if nouv public typealias RunLoop = DispatchRunLoop #else public typealias RunLoop = UVRunLoop #endif #else #if nouv private func error() { let error = "You can not use 'nouv' key' without dispatch support" } #else public typealias RunLoop = UVRunLoop #endif #endif #else #if nouv public typealias RunLoop = DispatchRunLoop #else public typealias RunLoop = UVRunLoop #endif #endif
mit
a1a34225c133aa9e988a445d02a42e1e
29.229885
103
0.629897
4.564236
false
false
false
false
djwbrown/swift
test/IRGen/big_types_corner_cases.swift
1
5732
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( protected)?}} internal swiftcc void @_T022big_types_corner_cases21OptionalInoutFuncTypeC7executeys5Error_pSgFyycfU_(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIxcx_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @_T0SqWy // CHECK: call void @_T0SqWe // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10f3_uses_f2yyF() // CHECK:call swiftcc void @_T022big_types_corner_cases9BigStructVACycfC(%T22big_types_corner_cases9BigStructV* nocapture dereferenceable // CHECK: call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* nocapture dereferenceable({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases18f4_tuple_use_of_f2yyF() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* nocapture dereferenceable({{.*}}) {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( protected)?}} hidden swiftcc void @_T022big_types_corner_cases8BigClassC03useE6StructyAA0eH0V0aH0_tF(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) #0 { // CHECK: getelementptr inbounds %T22big_types_corner_cases8BigClassC, %T22big_types_corner_cases8BigClassC* // CHECK: call void @_T0SqWy // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @_T022big_types_corner_cases3FooC8myMethodyyAA8MyStructV_SitcFTc(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.refcounted*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_rt_swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( protected)?}} swiftcc void @_T022big_types_corner_cases10enumCalleeyAA9LargeEnumOF(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable(34)) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call %swift.type* @_T0ypMa() // CHECK-64: ret void
apache-2.0
b286d4984747cde69333cbb142d0173f
40.536232
363
0.702547
3.298044
false
false
false
false
Cellane/iWeb
Sources/App/Models/Comment.swift
1
2712
import Vapor import FluentProvider final class Comment: Model { let storage = Storage() var nickname: String var text: String var postId: Identifier? init(nickname: String, text: String, post: Post? = nil) throws { self.nickname = nickname self.text = text postId = try post?.assertExists() } // MARK: - Row init(row: Row) throws { nickname = try row.get(Properties.nickname) text = try row.get(Properties.text) postId = try row.get(Post.foreignIdKey) } func makeRow() throws -> Row { var row = Row() try row.set(Properties.nickname, nickname) try row.set(Properties.text, text) try row.set(Post.foreignIdKey, postId) return row } } extension Comment { var post: Parent<Comment, Post> { return parent(id: postId) } } // MARK: - Preparation extension Comment: Preparation { struct Properties { static let id = "id" // swiftlint:disable:this identifier_name static let nickname = "nickname" static let text = "text" static let post = "post" static let createdAt = "createdAt" } static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string(Properties.nickname) builder.string(Properties.text) builder.foreignKey(for: Post.self) } } static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSONConvertible extension Comment: JSONConvertible { convenience init(json: JSON) throws { try self.init( nickname: try json.get(Properties.nickname), text: try json.get(Properties.text) ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(Properties.id, id) try json.set(Properties.nickname, nickname) try json.set(Properties.text, text) try json.set(Post.foreignIdKey, postId) try json.set(Properties.createdAt, createdAt) return json } } // MARK: - NodeConvertible extension Comment: NodeConvertible { convenience init(node: Node) throws { try self.init( nickname: try node.get(Properties.nickname), text: try node.get(Properties.text) ) } func makeNode(in context: Context?) throws -> Node { return try Node(makeJSON()) } } // MARK: - ResponseRepresentable extension Comment: ResponseRepresentable { } // MARK: - TimeStampable extension Comment: Timestampable { } // MARK: - SoftDeletable extension Comment: SoftDeletable { } // MARK: - Request extension Request { func comment() throws -> Comment { let comment: Comment if let json = json { comment = try Comment(json: json) } else if let node = formURLEncoded { comment = try Comment(node: node) } else { throw Abort(.badRequest) } comment.postId = try parameters.next(Post.self).id return comment } }
mit
365a0e177774fa7f7c5a4bc54a3b5447
19.861538
65
0.700221
3.335793
false
false
false
false
JaSpa/swift
test/IRGen/objc_extensions.swift
3
6367
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-objc-attr-requires-foundation-module -emit-module %S/Inputs/objc_extension_base.swift -o %t // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation import gizmo import objc_extension_base // Check that metadata for nested enums added in extensions to imported classes // gets emitted concretely. // CHECK: @_T0So8NSObjectC15objc_extensionsE8SomeEnum33_1F05E59585E0BB585FCA206FBFF1A92DLLOs9EquatableACWP = // CHECK: [[CATEGORY_NAME:@.*]] = private unnamed_addr constant [16 x i8] c"objc_extensions\00" // CHECK: [[METHOD_TYPE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK-LABEL: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions" = private constant // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP15objc_extensions11NewProtocol_ // CHECK-LABEL: @"_CATEGORY_Gizmo_$_objc_extensions" = private constant // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK: @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions", // CHECK: @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions", // CHECK: @"_CATEGORY_PROTOCOLS_Gizmo_$_objc_extensions", // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 @objc protocol NewProtocol { func brandNewInstanceMethod() } extension NSObject { func someMethod() -> String { return "Hello" } } extension Gizmo: NewProtocol { func brandNewInstanceMethod() { } class func brandNewClassMethod() { } // Overrides an instance method of NSObject override func someMethod() -> String { return super.someMethod() } // Overrides a class method of NSObject open override class func initialize() { } } /* * Make sure that two extensions of the same ObjC class in the same module can * coexist by having different category names. */ // CHECK: [[CATEGORY_NAME_1:@.*]] = private unnamed_addr constant [17 x i8] c"objc_extensions1\00" // CHECK: @"_CATEGORY_Gizmo_$_objc_extensions1" = private constant // CHECK: i8* getelementptr inbounds ([17 x i8], [17 x i8]* [[CATEGORY_NAME_1]], i64 0, i64 0), // CHECK: %objc_class* @"OBJC_CLASS_$_Gizmo", // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS_Gizmo_$_objc_extensions1", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS_Gizmo_$_objc_extensions1", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 extension Gizmo { func brandSpankingNewInstanceMethod() { } class func brandSpankingNewClassMethod() { } } /* * Check that extensions of Swift subclasses of ObjC objects get categories. */ class Hoozit : NSObject { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR:@.*]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:%.*]]*, i8*)* @_T015objc_extensions6HoozitC7blibbleyyFTo to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-LABEL: @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(blobble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @_T015objc_extensions6HoozitC7blobbleyyFZTo to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK-LABEL: @"_CATEGORY__TtC15objc_extensions6Hoozit_$_objc_extensions" = private constant // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* [[CATEGORY_NAME]], i64 0, i64 0), // CHECK: %swift.type* {{.*}} @_T015objc_extensions6HoozitCMf, // CHECK: {{.*}} @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: {{.*}} @"_CATEGORY_CLASS_METHODS__TtC15objc_extensions6Hoozit_$_objc_extensions", // CHECK: i8* null, // CHECK: i8* null // CHECK: }, section "__DATA, __objc_const", align 8 extension Hoozit { func blibble() { } class func blobble() { } } class SwiftOnly { } // CHECK-LABEL: @"_CATEGORY_INSTANCE_METHODS__TtC15objc_extensions9SwiftOnly_$_objc_extensions" = private constant // CHECK: i32 24, // CHECK: i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(wibble)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[STR]], i64 0, i64 0), // CHECK: i8* bitcast (void (i8*, i8*)* @_T015objc_extensions9SwiftOnlyC6wibbleyyFTo to i8*) // CHECK: }] }, section "__DATA, __objc_const", align 8 extension SwiftOnly { @objc func wibble() { } } class Wotsit: Hoozit {} extension Hoozit { @objc func overriddenByExtensionInSubclass() {} } extension Wotsit { @objc override func overriddenByExtensionInSubclass() {} } extension NSObject { private enum SomeEnum { case X } } /* * Make sure that @NSManaged causes a category to be generated. */ class NSDogcow : NSObject {} // CHECK: [[NAME:@.*]] = private unnamed_addr constant [5 x i8] c"woof\00" // CHECK: [[ATTR:@.*]] = private unnamed_addr constant [7 x i8] c"Tq,N,D\00" // CHECK: @"_CATEGORY_PROPERTIES__TtC15objc_extensions8NSDogcow_$_objc_extensions" = private constant {{.*}} [[NAME]], {{.*}} [[ATTR]], {{.*}}, section "__DATA, __objc_const", align 8 extension NSDogcow { @NSManaged var woof: Int } class SwiftSubGizmo : SwiftBaseGizmo { // Don't crash on this call. Emit an objC method call to super. // // CHECK-LABEL: define {{.*}} @_T015objc_extensions13SwiftSubGizmoC4frobyyF // CHECK: _T015objc_extensions13SwiftSubGizmoCMa // CHECK: objc_msgSendSuper2 // CHECK: ret public override func frob() { super.frob() } }
apache-2.0
2b763482c13bc6f675119a77d1b44e20
35.591954
183
0.658395
3.177146
false
false
false
false
onebytecode/krugozor-iOSVisitors
krugozor-visitorsAppUITests/krugozor_visitorsAppUITests.swift
1
2447
// // krugozor_visitorsAppUITests.swift // krugozor-visitorsAppUITests // // Created by Alexander Danilin on 25/09/2017. // Copyright © 2017 oneByteCode. All rights reserved. // import XCTest class krugozor_visitorsAppUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { } func testSegueBeetwinViewControllers () { let element = XCUIApplication().otherElements.containing(.pageIndicator, identifier:"page 1 of 3").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element element.swipeLeft() let element2 = XCUIApplication().otherElements.containing(.pageIndicator, identifier:"page 2 of 3").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element element2.swipeLeft() let app = XCUIApplication().otherElements.containing(.pageIndicator, identifier:"page 3 of 3").children(matching: .other).element.children(matching: .other).element.children(matching: .other).element let oliverTextField = app.textFields["oliver@"] oliverTextField.tap() oliverTextField.typeText("[email protected]") let passwordSecureTextField = app.secureTextFields["password"] passwordSecureTextField.tap() passwordSecureTextField.tap() passwordSecureTextField.typeText("ацуацуа") app.buttons["Login"].tap() XCUIApplication()/*@START_MENU_TOKEN@*/.buttons["Register"]/*[[".scrollViews.buttons[\"Register\"]",".buttons[\"Register\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() } }
apache-2.0
3f74d542eb6c31d1d8cdf9fa42eb3bda
44.12963
212
0.684448
4.55514
false
true
false
false
griotspeak/Rational
Carthage/Checkouts/SwiftCheck/Sources/Arbitrary.swift
1
11443
// // Arbitrary.swift // SwiftCheck // // Created by Robert Widmann on 7/31/14. // Copyright (c) 2015 TypeLift. All rights reserved. // /// A type that implements random generation and shrinking of values. /// /// While testing, SwiftCheck will invoke `arbitrary` a given amount of times /// (usually 100 if the default settings are used). During that time, the /// receiver has an opportunity to call through to any data or sources of /// randomness it needs to return what it deems an "Arbitrary" value. /// /// Shrinking is reduction in the complexity of a tested value to remove noise /// and present a minimal counterexample when a property fails. A shrink /// necessitates returning a list of all possible "smaller" values for /// SwiftCheck to run through. As long as each individual value in the returned /// list is less than or equal to the size of the input value, and is not a /// duplicate of the input value, a minimal case should be reached fairly /// efficiently. Shrinking is an optional extension of normal testing. If no /// implementation of `shrink` is provided, SwiftCheck will default to an empty /// one - that is, no shrinking will occur. /// /// As an example, take the `ArrayOf` implementation of shrink: /// /// Arbitrary.shrink(ArrayOf([1, 2, 3])) /// > [[], [2,3], [1,3], [1,2], [0,2,3], [1,0,3], [1,1,3], [1,2,0], [1,2,2]] /// /// SwiftCheck will search each case forward, one-by-one, and continue shrinking /// until it has reached a case it deems minimal enough to present. /// /// SwiftCheck implements a number of generators for common Swift Standard /// Library types for convenience. If more fine-grained testing is required see /// `Modifiers.swift` for an example of how to define a "Modifier" type to /// implement it. public protocol Arbitrary { /// The generator for this particular type. /// /// This function should call out to any sources of randomness or state /// necessary to generate values. It should not, however, be written as a /// deterministic function. If such a generator is needed, combinators are /// provided in `Gen.swift`. static var arbitrary : Gen<Self> { get } /// An optional shrinking function. If this function goes unimplemented, it /// is the same as returning the empty list. /// /// Shrunken values must be less than or equal to the "size" of the original /// type but never the same as the value provided to this function (or a loop /// will form in the shrinker). It is recommended that they be presented /// smallest to largest to speed up the overall shrinking process. static func shrink(_ : Self) -> [Self] } extension Arbitrary { /// The implementation of a shrink that returns no alternatives. public static func shrink(_ : Self) -> [Self] { return [] } } extension IntegerType { /// Shrinks any `IntegerType`. public var shrinkIntegral : [Self] { return unfoldr({ i in if i <= 0 { return .None } let n = i / 2 return .Some((n, n)) }, initial: self < 0 ? (Self.multiplyWithOverflow(self, -1).0) : self) } } extension Bool : Arbitrary { /// Returns a generator of `Bool`ean values. public static var arbitrary : Gen<Bool> { return Gen<Bool>.choose((false, true)) } /// The default shrinking function for `Bool`ean values. public static func shrink(x : Bool) -> [Bool] { if x { return [false] } return [] } } extension Int : Arbitrary { /// Returns a generator of `Int` values. public static var arbitrary : Gen<Int> { return Gen.sized { n in return Gen<Int>.choose((-n, n)) } } /// The default shrinking function for `Int` values. public static func shrink(x : Int) -> [Int] { return x.shrinkIntegral } } extension Int8 : Arbitrary { /// Returns a generator of `Int8` values. public static var arbitrary : Gen<Int8> { return Gen.sized { n in return Gen<Int8>.choose((Int8(truncatingBitPattern: -n), Int8(truncatingBitPattern: n))) } } /// The default shrinking function for `Int8` values. public static func shrink(x : Int8) -> [Int8] { return x.shrinkIntegral } } extension Int16 : Arbitrary { /// Returns a generator of `Int16` values. public static var arbitrary : Gen<Int16> { return Gen.sized { n in return Gen<Int16>.choose((Int16(truncatingBitPattern: -n), Int16(truncatingBitPattern: n))) } } /// The default shrinking function for `Int16` values. public static func shrink(x : Int16) -> [Int16] { return x.shrinkIntegral } } extension Int32 : Arbitrary { /// Returns a generator of `Int32` values. public static var arbitrary : Gen<Int32> { return Gen.sized { n in return Gen<Int32>.choose((Int32(truncatingBitPattern: -n), Int32(truncatingBitPattern: n))) } } /// The default shrinking function for `Int32` values. public static func shrink(x : Int32) -> [Int32] { return x.shrinkIntegral } } extension Int64 : Arbitrary { /// Returns a generator of `Int64` values. public static var arbitrary : Gen<Int64> { return Gen.sized { n in return Gen<Int64>.choose((Int64(-n), Int64(n))) } } /// The default shrinking function for `Int64` values. public static func shrink(x : Int64) -> [Int64] { return x.shrinkIntegral } } extension UInt : Arbitrary { /// Returns a generator of `UInt` values. public static var arbitrary : Gen<UInt> { return Gen.sized { n in Gen<UInt>.choose((0, UInt(n))) } } /// The default shrinking function for `UInt` values. public static func shrink(x : UInt) -> [UInt] { return x.shrinkIntegral } } extension UInt8 : Arbitrary { /// Returns a generator of `UInt8` values. public static var arbitrary : Gen<UInt8> { return Gen.sized { n in return Gen.sized { n in Gen<UInt8>.choose((0, UInt8(truncatingBitPattern: n))) } } } /// The default shrinking function for `UInt8` values. public static func shrink(x : UInt8) -> [UInt8] { return x.shrinkIntegral } } extension UInt16 : Arbitrary { /// Returns a generator of `UInt16` values. public static var arbitrary : Gen<UInt16> { return Gen.sized { n in Gen<UInt16>.choose((0, UInt16(truncatingBitPattern: n))) } } /// The default shrinking function for `UInt16` values. public static func shrink(x : UInt16) -> [UInt16] { return x.shrinkIntegral } } extension UInt32 : Arbitrary { /// Returns a generator of `UInt32` values. public static var arbitrary : Gen<UInt32> { return Gen.sized { n in Gen<UInt32>.choose((0, UInt32(truncatingBitPattern: n))) } } /// The default shrinking function for `UInt32` values. public static func shrink(x : UInt32) -> [UInt32] { return x.shrinkIntegral } } extension UInt64 : Arbitrary { /// Returns a generator of `UInt64` values. public static var arbitrary : Gen<UInt64> { return Gen.sized { n in Gen<UInt64>.choose((0, UInt64(n))) } } /// The default shrinking function for `UInt64` values. public static func shrink(x : UInt64) -> [UInt64] { return x.shrinkIntegral } } extension Float : Arbitrary { /// Returns a generator of `Float` values. public static var arbitrary : Gen<Float> { let precision : Int64 = 9999999999999 return Gen<Float>.sized { n in if n == 0 { return Gen<Float>.pure(0.0) } let numerator = Gen<Int64>.choose((Int64(-n) * precision, Int64(n) * precision)) let denominator = Gen<Int64>.choose((1, precision)) return numerator >>- { a in denominator >>- { b in Gen<Float>.pure(Float(a) / Float(b)) } } } } /// The default shrinking function for `Float` values. public static func shrink(x : Float) -> [Float] { return unfoldr({ i in if i == 0.0 { return .None } let n = i / 2.0 return .Some((n, n)) }, initial: x) } } extension Double : Arbitrary { /// Returns a generator of `Double` values. public static var arbitrary : Gen<Double> { let precision : Int64 = 9999999999999 return Gen<Double>.sized { n in if n == 0 { return Gen<Double>.pure(0.0) } let numerator = Gen<Int64>.choose((Int64(-n) * precision, Int64(n) * precision)) let denominator = Gen<Int64>.choose((1, precision)) return numerator >>- { a in denominator >>- { b in Gen<Double>.pure(Double(a) / Double(b)) } } } } /// The default shrinking function for `Double` values. public static func shrink(x : Double) -> [Double] { return unfoldr({ i in if i == 0.0 { return .None } let n = i / 2.0 return .Some((n, n)) }, initial: x) } } extension UnicodeScalar : Arbitrary { /// Returns a generator of `UnicodeScalar` values. public static var arbitrary : Gen<UnicodeScalar> { return UInt32.arbitrary.flatMap(Gen<UnicodeScalar>.pure • UnicodeScalar.init) } /// The default shrinking function for `UnicodeScalar` values. public static func shrink(x : UnicodeScalar) -> [UnicodeScalar] { let s : UnicodeScalar = UnicodeScalar(UInt32(tolower(Int32(x.value)))) return [ "a", "b", "c", s, "A", "B", "C", "1", "2", "3", "\n", " " ].nub.filter { $0 < x } } } extension String : Arbitrary { /// Returns a generator of `String` values. public static var arbitrary : Gen<String> { let chars = Gen.sized(Character.arbitrary.proliferateSized) return chars >>- { Gen<String>.pure(String($0)) } } /// The default shrinking function for `String` values. public static func shrink(s : String) -> [String] { return [Character].shrink([Character](s.characters)).map { String($0) } } } extension Character : Arbitrary { /// Returns a generator of `Character` values. public static var arbitrary : Gen<Character> { return Gen<UInt32>.choose((32, 255)) >>- (Gen<Character>.pure • Character.init • UnicodeScalar.init) } /// The default shrinking function for `Character` values. public static func shrink(x : Character) -> [Character] { let ss = String(x).unicodeScalars return UnicodeScalar.shrink(ss[ss.startIndex]).map(Character.init) } } extension AnyForwardIndex : Arbitrary { /// Returns a generator of `AnyForwardIndex` values. public static var arbitrary : Gen<AnyForwardIndex> { return Gen<Int64>.choose((1, Int64.max)).flatMap(Gen<AnyForwardIndex>.pure • AnyForwardIndex.init) } } extension AnyRandomAccessIndex : Arbitrary { /// Returns a generator of `AnyRandomAccessIndex` values. public static var arbitrary : Gen<AnyRandomAccessIndex> { return Gen<Int64>.choose((1, Int64.max)).flatMap(Gen<AnyRandomAccessIndex>.pure • AnyRandomAccessIndex.init) } } extension Mirror : Arbitrary { /// Returns a generator of `Mirror` values. public static var arbitrary : Gen<Mirror> { let genAny : Gen<Any> = Gen<Any>.oneOf([ Bool.arbitrary.map(asAny), Int.arbitrary.map(asAny), UInt.arbitrary.map(asAny), Float.arbitrary.map(asAny), Double.arbitrary.map(asAny), Character.arbitrary.map(asAny), ]) let genAnyWitnessed : Gen<Any> = Gen<Any>.oneOf([ Optional<Int>.arbitrary.map(asAny), Array<Int>.arbitrary.map(asAny), Set<Int>.arbitrary.map(asAny), ]) return Gen<Any>.oneOf([ genAny, genAnyWitnessed, ]).map(Mirror.init) } } // MARK: - Implementation Details Follow private func asAny<T>(x : T) -> Any { return x } extension Array where Element : Hashable { private var nub : [Element] { return [Element](Set(self)) } } private func unfoldr<A, B>(f : B -> Optional<(A, B)>, initial : B) -> [A] { var acc = [A]() var ini = initial while let next = f(ini) { acc.insert(next.0, atIndex: 0) ini = next.1 } return acc } #if os(Linux) import Glibc #else import Darwin #endif
mit
1fa3ac49344d347409a4a385e2527ac3
28.240409
110
0.678387
3.30052
false
false
false
false
ming1016/smck
smck/Parser/H5Sb.swift
1
673
// // H5Sb.swift // smck // // Created by DaiMing on 2017/4/18. // Copyright © 2017年 Starming. All rights reserved. // import Foundation class H5Sb { public static let divide = "/" public static let agBktL = "<" public static let agBktR = ">" public static let quotM = "\"" public static let sQuot = "'" public static let equal = "=" //css //js public static let add = "+" public static let minus = "-" public static let asterisk = "*" public static let comma = "," // public static let public static let empty = "" public static let space = " " public static let newLine = "\n" }
apache-2.0
d49744e4de3ca00e342301594b1d281f
19.9375
52
0.580597
3.806818
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/ElloDataSource.swift
1
4326
//// /// ElloDataSource.swift // class ElloDataSource: NSObject { // In StreamDataSource, visibleCellItems can be modified based on a stream // filter. In CollectionViewDataSource, there is only the one list. var visibleCellItems: [StreamCellItem] = [] var streamKind: StreamKind { didSet { didSetStreamKind() } } var currentUser: User? init(streamKind: StreamKind) { self.streamKind = streamKind super.init() } func didSetStreamKind() {} func isValidIndexPath(_ indexPath: IndexPath) -> Bool { return indexPath.section == 0 && indexPath.item >= 0 && indexPath.item < visibleCellItems.count } func streamCellItem(where filter: (StreamCellItem) -> Bool) -> StreamCellItem? { return visibleCellItems.find(filter) } func indexPath(where filter: (StreamCellItem) -> Bool) -> IndexPath? { guard let index = visibleCellItems.firstIndex(where: filter) else { return nil } return IndexPath(item: index, section: 0) } func indexPath(forItem item: StreamCellItem) -> IndexPath? { return indexPath(where: { $0 == item }) } func indexPaths(forPlaceholderType placeholderType: StreamCellType.PlaceholderType) -> [IndexPath] { return (0..<visibleCellItems.count).compactMap { index in guard visibleCellItems[index].placeholderType == placeholderType else { return nil } return IndexPath(item: index, section: 0) } } func firstIndexPath(forPlaceholderType placeholderType: StreamCellType.PlaceholderType) -> IndexPath? { if let index = self.visibleCellItems.firstIndex(where: { $0.placeholderType == placeholderType }) { return IndexPath(item: index, section: 0) } return nil } func footerIndexPath(forPost searchPost: Post) -> IndexPath? { for (index, value) in visibleCellItems.enumerated() { if value.type == .streamFooter, let post = value.jsonable as? Post, post.id == searchPost.id { return IndexPath(item: index, section: 0) } } return nil } func streamCellItem(at indexPath: IndexPath) -> StreamCellItem? { guard isValidIndexPath(indexPath) else { return nil } return visibleCellItems[indexPath.item] } func jsonable(at indexPath: IndexPath) -> Model? { let item = streamCellItem(at: indexPath) return item?.jsonable } func post(at indexPath: IndexPath) -> Post? { guard let item = streamCellItem(at: indexPath) else { return nil } if let notification = item.jsonable as? Notification { if let comment = notification.activity.subject as? ElloComment { return comment.loadedFromPost } return notification.activity.subject as? Post } if let editorial = item.jsonable as? Editorial { return editorial.post } return item.jsonable as? Post } func comment(at indexPath: IndexPath) -> ElloComment? { return jsonable(at: indexPath) as? ElloComment } func user(at indexPath: IndexPath) -> User? { guard let item = streamCellItem(at: indexPath) else { return nil } if case .streamHeader = item.type, let repostAuthor = (item.jsonable as? Post)?.repostAuthor { return repostAuthor } if let user = (item.jsonable as? PageHeader)?.user { return user } if let authorable = item.jsonable as? Authorable { return authorable.author } return item.jsonable as? User } func reposter(at indexPath: IndexPath) -> User? { guard let item = streamCellItem(at: indexPath) else { return nil } if let authorable = item.jsonable as? Authorable { return authorable.author } return item.jsonable as? User } func imageRegion(at indexPath: IndexPath) -> ImageRegion? { let item = streamCellItem(at: indexPath) return item?.type.data as? ImageRegion } func imageAsset(at indexPath: IndexPath) -> Asset? { return imageRegion(at: indexPath)?.asset } }
mit
dd38de889d5f62c36b74c9b6d2bc0e0a
30.347826
96
0.616505
4.686891
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Authentication/WhenLoggingIn.swift
1
8828
import EurofurenceModel import XCTest class WhenLoggingIn: XCTestCase { private func makeLoginResponse( uid: String = "", username: String = "", token: String = "", tokenValidUntil: Date = Date() ) -> LoginResponse { return LoginResponse(userIdentifier: uid, username: username, token: token, tokenValidUntil: tokenValidUntil) } var context: EurofurenceSessionTestBuilder.Context! override func setUp() { super.setUp() context = EurofurenceSessionTestBuilder().build() } func testUsesLoginArgumentsAgainstAPI() { let username = "Some awesome guy" let registrationNumber = 42 let password = "Some awesome password" let arguments = LoginArguments(registrationNumber: registrationNumber, username: username, password: password) context.authenticationService.login(arguments) { (_) in } let capturedLoginRequest: LoginRequest? = context.api.capturedLoginRequest XCTAssertEqual(username, capturedLoginRequest?.username) XCTAssertEqual(registrationNumber, capturedLoginRequest?.regNo) XCTAssertEqual(password, capturedLoginRequest?.password) } func testPersistsCredentialFromResponse() { let expectedUsername = "Some awesome guy" let expectedUserID = 42 let expectedToken = "JWT Token" let expectedTokenExpiry = Date.distantFuture let arguments = LoginArguments(registrationNumber: expectedUserID, username: expectedUsername, password: "Not used for this test") let response = LoginResponse(userIdentifier: "", username: "", token: expectedToken, tokenValidUntil: .distantFuture) context.authenticationService.login(arguments, completionHandler: { (_) in }) context.api.simulateLoginResponse(response) XCTAssertEqual(expectedUsername, context.credentialRepository.capturedCredential?.username) XCTAssertEqual(expectedUserID, context.credentialRepository.capturedCredential?.registrationNumber) XCTAssertEqual(expectedToken, context.credentialRepository.capturedCredential?.authenticationToken) XCTAssertEqual(expectedTokenExpiry, context.credentialRepository.capturedCredential?.tokenExpiryDate) } func testLoggingInSuccessfulyShouldNotifyObserversAboutIt() { let loginObserver = CapturingLoginObserver() context.login(completionHandler: loginObserver.completionHandler) context.api.simulateLoginResponse(makeLoginResponse()) XCTAssertTrue(loginObserver.notifiedLoginSucceeded) } func testLoggingInSuccessfulyShouldNotNotifyObserversAboutItUntilTokenPersistenceCompletes() { let loginObserver = CapturingLoginObserver() context.credentialRepository.blockToRunBeforeCompletingCredentialStorage = { XCTAssertFalse(loginObserver.notifiedLoginSucceeded) } context.login(completionHandler: loginObserver.completionHandler) context.api.simulateLoginResponse(makeLoginResponse()) } func testLoggingInSuccessfulyShouldNotNotifyObserversAboutLoginFailure() { let loginObserver = CapturingLoginObserver() context.login(completionHandler: loginObserver.completionHandler) context.api.simulateLoginResponse(makeLoginResponse()) XCTAssertFalse(loginObserver.notifiedLoginFailed) } func testLoggingInSuccessfullyThenRegisteringPushTokenShouldProvideAuthTokenWithPushRegistration() { let expectedToken = "JWT Token" context.login() context.api.simulateLoginResponse(makeLoginResponse(token: expectedToken)) context.notificationsService.storeRemoteNotificationsToken(Data()) XCTAssertEqual(expectedToken, context.notificationTokenRegistration.capturedUserAuthenticationToken) } func testLoggingInAfterRegisteringPushTokenShouldReRegisterThePushTokenWithTheUserAuthenticationToken() { let expectedToken = "JWT Token" context.notificationsService.storeRemoteNotificationsToken(Data()) context.login() context.api.simulateLoginResponse(makeLoginResponse(token: expectedToken)) XCTAssertEqual(expectedToken, context.notificationTokenRegistration.capturedUserAuthenticationToken) } func testLoggingInSuccessfullyShouldProvideExpectedLoginToHandler() { let loginObserver = CapturingLoginObserver() let username = "Some cool guy" let regNo = 42 context.login(registrationNumber: regNo, username: username, completionHandler: loginObserver.completionHandler) context.api.simulateLoginResponse(makeLoginResponse()) XCTAssertEqual(username, loginObserver.loggedInUser?.username) XCTAssertEqual(regNo, loginObserver.loggedInUser?.registrationNumber) } func testSuccessfulLoginShouldRequestLatestMessages() { let loginObserver = CapturingLoginObserver() let username = "Some cool guy" let regNo = 42 context.login(registrationNumber: regNo, username: username, completionHandler: loginObserver.completionHandler) context.api.simulateLoginResponse(makeLoginResponse()) XCTAssertTrue( context.api.wasToldToLoadPrivateMessages, "Successful login should request the user's messages are loaded" ) } func testSuccessfulLoginTellsObserversTheUserHasLoggedIn() { let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) let regNo: Int = .random let username: String = .random context.login(registrationNumber: regNo, username: username, completionHandler: { (_) in }) context.api.simulateLoginResponse(makeLoginResponse()) XCTAssertEqual(username, observer.capturedLoggedInUser?.username) XCTAssertEqual(regNo, observer.capturedLoggedInUser?.registrationNumber) } func testAddingObserverAfterSuccessfullyLoggingInTellsItAboutTheLoggedInUser() { let regNo: Int = .random let username: String = .random context.login(registrationNumber: regNo, username: username, completionHandler: { (_) in }) context.api.simulateLoginResponse(makeLoginResponse()) let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) XCTAssertEqual(username, observer.capturedLoggedInUser?.username) XCTAssertEqual(regNo, observer.capturedLoggedInUser?.registrationNumber) } func testLoggingOutTellsObserversTheUserHasLoggedOut() { let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) let user = User(registrationNumber: .random, username: .random) context.login(registrationNumber: user.registrationNumber, username: user.username) context.api.simulateLoginResponse(makeLoginResponse()) context.authenticationService.logout(completionHandler: { (_) in }) context.notificationTokenRegistration.succeedLastRequest() XCTAssertTrue(observer.loggedOut) } func testObserverNotToldUserLoggedOutUntilLogoutSucceeds() { let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) observer.loggedOut = false let user = User(registrationNumber: .random, username: .random) context.login(registrationNumber: user.registrationNumber, username: user.username) context.api.simulateLoginResponse(makeLoginResponse()) context.authenticationService.logout(completionHandler: { (_) in }) XCTAssertFalse(observer.loggedOut) } func testObserverNotToldUserLoggedOutWhenLogoutFails() { let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) observer.loggedOut = false let user = User(registrationNumber: .random, username: .random) context.login(registrationNumber: user.registrationNumber, username: user.username) context.api.simulateLoginResponse(makeLoginResponse()) context.authenticationService.logout(completionHandler: { (_) in }) context.notificationTokenRegistration.failLastRequest() XCTAssertFalse(observer.loggedOut) } func testAddingObserverWhenNotLoggedInTellsObserverUserLoggedOut() { let observer = CapturingAuthenticationStateObserver() context.authenticationService.add(observer) XCTAssertTrue(observer.loggedOut) } }
mit
1581c444b99298f3a49077f5401c0bc9
44.040816
120
0.719529
5.725032
false
true
false
false
PrashantMangukiya/SwiftUIDemo
Demo16-UIContainerView/Demo16-UIContainerView/ViewController.swift
1
1432
// // ViewController.swift // Demo16-UIContainerView // // Created by Prashant on 01/10/15. // Copyright © 2015 PrashantKumar Mangukiya. All rights reserved. // import UIKit class ViewController: UIViewController { // action - segment control @IBAction func segmentControlAction(_ sender: UISegmentedControl) { // Show/Hide container view based on segment control if sender.selectedSegmentIndex == 0 { self.containerView1.isHidden = false self.containerView2.isHidden = true }else if sender.selectedSegmentIndex == 1 { self.containerView1.isHidden = true self.containerView2.isHidden = false } } // outlet - containerView1. containerView2 @IBOutlet var containerView1: UIView! @IBOutlet var containerView2: UIView! // MARK: - View functions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // show first container at load time self.containerView1.isHidden = false // hide second container at load time self.containerView2.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
50ae5e32ae7f43c045097286cffc9aed
24.553571
80
0.624039
5.319703
false
false
false
false
coolgeng/swiftris
swiftris/swiftris/GameViewController.swift
1
7107
// // GameViewController.swift // swiftris // // Created by Yong on 5/7/15. // Copyright (c) 2015 Yong. All rights reserved. // import UIKit import SpriteKit //extension SKNode { // class func unarchiveFromFile(file : String) -> SKNode? { // if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") { // var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)! // var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData) // // archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") // let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene // archiver.finishDecoding() // return scene // } else { // return nil // } // } //} class GameViewController: UIViewController, SwiftrisDelegate, UIGestureRecognizerDelegate{ var scene: GameScene! var swiftris:Swiftris! var panPointReference:CGPoint? @IBOutlet var scoreLabel: UILabel! @IBOutlet var levelLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Configure the view let skView = view as! SKView skView.multipleTouchEnabled = false // Create and configure the scene scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill scene.tick = didTick swiftris = Swiftris() swiftris.delegate = self swiftris.beginGame() // Present the scene skView.presentScene(scene) // if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // // Configure the view. // let skView = self.view as! SKView // skView.showsFPS = true // skView.showsNodeCount = true // // /* Sprite Kit applies additional optimizations to improve rendering performance */ // skView.ignoresSiblingOrder = true // // /* Set the scale mode to scale to fit the window */ // scene.scaleMode = .AspectFill // // skView.presentScene(scene) // } } // override func shouldAutorotate() -> Bool { // return true // } // // override func supportedInterfaceOrientations() -> Int { // if UIDevice.currentDevice().userInterfaceIdiom == .Phone { // return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) // } else { // return Int(UIInterfaceOrientationMask.All.rawValue) // } // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Release any cached data, images, etc that aren't in use. // } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func didTap(sender: UITapGestureRecognizer) { swiftris.rotateShape() } @IBAction func didPan(sender: UIPanGestureRecognizer) { let currentPoint = sender.translationInView(self.view) if let originalPoint = panPointReference { if abs(currentPoint.x - originalPoint.x) > (BlockSize * 0.9) { if sender.velocityInView(self.view).x > CGFloat(0) { swiftris.moveShapeRight() panPointReference = currentPoint } else { swiftris.moveShapeLeft() panPointReference = currentPoint } } } else if sender.state == .Began { panPointReference = currentPoint } } @IBAction func didSwipe(sender: UISwipeGestureRecognizer) { swiftris.dropShape() } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if let swipeRec = gestureRecognizer as? UISwipeGestureRecognizer { if let panRec = otherGestureRecognizer as? UIPanGestureRecognizer { return true } } else if let panRec = gestureRecognizer as? UIPanGestureRecognizer { if let tapRec = otherGestureRecognizer as? UITapGestureRecognizer { return true } } return false } func didTick() { swiftris.letShapeFall() } func nextShape() { let newShapes = swiftris.newShape() if let fallingShape = newShapes.fallingShape { self.scene.addPreviewShapeToScene(newShapes.nextShape!) {} self.scene.movePreviewShape(fallingShape) { self.view.userInteractionEnabled = true self.scene.startTicking() } } } func gameDidBegin(swiftris: Swiftris) { levelLabel.text = "\(swiftris.level)" scoreLabel.text = "\(swiftris.score)" scene.tickLengthMillis = TickLengthLevelOne // The following is false when restarting a new game if swiftris.nextShape != nil && swiftris.nextShape!.blocks[0].sprite == nil { scene.addPreviewShapeToScene(swiftris.nextShape!) { self.nextShape() } } else { nextShape() } } func gameDidEnd(swiftris: Swiftris) { view.userInteractionEnabled = false scene.stopTicking() scene.playSound("gameover.mp3") scene.animateCollapsingLines(swiftris.removeAllBlocks(), fallenBlocks: Array<Array<Block>>()) { swiftris.beginGame() } } func gameDidLevelUp(swiftris: Swiftris) { levelLabel.text = "\(swiftris.level)" if scene.tickLengthMillis >= 100 { scene.tickLengthMillis -= 100 } else if scene.tickLengthMillis > 50 { scene.tickLengthMillis -= 50 } scene.playSound("levelup.mp3") } func gameShapeDidDrop(swiftris: Swiftris) { scene.stopTicking() scene.redrawShape(swiftris.fallingShape!) { swiftris.letShapeFall() } scene.playSound("drop.mp3") } func gameShapeDidLand(swiftris: Swiftris) { scene.stopTicking() self.view.userInteractionEnabled = false let removedLines = swiftris.removeCompletedLines() if removedLines.linesRemoved.count > 0 { self.scoreLabel.text = "\(swiftris.score)" scene.animateCollapsingLines(removedLines.linesRemoved, fallenBlocks:removedLines.fallenBlocks) { self.gameShapeDidLand(swiftris) } scene.playSound("bomb.mp3") } else { nextShape() } } func gameShapeDidMove(swiftris: Swiftris) { scene.redrawShape(swiftris.fallingShape!) {} } }
mit
df5c173b2d5cac7c921acd67d8bcd569
32.523585
172
0.601238
4.966457
false
false
false
false
material-components/material-components-ios
components/FlexibleHeader/tests/unit/FlexibleHeaderTrackingScrollViewDidScroll.swift
2
2483
// Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import MaterialComponents.MaterialFlexibleHeader // Tests confirming contract with a tracking scroll view that has scrolled class FlexibleHeaderTrackingScrollViewDidScroll: XCTestCase { // Implicitly unwrapped to indicate the contract of creating these values in setUp and make our // accessors cleaner in tests. var view: MDCFlexibleHeaderView! var beforeFrame: CGRect! var scrollView: UIScrollView! override func setUp() { super.setUp() view = MDCFlexibleHeaderView() let originalFrame = CGRect(x: 0, y: 0, width: 100, height: 50) view.frame = originalFrame view.sizeToFit() beforeFrame = view.frame scrollView = UIScrollView() scrollView.contentSize = CGSize(width: originalFrame.size.width, height: 1000) scrollView.frame = CGRect(x: 0, y: 0, width: originalFrame.size.width, height: 250) view.trackingScrollView = scrollView } override func tearDown() { view.trackingScrollView = nil scrollView = nil view = nil super.tearDown() } // MARK: Initial changes are ignored. func testFirstChangeDoesNothingNegative() { scrollView.setContentOffset(CGPoint(x: 0, y: -view.maximumHeight), animated: false) view.trackingScrollDidScroll() XCTAssertEqual(beforeFrame, view.frame) } func testFirstChangeDoesNothingPositive() { scrollView.setContentOffset(CGPoint(x: 0, y: 200), animated: false) view.trackingScrollDidScroll() XCTAssertEqual(beforeFrame, view.frame) } // MARK: Expansion on scroll to top. func testFullyExpandedOnScrollToTop() { view.trackingScrollDidScroll() view.maximumHeight = 200 scrollView.setContentOffset(CGPoint(x: 0, y: -view.maximumHeight), animated: false) view.trackingScrollDidScroll() XCTAssertEqual(view.frame.size.height, view.maximumHeight) } }
apache-2.0
6e5ecce40be8bdb16897dc0626a9a0a8
29.280488
97
0.739428
4.514545
false
true
false
false
everald/JetPack
Sources/UI/PartialSize.swift
1
2124
import CoreGraphics public struct PartialSize: CustomDebugStringConvertible, Hashable { public var height: CGFloat? public var width: CGFloat? public init(width: CGFloat? = nil, height: CGFloat? = nil) { self.height = height self.width = width } public init(square: CGFloat?) { self.height = square self.width = square } public var debugDescription: String { return "(\(width?.description ?? "nil"), \(height?.description ?? "nil"))" } public var hashValue: Int { return (height?.hashValue ?? 0) ^ (width?.hashValue ?? 0) } public func toSize() -> CGSize? { guard let height = height, let width = width else { return nil } return CGSize(width: width, height: height) } public static func == (a: PartialSize, b: PartialSize) -> Bool { return a.height == b.height && a.width == b.width } } extension CGSize { public func coerced(atLeast minimum: PartialSize) -> CGSize { var coercedSize = self if let minimumWidth = minimum.width { coercedSize.width = coercedSize.width.coerced(atLeast: minimumWidth) } if let minimumHeight = minimum.height { coercedSize.height = coercedSize.height.coerced(atLeast: minimumHeight) } return coercedSize } public func coerced(atMost maximum: PartialSize) -> CGSize { var coercedSize = self if let maximumWidth = maximum.width { coercedSize.width = coercedSize.width.coerced(atMost: maximumWidth) } if let maximumHeight = maximum.height { coercedSize.height = coercedSize.height.coerced(atMost: maximumHeight) } return coercedSize } public func coerced(atLeast minimum: PartialSize, atMost maximum: PartialSize) -> CGSize { return coerced(atMost: maximum).coerced(atLeast: minimum) } public func coerced(atLeast minimum: CGSize, atMost maximum: PartialSize) -> CGSize { return coerced(atMost: maximum).coerced(atLeast: minimum) } public func coerced(atLeast minimum: PartialSize, atMost maximum: CGSize) -> CGSize { return coerced(atMost: maximum).coerced(atLeast: minimum) } public func toPartial() -> PartialSize { return PartialSize(width: width, height: height) } }
mit
3c67f4204ab46564aaf0cbb86929c010
21.595745
91
0.710452
3.668394
false
false
false
false
ta2yak/FloatLabelFields
FloatLabelFields/FloatLabelTextField.swift
1
4944
// // FloatLabelTextField.swift // FloatLabelFields // // Created by Fahim Farook on 28/11/14. // Copyright (c) 2014 RookSoft Ltd. All rights reserved. // // Original Concept by Matt D. Smith // http://dribbble.com/shots/1254439--GIF-Mobile-Form-Interaction?list=users // // Objective-C version by Jared Verdi // https://github.com/jverdi/JVFloatLabeledTextField // import UIKit @IBDesignable class FloatLabelTextField: UITextField { let animationDuration = 0.3 var title = UILabel() // MARK:- Properties override var accessibilityLabel:String! { get { if text.isEmpty { return title.text } else { return text } } set { self.accessibilityLabel = newValue } } override var placeholder:String? { didSet { title.text = placeholder title.sizeToFit() } } override var attributedPlaceholder:NSAttributedString? { didSet { title.text = attributedPlaceholder?.string title.sizeToFit() } } var titleFont:UIFont = UIFont.systemFontOfSize(12.0) { didSet { title.font = titleFont title.sizeToFit() } } @IBInspectable var hintYPadding:CGFloat = 0.0 @IBInspectable var titleYPadding:CGFloat = 0.0 { didSet { var r = title.frame r.origin.y = titleYPadding title.frame = r } } @IBInspectable var titleTextColour:UIColor = UIColor.grayColor() { didSet { if !isFirstResponder() { title.textColor = titleTextColour } } } @IBInspectable var titleActiveTextColour:UIColor! { didSet { if isFirstResponder() { title.textColor = titleActiveTextColour } } } // MARK:- Init required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) setup() } override init(frame:CGRect) { super.init(frame:frame) setup() } // MARK:- Overrides override func layoutSubviews() { super.layoutSubviews() setTitlePositionForTextAlignment() let isResp = isFirstResponder() if isResp && !text.isEmpty { title.textColor = titleActiveTextColour } else { title.textColor = titleTextColour } // Should we show or hide the title label? if text.isEmpty { // Hide hideTitle(isResp) } else { // Show showTitle(isResp) } } override func textRectForBounds(bounds:CGRect) -> CGRect { var r = super.textRectForBounds(bounds) if !text.isEmpty { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top, 0.0, 0.0, 0.0)) } return CGRectIntegral(r) } override func editingRectForBounds(bounds:CGRect) -> CGRect { var r = super.editingRectForBounds(bounds) if !text.isEmpty { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top, 0.0, 0.0, 0.0)) } return CGRectIntegral(r) } override func clearButtonRectForBounds(bounds:CGRect) -> CGRect { var r = super.clearButtonRectForBounds(bounds) if !text.isEmpty { var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = CGRect(x:r.origin.x, y:r.origin.y + (top * 0.5), width:r.size.width, height:r.size.height) } return CGRectIntegral(r) } // MARK:- Public Methods // MARK:- Private Methods private func setup() { borderStyle = UITextBorderStyle.None titleActiveTextColour = tintColor // Set up title label title.alpha = 0.0 title.font = titleFont title.textColor = titleTextColour if let str = placeholder { if !str.isEmpty { title.text = str title.sizeToFit() } } self.addSubview(title) } private func maxTopInset()->CGFloat { return max(0, floor(bounds.size.height - font.lineHeight - 4.0)) } private func setTitlePositionForTextAlignment() { var r = textRectForBounds(bounds) var x = r.origin.x if textAlignment == NSTextAlignment.Center { x = r.origin.x + (r.size.width * 0.5) - title.frame.size.width } else if textAlignment == NSTextAlignment.Right { x = r.origin.x + r.size.width - title.frame.size.width } title.frame = CGRect(x:x, y:title.frame.origin.y, width:title.frame.size.width, height:title.frame.size.height) } private func showTitle(animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animateWithDuration(dur, delay:0, options: UIViewAnimationOptions.BeginFromCurrentState|UIViewAnimationOptions.CurveEaseOut, animations:{ // Animation self.title.alpha = 1.0 var r = self.title.frame r.origin.y = self.titleYPadding self.title.frame = r }, completion:nil) } private func hideTitle(animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animateWithDuration(dur, delay:0, options: UIViewAnimationOptions.BeginFromCurrentState|UIViewAnimationOptions.CurveEaseIn, animations:{ // Animation self.title.alpha = 0.0 var r = self.title.frame r.origin.y = self.title.font.lineHeight + self.hintYPadding self.title.frame = r }, completion:nil) } }
mit
b25ffbd45f739eb9a1a3048e32e9a4ba
23.969697
146
0.696197
3.349593
false
false
false
false
armendo/CP-W3Lab
GithubDemo/GithubRepo.swift
1
3254
// // GithubRepo.swift // GithubDemo // // Created by Nhan Nguyen on 5/12/15. // Copyright (c) 2015 codepath. All rights reserved. // import Foundation import AFNetworking private let reposUrl = "https://api.github.com/search/repositories" private let clientId: String? = nil private let clientSecret: String? = nil // Model class that represents a GitHub repository class GithubRepo: CustomStringConvertible { var name: String? var ownerHandle: String? var ownerAvatarURL: String? var stars: Int? var forks: Int? var repoDescription: String? // Initializes a GitHubRepo from a JSON dictionary init(jsonResult: NSDictionary) { if let name = jsonResult["name"] as? String { self.name = name } if let stars = jsonResult["stargazers_count"] as? Int? { self.stars = stars } if let forks = jsonResult["forks_count"] as? Int? { self.forks = forks } if let owner = jsonResult["owner"] as? NSDictionary { if let ownerHandle = owner["login"] as? String { self.ownerHandle = ownerHandle } if let ownerAvatarURL = owner["avatar_url"] as? String { self.ownerAvatarURL = ownerAvatarURL } } if let repoDescription = jsonResult["description"] as? String?{ self.repoDescription = repoDescription } } // Actually fetch the list of repositories from the GitHub API. // Calls successCallback(...) if the request is successful class func fetchRepos(settings: GithubRepoSearchSettings, successCallback: ([GithubRepo]) -> Void, error: ((NSError?) -> Void)?) { let manager = AFHTTPRequestOperationManager() let params = queryParamsWithSettings(settings); manager.GET(reposUrl, parameters: params, success: { (operation ,responseObject) -> Void in if let results = responseObject["items"] as? NSArray { var repos: [GithubRepo] = [] for result in results as! [NSDictionary] { repos.append(GithubRepo(jsonResult: result)) } successCallback(repos) } }, failure: { (operation, requestError) -> Void in if let errorCallback = error { errorCallback(requestError) } }) } // Helper method that constructs a dictionary of the query parameters used in the request to the // GitHub API private class func queryParamsWithSettings(settings: GithubRepoSearchSettings) -> [String: String] { var params: [String:String] = [:]; if let clientId = clientId { params["client_id"] = clientId; } if let clientSecret = clientSecret { params["client_secret"] = clientSecret; } var q = ""; if let searchString = settings.searchString { q = q + searchString; } q = q + " stars:>\(settings.minStars)"; params["q"] = q; params["sort"] = "stars"; params["order"] = "desc"; return params; } // Creates a text representation of a GitHub repo var description: String { return "[Name: \(self.name!)]" + "\n\t[Stars: \(self.stars!)]" + "\n\t[Forks: \(self.forks!)]" + "\n\t[Owner: \(self.ownerHandle!)]" + "\n\t[Description: \(self.repoDescription!)]" + "\n\t[Avatar: \(self.ownerAvatarURL!)]" } }
apache-2.0
0dbcd8233cd5ce8361c4fe882d2c2c56
28.862385
132
0.633682
4.220493
false
false
false
false
1457792186/JWSwift
熊猫TV2/Pods/Kingfisher/Sources/AnimatedImageView.swift
39
12340
// // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2014-2016 Reda Lemeden. // // 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. // // The name and characters used in the demo of this software are property of their // respective owners. import UIKit import ImageIO /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image. open class AnimatedImageView: UIImageView { /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrame() } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is true. public var autoPlayAnimatedImage = true /// The size of the frame cache. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true. public var needsPrescaling = true /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling. public var runLoopMode = RunLoopMode.commonModes { willSet { if runLoopMode == newValue { return } else { stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } } // MARK: - Private property /// `Animator` instance that holds the frames of a specific image in memory. private var animator: Animator? /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D private var isDisplayLinkInitialized: Bool = false /// A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { self.isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: self.runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: Image? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { if self.isAnimating { return } else { displayLink.isPaused = false } } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { if let currentFrame = animator?.currentFrame { layer.contents = currentFrame.cgImage } else { layer.contents = image?.cgImage } } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular UIImageView to show GIF. override func shouldPreloadAllGIF() -> Bool { return false } // MARK: - Private method /// Reset the animator. private func reset() { animator = nil if let imageSource = image?.kf.imageSource?.imageRef { animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount) animator?.needsPrescaling = needsPrescaling animator?.prepareFramesAsynchronously() } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrame() { if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false { layer.setNeedsDisplay() } } } /// Keeps a reference to an `Image` instance and its duration as a GIF frame. struct AnimatedFrame { var image: Image? let duration: TimeInterval static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0) } // MARK: - Animator class Animator { // MARK: Private property fileprivate let size: CGSize fileprivate let maxFrameCount: Int fileprivate let imageSource: CGImageSource fileprivate var animatedFrames = [AnimatedFrame]() fileprivate let maxTimeStep: TimeInterval = 1.0 fileprivate var frameCount = 0 fileprivate var currentFrameIndex = 0 fileprivate var currentPreloadIndex = 0 fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0 fileprivate var needsPrescaling = true /// Loop count of animatd image. private var loopCount = 0 var currentFrame: UIImage? { return frame(at: currentFrameIndex) } var contentMode = UIViewContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /** Init an animator with image source reference. - parameter imageSource: The reference of animated image. - parameter contentMode: Content mode of AnimatedImageView. - parameter size: Size of AnimatedImageView. - parameter framePreloadCount: Frame cache size. - returns: The animator object. */ init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) { self.imageSource = source self.contentMode = mode self.size = size self.maxFrameCount = count } func frame(at index: Int) -> Image? { return animatedFrames[safe: index]?.image } func prepareFramesAsynchronously() { preloadQueue.async { [weak self] in self?.prepareFrames() } } private func prepareFrames() { frameCount = CGImageSourceGetCount(imageSource) if let properties = CGImageSourceCopyProperties(imageSource, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary, let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int { self.loopCount = loopCount } let frameToProcess = min(frameCount, maxFrameCount) animatedFrames.reserveCapacity(frameToProcess) animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))} } private func prepareFrame(at index: Int) -> AnimatedFrame { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { return AnimatedFrame.null } let frameDuration = imageSource.kf.gifProperties(at: index).flatMap { gifInfo -> Double? in let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double? let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double? let duration = unclampedDelayTime ?? delayTime ?? 0.0 /** http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp Many annoying ads specify a 0 duration to make an image flash as quickly as possible. We follow Safari and Firefox's behavior and use a duration of 100 ms for any frames that specify a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser. */ return duration > 0.011 ? duration : 0.100 } let image = Image(cgImage: imageRef) let scaledImage: Image? if needsPrescaling { scaledImage = image.kf.resize(to: size, for: contentMode) } else { scaledImage = image } return AnimatedFrame(image: scaledImage, duration: frameDuration ?? 0.0) } /** Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`. */ func updateCurrentFrame(duration: CFTimeInterval) -> Bool { timeSinceLastFrameChange += min(maxTimeStep, duration) guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else { return false } timeSinceLastFrameChange -= frameDuration let lastFrameIndex = currentFrameIndex currentFrameIndex += 1 currentFrameIndex = currentFrameIndex % animatedFrames.count if animatedFrames.count < frameCount { preloadFrameAsynchronously(at: lastFrameIndex) } return true } private func preloadFrameAsynchronously(at index: Int) { preloadQueue.async { [weak self] in self?.preloadFrame(at: index) } } private func preloadFrame(at index: Int) { animatedFrames[index] = prepareFrame(at: currentPreloadIndex) currentPreloadIndex += 1 currentPreloadIndex = currentPreloadIndex % frameCount } } extension CGImageSource: KingfisherCompatible { } extension Kingfisher where Base: CGImageSource { func gifProperties(at index: Int) -> [String: Double]? { let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary? return properties?[kCGImagePropertyGIFDictionary] as? [String: Double] } } extension Array { subscript(safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } private func pure<T>(_ value: T) -> [T] { return [value] }
apache-2.0
08ad5d0c0c2c83f03926b7c65135812f
34.156695
184
0.642626
5.325852
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/platform/macos/AppDelegate.swift
1
2275
// // AppDelegate.swift // Fiber2D // // Created by Andrey Volodin on 25.07.16. // Copyright © 2016 s1ddok. All rights reserved. // import Cocoa import SwiftBGFX class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow! var director: Director! var renderer: Renderer! func applicationDidFinishLaunching(_ aNotification: Notification) { Setup.shared.contentScale = 2.0 //;2*[_view convertSizeToBacking:NSMakeSize(1, 1)].width; Setup.shared.assetScale = Setup.shared.contentScale Setup.shared.UIScale = 0.5 let rect: CGRect = CGRect(x: 0, y: 0, width: 1024, height: 768) window = NSWindow(contentRect: rect, styleMask: [NSClosableWindowMask, NSResizableWindowMask, NSTitledWindowMask], backing: .buffered, defer: false, screen: NSScreen.main()) let view: MetalView = MetalView(frame: rect) view.wantsBestResolutionOpenGLSurface = true self.window.contentView = view let locator = FileLocator.shared locator.untaggedContentScale = 4 locator.searchPaths = [ Bundle.main.resourcePath!, Bundle.main.resourcePath! + "/Resources" ] window.center() window.makeFirstResponder(view) window.makeKeyAndOrderFront(window) var pd = PlatformData() pd.nwh = UnsafeMutableRawPointer(Unmanaged.passRetained(view).toOpaque()) pd.context = UnsafeMutableRawPointer(Unmanaged.passRetained(view.device!).toOpaque()) bgfx.setPlatformData(pd) bgfx.renderFrame() bgfx.initialize(type: .metal) bgfx.reset(width: 1024, height: 768, options: [.vsync, .flipAfterRender]) //bgfx.renderFrame() self.window.acceptsMouseMovedEvents = true let director: Director = view.director // director = Director(view: self) Director.pushCurrentDirector(director) director.present(scene: MainScene(size: director.designSize)) //director.present(scene: ViewportScene(size: director.designSize)) Director.popCurrentDirector() } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
apache-2.0
d8afd49807fed63eb928fcdbd936836c
35.095238
181
0.664028
4.450098
false
false
false
false
wleofeng/UpChallenge
UpChallenge/UpChallenge/Lyric.swift
1
621
// // Lyric.swift // UpChallenge // // Created by Wo Jun Feng on 3/28/17. // Copyright © 2017 wojunfeng. All rights reserved. // import Foundation class Lyric { /* utterance.rate = 0.3 // Range 0.0 - 1.0, default is 0.5 utterance.pitchMultiplier = 1.5 // [0.5 - 2] Default = 1 utterance.volume = 1 // [0-1] Default = 1 */ var time: Int = 0 var lyric: String = "" var rate: Float = 0.5 var pitchMultiplier: Float = 1.0 var volume: Float = 1.0 init() {} init(time: Int, lyric: String) { self.time = time self.lyric = lyric } }
mit
f62a4779818f983c44ded1098dc95429
19
61
0.55
3.163265
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Extensions/ExtensionArray.swift
1
652
// // ExtensionArray.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2019 Erik Berglund. All rights reserved. // import Foundation extension Array { // https://stackoverflow.com/a/50835467 mutating func remove(at indexes: IndexSet) { guard var i = indexes.first, i < count else { return } var j = index(after: i) var k = indexes.integerGreaterThan(i) ?? endIndex while j != endIndex { if k != j { swapAt(i, j); formIndex(after: &i) } else { k = indexes.integerGreaterThan(k) ?? endIndex } formIndex(after: &j) } removeSubrange(i...) } }
mit
1e99a0c8d8811a416552cba36b252d4b
26.125
115
0.600614
3.829412
false
false
false
false
niunaruto/DeDaoAppSwift
DeDaoSwift/DeDaoSwift/Home/Model/DDHomeModel.swift
1
2762
// // DDHomeModel.swift // DeDaoSwift // // Created by niuting on 2017/3/6. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit import ObjectMapper class DDHomeDataModel: Mappable { var slider : DDHomeSliderModel? var category : DDHomeSliderModel? var freeAudio : DDHomeFreeAudioModel? var column : DDHomeColumnModel? var storytell : DDHomeStorytellModel? var magazine : DDHomeStorytellModel? var new : DDHomeSliderModel? var subject : DDHomeSubjectModel? var verse : DDHomeVerseModel? var dataMiningAduioOrBook : DDHomeSliderModel? var freecolumn : DDHomeVerseModel? var live : DDHomeLiveModel? required init?(map : Map) { } func mapping(map:Map) { slider <- map["slider"] category <- map["category"] freeAudio <- map["freeAudio"] column <- map["column"] storytell <- map["storytell"] magazine <- map["magazine"] new <- map["new"] subject <- map["subject"] verse <- map["verse"] dataMiningAduioOrBook <- map["dataMiningAduioOrBook"] freecolumn <- map["freecolumn"] live <- map["live"] } } class DDCDataModel: Mappable { var data : DDHomeDataModel? required init?(map : Map) { } func mapping(map:Map) { data <- map["data"] } } class DDHomeModel: Mappable { var c : DDCDataModel? required init?(map : Map) { } func mapping(map:Map) { c <- map["c"] } } class DDHomeLiveDataModel: Mappable { var status = 0 var online_num = 0 var reservation_num = 0 var title = "" var room_id = 0 var intro = "" var column_id = 0 required init?(map : Map) { } func mapping(map:Map) { status <- map["status"] online_num <- map["online_num"] reservation_num <- map["reservation_num"] title <- map["title"] room_id <- map["room_id"] intro <- map["intro"] column_id <- map["column_id"] } } class DDHomeLiveModel: Mappable { var data : DDHomeLiveDataModel? required init?(map : Map) { } func mapping(map:Map) { data <- map["data"] } }
mit
edb1632cd7af131e4b49965f50620ea7
20.223077
68
0.47046
4.33124
false
false
false
false
nguyenantinhbk77/practice-swift
Views/ScrollViews/ScrollViews/ScrollViews/PeekPagedScrollViewController.swift
2
3792
// // PeekPagedScrollViewController.swift // ScrollViews // // Created by Domenico on 06/06/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit class PeekPagedScrollViewController: UIViewController { @IBOutlet var scrollView: UIScrollView! @IBOutlet var pageControl: UIPageControl! var pageImages: [UIImage] = [] var pageViews: [UIImageView?] = [] override func viewDidLoad() { super.viewDidLoad() // Set up the image you want to scroll & zoom and add it to the scroll view pageImages = [UIImage(named: "photo1.png")!, UIImage(named: "photo2.png")!, UIImage(named: "photo3.png")!, UIImage(named: "photo4.png")!, UIImage(named: "photo5.png")!] let pageCount = pageImages.count // Set up the page control pageControl.currentPage = 0 pageControl.numberOfPages = pageCount // Set up the array to hold the views for each page for _ in 0..<pageCount { pageViews.append(nil) } // Set up the content size of the scroll view let pagesScrollViewSize = scrollView.frame.size scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(pageImages.count), pagesScrollViewSize.height) // Load the initial set of pages that are on screen loadVisiblePages() } func loadVisiblePages() { // First, determine which page is currently visible let pageWidth = scrollView.frame.size.width let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0))) // Update the page control pageControl.currentPage = page // Work out which pages you want to load let firstPage = page - 1 let lastPage = page + 1 // Purge anything before the first page for var index = 0; index < firstPage; ++index { purgePage(index) } // Load pages in our range for index in firstPage...lastPage { loadPage(index) } // Purge anything after the last page for var index = lastPage+1; index < pageImages.count; ++index { purgePage(index) } } func loadPage(page: Int) { if page < 0 || page >= pageImages.count { // If it's outside the range of what you have to display, then do nothing return } // Load an individual page, first checking if you've already loaded it if let pageView = pageViews[page] { // Do nothing. The view is already loaded. } else { var frame = scrollView.bounds frame.origin.x = frame.size.width * CGFloat(page) frame.origin.y = 0.0 frame = CGRectInset(frame, 10.0, 0.0) let newPageView = UIImageView(image: pageImages[page]) newPageView.contentMode = .ScaleAspectFit newPageView.frame = frame scrollView.addSubview(newPageView) pageViews[page] = newPageView } } func purgePage(page: Int) { if page < 0 || page >= pageImages.count { // If it's outside the range of what you have to display, then do nothing return } // Remove a page from the scroll view and reset the container array if let pageView = pageViews[page] { pageView.removeFromSuperview() pageViews[page] = nil } } func scrollViewDidScroll(scrollView: UIScrollView!) { // Load the pages that are now on screen loadVisiblePages() } }
mit
dda5a31df24505eb7eb81651f8085116
31.973913
126
0.575949
4.976378
false
false
false
false
automationWisdri/WISData.JunZheng
WISData.JunZheng/ViewModel/DataTableViewModel.swift
1
1323
// // FurnaceViewModel.swift // WISData.JunZheng // // Created by Jingwei Wu on 9/2/16. // Copyright © 2016 Wisdri. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxDataSources import RxSwift import RxCocoa #endif class DataTableViewModel: ViewModel { weak var tableView: DataTableView! var headerString: String = EMPTY_STRING var titleArray: [String] = [] var headerStringSubject: BehaviorSubject<String> = BehaviorSubject(value: EMPTY_STRING) var titleArraySubject: BehaviorSubject<[String]> = BehaviorSubject(value: []) let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>() init(sourceTableView: DataTableView) { super.init() tableView = sourceTableView // use local variable to avoid reference cycle. let dataSource = self.dataSource let tableViewItems = Observable.combineLatest(headerStringSubject, titleArraySubject) {headerString, titleArray in return [SectionModel(model: headerString, items: titleArray)] } tableViewItems .subscribeOn(MainScheduler.instance) .bindTo(tableView.rx_itemsWithDataSource(dataSource)) .addDisposableTo(disposeBag) } }
mit
06f547c7f00413b6c624285a0bc3bd3f
28.377778
122
0.66944
5.065134
false
false
false
false
zyrx/eidolon
Kiosk/App/Models/Artist.swift
7
625
import Foundation import SwiftyJSON class Artist: JSONAble { let id: String dynamic var name: String let sortableID: String? var blurb: String? init(id: String, name: String, sortableID: String?) { self.id = id self.name = name self.sortableID = sortableID } override class func fromJSON(json:[String: AnyObject]) -> JSONAble { let json = JSON(json) let id = json["id"].stringValue let name = json["name"].stringValue let sortableID = json["sortable_id"].string return Artist(id: id, name:name, sortableID:sortableID) } }
mit
5ab398fdb14baaefd72e752f604f30db
22.148148
72
0.6224
4.111842
false
false
false
false
tiger8888/LayerPlayer
LayerPlayer/TilingViewForImage.swift
3
1731
// // TilingViewForImage.swift // LayerPlayer // // Created by Scott Gardner on 7/27/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit let sideLength: CGFloat = 640.0 let fileName = "windingRoad" class TilingViewForImage: UIView { let sideLength = CGFloat(640.0) let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String override class func layerClass() -> AnyClass { return TiledLayer.self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let layer = self.layer as TiledLayer layer.contentsScale = UIScreen.mainScreen().scale layer.tileSize = CGSize(width: sideLength, height: sideLength) } override func drawRect(rect: CGRect) { let firstColumn = Int(CGRectGetMinX(rect) / sideLength) let lastColumn = Int(CGRectGetMaxX(rect) / sideLength) let firstRow = Int(CGRectGetMinY(rect) / sideLength) let lastRow = Int(CGRectGetMaxY(rect) / sideLength) for row in firstRow...lastRow { for column in firstColumn...lastColumn { if let tile = imageForTileAtColumn(column, row: row) { let x = sideLength * CGFloat(column) let y = sideLength * CGFloat(row) let point = CGPoint(x: x, y: y) let size = CGSize(width: sideLength, height: sideLength) var tileRect = CGRect(origin: point, size: size) tileRect = CGRectIntersection(bounds, tileRect) tile.drawInRect(tileRect) } } } } func imageForTileAtColumn(column: Int, row: Int) -> UIImage? { let filePath = "\(cachesPath)/\(fileName)_\(column)_\(row)" return UIImage(contentsOfFile: filePath) } }
mit
880e611c99310057944d05424bacb8d7
29.910714
108
0.669555
4.082547
false
false
false
false
smud/Smud
Sources/Smud/Config.swift
1
1354
// // Config.swift // // This source file is part of the SMUD open source project // // Copyright (c) 2016 SMUD project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SMUD project authors // import Foundation open class Config { // Database public var databaseUpdateInterval = 15.0 public var databaseUpdateLeeway: DispatchTimeInterval? = nil // Networking public var port: UInt16 = 4000 public var maximumLineLengthBytes = 1024 // Directories public var areasDirectory = "Data/Areas" public var areaFileExtensions = ["smud", "area", "rooms", "mobiles", "items"] public var accountsDirectory = "Live/Accounts" public var playersDirectory = "Live/Players" // Character naming public var playerNameLength = 2...16 public var playerNameAllowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz") public var playerNameInvalidCharactersMessage = "Name contains invalid characters. Allowed characters: a-z" public var internalErrorMessage = "An internal error has occured, the developers have been notified. If the error persists, please contact the support." // Game constants public var combatRoundInterval: DispatchTimeInterval = .seconds(6) }
apache-2.0
9f57b55eb903f7c52fcfadb54d62f183
33.717949
157
0.74003
4.668966
false
true
false
false
budbee/SelfieKit
SelfieKit/Classes/ButtonPicker.swift
1
1317
// // ButtonPicker.swift // SelfieKit // // Created by Axel Möller on 28/04/16. // Copyright © 2016 Budbee AB. All rights reserved. // import UIKit protocol ButtonPickerDelegate: class { func buttonDidPress() } class ButtonPicker: UIButton { struct Dimensions { static let borderWidth: CGFloat = 2 static let buttonSize: CGFloat = 58 static let buttonBorderSize: CGFloat = 68 } weak var delegate: ButtonPickerDelegate? override init(frame: CGRect) { super.init(frame: frame) setupButton() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupButton() { backgroundColor = .white layer.cornerRadius = Dimensions.buttonSize / 2 addTarget(self, action: #selector(ButtonPicker.pickerButtonDidPress(_:)), for: .touchUpInside) addTarget(self, action: #selector(ButtonPicker.pickerButtonDidHighlight(_:)), for: .touchDown) } func pickerButtonDidPress(_ button: UIButton) { backgroundColor = .white delegate?.buttonDidPress() } func pickerButtonDidHighlight(_ button: UIButton) { backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1) } }
mit
705252a04667eb42506b2a554ab23478
24.784314
102
0.634981
4.457627
false
false
false
false
bastienFalcou/FindMyContacts
ContactSyncing/Models/Sync/PhoneContact+Sync.swift
1
631
// // PhoneContact+Sync.swift // FindMyContacts // // Created by Bastien Falcou on 1/12/17. // Copyright © 2017 Bastien Falcou. All rights reserved. // import Foundation import RealmSwift extension PhoneContact: SyncProtocol { static func uniqueObject(for id: Any, in realm: Realm?) -> PhoneContact { let identifier: String = id as! String let realm = realm ?? RealmManager.shared.realm if let existingObject = realm.object(ofType: PhoneContact.self, forPrimaryKey: identifier) { return existingObject } else { let newObject = PhoneContact() newObject.identifier = identifier return newObject } } }
mit
9f4cfb7c7b03cc9d6ace5b18ed57b494
24.2
94
0.726984
3.62069
false
false
false
false
slavapestov/swift
test/Misc/misc_diagnostics.swift
1
5657
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop import Foundation import CoreGraphics var roomName : String? = nil if let realRoomName = roomName as! NSString { // expected-error {{initializer for conditional binding must have Optional type, not 'NSString'}} expected-warning {{cast from 'String?' to unrelated type 'NSString' always fails}} } var pi = 3.14159265358979 var d: CGFloat = 2.0 var dpi:CGFloat = d*pi // expected-error{{cannot convert value of type 'Double' to expected argument type 'CGFloat'}} let ff: CGFloat = floorf(20.0) // expected-error{{cannot convert value of type 'Float' to specified type 'CGFloat'}} let total = 15.0 let count = 7 let median = total / count // expected-error {{binary operator '/' cannot be applied to operands of type 'Double' and 'Int'}} expected-note {{overloads for '/' exist with these partially matching parameter lists: (Int, Int), (Double, Double)}} if (1) {} // expected-error{{type 'Int' does not conform to protocol 'BooleanType'}} if 1 {} // expected-error {{type 'Int' does not conform to protocol 'BooleanType'}} var a: [String] = [1] // expected-error{{cannot convert value of type 'Int' to expected element type 'String'}} var b: Int = [1, 2, 3] // expected-error{{contextual type 'Int' cannot be used with array literal}} var f1: Float = 2.0 var f2: Float = 3.0 var dd: Double = f1 - f2 // expected-error{{cannot convert value of type 'Float' to expected argument type 'Double'}} func f() -> Bool { return 1 + 1 // expected-error{{no '+' candidates produce the expected contextual result type 'Bool'}} // expected-note @-1 {{overloads for '+' exist with these result types: UInt8, Int8, UInt16, Int16, UInt32, Int32, UInt64, Int64, UInt, Int, Float, Double}} } // Test that nested diagnostics are properly surfaced. func takesInt(i: Int) {} func noParams() -> Int { return 0 } func takesAndReturnsInt(i: Int) -> Int { return 0 } takesInt(noParams(1)) // expected-error{{argument passed to call that takes no arguments}} takesInt(takesAndReturnsInt("")) // expected-error{{cannot convert value of type 'String' to expected argument type 'Int'}} // Test error recovery for type expressions. struct MyArray<Element> {} class A { var a: MyArray<Int> init() { a = MyArray<Int // expected-error{{no '<' candidates produce the expected contextual result type 'MyArray<Int>'}} // expected-note @-1 {{produces result of type 'Bool'}} } } func retV() { return true } // expected-error {{unexpected non-void return value in void function}} func retAI() -> Int { let a = [""] let b = [""] return (a + b) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}} } func bad_return1() { return 42 // expected-error {{unexpected non-void return value in void function}} } func bad_return2() -> (Int, Int) { return 42 // expected-error {{cannot convert return expression of type 'Int' to return type '(Int, Int)'}} } // <rdar://problem/14096697> QoI: Diagnostics for trying to return values from void functions func bad_return3(lhs:Int, rhs:Int) { return lhs != 0 // expected-error {{no '!=' candidates produce the expected contextual result type '()'}} // expected-note @-1 {{produces result of type 'Bool'}} } class MyBadReturnClass { static var intProperty = 42 } func ==(lhs:MyBadReturnClass, rhs:MyBadReturnClass) { return MyBadReturnClass.intProperty == MyBadReturnClass.intProperty // expected-error {{cannot convert value of type 'Int' to expected argument type 'MyBadReturnClass'}} } func testIS1() -> Int { return 0 } let _: String = testIS1() // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} func insertA<T>(inout array : [T], elt : T) { array.append(T); // expected-error {{cannot invoke 'append' with an argument list of type '((T).Type)'}} expected-note {{expected an argument list of type '(T)'}} } // <rdar://problem/17875634> can't append to array of tuples func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 var coord = (row, col) match += (1, 2) // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} // expected-note @-1 {{overloads for '+=' exist with these partially matching parameter lists:}} match += (row, col) // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} // expected-note @-1 {{overloads for '+=' exist with these partially matching parameter lists:}} match += coord // expected-error{{binary operator '+=' cannot be applied to operands of type '[(Int, Int)]' and '(Int, Int)'}} // expected-note @-1 {{overloads for '+=' exist with these partially matching parameter lists:}} match.append(row, col) // expected-error{{extra argument in call}} match.append(1, 2) // expected-error{{extra argument in call}} match.append(coord) match.append((1, 2)) // Make sure the behavior matches the non-generic case. struct FakeNonGenericArray { func append(p: (Int, Int)) {} } let a2 = FakeNonGenericArray() a2.append(row, col) // expected-error{{extra argument in call}} a2.append(1, 2) // expected-error{{extra argument in call}} a2.append(coord) a2.append((1, 2)) } // <rdar://problem/20770032> Pattern matching ranges against tuples crashes the compiler func test20770032() { if case let 1...10 = (1, 1) { // expected-warning{{'let' pattern has no effect; sub-pattern didn't bind any variables}} {{11-15=}} expected-error{{expression pattern of type 'Range<Int>' cannot match values of type '(Int, Int)'}} } }
apache-2.0
1bba031b4c4796300a2ffb83bf4ffb99
40.903704
243
0.686053
3.680547
false
false
false
false
JasonPan/ADSSocialFeedScrollView
ADSSocialFeedScrollView/Providers/Facebook/Data/FacebookPage.swift
1
5683
// // FacebookPage.swift // ADSSocialFeedScrollView // // Created by Jason Pan on 13/02/2016. // Copyright © 2016 ANT Development Studios. All rights reserved. // import UIKit import FBSDKCoreKit class FacebookPage: PostCollectionProtocol { private(set) var id : String! private(set) var name : String! private(set) var profilePhotoURL : String! private(set) var coverPhotoURL : String! var feed : Array<FacebookPost>! //********************************************************************************************************* // MARK: - Constructors //********************************************************************************************************* init(id: String) { self.id = id } //********************************************************************************************************* // MARK: - Data retrievers //********************************************************************************************************* func fetchProfileInfoInBackgroundWithCompletionHandler(block: (() -> Void)?) { //SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug? dispatch_async(dispatch_get_main_queue(), { FBSDKGraphRequest.init(graphPath: self.id, parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "name, picture, cover"]).startWithCompletionHandler({ connection, result, error in if error == nil { if let dictionary = result as? Dictionary<String, AnyObject> { let name = dictionary["name"] as? String let picture = dictionary["picture"]?["data"]??["url"] as? String let cover = dictionary["cover"]?["source"] as? String self.name = name self.profilePhotoURL = picture self.coverPhotoURL = cover } }else { NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching profile info: \(error?.description)"); } self.fetchPostsInBackgroundWithCompletionHandler(block) }) }) } private func fetchPostsInBackgroundWithCompletionHandler(block: (() -> Void)?) { //SIDENOTE: Facebook iOS SDK requires requests to be sent from main queue?? Bug? dispatch_async(dispatch_get_main_queue(), { FBSDKGraphRequest.init(graphPath: self.id + "/posts", parameters: ["access_token": ADSSocialFeedFacebookAccountProvider.authKey, "fields": "created_time, id, message, picture, attachments"]).startWithCompletionHandler({ connection, result, error in if error == nil { let JSON_data: Dictionary<String, AnyObject>? = result as? Dictionary<String, AnyObject> guard JSON_data != nil else { return } if let feedData_JSON: Array<Dictionary<String, AnyObject>> = JSON_data?["data"] as? Array<Dictionary<String, AnyObject>> { var feedArray: Array<FacebookPost> = Array<FacebookPost>() for dictionary in feedData_JSON { let id = dictionary["id"] as? String let created_time = dictionary["created_time"] as? String let message = dictionary["message"] as? String var picture = dictionary["picture"] as? String if let attachments = dictionary["attachments"] as? NSDictionary { if let data = attachments["data"] as? NSArray { if let media = data[0]["media"] as? NSDictionary { if let image = media["image"] { if let src = image["src"] as? String { picture = src } } } } } let facebookPost: FacebookPost = FacebookPost(id: id!, createdTime: created_time!, message: message, image: picture, owner: self) feedArray.append(facebookPost) } self.feed = feedArray } }else { NSLog("[ADSSocialFeedScrollView][Facebook] An error occurred while fetching posts: \(error?.description)"); self.feed = Array<FacebookPost>() } block?() }) }) } //********************************************************************************************************* // MARK: - PostCollectionProtocol //********************************************************************************************************* var postItems: [PostProtocol]? { // See: https://stackoverflow.com/a/30101004/699963 return self.feed.map({ $0 as PostProtocol }) } }
mit
f2ea63c47b13a7e1d3603cb7b79ef02a
46.35
231
0.421331
6.53855
false
false
false
false
roehrdor/diagnoseit-ios-mobile-agent
DataSerializer.swift
1
6033
/* Copyright (c) 2017 Oliver Roehrdanz Copyright (c) 2017 Matteo Sassano Copyright (c) 2017 Christopher Voelker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import CoreLocation class DataSerializer { var metricsJsonData : String! var spans : [UInt64 : [[String : Any]]] init() { spans = [UInt64 : [[String : Any]]]() } func serializeSpan(_ span : Span) { if let uc = span as? UseCase { self.serializeUsecaseSpan(uc) } else if let rc = span as? RemoteCall { self.serializeRemoteCallSpan(rc) } } func serializeUsecaseSpan(_ usecase: UseCase) { var span: [String : Any] = [String : Any]() var tags: [String : Any] = [String : Any]() var spanContext: [String : Any] = [String : Any]() span["operationName"] = usecase.name span["startTimeMicros"] = usecase.beginTime span["duration"] = usecase.duration tags["span.kind"] = "client" tags["ext.propagation.type"] = "IOS" span["tags"] = tags spanContext["id"] = usecase.id spanContext["traceId"] = usecase.traceid spanContext["parentId"] = usecase.parentid span["spanContext"] = spanContext if spans[usecase.traceid] == nil { spans[usecase.traceid] = [[String : Any]]() } spans[usecase.traceid]?.append(span) } func serializeRemoteCallSpan(_ remotecall: RemoteCall) { var span: [String : Any] = [String : Any]() var tags: [String : Any] = [String : Any]() var spanContext: [String : Any] = [String : Any]() span["operationName"] = remotecall.name span["startTimeMicros"] = remotecall.beginTime span["duration"] = remotecall.duration tags["http.url"] = remotecall.url tags["http.request.networkConnection"] = remotecall.beginConnection tags["http.request.latitude"] = remotecall.beginLatitude tags["http.request.longitude"] = remotecall.beginLongitude tags["http.request.ssid"] = remotecall.beginSSID tags["http.request.networkProvider"] = remotecall.beginProvider tags["http.request.responseCode"] = remotecall.responseCode tags["http.request.timeout"] = remotecall.timeout tags["http.response.networkConnection"] = remotecall.endConnection tags["http.response.latitude"] = remotecall.endLatitude tags["http.response.longitude"] = remotecall.endLongitude tags["http.response.ssid"] = remotecall.endSSID tags["http.response.networkProvider"] = remotecall.endProvider tags["http.response.timeout"] = remotecall.timeout tags["ext.propagation.type"] = "HTTP" tags["span.kind"] = "client" span["tags"] = tags spanContext["id"] = remotecall.id spanContext["traceId"] = remotecall.traceid spanContext["parentId"] = remotecall.parentid span["spanContext"] = spanContext if spans[remotecall.traceid] == nil { spans[remotecall.traceid] = [[String : Any]]() } spans[remotecall.traceid]?.append(span) } func getJsonObject(_ metricsController : IntervalMetricsController, deviceID : UInt64, rootId: UInt64) -> String? { var timestampList = metricsController.timestampList var cpuList = metricsController.cpuList var powerList = metricsController.powerList var memoryList = metricsController.memoryList var diskList = metricsController.diskList var measurements = [NSMutableDictionary]() for (i, _) in timestampList.enumerated() { let measurement = NSMutableDictionary() measurement["type"] = "MobilePeriodicMeasurement" measurement["timestamp"] = timestampList[i] if i < cpuList.count { measurement["cpuUsage"] = cpuList[i] } if i < powerList.count { measurement["batteryPower"] = powerList[i] } if i < memoryList.count { measurement["memoryUsage"] = memoryList[i] } if i < diskList.count { measurement["storageUsage"] = diskList[i] } measurements.append(measurement) } var jsonObject = [String : Any]() jsonObject["deviceID"] = deviceID jsonObject["spans"] = spans[rootId] jsonObject["measurements"] = measurements do { let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions.prettyPrinted) let jsonString : String = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)! as String print(jsonString) spans[rootId] = [] return jsonString } catch { print(error) } return nil } }
mit
95a872f46f03523050a388117c019d93
40.895833
138
0.629206
4.423021
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01651-getselftypeforcontainer.swift
11
606
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse <T, i : Boolean, x } func c] = B } } } protocol P { typealias C = A(2, c] extension NSSet { class b() case s: T, V, ().B == B convenience init(t.h: ("cd"foo" protocol A : C { t.g == B<h = f, 3) class func a<d(b[se
apache-2.0
5a710e42903c072e156626bdb37f414b
26.545455
78
0.683168
3.091837
false
false
false
false