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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
coach-plus/ios | CoachPlus/app/usersettings/UserSettingsViewController.swift | 1 | 7466 | //
// UserSettingsViewController.swift
// CoachPlus
//
// Created by Breit, Maurice on 09.03.19.
// Copyright © 2019 Mathandoro GbR. All rights reserved.
//
import UIKit
import Eureka
import SkyFloatingLabelTextField
import PromiseKit
class UserSettingsViewController: CoachPlusViewController {
var user: User?
@IBOutlet weak var verificationLbl: UILabel!
@IBOutlet weak var verificationBtn: UIButton!
@IBAction func verificationBtnTapped(_ sender: Any) {
self.resendVerificationEmail()
}
@IBOutlet weak var verificationViewHeight: NSLayoutConstraint!
@IBOutlet weak var personalHeader: TableHeaderView!
@IBOutlet weak var firstnameTf: SkyFloatingLabelTextField!
@IBOutlet weak var lastnameTf: SkyFloatingLabelTextField!
@IBOutlet weak var emailTf: SkyFloatingLabelTextField!
@IBOutlet weak var savePersonalBtn: OutlineButton!
@IBAction func savePersonalTapped(_ sender: Any) {
self.checkAndSavePersonal()
}
@IBOutlet weak var changePwHeader: TableHeaderView!
@IBOutlet weak var currentPwTf: SkyFloatingLabelTextField!
@IBOutlet weak var newPwTf: SkyFloatingLabelTextField!
@IBOutlet weak var repeatPwTf: SkyFloatingLabelTextField!
@IBOutlet weak var changePwBtn: OutlineButton!
@IBAction func changePwBtnTapped(_ sender: Any) {
self.checkAndSavePassword()
}
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
self.view.backgroundColor = UIColor.defaultBackground
self.loadData(text: nil, promise: DataHandler.def.getUser()).done({user in
self.user = user
self.showUserData()
})
}
func setup() {
self.setupNavBar()
self.setupTextFields()
}
func setupVerification() {
let isVerified = self.user?.emailVerified ?? false
if (isVerified) {
self.verificationViewHeight.constant = 0
} else {
self.verificationLbl.text = L10n.youAreNotVerified
self.verificationBtn.setTitleForAllStates(title: L10n.resendEMail)
}
}
func setupNavBar() {
self.setNavbarTitle(title: L10n.userSettings)
self.setLeftBarButton(type: .done)
}
func setupTextFields() {
self.personalHeader.title = L10n.personalSettings
self.personalHeader.showBtn = false
self.firstnameTf.placeholder = L10n.firstname
self.lastnameTf.placeholder = L10n.lastname
self.emailTf.placeholder = L10n.email
self.firstnameTf.coachPlus()
self.lastnameTf.coachPlus()
self.emailTf.coachPlus()
self.firstnameTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.lastnameTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.emailTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.currentPwTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.newPwTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.repeatPwTf.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
self.savePersonalBtn.setTitleForAllStates(title: L10n.save)
self.savePersonalBtn.coachPlus()
self.changePwHeader.title = L10n.changePassword
self.changePwHeader.showBtn = false
self.currentPwTf.coachPlus()
self.newPwTf.coachPlus()
self.repeatPwTf.coachPlus()
self.currentPwTf.placeholder = L10n.oldPassword
self.newPwTf.placeholder = L10n.newPassword
self.repeatPwTf.placeholder = L10n.repeatNewPassword
self.currentPwTf.isSecureTextEntry = true
self.newPwTf.isSecureTextEntry = true
self.repeatPwTf.isSecureTextEntry = true
self.changePwBtn.setTitleForAllStates(title: L10n.changePassword)
self.changePwBtn.coachPlus()
}
@objc func textFieldDidChange(_ textField: UITextField) {
switch textField {
case self.firstnameTf, self.lastnameTf, self.emailTf:
self.checkPersonal()
break
case self.currentPwTf, self.newPwTf, self.repeatPwTf:
self.checkPassword()
break
default:
break
}
}
func showUserData() {
self.firstnameTf.text = self.user!.firstname
self.lastnameTf.text = self.user!.lastname
self.emailTf.text = self.user!.email
self.setupVerification()
self.checkPersonal()
}
func checkAndSavePersonal() {
guard (self.checkPersonal()) else {
return
}
self.loadData(text: L10n.loading, promise: DataHandler.def.updateUserInfo(firstname: self.firstnameTf.text!, lastname: self.lastnameTf.text!, email: self.emailTf.text!)).done({ user in
UserManager.storeUser(user: user)
self.user = user
UserManager.shared.userWasEdited.onNext(user)
DropdownAlert.success(message: L10n.saved)
})
}
func checkAndSavePassword() {
guard (self.checkPassword()) else {
return
}
self.loadData(text: L10n.loading, promise: DataHandler.def.changePassword(oldPassword: self.currentPwTf.text!, newPassword: self.newPwTf.text!, newPasswordRepeat: self.repeatPwTf.text!)).done({ user in
DropdownAlert.success(message: L10n.saved)
})
}
func checkPersonal() -> Bool {
let firstname = self.checkIfFieldIsFilled(self.firstnameTf)
let lastname = self.checkIfFieldIsFilled(self.lastnameTf)
let email = self.checkIfFieldContainsValidEmail(self.emailTf)
return firstname && lastname && email
}
func checkPassword() -> Bool {
let oldPw = self.checkIfFieldIsFilled(self.currentPwTf)
let newPw = self.checkIfFieldIsFilled(self.newPwTf)
let repeatPw = self.checkIfFieldIsFilled(self.repeatPwTf)
let pwsAreEqual = (repeatPw && newPw && repeatPwTf.text == newPwTf.text)
if (!pwsAreEqual) {
repeatPwTf.errorMessage = L10n.passwordsMustMatch
}
return oldPw && pwsAreEqual
}
func checkIfFieldIsFilled(_ tf: SkyFloatingLabelTextField) -> Bool {
if (tf.text != nil && tf.text!.count > 0) {
tf.errorMessage = nil
return true
} else {
tf.errorMessage = L10n.pleaseFillInThisField
return false
}
}
func checkIfFieldContainsValidEmail(_ tf: SkyFloatingLabelTextField) -> Bool {
if (self.checkIfFieldIsFilled(tf) && tf.text!.isValidEmail) {
tf.errorMessage = nil
return true
} else {
tf.errorMessage = L10n.pleaseEnterYourEmailAddress
return false
}
}
func resendVerificationEmail() {
self.loadData(text: L10n.loading, promise: DataHandler.def.resendVerificationEmail()).done({ response in
DropdownAlert.success(message: L10n.confirmationEmailSent)
})
}
}
| mit | 65262fc52ee317c3113a9ae56c02434d | 31.598253 | 209 | 0.635633 | 4.516031 | false | false | false | false |
palaunchpad/agenda | Agenda/AppDelegate.swift | 2 | 1175 | //
// AppDelegate.swift
// Agenda
//
// Created by Rudd Fawcett on 10/16/15.
// Copyright © 2015 Phillips Academy Launch Pad. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.backgroundColor = UIColor.whiteColor()
UINavigationBar.appearance().barTintColor = UIColor(red:0.19, green:0.6, blue:0.87, alpha:1)
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [
NSForegroundColorAttributeName : UIColor.whiteColor()
]
let navigationController = UINavigationController(rootViewController: AgendaViewController())
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
}
| mit | e9331a3ae59f59ab7b5ac65747e9cd3a | 30.72973 | 127 | 0.689097 | 5.460465 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos | WorldWeather/WorldWeather/AppDelegate.swift | 2 | 2585 | /*
* Copyright (c) 2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController!, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.cityWeather == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
}
| gpl-2.0 | dc226eaf0b39f60b08ff48757135b3f0 | 45.160714 | 223 | 0.772921 | 5.822072 | false | false | false | false |
eleks/rnd-nearables-wearables | iOS/BeaconMe/BeaconMe/Model/AuthentificationManager.swift | 1 | 2157 | //
// AuthentificationManager.swift
// BeaconMe
//
// Created by Bogdan Shubravyi on 7/16/15.
// Copyright (c) 2015 Eleks. All rights reserved.
//
import UIKit
class AuthentificationManager {
class var instance: AuthentificationManager
{
struct Singleton {
static let privateInstance = AuthentificationManager()
}
return Singleton.privateInstance
}
private let tokenKey = "accessToken"
private let usernameKey = "username"
init()
{
self.token = KeychainWrapper.stringForKey(tokenKey)
self.username = KeychainWrapper.stringForKey(usernameKey)
// println("token: \(token) username \(username)")
}
var token : String? = nil {
didSet {
self.setKeychainValue(token, forKey: tokenKey)
}
}
var username : String? = nil {
didSet {
self.setKeychainValue(username, forKey: usernameKey)
}
}
private func setKeychainValue(text: String?, forKey key: String)
{
if let value = text where count(value) > 0 {
KeychainWrapper.setString(value, forKey: key)
}
else {
KeychainWrapper.setString("", forKey: key)
}
}
func logInWithUsername(username: String, password: String, completion: ((Bool) -> Void))
{
if self.isLoggedIn {
completion(false)
return
}
SynchronizationService.authentificateWithUserName(username, password: password) { (parsedToken: String?) -> (Void) in
if let token = parsedToken
{
self.token = token
self.username = username
completion(true)
return
}
completion(false)
}
}
func logOut()
{
self.token = nil
self.username = nil
}
var isLoggedIn : Bool
{
get {
if let tokenValue = token {
return count(tokenValue) > 0
}
return false
}
}
}
| mit | f24bc4ca4bb2ae9ceeac11bf706d4dca | 22.703297 | 125 | 0.533611 | 4.869074 | false | false | false | false |
BronxDupaix/WaffleLuv | WaffleLuv/MyColors.swift | 1 | 1474 | //
// UIColor extension.swift
// WaffleLuv
//
// Created by Bronson Dupaix on 4/7/16.
// Copyright © 2016 Bronson Dupaix. All rights reserved.
//
import Foundation
struct MyColors{
static var getCustomPurpleColor = {
return UIColor(red:0.55, green:0.5 , blue:1.00, alpha:1.0)
}
static var getCustomCyanColor = {
return UIColor(red:1.00, green:0.93, blue:0.88, alpha:1.00)
}
static var getCustomPinkColor = {
return UIColor(red:1.0, green:0.4 ,blue:0.78 , alpha:1.00) }
static var getCustomRedColor = {
return UIColor(red:1.0, green:0.00, blue:0.00, alpha:1.00)
}
static var getCustomCreamColor = {
return UIColor(red:0.9, green:0.9, blue:1.00, alpha:1.00)
}
static var getCustomBananaColor = {
return UIColor(red:1.00, green:0.93, blue:0.50, alpha:1.00 )
}
static var getCustomBlueGreenColor = {
return UIColor(red:0.00, green:1 , blue:1 , alpha:0.75)
}
static var getCustomYellowColor = {
return UIColor(red:1.00, green:0.93, blue:0.00, alpha:1.00)
}
static var getCustomlightPurpleColor = {
return UIColor(red:0.8, green:0.18 , blue:1.00, alpha:0.6)
}
static var getCustomOrangeColor = {
return UIColor(red:1.00, green:0.66 , blue:0.00, alpha:1.00)
}
}
| apache-2.0 | 7998cca4a6fcf6a11279d81f2e84d257 | 21.661538 | 68 | 0.562118 | 3.287946 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/SavedCardToken.swift | 2 | 1693 | //
// SavedCard.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 31/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class SavedCardToken : NSObject {
public var cardId : String?
public var securityCode : String?
public var device : Device?
public var securityCodeRequired : Bool = true
public init(cardId : String, securityCode : String) {
super.init()
self.cardId = cardId
self.securityCode = securityCode
}
public init(cardId : String, securityCode : String?, securityCodeRequired: Bool) {
super.init()
self.cardId = cardId
self.securityCode = securityCode
self.securityCodeRequired = securityCodeRequired
}
public func validate() -> Bool {
return validateCardId() && (!securityCodeRequired || validateSecurityCode())
}
public func validateCardId() -> Bool {
return !String.isNullOrEmpty(cardId) && String.isDigitsOnly(cardId!)
}
public func validateSecurityCode() -> Bool {
let isEmptySecurityCode : Bool = String.isNullOrEmpty(self.securityCode)
return !isEmptySecurityCode && count(self.securityCode!) >= 3 && count(self.securityCode!) <= 4
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"card_id": String.isNullOrEmpty(self.cardId) ? JSON.null : self.cardId!,
"security_code" : String.isNullOrEmpty(self.securityCode) ? JSON.null : self.securityCode!,
"device" : self.device == nil ? JSON.null : self.device!.toJSONString()
]
return JSON(obj).toString()
}
} | mit | a699564cbd477e086e3fccb6992f5d40 | 32.215686 | 103 | 0.640284 | 4.44357 | false | false | false | false |
morganwesemann/SKButtonNode | SKButtonNode.swift | 1 | 4427 | //SKButtonNode.swift
//Using contributions from: http://stackoverflow.com/questions/19082202/setting-up-buttons-in-skscene
// updated to Swift 3 syntax by JG 1/13/17
import Foundation
import SpriteKit
class SKButtonNode: SKSpriteNode {
enum SKButtonNodeActionType: Int {
case TouchUpInside = 1,
TouchDown, TouchUp
}
var isEnabled: Bool = true {
didSet {
if (disabledTexture != nil) {
texture = isEnabled ? defaultTexture : disabledTexture
}
}
}
var isSelected: Bool = false {
didSet {
texture = isSelected ? selectedTexture : defaultTexture
}
}
var defaultTexture: SKTexture
var selectedTexture: SKTexture
var label: SKLabelNode
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
init(normalTexture defaultTexture: SKTexture!, selectedTexture:SKTexture!, disabledTexture: SKTexture?) {
self.defaultTexture = defaultTexture
self.selectedTexture = selectedTexture
self.disabledTexture = disabledTexture
self.label = SKLabelNode(fontNamed: "Helvetica")
super.init(texture: defaultTexture, color: UIColor.white, size: defaultTexture.size())
isUserInteractionEnabled = true
//Creating and adding a blank label, centered on the button
self.label.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center;
self.label.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center;
//make sure label is above button
self.label.zPosition = self.zPosition + 1
addChild(self.label)
// Adding this node as an empty layer. Without it the touch functions are not being called
// The reason for this is unknown when this was implemented...?
let bugFixLayerNode = SKSpriteNode(texture: nil, color: UIColor.clear, size: defaultTexture.size())
bugFixLayerNode.position = self.position
addChild(bugFixLayerNode)
}
/**
* Taking a target object and adding an action that is triggered by a button event.
*/
func setButtonAction(target: AnyObject, triggerEvent event:SKButtonNodeActionType, action:Selector) {
switch (event) {
case .TouchUpInside:
targetTouchUpInside = target
actionTouchUpInside = action
case .TouchDown:
targetTouchDown = target
actionTouchDown = action
case .TouchUp:
targetTouchUp = target
actionTouchUp = action
}
}
/*
New function for setting text. Calling function multiple times does
not create a ton of new labels, just updates existing label.
You can set the title, font type and font size with this function
*/
func setButtonLabel(title: NSString, font: String, fontSize: CGFloat) {
self.label.text = title as String
self.label.fontSize = fontSize
self.label.fontName = font
}
var disabledTexture: SKTexture?
var actionTouchUpInside: Selector?
var actionTouchUp: Selector?
var actionTouchDown: Selector?
weak var targetTouchUpInside: AnyObject?
weak var targetTouchUp: AnyObject?
weak var targetTouchDown: AnyObject?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if (!isEnabled) {
return
}
isSelected = true
if (targetTouchDown != nil && targetTouchDown!.responds(to: actionTouchDown!))
{
UIApplication.shared.sendAction(actionTouchDown!, to: targetTouchDown, from: self, for: nil)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if (!isEnabled) {
return
}
let touch = touches.first
let touchLocation = touch?.location(in: parent!)
if (frame.contains(touchLocation!)) {
isSelected = true
} else {
isSelected = false
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if (!isEnabled) {
return
}
isSelected = false
if (targetTouchUpInside != nil && targetTouchUpInside!.responds(to: actionTouchUpInside!)) {
let touch = touches.first
let touchLocation = touch?.location(in: parent!)
if (frame.contains(touchLocation!) ) {
UIApplication.shared.sendAction(actionTouchUpInside!, to: targetTouchUpInside, from: self, for: nil)
}
}
if (targetTouchUp != nil && targetTouchUp!.responds(to: actionTouchUp!)) {
UIApplication.shared.sendAction(actionTouchUp!, to: targetTouchUp, from: self, for: nil)
}
}
}
| mit | 6c71b8ff675fbcea4d02176d15160b18 | 27.934641 | 112 | 0.692794 | 4.545175 | false | false | false | false |
mohsinalimat/UZImageCollection | UZImageCollection/ImageCollectionViewController.swift | 1 | 11334 | //
// ImageCollectionViewController.swift
// UZImageCollectionView
//
// Created by sonson on 2015/06/05.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
func imageViewFrame(sourceImageViewFrame:CGRect, destinationImageViewFrame:CGRect, imageSize:CGSize, contentMode:UIViewContentMode) -> CGRect {
var scaleToFitImageOverContainerView:CGFloat = 1.0 /**< アニメーションさせるビューを画面全体に引き伸ばすための比.アニメーションさせるビューの最終フレームサイズを決めるために使う. */
if destinationImageViewFrame.size.width / destinationImageViewFrame.size.height < imageSize.width / imageSize.height {
scaleToFitImageOverContainerView = destinationImageViewFrame.size.width / imageSize.width;
}
else {
scaleToFitImageOverContainerView = destinationImageViewFrame.size.height / imageSize.height;
}
var endFrame = CGRectMake(0, 0, imageSize.width * scaleToFitImageOverContainerView, imageSize.height * scaleToFitImageOverContainerView);
endFrame.origin.x = (destinationImageViewFrame.size.width - endFrame.size.width)/2
endFrame.origin.y = (destinationImageViewFrame.size.height - endFrame.size.height)/2
return endFrame
}
public class ImageCollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {
var cellSize:CGFloat = 0
let collection:ImageCollection
var animatingImageView:UIImageView? = nil
var animatingBackgroundView:UIView? = nil
var currentFocusedPath:NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
func numberOfItemsInLine() -> Int {
return 3
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
init(collection:ImageCollection) {
self.collection = collection
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
layout.minimumLineSpacing = 0
super.init(collectionViewLayout: layout)
}
public required init?(coder aDecoder: NSCoder) {
self.collection = ImageCollection(newList: [])
super.init(coder: aDecoder)
}
public class func controller(URLList:[NSURL]) -> ImageCollectionViewController {
let collection = ImageCollection(newList: URLList)
let vc = ImageCollectionViewController(collection:collection)
return vc
}
public class func controllerInNavigationController(URLList:[NSURL]) -> UINavigationController {
let collection = ImageCollection(newList: URLList)
let vc = ImageCollectionViewController(collection:collection)
let nav = UINavigationController(rootViewController: vc)
return nav
}
public override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.registerClass(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.collectionView?.alwaysBounceVertical = true
self.view.backgroundColor = UIColor.whiteColor()
self.collectionView?.backgroundColor = UIColor.whiteColor()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didMoveCurrentImage:", name: ImageViewControllerDidChangeCurrentImage, object: nil)
cellSize = floor((self.view.frame.size.width - CGFloat(numberOfItemsInLine()) + 1) / CGFloat(numberOfItemsInLine()));
self.title = String(format: NSLocalizedString("%ld images", comment: ""), arguments: [self.collection.count])
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let imageView = self.animatingImageView {
let backgroundView = UIView(frame: self.view.bounds)
backgroundView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(backgroundView)
self.view.addSubview(imageView)
animatingBackgroundView = backgroundView
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let path = self.currentFocusedPath
let cell = self.collectionView?.cellForItemAtIndexPath(path)
if let imageView = self.animatingImageView {
if let cell = cell as? ImageCollectionViewCell {
cell.hidden = true
self.view.addSubview(imageView)
imageView.clipsToBounds = true
let destination = self.view.convertRect(cell.imageView.frame, fromView: cell.imageView.superview)
UIView.animateWithDuration(0.4,
animations: { () -> Void in
self.animatingBackgroundView?.alpha = 0
imageView.frame = destination
}, completion: { (success) -> Void in
imageView.removeFromSuperview()
self.animatingBackgroundView?.removeFromSuperview()
self.animatingImageView = nil
self.animatingBackgroundView = nil
cell.hidden = false
})
}
else {
UIView.animateWithDuration(0.4,
animations: { () -> Void in
imageView.alpha = 0
self.animatingBackgroundView?.alpha = 0
}, completion: { (success) -> Void in
imageView.removeFromSuperview()
self.animatingBackgroundView?.removeFromSuperview()
self.animatingImageView = nil
self.animatingBackgroundView = nil
})
}
}
}
func didMoveCurrentImage(notification:NSNotification) {
if let userInfo = notification.userInfo {
if let index = userInfo[ImageViewControllerDidChangeCurrentImageIndexKey] as? Int {
self.currentFocusedPath = NSIndexPath(forItem: index, inSection: 0)
if let collectionView = self.collectionView {
if let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) {
if !collectionView.visibleCells().contains(cell) {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
}
else{
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
}
}
}
}
}
extension ImageCollectionViewController {
public override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if let collectionView = self.collectionView {
for cell in collectionView.visibleCells() {
if let cell = cell as? ImageCollectionViewCell {
cell.reload(false)
}
}
}
}
}
extension ImageCollectionViewController {
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: cellSize, height: cellSize + 1)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
}
extension ImageCollectionViewController {
public override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collection.count
}
public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell {
if let sourceImage = cell.fullImage() {
cell.hidden = true
let whiteBackgroundView = UIView(frame: self.view.bounds)
whiteBackgroundView.alpha = 0
whiteBackgroundView.backgroundColor = UIColor.whiteColor()
let imageView = UIImageView(image: sourceImage)
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
self.view.addSubview(whiteBackgroundView)
self.view.addSubview(imageView)
let sourceRect = self.view.convertRect(cell.imageView.frame, fromView: cell.imageView.superview)
let e = imageViewFrame(sourceRect, destinationImageViewFrame: self.view.bounds, imageSize: sourceImage.size, contentMode: UIViewContentMode.ScaleAspectFill)
imageView.frame = sourceRect
UIView.animateWithDuration(0.4, animations: { () -> Void in
imageView.frame = e
whiteBackgroundView.alpha = 1
}, completion: { (success) -> Void in
let con = ImageViewPageController.controller(self.collection, index: indexPath.row, imageCollectionViewController:self)
self.presentViewController(con, animated: false) { () -> Void in
imageView.removeFromSuperview()
whiteBackgroundView.removeFromSuperview()
}
cell.hidden = false
})
}
}
}
public override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? ImageCollectionViewCell {
cell.cancelDownloadingImage()
}
}
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
cell.prepareForReuse()
if let cell = cell as? ImageCollectionViewCell {
let imageURL = collection.URLList[indexPath.row]
cell.imageURL = imageURL
cell.reload(collectionView.decelerating)
}
return cell
}
}
| mit | 0da1a70b3f21d3e5964c4c530b6965bc | 43.300395 | 194 | 0.638205 | 6.148108 | false | false | false | false |
mpclarkson/StravaSwift | Sources/StravaSwift/Event.swift | 1 | 1775 | //
// Event.swift
// StravaSwift
//
// Created by Matthew on 11/11/2015.
// Copyright © 2015 Matthew Clarkson. All rights reserved.
//
import Foundation
import SwiftyJSON
/**
Group Events are optionally recurring events for club members. Only club members can access private club events. The objects are returned in summary representation.
**/
public final class Event: Strava {
public let id: Int?
public let resourceState: ResourceState?
public let title: String?
public let descr: String?
public let clubId: Int?
public let organizingAthlete: Athlete?
public let activityType: ActivityType?
public let createdAt: Date?
public let routeId: Int?
public let womenOnly: Bool?
public let `private`: Bool?
public let skillLevels: SkillLevel?
public let terrain: Terrain?
public let upcomingOccurrences: [Date]?
/**
Initializer
- Parameter json: SwiftyJSON object
- Internal
**/
required public init(_ json: JSON) {
resourceState = json["resource_state"].strava(ResourceState.self)
id = json["id"].int
title = json["title"].string
descr = json["description"].string
clubId = json["club_id"].int
organizingAthlete = json["organizing_athlete"].strava(Athlete.self)
activityType = json["activity_type"].strava(ActivityType.self)
createdAt = json["created_at"].string?.toDate()
routeId = json["route_id"].int
womenOnly = json["women_only"].bool
`private` = json["private"].bool
skillLevels = json["skill_level"].strava(SkillLevel.self)
terrain = json["terrain"].strava(Terrain.self)
upcomingOccurrences = json["terrain"].arrayValue.compactMap { $0.string?.toDate() }
}
}
| mit | c78ca6ff15e5d1231d56bb41e40ffb91 | 32.471698 | 165 | 0.667418 | 4.22381 | false | false | false | false |
brave/browser-ios | Client/Frontend/Reader/ReaderModeUtils.swift | 2 | 3084 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
struct ReaderModeUtils {
static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
static func simplifyDomain(_ domain: String) -> String {
for prefix in DomainPrefixesToSimplify {
if domain.hasPrefix(prefix) {
return domain.substring(from: domain.characters.index(domain.startIndex, offsetBy: prefix.characters.count))
}
}
return domain
}
static func generateReaderContent(_ readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? {
guard let tmplPath = Bundle.main.path(forResource: "Reader", ofType: "html") else { return nil }
do {
let tmpl = try NSMutableString(contentsOfFile: tmplPath, encoding: String.Encoding.utf8.rawValue)
let replacements: [String: String] = ["%READER-STYLE%": initialStyle.encode(),
"%READER-DOMAIN%": simplifyDomain(readabilityResult.domain),
"%READER-URL%": readabilityResult.url,
"%READER-TITLE%": readabilityResult.title,
"%READER-CREDITS%": readabilityResult.credits,
"%READER-CONTENT%": readabilityResult.content
]
for (k,v) in replacements {
tmpl.replaceOccurrences(of: k, with: v, options: NSString.CompareOptions(), range: NSMakeRange(0, tmpl.length))
}
return tmpl as String
} catch _ {
return nil
}
}
static func isReaderModeURL(_ url: URL) -> Bool {
let scheme = url.scheme, host = url.host, path = url.path
return scheme == "http" && host == "localhost" && path == "/reader-mode/page"
}
static func decodeURL(_ url: URL) -> URL? {
if ReaderModeUtils.isReaderModeURL(url) {
if let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 {
if let queryItem = queryItems.first, let value = queryItem.value {
return URL(string: value)
}
}
}
return nil
}
static func encodeURL(_ url: URL?) -> URL? {
let baseReaderModeURL: String = WebServer.sharedInstance.URLForResource("page", module: "reader-mode")
if let absoluteString = url?.absoluteString {
if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) {
if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") {
return aboutReaderURL
}
}
}
return nil
}
}
| mpl-2.0 | 6327821de6b5e8a24534709cc4bca36b | 42.43662 | 152 | 0.572957 | 5.191919 | false | false | false | false |
SwifterSwift/SwifterSwift | Sources/SwifterSwift/CoreLocation/CLLocationExtensions.swift | 1 | 2922 | // CLLocationExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(CoreLocation)
import CoreLocation
// MARK: - Methods
public extension CLLocation {
/// SwifterSwift: Calculate the half-way point along a great circle path between the two points.
///
/// - Parameters:
/// - start: Start location.
/// - end: End location.
/// - Returns: Location that represents the half-way point.
static func midLocation(start: CLLocation, end: CLLocation) -> CLLocation {
let lat1 = Double.pi * start.coordinate.latitude / 180.0
let long1 = Double.pi * start.coordinate.longitude / 180.0
let lat2 = Double.pi * end.coordinate.latitude / 180.0
let long2 = Double.pi * end.coordinate.longitude / 180.0
// Formula
// Bx = cos φ2 ⋅ cos Δλ
// By = cos φ2 ⋅ sin Δλ
// φm = atan2( sin φ1 + sin φ2, √(cos φ1 + Bx)² + By² )
// λm = λ1 + atan2(By, cos(φ1)+Bx)
// Source: http://www.movable-type.co.uk/scripts/latlong.html
let bxLoc = cos(lat2) * cos(long2 - long1)
let byLoc = cos(lat2) * sin(long2 - long1)
let mlat = atan2(sin(lat1) + sin(lat2), sqrt((cos(lat1) + bxLoc) * (cos(lat1) + bxLoc) + (byLoc * byLoc)))
let mlong = long1 + atan2(byLoc, cos(lat1) + bxLoc)
return CLLocation(latitude: mlat * 180 / Double.pi, longitude: mlong * 180 / Double.pi)
}
/// SwifterSwift: Calculate the half-way point along a great circle path between self and another points.
///
/// - Parameter point: End location.
/// - Returns: Location that represents the half-way point.
func midLocation(to point: CLLocation) -> CLLocation {
return CLLocation.midLocation(start: self, end: point)
}
/// SwifterSwift: Calculates the bearing to another CLLocation.
///
/// - Parameters:
/// - destination: Location to calculate bearing.
/// - Returns: Calculated bearing degrees in the range 0° ... 360°
func bearing(to destination: CLLocation) -> Double {
// http://stackoverflow.com/questions/3925942/cllocation-category-for-calculating-bearing-w-haversine-function
let lat1 = Double.pi * coordinate.latitude / 180.0
let long1 = Double.pi * coordinate.longitude / 180.0
let lat2 = Double.pi * destination.coordinate.latitude / 180.0
let long2 = Double.pi * destination.coordinate.longitude / 180.0
// Formula: θ = atan2( sin Δλ ⋅ cos φ2 , cos φ1 ⋅ sin φ2 − sin φ1 ⋅ cos φ2 ⋅ cos Δλ )
// Source: http://www.movable-type.co.uk/scripts/latlong.html
let rads = atan2(
sin(long2 - long1) * cos(lat2),
cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(long2 - long1))
let degrees = rads * 180 / Double.pi
return (degrees + 360).truncatingRemainder(dividingBy: 360)
}
}
#endif
| mit | 1fa0a90d2815984f891b02fd9c685714 | 41.338235 | 118 | 0.622438 | 3.506699 | false | false | false | false |
apple/swift | test/Sema/struct_equatable_hashable.swift | 16 | 13580 | // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/struct_equatable_hashable_other.swift -verify-ignore-unknown -swift-version 4
var hasher = Hasher()
struct Point: Hashable {
let x: Int
let y: Int
}
func point() {
if Point(x: 1, y: 2) == Point(x: 2, y: 1) { }
let _: Int = Point(x: 3, y: 5).hashValue
Point(x: 3, y: 5).hash(into: &hasher)
Point(x: 1, y: 2) == Point(x: 2, y: 1) // expected-warning {{result of operator '==' is unused}}
}
struct Pair<T: Hashable>: Hashable {
let first: T
let second: T
func same() -> Bool {
return first == second
}
}
func pair() {
let p1 = Pair(first: "a", second: "b")
let p2 = Pair(first: "a", second: "c")
if p1 == p2 { }
let _: Int = p1.hashValue
p1.hash(into: &hasher)
}
func localStruct() -> Bool {
struct Local: Equatable {
let v: Int
}
return Local(v: 5) == Local(v: 4)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hash(into:) implementation from hashValue
struct CustomHashValue: Hashable {
let x: Int
let y: Int
static func ==(x: CustomHashValue, y: CustomHashValue) -> Bool { return true }
func hash(into hasher: inout Hasher) {}
}
func customHashValue() {
if CustomHashValue(x: 1, y: 2) == CustomHashValue(x: 2, y: 3) { }
let _: Int = CustomHashValue(x: 1, y: 2).hashValue
CustomHashValue(x: 1, y: 2).hash(into: &hasher)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hashValue implementation from hash(into:)
struct CustomHashInto: Hashable {
let x: Int
let y: Int
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
static func ==(x: CustomHashInto, y: CustomHashInto) -> Bool { return true }
}
func customHashInto() {
if CustomHashInto(x: 1, y: 2) == CustomHashInto(x: 2, y: 3) { }
let _: Int = CustomHashInto(x: 1, y: 2).hashValue
CustomHashInto(x: 1, y: 2).hash(into: &hasher)
}
// Check use of an struct's synthesized members before the struct is actually declared.
struct UseStructBeforeDeclaration {
let eqValue = StructToUseBeforeDeclaration(v: 4) == StructToUseBeforeDeclaration(v: 5)
let hashValue = StructToUseBeforeDeclaration(v: 1).hashValue
let hashInto: (inout Hasher) -> Void = StructToUseBeforeDeclaration(v: 1).hash(into:)
}
struct StructToUseBeforeDeclaration: Hashable {
let v: Int
}
func getFromOtherFile() -> AlsoFromOtherFile { return AlsoFromOtherFile(v: 4) }
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return YetAnotherFromOtherFile(v: 1.2) }
func overloadFromOtherFile() -> Bool { return false }
func useStructBeforeDeclaration() {
// Check structs from another file in the same module.
if FromOtherFile(v: "a") == FromOtherFile(v: "b") {}
let _: Int = FromOtherFile(v: "c").hashValue
FromOtherFile(v: "d").hash(into: &hasher)
if AlsoFromOtherFile(v: 3) == getFromOtherFile() {}
if YetAnotherFromOtherFile(v: 1.9) == overloadFromOtherFile() {}
}
// Even if the struct has only equatable/hashable members, it's not synthesized
// implicitly.
struct StructWithoutExplicitConformance {
let a: Int
let b: String
}
func structWithoutExplicitConformance() {
// FIXME(rdar://problem/64844584) - on iOS simulator this diagnostic is flaky
// This diagnostic is about `Equatable` because it's considered the best possible solution among other ones for operator `==`.
if StructWithoutExplicitConformance(a: 1, b: "b") == StructWithoutExplicitConformance(a: 2, b: "a") { }
// expected-error@-1 {{requires that 'StructWithoutExplicitConformance' conform to 'Equatable'}}
}
// Structs with non-hashable/equatable stored properties don't derive conformance.
struct NotHashable {}
struct StructWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}}
let a: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Equatable'}}
}
// ...but computed properties and static properties are not considered.
struct StructIgnoresComputedProperties: Hashable {
var a: Int
var b: String
static var staticComputed = NotHashable()
var computed: NotHashable { return NotHashable() }
}
func structIgnoresComputedProperties() {
if StructIgnoresComputedProperties(a: 1, b: "a") == StructIgnoresComputedProperties(a: 2, b: "c") {}
let _: Int = StructIgnoresComputedProperties(a: 3, b: "p").hashValue
StructIgnoresComputedProperties(a: 4, b: "q").hash(into: &hasher)
}
// Structs should be able to derive conformances based on the conformances of
// their generic arguments.
struct GenericHashable<T: Hashable>: Hashable {
let value: T
}
func genericHashable() {
if GenericHashable<String>(value: "a") == GenericHashable<String>(value: "b") { }
let _: Int = GenericHashable<String>(value: "c").hashValue
GenericHashable<String>(value: "c").hash(into: &hasher)
}
// But it should be an error if the generic argument doesn't have the necessary
// constraints to satisfy the conditions for derivation.
struct GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}}
let value: T // expected-note 2 {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}}
}
func genericNotHashable() {
if GenericNotHashable<String>(value: "a") == GenericNotHashable<String>(value: "b") { }
let gnh = GenericNotHashable<String>(value: "b")
let _: Int = gnh.hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails
gnh.hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}}
}
// Synthesis can be from an extension...
struct StructConformsInExtension {
let v: Int
}
extension StructConformsInExtension : Equatable {}
// and explicit conformance in an extension should also work.
public struct StructConformsAndImplementsInExtension {
let v: Int
}
extension StructConformsAndImplementsInExtension : Equatable {
public static func ==(lhs: StructConformsAndImplementsInExtension, rhs: StructConformsAndImplementsInExtension) -> Bool {
return true
}
}
// No explicit conformance and it cannot be derived.
struct NotExplicitlyHashableAndCannotDerive {
let v: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}}
}
extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}}
// A struct with no stored properties trivially derives conformance.
struct NoStoredProperties: Hashable {}
// Verify that conformance (albeit manually implemented) can still be added to
// a type in a different file.
extension OtherFileNonconforming: Hashable {
static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
// ...but synthesis in a type defined in another file doesn't work yet.
extension YetOtherFileNonconforming: Equatable {} // expected-error {{extension outside of file declaring struct 'YetOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}}
// Verify that we can add Hashable conformance in an extension by only
// implementing hash(into:)
struct StructConformsAndImplementsHashIntoInExtension: Equatable {
let v: String
}
extension StructConformsAndImplementsHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(v)
}
}
func structConformsAndImplementsHashIntoInExtension() {
let _: Int = StructConformsAndImplementsHashIntoInExtension(v: "a").hashValue
StructConformsAndImplementsHashIntoInExtension(v: "b").hash(into: &hasher)
}
struct GenericHashIntoInExtension<T: Hashable>: Equatable {
let value: T
}
extension GenericHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
func genericHashIntoInExtension() {
let _: Int = GenericHashIntoInExtension<String>(value: "a").hashValue
GenericHashIntoInExtension(value: "b").hash(into: &hasher)
}
// Conditional conformances should be able to be synthesized
struct GenericDeriveExtension<T> {
let value: T
}
extension GenericDeriveExtension: Equatable where T: Equatable {}
extension GenericDeriveExtension: Hashable where T: Hashable {}
// Incorrectly/insufficiently conditional shouldn't work
struct BadGenericDeriveExtension<T> {
let value: T // expected-note {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}}
// expected-note@-1 {{stored property type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}}
}
extension BadGenericDeriveExtension: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}}
extension BadGenericDeriveExtension: Hashable where T: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}}
// But some cases don't need to be conditional, even if they look similar to the
// above
struct AlwaysHashable<T>: Hashable {}
struct UnusedGenericDeriveExtension<T> {
let value: AlwaysHashable<T>
}
extension UnusedGenericDeriveExtension: Hashable {}
// Cross-file synthesis is still disallowed for conditional cases
extension GenericOtherFileNonconforming: Equatable where T: Equatable {}
// expected-error@-1{{extension outside of file declaring generic struct 'GenericOtherFileNonconforming' prevents automatic synthesis of '==' for protocol 'Equatable'}}
// rdar://problem/41852654
// There is a conformance to Equatable (or at least, one that implies Equatable)
// in the same file as the type, so the synthesis is okay. Both orderings are
// tested, to catch choosing extensions based on the order of the files, etc.
protocol ImplierMain: Equatable {}
struct ImpliedMain: ImplierMain {}
extension ImpliedOther: ImplierMain {}
// Hashable conformances that rely on a manual implementation of `hashValue`
// should produce a deprecation warning.
struct OldSchoolStruct: Hashable {
static func ==(left: OldSchoolStruct, right: OldSchoolStruct) -> Bool {
return true
}
var hashValue: Int { return 42 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolStruct' to 'Hashable' by implementing 'hash(into:)' instead}}
}
enum OldSchoolEnum: Hashable {
case foo
case bar
static func ==(left: OldSchoolEnum, right: OldSchoolEnum) -> Bool {
return true
}
var hashValue: Int { return 23 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolEnum' to 'Hashable' by implementing 'hash(into:)' instead}}
}
class OldSchoolClass: Hashable {
static func ==(left: OldSchoolClass, right: OldSchoolClass) -> Bool {
return true
}
var hashValue: Int { return -9000 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolClass' to 'Hashable' by implementing 'hash(into:)' instead}}
}
// However, it's okay to implement `hashValue` as long as `hash(into:)` is also
// provided.
struct MixedStruct: Hashable {
static func ==(left: MixedStruct, right: MixedStruct) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 42 }
}
enum MixedEnum: Hashable {
case foo
case bar
static func ==(left: MixedEnum, right: MixedEnum) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 23 }
}
class MixedClass: Hashable {
static func ==(left: MixedClass, right: MixedClass) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return -9000 }
}
// Ensure equatable and hashable works with weak/unowned properties as well
struct Foo: Equatable, Hashable {
weak var foo: Bar?
unowned var bar: Bar
}
class Bar {
let bar: String
init(bar: String) {
self.bar = bar
}
}
extension Bar: Equatable, Hashable {
static func == (lhs: Bar, rhs: Bar) -> Bool {
return lhs.bar == rhs.bar
}
func hash(into hasher: inout Hasher) {}
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
| apache-2.0 | 506e123255108ca9a32fe0bcf4cf023d | 37.8 | 208 | 0.726804 | 4.027284 | false | false | false | false |
AlwaysRightInstitute/SwiftSockets | Sources/SwiftSockets/Socket.swift | 1 | 7791 | //
// Socket.swift
// SwiftSockets
//
// Created by Helge Heß on 6/9/14.
// Copyright (c) 2014-2017 Always Right Institute. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Dispatch
/**
* Simple Socket classes for Swift.
*
* PassiveSockets are 'listening' sockets, ActiveSockets are open connections.
*/
public class Socket<T: SocketAddress> {
public var fd : FileDescriptor = nil
public var boundAddress : T? = nil
public var isValid : Bool { return fd.isValid }
public var isBound : Bool { return boundAddress != nil }
var closeCB : ((FileDescriptor) -> Void)? = nil
var closedFD : FileDescriptor? = nil // for delayed callback
/* initializer / deinitializer */
public init(fd: FileDescriptor) {
self.fd = fd
}
deinit {
close() // TBD: is this OK/safe?
}
public convenience init?(type: Int32 = xsys.SOCK_STREAM) {
let lfd = socket(T.domain, type, 0)
guard lfd != -1 else { return nil }
self.init(fd: FileDescriptor(lfd))
}
/* explicitly close the socket */
let debugClose = false
public func close() {
if fd.isValid {
closedFD = fd
if debugClose { print("Closing socket \(closedFD!) for good ...") }
fd.close()
fd = nil
if let cb = closeCB {
// can be used to unregister socket etc when the socket is really closed
if debugClose { print(" let closeCB \(closedFD as Optional) know...") }
cb(closedFD!)
closeCB = nil // break potential cycles
}
if debugClose { print("done closing \(closedFD as Optional)") }
}
else if debugClose {
print("socket \(closedFD as Optional) already closed.")
}
boundAddress = nil
}
public func onClose(cb: ((FileDescriptor) -> Void)?) -> Self {
if let fd = closedFD { // socket got closed before event-handler attached
if let lcb = cb {
lcb(fd)
}
else {
closeCB = nil
}
}
else {
closeCB = cb
}
return self
}
/* bind the socket. */
public func bind(_ address: T) -> Bool {
guard fd.isValid else { return false }
guard !isBound else {
print("Socket is already bound!")
return false
}
// Note: must be 'var' for ptr stuff, can't use let
var addr = address
let rc = withUnsafePointer(to: &addr) { ptr -> Int32 in
return ptr.withMemoryRebound(to: xsys_sockaddr.self, capacity: 1) {
bptr in
return xsys.bind(fd.fd, bptr, socklen_t(address.len))
}
}
if rc == 0 {
// Generics TBD: cannot check for isWildcardPort, always grab the name
boundAddress = getsockname()
/* if it was a wildcard port bind, get the address */
// boundAddress = addr.isWildcardPort ? getsockname() : addr
}
return rc == 0 ? true : false
}
public func getsockname() -> T? {
return _getaname(fn: xsys.getsockname)
}
public func getpeername() -> T? {
return _getaname(fn: xsys.getpeername)
}
typealias GetNameFN = ( Int32, UnsafeMutablePointer<sockaddr>,
UnsafeMutablePointer<socklen_t>) -> Int32
func _getaname(fn nfn: GetNameFN) -> T? {
guard fd.isValid else { return nil }
// FIXME: tried to encapsulate this in a sockaddrbuf which does all the
// ptr handling, but it ain't work (autoreleasepool issue?)
var baddr = T()
var baddrlen = socklen_t(baddr.len)
// Note: we are not interested in the length here, would be relevant
// for AF_UNIX sockets
let rc = withUnsafeMutablePointer(to: &baddr) {
ptr -> Int32 in
// TODO: is this right, or is there a better way?
return ptr.withMemoryRebound(to: xsys_sockaddr.self, capacity: 1) {
bptr in
return nfn(fd.fd, bptr, &baddrlen)
}
}
guard rc == 0 else {
print("Could not get sockname? \(rc)")
return nil
}
// print("PORT: \(baddr.sin_port)")
return baddr
}
/* description */
// must live in the main-class as 'declarations in extensions cannot be
// overridden yet' (Same in Swift 2.0)
func descriptionAttributes() -> String {
var s = fd.isValid
? " fd=\(fd.fd)"
: (closedFD != nil ? " closed[\(closedFD!)]" :" not-open")
if boundAddress != nil {
s += " \(boundAddress!)"
}
return s
}
}
extension Socket { // Socket Flags
public var flags : Int32? {
get { return fd.flags }
set { fd.flags = newValue! }
}
public var isNonBlocking : Bool {
get { return fd.isNonBlocking }
set { fd.isNonBlocking = newValue }
}
}
extension Socket { // Socket Options
public var reuseAddress: Bool {
get { return getSocketOption(SO_REUSEADDR) }
set { _ = setSocketOption(SO_REUSEADDR, value: newValue) }
}
#if os(Linux)
// No: SO_NOSIGPIPE on Linux, use MSG_NOSIGNAL in send()
public var isSigPipeDisabled: Bool {
get { return false }
set { /* DANGER, DANGER, ALERT */ }
}
#else
public var isSigPipeDisabled: Bool {
get { return getSocketOption(SO_NOSIGPIPE) }
set { _ = setSocketOption(SO_NOSIGPIPE, value: newValue) }
}
#endif
public var keepAlive: Bool {
get { return getSocketOption(SO_KEEPALIVE) }
set { _ = setSocketOption(SO_KEEPALIVE, value: newValue) }
}
public var dontRoute: Bool {
get { return getSocketOption(SO_DONTROUTE) }
set { _ = setSocketOption(SO_DONTROUTE, value: newValue) }
}
public var socketDebug: Bool {
get { return getSocketOption(SO_DEBUG) }
set { _ = setSocketOption(SO_DEBUG, value: newValue) }
}
public var sendBufferSize: Int32 {
get { return getSocketOption(SO_SNDBUF) ?? -42 }
set { _ = setSocketOption(SO_SNDBUF, value: newValue) }
}
public var receiveBufferSize: Int32 {
get { return getSocketOption(SO_RCVBUF) ?? -42 }
set { _ = setSocketOption(SO_RCVBUF, value: newValue) }
}
public var socketError: Int32 {
return getSocketOption(SO_ERROR) ?? -42
}
/* socket options (TBD: would we use subscripts for such?) */
public func setSocketOption(_ option: Int32, value: Int32) -> Bool {
if !isValid {
return false
}
var buf = value
let rc = setsockopt(fd.fd, SOL_SOCKET, option, &buf, socklen_t(4))
if rc != 0 { // ps: Great Error Handling
print("Could not set option \(option) on socket \(self)")
}
return rc == 0
}
// TBD: Can't overload optionals in a useful way?
// func getSocketOption(option: Int32) -> Int32
public func getSocketOption(_ option: Int32) -> Int32? {
if !isValid {
return nil
}
var buf = Int32(0)
var buflen = socklen_t(4)
let rc = getsockopt(fd.fd, SOL_SOCKET, option, &buf, &buflen)
if rc != 0 { // ps: Great Error Handling
print("Could not get option \(option) from socket \(self)")
return nil
}
return buf
}
public func setSocketOption(_ option: Int32, value: Bool) -> Bool {
return setSocketOption(option, value: value ? 1 : 0)
}
public func getSocketOption(_ option: Int32) -> Bool {
let v: Int32? = getSocketOption(option)
return v != nil ? (v! == 0 ? false : true) : false
}
}
public extension Socket { // poll()
public var isDataAvailable: Bool { return fd.isDataAvailable }
public func pollFlag(flag: Int32) -> Bool { return fd.poll(flag: flag) }
public func poll(events: Int32, timeout: UInt? = 0) -> Int32? {
return fd.poll(events: events, timeout: timeout)
}
}
extension Socket: CustomStringConvertible {
public var description : String {
return "<Socket:" + descriptionAttributes() + ">"
}
}
| mit | 1817a3328bead05d85b4de87a66a098c | 25.053512 | 80 | 0.606547 | 3.777886 | false | false | false | false |
bag-umbala/music-umbala | Music-Umbala/Pods/M13Checkbox/Sources/M13CheckboxController.swift | 2 | 6186 | //
// M13CheckboxController.swift
// M13Checkbox
//
// Created by McQuilkin, Brandon on 3/18/16.
// Copyright © 2016 Brandon McQuilkin. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
internal class M13CheckboxController {
//----------------------------
// MARK: - Properties
//----------------------------
/// The path presets for the manager.
var pathGenerator: M13CheckboxPathGenerator = M13CheckboxCheckPathGenerator()
/// The animation presets for the manager.
var animationGenerator: M13CheckboxAnimationGenerator = M13CheckboxAnimationGenerator()
/// The current state of the checkbox.
var state: M13Checkbox.CheckState = .unchecked
/// The current tint color.
/// - Note: Subclasses should override didSet to update the layers when this value changes.
var tintColor: UIColor = UIColor.black
/// The secondary tint color.
/// - Note: Subclasses should override didSet to update the layers when this value changes.
var secondaryTintColor: UIColor? = UIColor.lightGray
/// The secondary color of the mark.
/// - Note: Subclasses should override didSet to update the layers when this value changes.
var secondaryCheckmarkTintColor: UIColor? = UIColor.white
/// Whether or not to hide the box.
/// - Note: Subclasses should override didSet to update the layers when this value changes.
var hideBox: Bool = false
/// Whether or not to allow morphong between states.
var enableMorphing: Bool = true
// The type of mark to display.
var markType: M13Checkbox.MarkType = .checkmark {
willSet {
if markType == newValue {
return
}
setMarkType(type: markType, animated: false)
}
}
func setMarkType(type: M13Checkbox.MarkType, animated: Bool) {
var newPathGenerator: M13CheckboxPathGenerator? = nil
if type != markType {
switch type {
case .checkmark:
newPathGenerator = M13CheckboxCheckPathGenerator()
break
case .radio:
newPathGenerator = M13CheckboxRadioPathGenerator()
break
case .addRemove:
newPathGenerator = M13CheckboxAddRemovePathGenerator()
break
case .disclosure:
newPathGenerator = M13CheckboxDisclosurePathGenerator()
break
}
newPathGenerator?.boxLineWidth = pathGenerator.boxLineWidth
newPathGenerator?.boxType = pathGenerator.boxType
newPathGenerator?.checkmarkLineWidth = pathGenerator.checkmarkLineWidth
newPathGenerator?.cornerRadius = pathGenerator.cornerRadius
newPathGenerator?.size = pathGenerator.size
// Animate the change.
if pathGenerator.pathForMark(state) != nil && animated {
let previousState = state
animate(state, toState: nil, completion: { [weak self] in
self?.pathGenerator = newPathGenerator!
self?.resetLayersForState(previousState)
if self?.pathGenerator.pathForMark(previousState) != nil {
self?.animate(nil, toState: previousState)
}
})
} else if newPathGenerator?.pathForMark(state) != nil && animated {
let previousState = state
pathGenerator = newPathGenerator!
resetLayersForState(nil)
animate(nil, toState: previousState)
} else {
pathGenerator = newPathGenerator!
resetLayersForState(state)
}
markType = type
}
}
//----------------------------
// MARK: - Layers
//----------------------------
/// The layers to display in the checkbox. The top layer is the last layer in the array.
var layersToDisplay: [CALayer] {
return []
}
//----------------------------
// MARK: - Animations
//----------------------------
/**
Animates the layers between the two states.
- parameter fromState: The previous state of the checkbox.
- parameter toState: The new state of the checkbox.
*/
func animate(_ fromState: M13Checkbox.CheckState?, toState: M13Checkbox.CheckState?, completion: (() -> Void)? = nil) {
if let toState = toState {
state = toState
}
}
//----------------------------
// MARK: - Layout
//----------------------------
/// Layout the layers.
func layoutLayers() {
}
//----------------------------
// MARK: - Display
//----------------------------
/**
Reset the layers to be in the given state.
- parameter state: The new state of the checkbox.
*/
func resetLayersForState(_ state: M13Checkbox.CheckState?) {
if let state = state {
self.state = state
}
layoutLayers()
}
}
| mit | 0d957cef0fcabe6f6005b7d07a1e31c7 | 38.647436 | 464 | 0.594341 | 5.259354 | false | false | false | false |
enstulen/ARKitAnimation | Pods/SwiftCharts/SwiftCharts/ChartLineModel.swift | 2 | 1626 | //
// ChartLineModel.swift
// swift_charts
//
// Created by ischuetz on 11/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// Models a line to be drawn in a chart based on an array of chart points.
public struct ChartLineModel<T: ChartPoint> {
/// The array of chart points that the line should be drawn with. In a simple case this would be drawn as straight line segments connecting each point.
public let chartPoints: [T]
/// The color that the line is drawn with
public let lineColor: UIColor
/// The width of the line in points
public let lineWidth: CGFloat
public let lineJoin: LineJoin
public let lineCap: LineCap
/// The duration in seconds of the animation that is run when the line appears
public let animDuration: Float
/// The delay in seconds before the animation runs
public let animDelay: Float
/// The dash pattern for the line
public let dashPattern: [Double]?
public init(chartPoints: [T], lineColor: UIColor, lineWidth: CGFloat = 1, lineJoin: LineJoin = .round, lineCap: LineCap = .round, animDuration: Float, animDelay: Float, dashPattern: [Double]? = nil) {
self.chartPoints = chartPoints
self.lineColor = lineColor
self.lineWidth = lineWidth
self.lineJoin = lineJoin
self.lineCap = lineCap
self.animDuration = animDuration
self.animDelay = animDelay
self.dashPattern = dashPattern
}
/// The number of chart points in the model
var chartPointsCount: Int {
return chartPoints.count
}
}
| mit | 80258a12763da274330e720959bc0fa5 | 30.269231 | 204 | 0.675277 | 4.754386 | false | false | false | false |
yaobanglin/viossvc | viossvc/Scenes/User/ServerTableView.swift | 1 | 2001 | //
// ServerTableView.swift
// viossvc
//
// Created by 木柳 on 2016/12/2.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class ServerCell: UITableViewCell {
@IBOutlet weak var upLine: UIView!
@IBOutlet weak var serverNameLabel: UILabel!
@IBOutlet weak var serverTimeLabel: UILabel!
@IBOutlet weak var serverPriceLabel: UILabel!
}
class ServerTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var serverData: [UserServerModel] = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
dataSource = self
scrollEnabled = false
}
//MARK: --delegate and datasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return serverData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ServerCell = tableView.dequeueReusableCellWithIdentifier(ServerCell.className()) as! ServerCell
let model = serverData[indexPath.row]
cell.serverNameLabel.text = model.service_name
cell.serverPriceLabel.text = "¥\(Double(model.service_price)/100)"
cell.serverTimeLabel.text = "\(time(model.service_start))--\(time(model.service_end))"
cell.upLine.hidden = indexPath.row == 0
return cell
}
func time(minus: Int) -> String {
let hour = minus / 60
let leftMinus = minus % 60
return String(format: "%02d:%02d", hour, leftMinus) //"\(hourStr):\(minusStr)"
// let hourStr = hour > 9 ? "\(hour)" : "0\(hour)"
// let minusStr = leftMinus > 9 ? "\(minus)" : "0\(leftMinus)"
// return "\(hourStr):\(minusStr)"
}
func updateData(data: AnyObject!, complete:CompleteBlock) {
serverData = data as! [UserServerModel]
reloadData()
complete(contentSize.height > 0 ? contentSize.height+20 : 0)
}
}
| apache-2.0 | 1c561688a8c09523b7ebb97931162644 | 35.218182 | 113 | 0.653112 | 4.220339 | false | false | false | false |
beeth0ven/LTMorphingLabel | LTMorphingLabel/LTMorphingLabel+Evaporate.swift | 6 | 3077 | //
// LTMorphingLabel+Evaporate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2015 Lex Tang, http://lexrus.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 UIKit
extension LTMorphingLabel {
func EvaporateLoad() {
progressClosures["Evaporate\(LTMorphingPhaseManipulateProgress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
let j: Int = Int(round(cos(Double(index)) * 1.2))
let delay = isNewChar ? self.morphingCharacterDelay * -1.0 : self.morphingCharacterDelay
return min(1.0, max(0.0, self.morphingProgress + delay * Float(j)))
}
effectClosures["Evaporate\(LTMorphingPhaseDisappear)"] = {
(char:Character, index: Int, progress: Float) in
let newProgress = LTEasing.easeOutQuint(progress, 0.0, 1.0, 1.0)
let yOffset: CGFloat = -0.8 * CGFloat(self.font.pointSize) * CGFloat(newProgress)
let currentRect = CGRectOffset(self.previousRects[index], 0, yOffset)
let currentAlpha = CGFloat(1.0 - newProgress)
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: self.font.pointSize,
drawingProgress: 0.0)
}
effectClosures["Evaporate\(LTMorphingPhaseAppear)"] = {
(char:Character, index: Int, progress: Float) in
let newProgress = 1.0 - LTEasing.easeOutQuint(progress, 0.0, 1.0)
let yOffset = CGFloat(self.font.pointSize) * CGFloat(newProgress) * 1.2
return LTCharacterLimbo(
char: char,
rect: CGRectOffset(self.newRects[index], 0.0, yOffset),
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
}
}
| mit | ae07d786da9dfc7136d740db3aaea0c4 | 41.041096 | 100 | 0.632779 | 4.506608 | false | false | false | false |
raptorxcz/Rubicon | Rubicon/HelpController.swift | 1 | 812 | //
// HelpController.swift
// Rubicon
//
// Created by Kryštof Matěj on 06/05/2017.
// Copyright © 2017 Kryštof Matěj. All rights reserved.
//
public protocol HelpController {
func run()
}
public class HelpControllerImpl {
fileprivate let output: ErrorGeneratorOutput
public init(output: ErrorGeneratorOutput) {
self.output = output
}
}
extension HelpControllerImpl: HelpController {
public func run() {
var helpString = ""
helpString += "Required arguments:\n"
helpString += "--mocks path - generates spies (deprecated)\n"
helpString += "--spy path - generates spies\n"
helpString += "--stub path - generates stubs\n"
helpString += "--dummy path - generates dummies\n"
output.showError(text: helpString)
}
}
| mit | 53aa3b74a56e57a8e093ba3a2edbabe6 | 23.454545 | 69 | 0.649318 | 4.055276 | false | false | false | false |
zhou9734/Warm | Warm/Classes/Experience/Model/WClass.swift | 1 | 2857 | //
// WClass.swift
// Warm
//
// Created by zhoucj on 16/9/14.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
class WClass: WRecommendData {
//分享url
var share_url: String?
//地区
var area: String?
var tags: [WTag]?
var tags_bd: [WTag]?
var heat_detail: AnyObject?
var areatimeStr: String?
var teacher: WTeacher?
var info: WInfo?
var goods: [WGoods] = [WGoods]()
override func setValue(value: AnyObject?, forKey key: String) {
if key == "tags"{
guard let _data = value as? [[String: AnyObject]] else{
return
}
var _tags = [WTag]()
for i in _data{
let tmpTag = WTag(dict: i )
_tags.append(tmpTag)
}
tags = _tags
return
}
if key == "tags_bd"{
guard let _data = value as? [[String: AnyObject]] else{
return
}
var _tags_bds = [WTag]()
for i in _data{
let temp = WTag(dict: i)
_tags_bds.append(temp)
}
tags_bd = _tags_bds
return
}
if key == "teacher"{
guard let _data = value as? [String: AnyObject] else{
return
}
teacher = WTeacher(dict: _data)
return
}
if key == "info"{
guard let _data = value as? [String: AnyObject] else{
return
}
info = WInfo(dict: _data)
return
}
if key == "goods"{
guard let _data = value as? [[String: AnyObject]] else{
return
}
var _goods = [WGoods]()
for i in _data{
let temp = WGoods(dict: i)
_goods.append(temp)
}
goods = _goods
return
}
super.setValue(value, forKey: key)
}
}
class WInfo: NSObject {
var classesid: Int64 = -1
//详细
var detail: String?
//如何参与
var buy_tips: String = ""
//提示
var warmup_tips: String = ""
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class WGoods: NSObject{
var id: Int64 = -1
var price: CGFloat = 0.0
var price_detail: String = ""
var classesid: Int64 = -1
var start_time: Int64 = -1
var end_time: Int64 = -1
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
} | mit | c39df31cc78fd60ff069bbd2e5b441f7 | 24.605505 | 76 | 0.489964 | 3.929577 | false | false | false | false |
Mogendas/apiproject | apiproject/ApiConnector.swift | 1 | 8253 | //
// ApiConnector.swift
// apiproject
//
// Created by Johan Wejdenstolpe on 2017-05-04.
// Copyright © 2017 Johan Wejdenstolpe. All rights reserved.
//
import Foundation
import MapKit
protocol ApiConnectorDelegate: class {
func showStationData(stations: [StationAnnotation])
func showWeatherData(weatherData: [String: Any])
func downloadError(error: String)
func updateDownloadTime(time: String)
}
class ApiConnector {
weak var delegate: ApiConnectorDelegate?
var searchRadius: Int = 1000
var maxResult: Int = 10
var stations: [StationAnnotation] = [StationAnnotation]()
var startDownloadTime: UInt = 0
func getStations(location: CLLocation){
var urlString = "http://api.sl.se/api2/nearbystops.json?key=11dc6f9c5b88426098e07cd020a4444c&originCoordLat="
urlString += "\(location.coordinate.latitude)"
urlString += "&originCoordLong="
urlString += "\(location.coordinate.longitude)"
urlString += "&maxresults="
urlString += "\(maxResult)"
urlString += "&radius="
urlString += "\(searchRadius)"
let url: URL = URL(string: urlString)!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) in
if error != nil {
print("Error: \(String(describing: error))")
}
if data != nil {
self.parseStationData(data!)
}else{
self.delegate?.downloadError(error: "Kunde inte ladda ner stationer")
}
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 400:
self.delegate?.downloadError(error: "Dålig förfrågan")
break
case 404:
self.delegate?.downloadError(error: "Kunde inte hitta sidan")
break
case 500:
self.delegate?.downloadError(error: "Internt fel på webbservern")
break
default:
break
}
}
}
startDownloadTime = getCurrentMilliseconds()
task.resume()
}
func parseStationData(_ data: Data) {
var jsonResult: [String: Any] = [String: Any]()
stations.removeAll()
do {
try jsonResult = JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as! [String: Any]
} catch let error as NSError {
print(error)
}
if let locationList = jsonResult["LocationList"] as? [String: Any], let stopLocations = locationList["StopLocation"] as? [[String: Any]] {
for location in stopLocations {
if let name = location["name"] as? String, let latitude = location["lat"] as? String, let longitude = location["lon"] as? String, let distance = location["dist"] as? String {
var coordinates: CLLocationCoordinate2D = CLLocationCoordinate2D()
coordinates.latitude = Double(latitude)!
coordinates.longitude = Double(longitude)!
let station = StationAnnotation(coordinate: coordinates)
station.title = formatNameOfStation(name: name)
station.distance = distance
station.coordinate = coordinates
stations.append(station)
}
}
let currentMilliseconds = getCurrentMilliseconds()
let timeToDownload: String = "\(currentMilliseconds - startDownloadTime) ms"
DispatchQueue.main.async {
self.delegate?.updateDownloadTime(time: timeToDownload)
self.delegate?.showStationData(stations: self.stations)
}
}else{
DispatchQueue.main.async {
self.delegate?.showStationData(stations: self.stations)
}
}
}
func getWeather(name: String, coordinates: CLLocationCoordinate2D){
var weatherUrl = "http://api.openweathermap.org/data/2.5/weather?lat="
weatherUrl += "\(coordinates.latitude)"
weatherUrl += "&lon="
weatherUrl += "\(coordinates.longitude)"
weatherUrl += "&appid=87a6bf1e2648b73aaac1a5fb1ac3791a"
weatherUrl += "&units=metric&lang=se"
let url: URL = URL(string: weatherUrl)!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) in
if error != nil {
print("Error: \(String(describing: error))")
}
if data != nil {
self.parseWeatherData(data!, name: name)
}else{
self.delegate?.downloadError(error: "Kunde inte ladda ner vädret")
}
if let httpResponse = response as? HTTPURLResponse {
switch httpResponse.statusCode {
case 400:
self.delegate?.downloadError(error: "Dålig förfrågan")
break
case 404:
self.delegate?.downloadError(error: "Kunde inte hitta sidan")
break
case 500:
self.delegate?.downloadError(error: "Internt fel på webbservern")
break
default:
break
}
}
}
task.resume()
}
func parseWeatherData(_ data: Data, name: String){
var jsonResult: [String: Any] = [String: Any]()
var stationWeather: [String: Any] = [String: Any]()
do {
try jsonResult = JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as! [String: Any]
} catch let error as NSError {
print(error)
}
if let weather = jsonResult["weather"] as? [[String: Any]], let weatherInfo = weather.first, let weatherMain = jsonResult["main"] as? [String: Any], let weatherWind = jsonResult["wind"] as? [String: Any] {
let tempDouble: Double = weatherMain["temp"] as! Double
let temperature: String = String(format: "%.1f", tempDouble)
let windSpeedDouble: Double = weatherWind["speed"] as! Double
let windSpeed: String = String(format: "%.1f", windSpeedDouble)
if let windDegrees = weatherWind["deg"] {
stationWeather.updateValue("\(windDegrees)", forKey: "windDeg")
}
else{
stationWeather.updateValue("0", forKey: "windDeg")
}
stationWeather.updateValue(name, forKey: "location")
stationWeather.updateValue(weatherInfo["description"]! as! String, forKey: "description")
stationWeather.updateValue(weatherInfo["icon"]! as! String, forKey: "icon")
stationWeather.updateValue("\(temperature)", forKey: "temp")
stationWeather.updateValue("\(windSpeed)", forKey: "windSpeed")
DispatchQueue.main.async {
self.delegate?.showWeatherData(weatherData: stationWeather)
}
}
}
func formatNameOfStation(name: String) -> String {
var newName:String = ""
let needle: Character = "("
if var idx = name.characters.index(of: needle) {
idx = name.characters.index(before: idx)
newName = String(name.characters.prefix(upTo: idx))
}
else {
newName = name
}
return newName
}
func getCurrentMilliseconds()->UInt{
return UInt(NSDate().timeIntervalSince1970 * 1000)
}
}
| gpl-3.0 | ba313ce44c534edf1ae41b8252276895 | 36.639269 | 213 | 0.547737 | 4.977657 | false | false | false | false |
hoolrory/VideoInfoViewer-iOS | VideoInfoViewer/MediaUtils.swift | 1 | 4541 | /**
Copyright (c) 2016 Rory Hool
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 AVFoundation
import Foundation
import UIKit
class MediaUtils {
static func renderThumbnailFromVideo(_ videoURL: URL, thumbURL: URL, time: CMTime) -> Bool {
let asset = AVURLAsset(url: videoURL, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
let rotation = getVideoRotation(videoURL)
do {
let cgImage = try imgGenerator.copyCGImage(at: time, actualTime: nil)
var uiImage = UIImage(cgImage: cgImage)
if rotation != 0 {
uiImage = uiImage.rotate(CGFloat(rotation))
}
let result = try? UIImagePNGRepresentation(uiImage)?.write(to: thumbURL, options: [.atomic])
return result != nil
} catch _ {
print("Failed to get thumbnail")
}
return false
}
static func getVideoDuration(_ videoURL: URL) -> CMTime {
let asset = AVURLAsset(url: videoURL, options: nil)
return asset.duration
}
static func getVideoResolution(_ videoURL: URL) -> CGSize {
let asset = AVURLAsset(url: videoURL, options: nil)
let videoTracks = asset.tracks(withMediaType: AVMediaTypeVideo)
if videoTracks.count == 0 {
return CGSize(width: 0, height: 0)
}
return videoTracks[0].naturalSize
}
static func getVideoFrameRate(_ videoURL:URL) -> Float {
let asset = AVURLAsset(url: videoURL, options: nil)
let videoTracks = asset.tracks(withMediaType: AVMediaTypeVideo)
if videoTracks.count == 0 {
return 0
}
return videoTracks[0].nominalFrameRate
}
static func getVideoMimeType(_ videoURL:URL) -> String {
if videoURL.lastPathComponent.contains(".mov"){
return "video/quicktime"
} else {
return "video/mp4"
}
}
static func getVideoFileSize(_ videoURL: URL) -> String {
var fileSize: UInt64 = 0
do {
let attr: NSDictionary? = try FileManager.default.attributesOfItem(atPath: videoURL.path) as NSDictionary?
if let _attr = attr {
fileSize = _attr.fileSize()
}
} catch {
print("Error: \(error)")
}
let formatter = ByteCountFormatter()
return formatter.string(fromByteCount: Int64(fileSize))
}
static func getVideoDurationFormatted(_ videoURL:URL) -> String {
let totalSeconds = CMTimeGetSeconds(getVideoDuration(videoURL))
let hours = floor(totalSeconds / 3600)
let minutes = floor(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
let seconds = totalSeconds.truncatingRemainder(dividingBy: 60)
if hours == 0 {
return NSString(format:"%02.0f:%02.0f", minutes, seconds) as String
} else {
return NSString(format:"%02.0f:%02.0f:%02.0f", hours, minutes, seconds) as String
}
}
static func getVideoBitrate(_ videoURL: URL) -> String {
let asset = AVURLAsset(url: videoURL)
let videoTracks = asset.tracks(withMediaType: AVMediaTypeVideo)
if videoTracks.count == 0 {
return ""
}
return String(format:"%.0f kbps", videoTracks[0].estimatedDataRate/1024)
}
static func getVideoRotation(_ videoURL: URL) -> Float {
let asset = AVURLAsset(url: videoURL)
let videoTracks = asset.tracks(withMediaType: AVMediaTypeVideo)
if videoTracks.count == 0 {
return 0.0
}
let transform = videoTracks[0].preferredTransform
let radians = atan2f(Float(transform.b), Float(transform.a))
let videoAngleInDegrees = (radians * 180.0) / Float(M_PI)
return videoAngleInDegrees
}
}
| apache-2.0 | 9790a22409df2f9bc3c808a0b8bf4e36 | 32.145985 | 118 | 0.603832 | 4.882796 | false | false | false | false |
shorlander/firefox-ios | XCUITests/NoImageTests.swift | 2 | 2851 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import XCTest
class NoImageTests: BaseTestCase {
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
navigator = nil
app = nil
super.tearDown()
}
private func showImages() {
app.buttons["TabToolbar.menuButton"].tap()
app.collectionViews.containing(.cell, identifier:"FindInPageMenuItem").element.swipeLeft()
let collectionViewsQuery = app.collectionViews
collectionViewsQuery.cells["ShowImageModeMenuItem"].tap()
}
private func hideImages() {
app.buttons["TabToolbar.menuButton"].tap()
app.collectionViews.containing(.cell, identifier:"FindInPageMenuItem").element.swipeLeft()
let collectionViewsQuery = app.collectionViews
collectionViewsQuery.cells["HideImageModeMenuItem"].tap()
}
private func checkShowImages() {
navigator.goto(BrowserTabMenu)
app.collectionViews.containing(.cell, identifier:"FindInPageMenuItem").element.swipeLeft()
waitforExistence(app.collectionViews.cells["ShowImageModeMenuItem"])
navigator.goto(BrowserTab)
}
private func checkHideImages() {
navigator.goto(BrowserTabMenu)
app.collectionViews.containing(.cell, identifier:"FindInPageMenuItem").element.swipeLeft()
waitforExistence(app.collectionViews.cells["HideImageModeMenuItem"])
navigator.goto(BrowserTab)
}
func testImageOnOff() {
let url1 = "www.google.com"
// Go to a webpage, and select no images or hide images, check it's hidden or not
navigator.openNewURL(urlString: url1)
if iPad() {
XCTAssertTrue(app.images.count == 3)
} else {
XCTAssertTrue(app.images.count == 2)
}
hideImages()
//After image is hidden, only image detected is the lock icon in the UI
if iPad() {
XCTAssertTrue(app.images.count == 2)
} else {
XCTAssertTrue(app.images.count == 1)
}
checkShowImages()
// Load a same page on a new tab, check images are hidden
navigator.openURL(urlString: url1)
// Open it, then select show images it, and check it's showing the images
showImages()
if iPad() {
XCTAssertTrue(app.images.count == 3)
} else {
XCTAssertTrue(app.images.count == 2)
}
checkHideImages()
}
}
| mpl-2.0 | 6278283a3837c8f24396f367b5742617 | 32.940476 | 98 | 0.627148 | 4.907057 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/00185-swift-completegenerictyperesolver-resolvegenerictypeparamtype.swift | 11 | 3803 | // 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
protocol b {
class func e()
}
struct c {
var d: b.Type
func e() {
d.e()
}
}
import Foun {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
func b<e>(e : e) -> c { e
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: Int = 1, 1)
class g<j :g
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
func a<T>() {
enum b {
case c
}
}
)
func n<w>() -> (w, w -> w) -> w {
o m o.q = {
}
{
w) {
k }
}
protocol n {
class func q()
}
class o: n{ class func q {}
func p(e: Int = x) {
}
let c = p
c()
func r<o: y, s q n<s> ==(r(t))
protocol p : p {
}
protocol p {
class func c()
}
class e: p {
class func c() { }
}
(e() u p).v.c()
k e.w == l> {
}
func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) {
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protocol h {
q k {
t w
}
w
protocol k : w { func v <h: h m h.p == k>(l: h.p) {
}
}
protocol h {
n func w(w:
}
class h<u : h> {
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
func n<p>() -> (p, p -> p) -> p {
b, l]
g(o(q))
h e {
j class func r()
}
class k: h{ class func r {}
var k = 1
var s: r -> r t -> r) -> r m
u h>] {
u []
}
func r(e: () -> ()) {
}
class n {
var _ = r()
| apache-2.0 | f5a9330dda2935a4452bddbc5e477406 | 13.137546 | 78 | 0.417828 | 2.325994 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/Frontend/Home/TopSites/TopSitesViewModelTests.swift | 2 | 2869 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import XCTest
@testable import Client
import Shared
import Storage
import SyncTelemetry
class TopSitesViewModelTests: XCTestCase {
var profile: MockProfile!
override func setUp() {
super.setUp()
self.profile = MockProfile(databasePrefix: "FxHomeTopSitesViewModelTests")
FeatureFlagsManager.shared.initializeDeveloperFeatures(with: profile)
}
override func tearDown() {
super.tearDown()
self.profile.shutdown()
self.profile = nil
}
func testDeletionOfSingleSuggestedSite() {
let viewModel = TopSitesViewModel(profile: profile,
isZeroSearch: false,
theme: LightTheme(),
wallpaperManager: WallpaperManager())
let topSitesProvider = TopSitesProviderImplementation(browserHistoryFetcher: profile.history,
prefs: profile.prefs)
let siteToDelete = topSitesProvider.defaultTopSites(profile.prefs)[0]
viewModel.hideURLFromTopSites(siteToDelete)
let newSites = topSitesProvider.defaultTopSites(profile.prefs)
XCTAssertFalse(newSites.contains(siteToDelete, f: { (first, second) -> Bool in
return first.url == second.url
}))
}
func testDeletionOfAllDefaultSites() {
let viewModel = TopSitesViewModel(profile: self.profile,
isZeroSearch: false,
theme: LightTheme(),
wallpaperManager: WallpaperManager())
let topSitesProvider = TopSitesProviderImplementation(browserHistoryFetcher: profile.history,
prefs: profile.prefs)
let defaultSites = topSitesProvider.defaultTopSites(profile.prefs)
defaultSites.forEach({
viewModel.hideURLFromTopSites($0)
})
let newSites = topSitesProvider.defaultTopSites(profile.prefs)
XCTAssertTrue(newSites.isEmpty)
}
}
// MARK: Helper methods
extension TopSitesViewModelTests {
func createViewModel(overridenSiteCount: Int = 40, overridenNumberOfRows: Int = 2) -> TopSitesViewModel {
let viewModel = TopSitesViewModel(profile: self.profile,
isZeroSearch: false,
theme: LightTheme(),
wallpaperManager: WallpaperManager())
trackForMemoryLeaks(viewModel)
return viewModel
}
}
| mpl-2.0 | 8f489fa44206f20bcf849f08d41ea97f | 36.75 | 109 | 0.596026 | 5.761044 | false | true | false | false |
RedMadRobot/DAO | Example/DAO/Classes/Model/RealmDatabase/DBBook.swift | 1 | 390 | //
// DBBook.swift
// DAO
//
// Created by Ivan Vavilov on 5/17/17.
// Copyright © 2017 RedMadRobot LLC. All rights reserved.
//
import DAO
import RealmSwift
final class DBBook: DBEntity {
@objc dynamic var name: String = ""
let authors = List<String>()
let dates = List<Date>()
let pages = List<Int>()
let attachments = List<Data>()
}
| mit | 4046c12995429e814865ca7acd1c74e5 | 14.56 | 58 | 0.59383 | 3.504505 | false | false | false | false |
TG908/iOS | TUM Campus App/NewsManager.swift | 1 | 2970 | //
// NewsManages.swift
// TUM Campus App
//
// Created by Mathias Quintero on 7/21/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class NewsManager: Manager {
static var news = [News]()
var single = false
required init(mainManager: TumDataManager) {
}
init(single: Bool) {
self.single = single
}
func fetchData(_ handler: @escaping ([DataElement]) -> ()) {
if NewsManager.news.isEmpty {
if let uuid = UIDevice.current.identifierForVendor?.uuidString {
Alamofire.request(getURL(), method: .get, parameters: nil,
headers: ["X-DEVICE-ID": uuid]).responseJSON() { (response) in
if let data = response.result.value {
if let json = JSON(data).array {
for item in json {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let title = item["title"].string,
let link = item["link"].string,
let dateString = item["date"].string,
let id = item["news"].string,
let date = dateformatter.date(from: dateString) {
let image = item["image"].string
let newsItem = News(id: id, date: date, title: title, link: link, image: image)
NewsManager.news.append(newsItem)
}
}
self.handleNews(handler)
}
}
}
}
} else {
handleNews(handler)
}
}
func handleNews(_ handler: ([DataElement]) -> ()) {
if single {
if let story = getNextUpcomingNews() {
handler([story])
}
} else {
let items = NewsManager.news.sorted { (a, b) in
return a.date.compare(b.date as Date) == ComparisonResult.orderedDescending
}
var returnableArray = [DataElement]()
for item in items {
returnableArray.append(item)
}
handler(returnableArray)
}
}
func getNextUpcomingNews(in news: [News] = NewsManager.news) -> News? {
let now = Date()
if let firstStory = news.filter({ $0.date > now }).last ?? news.first {
return firstStory
}
return nil
}
func getURL() -> String {
return TumCabeApi.BaseURL.rawValue + TumCabeApi.News.rawValue
}
}
| gpl-3.0 | 230e0d509fdccd41b844d8fcbaed50b7 | 33.126437 | 115 | 0.453014 | 5.190559 | false | false | false | false |
zhoujihang/SwiftNetworkAgent | Source/Network/NetworkUploadAgent.swift | 1 | 9743 | //
// NetworkUploadAgent.swift
// Mara
//
// Created by 周际航 on 2016/12/14.
// Copyright © 2016年 com.maramara. All rights reserved.
//
import Foundation
import Alamofire
extension UploadRequestProtocol {
var net_agent: NetworkUploadAgent<Self> {return NetworkUploadAgent(self)}
}
typealias NetworkUploadProgress = (_ progress: Progress) -> Void
typealias NetworkUploadSuccess<T: UploadRequestProtocol> = (_ parseResponse: T.ResponseType) -> Void
typealias NetworkUploadFailure = (_ error: RequestError) -> Void
final class NetworkUploadAgent<T: UploadRequestProtocol> {
fileprivate(set) var isFinished: Bool = false // 请求是否已经完成
fileprivate(set) var isCanceled: Bool = false // 请求是否被cancel
fileprivate var isHintErrorInfo: Bool = true // 是否使用吐司工具提示用户网络错误的信息,默认提示
fileprivate weak var needLoadingVC: UIViewController? // 需要自动显示loading的页面
fileprivate var customUploadRequest: T
fileprivate var uploadSessionManager: Alamofire.SessionManager
fileprivate var alamofireUploadRequest: Alamofire.UploadRequest?
fileprivate var networkProgress: NetworkUploadProgress?
fileprivate var networkSuccess: NetworkUploadSuccess<T>?
fileprivate var networkFailure: NetworkUploadFailure?
init(_ uploadRequest: T) {
self.customUploadRequest = uploadRequest
let configuration = NetworkUploadAgent.generateConfiguration(by: uploadRequest)
self.uploadSessionManager = Alamofire.SessionManager(configuration: configuration)
}
// MARK: 上传 data 二进制数据
func uploadData(progress: @escaping NetworkUploadProgress, success: @escaping NetworkUploadSuccess<T>, failure: @escaping NetworkUploadFailure) -> NetworkUploadAgent {
guard let uploadData = self.customUploadRequest.uploadData else {
assert(false, "NetworkUploadAgent<\(type(of: self.customUploadRequest))>: uploadData不可为nil")
return self
}
self.cancel()
self.networkProgress = progress
self.networkSuccess = success
self.networkFailure = {
[weak self] error in
self?.commonFailureBlock(error)
failure(error)
}
let url = self.customUploadRequest.requestUrl
let method = Alamofire.HTTPMethod.post
let headers = self.customUploadRequest.headers
let handler = self.responseCompletionHandler()
self.uploadSessionManager.upload(uploadData, to: url, method: method, headers: headers).uploadProgress(closure: progress).responseJSON(completionHandler: handler)
return self
}
// MARK: 上传 multipartFormData 数据
func uploadMultipartFormData(progress: @escaping NetworkUploadProgress, success: @escaping NetworkUploadSuccess<T>, failure: @escaping NetworkUploadFailure) -> NetworkUploadAgent {
guard let multipartFormData = self.customUploadRequest.multipartFormDataBlock else {
assert(false, "NetworkUploadAgent<\(type(of: self.customUploadRequest))>: multipartFormData不可为nil")
return self
}
self.cancel()
self.networkProgress = progress
self.networkSuccess = success
self.networkFailure = {
[weak self] error in
self?.commonFailureBlock(error)
failure(error)
}
let url = self.customUploadRequest.requestUrl
let method = Alamofire.HTTPMethod.post
let headers = self.customUploadRequest.headers
let handler = self.responseCompletionHandler()
let encodingCompletion: (((Alamofire.SessionManager.MultipartFormDataEncodingResult) -> Void)?) = {
[weak self] encodingResult in
switch encodingResult {
case .success(let upload, _, _):
self?.alamofireUploadRequest = upload.uploadProgress { progress in
self?.networkProgress?(progress)
}.responseJSON(completionHandler: handler)
case .failure(let error):
defer {
self?.isFinished = true
self?.needLoadingVC?.ldt_loadingCountReduce()
}
self?.networkFailure?(RequestError.alamofireError(error))
}
}
self.uploadSessionManager.upload(multipartFormData: multipartFormData, to: url, method: method, headers: headers, encodingCompletion: encodingCompletion)
return self
}
@discardableResult
func cancel() -> NetworkUploadAgent {
self.alamofireUploadRequest?.cancel()
self.isCanceled = true
return self
}
}
// MARK: - 扩展 预处理网络结果
extension NetworkUploadAgent {
fileprivate func responseCompletionHandler() -> (Alamofire.DataResponse<Any>) -> Void {
let handler: ((Alamofire.DataResponse<Any>) -> Void) = {
[weak self] response in
defer {
self?.isFinished = true
self?.needLoadingVC?.ldt_loadingCountReduce()
}
// 1. 无 response 错误
guard let httpReponse = response.response else {
self?.networkFailure?(RequestError.responseNone)
return
}
switch response.result {
// 2. alamofire的错误
case .failure(let error):
self?.networkFailure?(RequestError.alamofireError(error))
case .success(let json):
if httpReponse.statusCode != 200 {
guard let dic = json as? [String: Any] else {
self?.networkFailure?(RequestError.responseParseNil(json))
return
}
guard let errorModel = RequestErrorModel(JSON: dic) else {
self?.networkFailure?(RequestError.responseParseNil(json))
return
}
// 3. 非 200 错误
self?.networkFailure?(RequestError.responseCodeError(errorModel))
return
}
if let parse = self?.customUploadRequest.parse(json) {
self?.networkSuccess?(parse)
} else {
// 4. 返回结果转模型失败错误
self?.networkFailure?(RequestError.responseParseNil(json))
}
}
}
return handler
}
fileprivate func commonFailureBlock(_ error: RequestError) {
self.printNetworkError(error)
guard self.isHintErrorInfo else {return}
let info = "上传失败"
switch error {
case RequestError.alamofireError(let error):
// alamofire错误
guard let afError = error as? AFError else {break}
switch afError {
case .responseValidationFailed(reason: let reason):
switch reason {
case .unacceptableStatusCode(code: let code):
if code == 401 {
// 交由 OAuth2Handler处理过了,这里不再重复提示
return
}
default: break
}
default: break
}
info.ext_hint()
return
case RequestError.responseCodeError(let errorModel):
// 后台提示错误
if let message = errorModel.error?.message {
message.ext_hint()
return
}
info.ext_hint()
return
default:
info.ext_hint()
}
}
}
// MARK: - 扩展 生成configuration
extension NetworkUploadAgent {
fileprivate static func generateConfiguration(by request: T) -> URLSessionConfiguration {
var additionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
for (key, value) in request.commonHeaders{
additionalHeaders.updateValue(value, forKey: key)
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = additionalHeaders
configuration.timeoutIntervalForRequest = request.timeoutForRequest
return configuration
}
}
// MARK: - 扩展 针对 LoadingTool 的加载框便利方法
extension NetworkUploadAgent {
func needLoading(_ viewController: UIViewController) -> NetworkUploadAgent {
self.needLoadingVC = viewController
self.needLoadingVC?.ldt_loadingCountAdd()
return self
}
}
// MARK: - 扩展 针对 HintTool 的错误弹窗便利方法
extension NetworkUploadAgent {
func hintErrorInfo(_ hint: Bool) -> NetworkUploadAgent {
self.isHintErrorInfo = hint
return self
}
}
// MARK: - 扩展 debug下,默认打印错误信息
extension NetworkUploadAgent {
fileprivate func printNetworkError(_ error: RequestError) {
#if DEBUG
let request = self.customUploadRequest
let url = request.requestUrl
let parameters = request.parameters
let headers = request.headers
debugPrint("=========================")
debugPrint("网络返回错误 url:\(url)")
debugPrint("method:post")
debugPrint("parameters:\(parameters)")
debugPrint("headers:\(headers)")
debugPrint("error:\(error)")
debugPrint("=========================")
#endif
}
}
| mit | 81cdb370c5cfb9f9b964cc5e49a79d80 | 37.064777 | 184 | 0.603063 | 5.351167 | false | false | false | false |
arvedviehweger/swift | stdlib/public/core/OutputStream.swift | 4 | 20101 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
//===----------------------------------------------------------------------===//
// Input/Output interfaces
//===----------------------------------------------------------------------===//
/// A type that can be the target of text-streaming operations.
///
/// You can send the output of the standard library's `print(_:to:)` and
/// `dump(_:to:)` functions to an instance of a type that conforms to the
/// `TextOutputStream` protocol instead of to standard output. Swift's
/// `String` type conforms to `TextOutputStream` already, so you can capture
/// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of
/// logging it to standard output.
///
/// var s = ""
/// for n in 1...5 {
/// print(n, terminator: "", to: &s)
/// }
/// // s == "12345"
///
/// Conforming to the TextOutputStream Protocol
/// ===========================================
///
/// To make your custom type conform to the `TextOutputStream` protocol,
/// implement the required `write(_:)` method. Functions that use a
/// `TextOutputStream` target may call `write(_:)` multiple times per writing
/// operation.
///
/// As an example, here's an implementation of an output stream that converts
/// any input to its plain ASCII representation before sending it to standard
/// output.
///
/// struct ASCIILogger: TextOutputStream {
/// mutating func write(_ string: String) {
/// let ascii = string.unicodeScalars.lazy.map { scalar in
/// scalar == "\n"
/// ? "\n"
/// : scalar.escaped(asASCII: true)
/// }
/// print(ascii.joined(separator: ""), terminator: "")
/// }
/// }
///
/// The `ASCIILogger` type's `write(_:)` method processes its string input by
/// escaping each Unicode scalar, with the exception of `"\n"` line returns.
/// By sending the output of the `print(_:to:)` function to an instance of
/// `ASCIILogger`, you invoke its `write(_:)` method.
///
/// let s = "Hearts ♡ and Diamonds ♢"
/// print(s)
/// // Prints "Hearts ♡ and Diamonds ♢"
///
/// var asciiLogger = ASCIILogger()
/// print(s, to: &asciiLogger)
/// // Prints "Hearts \u{2661} and Diamonds \u{2662}"
public protocol TextOutputStream {
mutating func _lock()
mutating func _unlock()
/// Appends the given string to the stream.
mutating func write(_ string: String)
}
extension TextOutputStream {
public mutating func _lock() {}
public mutating func _unlock() {}
}
/// A source of text-streaming operations.
///
/// Instances of types that conform to the `TextOutputStreamable` protocol can
/// write their value to instances of any type that conforms to the
/// `TextOutputStream` protocol. The Swift standard library's text-related
/// types, `String`, `Character`, and `UnicodeScalar`, all conform to
/// `TextOutputStreamable`.
///
/// Conforming to the TextOutputStreamable Protocol
/// =====================================
///
/// To add `TextOutputStreamable` conformance to a custom type, implement the
/// required `write(to:)` method. Call the given output stream's `write(_:)`
/// method in your implementation.
public protocol TextOutputStreamable {
/// Writes a textual representation of this instance into the given output
/// stream.
func write<Target : TextOutputStream>(to target: inout Target)
}
@available(*, unavailable, renamed: "TextOutputStreamable")
typealias Streamable = TextOutputStreamable
/// A type with a customized textual representation.
///
/// Types that conform to the `CustomStringConvertible` protocol can provide
/// their own representation to be used when converting an instance to a
/// string. The `String(describing:)` initializer is the preferred way to
/// convert an instance of *any* type to a string. If the passed instance
/// conforms to `CustomStringConvertible`, the `String(describing:)`
/// initializer and the `print(_:)` function use the instance's custom
/// `description` property.
///
/// Accessing a type's `description` property directly or using
/// `CustomStringConvertible` as a generic constraint is discouraged.
///
/// Conforming to the CustomStringConvertible Protocol
/// ==================================================
///
/// Add `CustomStringConvertible` conformance to your custom types by defining
/// a `description` property.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library:
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(p)
/// // Prints "Point(x: 21, y: 30)"
///
/// After implementing the `description` property and declaring
/// `CustomStringConvertible` conformance, the `Point` type provides its own
/// custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(p)
/// // Prints "(21, 30)"
///
/// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible`
public protocol CustomStringConvertible {
/// A textual representation of this instance.
///
/// Instead of accessing this property directly, convert an instance of any
/// type to a string by using the `String(describing:)` initializer. For
/// example:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(describing: p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
var description: String { get }
}
/// A type that can be represented as a string in a lossless, unambiguous way.
///
/// For example, the integer value 1050 can be represented in its entirety as
/// the string "1050".
///
/// The description property of a conforming type must be a value-preserving
/// representation of the original value. As such, it should be possible to
/// re-create an instance from its string representation.
public protocol LosslessStringConvertible : CustomStringConvertible {
/// Instantiates an instance of the conforming type from a string
/// representation.
init?(_ description: String)
}
/// A type with a customized textual representation suitable for debugging
/// purposes.
///
/// Swift provides a default debugging textual representation for any type.
/// That default representation is used by the `String(reflecting:)`
/// initializer and the `debugPrint(_:)` function for types that don't provide
/// their own. To customize that representation, make your type conform to the
/// `CustomDebugStringConvertible` protocol.
///
/// Because the `String(reflecting:)` initializer works for instances of *any*
/// type, returning an instance's `debugDescription` if the value passed
/// conforms to `CustomDebugStringConvertible`, accessing a type's
/// `debugDescription` property directly or using
/// `CustomDebugStringConvertible` as a generic constraint is discouraged.
///
/// Conforming to the CustomDebugStringConvertible Protocol
/// =======================================================
///
/// Add `CustomDebugStringConvertible` conformance to your custom types by
/// defining a `debugDescription` property.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library:
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing the
/// `debugDescription` property, `Point` provides its own custom debugging
/// representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// - SeeAlso: `String.init<T>(reflecting: T)`, `CustomStringConvertible`
public protocol CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
var debugDescription: String { get }
}
//===----------------------------------------------------------------------===//
// Default (ad-hoc) printing
//===----------------------------------------------------------------------===//
@_silgen_name("swift_EnumCaseName")
func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>?
@_silgen_name("swift_OpaqueSummary")
func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>?
/// Do our best to print a value that cannot be printed directly.
@_semantics("optimize.sil.specialize.generic.never")
internal func _adHocPrint_unlocked<T, TargetStream : TextOutputStream>(
_ value: T, _ mirror: Mirror, _ target: inout TargetStream,
isDebugPrint: Bool
) {
func printTypeName(_ type: Any.Type) {
// Print type names without qualification, unless we're debugPrint'ing.
target.write(_typeName(type, qualified: isDebugPrint))
}
if let displayStyle = mirror.displayStyle {
switch displayStyle {
case .optional:
if let child = mirror.children.first {
_debugPrint_unlocked(child.1, &target)
} else {
_debugPrint_unlocked("nil", &target)
}
case .tuple:
target.write("(")
var first = true
for (label, value) in mirror.children {
if first {
first = false
} else {
target.write(", ")
}
if let label = label {
if !label.isEmpty && label[label.startIndex] != "." {
target.write(label)
target.write(": ")
}
}
_debugPrint_unlocked(value, &target)
}
target.write(")")
case .struct:
printTypeName(mirror.subjectType)
target.write("(")
var first = true
for (label, value) in mirror.children {
if let label = label {
if first {
first = false
} else {
target.write(", ")
}
target.write(label)
target.write(": ")
_debugPrint_unlocked(value, &target)
}
}
target.write(")")
case .enum:
if let cString = _getEnumCaseName(value),
let caseName = String(validatingUTF8: cString) {
// Write the qualified type name in debugPrint.
if isDebugPrint {
printTypeName(mirror.subjectType)
target.write(".")
}
target.write(caseName)
} else {
// If the case name is garbage, just print the type name.
printTypeName(mirror.subjectType)
}
if let (_, value) = mirror.children.first {
if Mirror(reflecting: value).displayStyle == .tuple {
_debugPrint_unlocked(value, &target)
} else {
target.write("(")
_debugPrint_unlocked(value, &target)
target.write(")")
}
}
default:
target.write(_typeName(mirror.subjectType))
}
} else if let metatypeValue = value as? Any.Type {
// Metatype
printTypeName(metatypeValue)
} else {
// Fall back to the type or an opaque summary of the kind
if let cString = _opaqueSummary(mirror.subjectType),
let opaqueSummary = String(validatingUTF8: cString) {
target.write(opaqueSummary)
} else {
target.write(_typeName(mirror.subjectType, qualified: true))
}
}
}
@_versioned
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
@_semantics("stdlib_binary_only")
internal func _print_unlocked<T, TargetStream : TextOutputStream>(
_ value: T, _ target: inout TargetStream
) {
// Optional has no representation suitable for display; therefore,
// values of optional type should be printed as a debug
// string. Check for Optional first, before checking protocol
// conformance below, because an Optional value is convertible to a
// protocol if its wrapped type conforms to that protocol.
if _isOptional(type(of: value)) {
let debugPrintable = value as! CustomDebugStringConvertible
debugPrintable.debugDescription.write(to: &target)
return
}
if case let streamableObject as TextOutputStreamable = value {
streamableObject.write(to: &target)
return
}
if case let printableObject as CustomStringConvertible = value {
printableObject.description.write(to: &target)
return
}
if case let debugPrintableObject as CustomDebugStringConvertible = value {
debugPrintableObject.debugDescription.write(to: &target)
return
}
let mirror = Mirror(reflecting: value)
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false)
}
/// Returns the result of `print`'ing `x` into a `String`.
///
/// Exactly the same as `String`, but annotated 'readonly' to allow
/// the optimizer to remove calls where results are unused.
///
/// This function is forbidden from being inlined because when building the
/// standard library inlining makes us drop the special semantics.
@_inlineable
@_versioned
@inline(never) @effects(readonly)
func _toStringReadOnlyStreamable<T : TextOutputStreamable>(_ x: T) -> String {
var result = ""
x.write(to: &result)
return result
}
@_inlineable
@_versioned
@inline(never) @effects(readonly)
func _toStringReadOnlyPrintable<T : CustomStringConvertible>(_ x: T) -> String {
return x.description
}
//===----------------------------------------------------------------------===//
// `debugPrint`
//===----------------------------------------------------------------------===//
@_semantics("optimize.sil.specialize.generic.never")
@inline(never)
public func _debugPrint_unlocked<T, TargetStream : TextOutputStream>(
_ value: T, _ target: inout TargetStream
) {
if let debugPrintableObject = value as? CustomDebugStringConvertible {
debugPrintableObject.debugDescription.write(to: &target)
return
}
if let printableObject = value as? CustomStringConvertible {
printableObject.description.write(to: &target)
return
}
if let streamableObject = value as? TextOutputStreamable {
streamableObject.write(to: &target)
return
}
let mirror = Mirror(reflecting: value)
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)
}
@_semantics("optimize.sil.specialize.generic.never")
internal func _dumpPrint_unlocked<T, TargetStream : TextOutputStream>(
_ value: T, _ mirror: Mirror, _ target: inout TargetStream
) {
if let displayStyle = mirror.displayStyle {
// Containers and tuples are always displayed in terms of their element
// count
switch displayStyle {
case .tuple:
let count = mirror.children.count
target.write(count == 1 ? "(1 element)" : "(\(count) elements)")
return
case .collection:
let count = mirror.children.count
target.write(count == 1 ? "1 element" : "\(count) elements")
return
case .dictionary:
let count = mirror.children.count
target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs")
return
case .`set`:
let count = mirror.children.count
target.write(count == 1 ? "1 member" : "\(count) members")
return
default:
break
}
}
if let debugPrintableObject = value as? CustomDebugStringConvertible {
debugPrintableObject.debugDescription.write(to: &target)
return
}
if let printableObject = value as? CustomStringConvertible {
printableObject.description.write(to: &target)
return
}
if let streamableObject = value as? TextOutputStreamable {
streamableObject.write(to: &target)
return
}
if let displayStyle = mirror.displayStyle {
switch displayStyle {
case .`class`, .`struct`:
// Classes and structs without custom representations are displayed as
// their fully qualified type name
target.write(_typeName(mirror.subjectType, qualified: true))
return
case .`enum`:
target.write(_typeName(mirror.subjectType, qualified: true))
if let cString = _getEnumCaseName(value),
let caseName = String(validatingUTF8: cString) {
target.write(".")
target.write(caseName)
}
return
default:
break
}
}
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)
}
//===----------------------------------------------------------------------===//
// OutputStreams
//===----------------------------------------------------------------------===//
internal struct _Stdout : TextOutputStream {
mutating func _lock() {
_swift_stdlib_flockfile_stdout()
}
mutating func _unlock() {
_swift_stdlib_funlockfile_stdout()
}
mutating func write(_ string: String) {
if string.isEmpty { return }
if let asciiBuffer = string._core.asciiBuffer {
defer { _fixLifetime(string) }
_swift_stdlib_fwrite_stdout(
UnsafePointer(asciiBuffer.baseAddress!),
asciiBuffer.count,
1)
return
}
for c in string.utf8 {
_swift_stdlib_putchar_unlocked(Int32(c))
}
}
}
extension String : TextOutputStream {
/// Appends the given string to this string.
///
/// - Parameter other: A string to append.
public mutating func write(_ other: String) {
self += other
}
}
//===----------------------------------------------------------------------===//
// Streamables
//===----------------------------------------------------------------------===//
extension String : TextOutputStreamable {
/// Writes the string into the given output stream.
///
/// - Parameter target: An output stream.
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(self)
}
}
extension Character : TextOutputStreamable {
/// Writes the character into the given output stream.
///
/// - Parameter target: An output stream.
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(String(self))
}
}
extension UnicodeScalar : TextOutputStreamable {
/// Writes the textual representation of the Unicode scalar into the given
/// output stream.
///
/// - Parameter target: An output stream.
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(String(Character(self)))
}
}
/// A hook for playgrounds to print through.
public var _playgroundPrintHook : ((String) -> Void)? = {_ in () }
internal struct _TeeStream<
L : TextOutputStream,
R : TextOutputStream
> : TextOutputStream {
var left: L
var right: R
/// Append the given `string` to this stream.
mutating func write(_ string: String)
{ left.write(string); right.write(string) }
mutating func _lock() { left._lock(); right._lock() }
mutating func _unlock() { right._unlock(); left._unlock() }
}
@available(*, unavailable, renamed: "TextOutputStream")
public typealias OutputStreamType = TextOutputStream
extension TextOutputStreamable {
@available(*, unavailable, renamed: "write(to:)")
public func writeTo<Target : TextOutputStream>(_ target: inout Target) {
Builtin.unreachable()
}
}
| apache-2.0 | a44d79821d36cf604bbe0a248c38c7c9 | 32.488333 | 80 | 0.617877 | 4.607429 | false | false | false | false |
gzios/SystemLearn | SwiftBase/可选类型.playground/Contents.swift | 1 | 1450 | //: Playground - noun: a place where people can play
import UIKit
//需要创建但是不是直接使用的对象或者是变量
var str = "Hello, playground"
//对象中的任意属性都必须有初始化值 都必须有明确的初始化值
class Student: NSObject {
let name = "why"
// var names : String = nil 这是错误的写法 不能赋值为nil
}
// 1.定义可选类型
// 1.1 不常用的方式
var name : Optional<String> = nil;
// 1.2 语法糖!常用的方式 一般的开发都是这样使用的
var name2 : String? = nil
// 2.给可选类型赋值
name = "why"
// 可选类型中的值
// 可选类型取值 是需要强制解包的
// 可选类型+!
print(name!)
// 4.注意强制解包是非常危险的,如果以可选类型为nil,强制解包是会崩溃的
//建议在强制解包前对可选类型进行判断,判读是否为nil
if name != nil {
print(name!)
print(name!)
print(name!)
print(name!)
print(name!)
print(name!)
print(name!)
}
//每次用都是需要解包的
// 可选绑定
// 1.判断name是否有值,如果没有值就直接不执行{}
// 2.如果name有值,系统会自动将我name进行解包并且赋值给temp
if let temp = name {
print(temp)
print(temp)
print(temp)
print(temp)
print(temp)
}
// 2.常用
if let name = name {
print(name)
}
| apache-2.0 | 727bce5b43f8dde878095da65e62e728 | 11.275 | 53 | 0.598778 | 2.625668 | false | false | false | false |
muneebm/AsterockX | AsterockX/BaseTableViewController.swift | 1 | 1351 | //
// BasseTableViewController.swift
// AsterockX
//
// Created by Muneeb Rahim Abdul Majeed on 1/4/16.
// Copyright © 2016 beenum. All rights reserved.
//
import UIKit
import CoreData
class BaseTableViewController: UITableViewController {
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
var coreDataStack: CoreDataStack {
return CoreDataStack.sharedInstance()
}
var sharedContext: NSManagedObjectContext {
return coreDataStack.managedObjectContext
}
func startActitvityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.view.window?.userInteractionEnabled = false
self.view.window?.addSubview(self.activityIndicator)
self.activityIndicator.center = (self.view.window?.center)!
self.view.window?.alpha = 0.75
self.activityIndicator.startAnimating()
}
}
func stopActivityIndicator() {
dispatch_async(dispatch_get_main_queue()) {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
self.view.window?.alpha = 1
self.view.window?.userInteractionEnabled = true
}
}
}
| mit | 4b34b6df3b7e36196e1869d091bbc0a2 | 27.125 | 110 | 0.639259 | 5.378486 | false | false | false | false |
jpush/jchat-swift | JChat/Src/Utilites/Utility/JCVideoManager.swift | 1 | 1995 | //
// JCVideoManager.swift
// JChat
//
// Created by JIGUANG on 2017/4/26.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import AVFoundation
import AVKit
class JCVideoManager {
static func playVideo(data: Data, _ fileType: String = "MOV", currentViewController: UIViewController) {
let playVC = AVPlayerViewController()
let filePath = "\(NSHomeDirectory())/Documents/abcd." + fileType
if JCFileManager.saveFileToLocal(data: data, savaPath: filePath) {
let url = URL(fileURLWithPath: filePath)
let player = AVPlayer(url: url)
playVC.player = player
currentViewController.present(playVC, animated: true, completion: nil)
}
}
static func playVideo(path: String, currentViewController: UIViewController) {
let playVC = AVPlayerViewController()
let url = URL(fileURLWithPath: path)
let player = AVPlayer(url: url)
playVC.player = player
currentViewController.present(playVC, animated: true, completion: nil)
}
static func getFristImage(data: Data) -> UIImage? {
let filePath = "\(NSHomeDirectory())/Documents/getImage.MOV"
if !JCFileManager.saveFileToLocal(data: data, savaPath: filePath) {
return nil
}
let videoURL = URL(fileURLWithPath: filePath)
let avAsset = AVAsset(url: videoURL)
let generator = AVAssetImageGenerator(asset: avAsset)
generator.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(0.0,preferredTimescale: 600)
var actualTime = CMTimeMake(value: 0,timescale: 0)
do {
let imageRef = try generator.copyCGImage(at: time, actualTime: &actualTime)
let frameImg = UIImage(cgImage: imageRef)
return frameImg
} catch {
return UIImage.createImage(color: .gray, size: CGSize(width: 160, height: 120))
}
}
}
| mit | 067655a01c6e9ae85a4c791346ba5f63 | 34.571429 | 108 | 0.641064 | 4.632558 | false | false | false | false |
juliand665/LeagueKit | Sources/LeagueKit/Model/Static Data/Rune.swift | 1 | 2787 | import Foundation
public final class Runes: WritableAssetProvider {
public typealias AssetType = RunePath
public typealias Raw = [RunePath]
public static let shared = load()
public static let assetIdentifier = "runesReforged"
public var contents: [RunePath] = []
public var version = "N/A"
public required init() {}
}
public final class RunePath: Asset {
public typealias Provider = Runes
public let id: Int
public let key: String
public let name: String
public let slots: [[Rune]]
public let imageName: String
public var imageURL: URL {
return StaticDataClient.dataURL(path: "/cdn/img/\(imageName)")
}
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self)
if decoder.useAPIFormat {
let dataContainer = try decoder.container(keyedBy: DataCodingKeys.self)
try slots = container.decode([RawSlot].self, forKey: .slots).map { $0.runes }
try imageName = dataContainer.decodeValue(forKey: .imageName)
} else {
try slots = container.decodeValue(forKey: .slots)
try imageName = container.decodeValue(forKey: .imageName)
}
try id = container.decodeValue(forKey: .id)
try key = container.decodeValue(forKey: .key)
try name = container.decodeValue(forKey: .name)
}
/// translate riot's data into something usable
private enum DataCodingKeys: String, CodingKey {
case imageName = "icon"
}
private struct RawSlot: Decodable {
var runes: [Rune]
}
}
public final class Rune: Codable, Identified {
public let id: Int
public let key: String
public let name: String
public let summary: String
public let description: String
public let imageName: String
public var imageURL: URL {
return StaticDataClient.dataURL(path: "/cdn/img/\(imageName)")
}
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self)
if decoder.useAPIFormat {
let dataContainer = try decoder.container(keyedBy: DataCodingKeys.self)
try summary = dataContainer.decodeValue(forKey: .summary)
try description = dataContainer.decodeValue(forKey: .description)
try imageName = dataContainer.decodeValue(forKey: .imageName)
} else {
try summary = container.decodeValue(forKey: .summary)
try description = container.decodeValue(forKey: .description)
try imageName = container.decodeValue(forKey: .imageName)
}
try id = container.decodeValue(forKey: .id)
try key = container.decodeValue(forKey: .key)
try name = container.decodeValue(forKey: .name)
}
/// translate riot's data into something usable
private enum DataCodingKeys: String, CodingKey {
case summary = "shortDesc"
case description = "longDesc"
case imageName = "icon"
}
}
| mit | 4a5302e976997b8f1d63e055594ee380 | 28.03125 | 89 | 0.733405 | 3.781547 | false | false | false | false |
bitomule/ReactiveSwiftRealm | Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/ActionSpec.swift | 1 | 8470 | //
// ActionSpec.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-12-11.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import Dispatch
import Result
import Nimble
import Quick
import ReactiveSwift
class ActionSpec: QuickSpec {
override func spec() {
describe("Action") {
var action: Action<Int, String, NSError>!
var enabled: MutableProperty<Bool>!
var executionCount = 0
var completedCount = 0
var values: [String] = []
var errors: [NSError] = []
var scheduler: TestScheduler!
let testError = NSError(domain: "ActionSpec", code: 1, userInfo: nil)
beforeEach {
executionCount = 0
completedCount = 0
values = []
errors = []
enabled = MutableProperty(false)
scheduler = TestScheduler()
action = Action(enabledIf: enabled) { number in
return SignalProducer { observer, disposable in
executionCount += 1
if number % 2 == 0 {
observer.send(value: "\(number)")
observer.send(value: "\(number)\(number)")
scheduler.schedule {
observer.sendCompleted()
}
} else {
scheduler.schedule {
observer.send(error: testError)
}
}
}
}
action.values.observeValues { values.append($0) }
action.errors.observeValues { errors.append($0) }
action.completed.observeValues { completedCount += 1 }
}
it("should retain the state property") {
var property: MutableProperty<Bool>? = MutableProperty(false)
weak var weakProperty = property
var action: Action<(), (), NoError>? = Action(state: property!, enabledIf: { _ in true }) { _ in
return .empty
}
expect(weakProperty).toNot(beNil())
property = nil
expect(weakProperty).toNot(beNil())
action = nil
expect(weakProperty).to(beNil())
// Mute "unused variable" warning.
_ = action
}
it("should be disabled and not executing after initialization") {
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
it("should error if executed while disabled") {
var receivedError: ActionError<NSError>?
var disabledErrorsTriggered = false
action.disabledErrors.observeValues {
disabledErrorsTriggered = true
}
action.apply(0).startWithFailed {
receivedError = $0
}
expect(receivedError).notTo(beNil())
expect(disabledErrorsTriggered) == true
if let error = receivedError {
let expectedError = ActionError<NSError>.disabled
expect(error == expectedError) == true
}
}
it("should enable and disable based on the given property") {
enabled.value = true
expect(action.isEnabled.value) == true
expect(action.isExecuting.value) == false
enabled.value = false
expect(action.isEnabled.value) == false
expect(action.isExecuting.value) == false
}
it("should not deadlock") {
final class ViewModel {
let action2 = Action<(), (), NoError> { SignalProducer(value: ()) }
}
let action1 = Action<(), ViewModel, NoError> { SignalProducer(value: ViewModel()) }
// Fixed in #267. (https://github.com/ReactiveCocoa/ReactiveSwift/pull/267)
//
// The deadlock happened as the observer disposable releases the closure
// `{ _ in viewModel }` here without releasing the mapped signal's
// `updateLock` first. The deinitialization of the closure triggered the
// propagation of terminal event of the `Action`, which eventually hit
// the mapped signal and attempted to acquire `updateLock` to transition
// the signal's state.
action1.values
.flatMap(.latest) { viewModel in viewModel.action2.values.map { _ in viewModel } }
.observeValues { _ in }
action1.apply().start()
action1.apply().start()
}
if #available(macOS 10.10, *) {
it("should not loop indefinitely") {
let condition = MutableProperty(1)
let action = Action<Void, Void, NoError>(state: condition, enabledIf: { $0 == 0 }) { _ in
return .empty
}
let disposable = CompositeDisposable()
waitUntil(timeout: 0.01) { done in
let target = DispatchQueue(label: "test target queue")
let highPriority = QueueScheduler(qos: .userInitiated, targeting: target)
let lowPriority = QueueScheduler(qos: .default, targeting: target)
disposable += action.isExecuting.producer
.observe(on: highPriority)
.startWithValues { _ in
condition.value = 10
}
disposable += lowPriority.schedule {
done()
}
}
disposable.dispose()
}
}
describe("completed") {
beforeEach {
enabled.value = true
}
it("should send a value whenever the producer completes") {
action.apply(0).start()
expect(completedCount) == 0
scheduler.run()
expect(completedCount) == 1
action.apply(2).start()
scheduler.run()
expect(completedCount) == 2
}
it("should not send a value when the producer fails") {
action.apply(1).start()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the producer is interrupted") {
let disposable = action.apply(0).start()
disposable.dispose()
scheduler.run()
expect(completedCount) == 0
}
it("should not send a value when the action is disabled") {
enabled.value = false
action.apply(0).start()
scheduler.run()
expect(completedCount) == 0
}
}
describe("execution") {
beforeEach {
enabled.value = true
}
it("should execute successfully") {
var receivedValue: String?
action.apply(0)
.assumeNoErrors()
.startWithValues {
receivedValue = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
it("should execute with an error") {
var receivedError: ActionError<NSError>?
action.apply(1).startWithFailed {
receivedError = $0
}
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(receivedError).notTo(beNil())
if let error = receivedError {
let expectedError = ActionError<NSError>.producerFailed(testError)
expect(error == expectedError) == true
}
expect(values) == []
expect(errors) == [ testError ]
}
}
describe("bindings") {
it("should execute successfully") {
var receivedValue: String?
let (signal, observer) = Signal<Int, NoError>.pipe()
action.values.observeValues { receivedValue = $0 }
action <~ signal
enabled.value = true
expect(executionCount) == 0
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
observer.send(value: 0)
expect(executionCount) == 1
expect(action.isExecuting.value) == true
expect(action.isEnabled.value) == false
expect(receivedValue) == "00"
expect(values) == [ "0", "00" ]
expect(errors) == []
scheduler.run()
expect(action.isExecuting.value) == false
expect(action.isEnabled.value) == true
expect(values) == [ "0", "00" ]
expect(errors) == []
}
}
}
describe("using a property as input") {
let echo: (Int) -> SignalProducer<Int, NoError> = SignalProducer.init(value:)
it("executes the action with the property's current value") {
let input = MutableProperty(0)
let action = Action(input: input, echo)
var values: [Int] = []
action.values.observeValues { values.append($0) }
input.value = 1
action.apply().start()
input.value = 2
action.apply().start()
input.value = 3
action.apply().start()
expect(values) == [1, 2, 3]
}
it("is disabled if the property is nil") {
let input = MutableProperty<Int?>(1)
let action = Action(input: input, echo)
expect(action.isEnabled.value) == true
input.value = nil
expect(action.isEnabled.value) == false
}
}
}
}
| mit | f233c0a170462bb050de20c3040259a9 | 24.744681 | 100 | 0.630933 | 3.78125 | false | false | false | false |
luki/Telegraphum | Telegraphum/MainController.swift | 1 | 19833 | //
// ViewController.swift
// Telegraphum
//
// Created by L on 16/06/42.817.
// Copyright © 42.817 Lukas Mueller. All rights reserved.
//
import UIKit
import AudioToolbox
import AVFoundation
class MainController: UIViewController {
let telegram = Telegram(method: .toMorse, substitution: .itu)
var player = AVQueuePlayer()
let substitutions = ["International", "Continental"]
// UI Elements
// Upper
let topBackground: UIView = {
let tb = UIView()
tb.falseAutoResizingMaskTranslation()
tb.backgroundColor = .black
return tb
}()
let sectionOneLabel: UILabel = {
let label = UILabel()
label.falseAutoResizingMaskTranslation()
label.font = UIFont(name: "Okomito-Medium", size: 29 / 2)
label.textColor = UIColor(red: 166 / 255.0, green: 166 / 255.0, blue: 166 / 255.0, alpha: 1)
label.text = NSLocalizedString("section-one-label", comment: "")
return label
}()
lazy var sectionOneText: UITextView = {
let tv = UITextView()
tv.falseAutoResizingMaskTranslation()
tv.font = UIFont(name: "Okomito-Regular", size: 35 / 2)
tv.textColor = UIColor(red: 217 / 255.0, green: 217 / 255.0, blue: 217 / 255.0, alpha: 1)
// TODO: fixme
tv.tintColor = UIColor.green
tv.text = NSLocalizedString("example-text", comment: "")
tv.backgroundColor = .clear
tv.textContainer.lineFragmentPadding = 0
tv.textContainerInset = .zero
tv.delegate = self
tv.keyboardType = .asciiCapable
tv.keyboardAppearance = .dark
return tv
}()
// lazy var transcribeButton: UIButton = {
// let tb = UIButton()
// tb.falseAutoResizingMaskTranslation()
// tb.setTitle("Transcribe", for: .normal)
// tb.addTarget(self, action: #selector(transcribe), for: .touchUpInside)
// tb.setTitleColor(UIColor(red: 85/255, green: 215/255, blue: 130/250, alpha: 1.0), for: .normal)
// tb.setTitleColor(.black, for: .highlighted)
// tb.titleLabel?.font = UIFont(name: "Okomito-Medium", size: 29/2)
// return tb
// }()
lazy var selectionButton: UIButton = {
let tb = UIButton()
tb.falseAutoResizingMaskTranslation()
tb.setTitle(NSLocalizedString("selection-title", comment: ""), for: .normal)
tb.addTarget(self, action: #selector(selectionAction), for: .touchUpInside)
tb.setTitleColor(UIColor.darkGray, for: .normal)
tb.setTitleColor(.black, for: .highlighted)
tb.titleLabel?.font = UIFont(name: "Okomito-Bold", size: 29 / 2)
tb.backgroundColor = .lightGray
tb.layer.cornerRadius = 17
tb.clipsToBounds = true
return tb
}()
// Lower half
let lowerHalfArea: UIView = {
let v = UIView()
v.falseAutoResizingMaskTranslation()
v.backgroundColor = .clear
return v
}()
let sectionTwoLabel: UILabel = {
let label = UILabel()
label.falseAutoResizingMaskTranslation()
label.font = UIFont(name: "Okomito-Medium", size: 29 / 2)
label.textColor = UIColor(red: 166 / 255.0, green: 166 / 255.0, blue: 166 / 255.0, alpha: 1)
label.text = NSLocalizedString("section-two-label", comment: "")
return label
}()
let sectionTwoText: UITextView = {
let tv = UITextView()
tv.falseAutoResizingMaskTranslation()
tv.font = UIFont(name: "Okomito-Regular", size: 35 / 2)
tv.textColor = UIColor(red: 102 / 255.0, green: 102 / 255.0, blue: 102 / 255.0, alpha: 1)
// TODO: fixme
tv.tintColor = UIColor.green
tv.backgroundColor = .clear
tv.textContainer.lineFragmentPadding = 0
tv.textContainerInset = .zero
tv.isEditable = false
return tv
}()
var playButton: UIButton = {
let tb = UIButton()
tb.falseAutoResizingMaskTranslation()
tb.contentMode = .scaleAspectFit
tb.setImage(UIImage(named: "play"), for: .normal)
// tb.setTitle("Play", for: .normal)
tb.addTarget(self, action: #selector(play), for: .touchUpInside)
tb.setTitleColor(UIColor(red: 85 / 255, green: 215 / 255, blue: 130 / 250, alpha: 1.0), for: .normal)
tb.setTitleColor(.black, for: .highlighted)
tb.setTitleColor(.darkGray, for: .disabled)
tb.titleLabel?.font = UIFont(name: "Okomito-Medium", size: 29 / 2)
return tb
}()
var flashButton: UIButton = {
let tb = UIButton()
tb.falseAutoResizingMaskTranslation()
tb.contentMode = .scaleAspectFit
tb.setImage(UIImage(named: "flashlight"), for: .normal)
// tb.setTitle("Play", for: .normal)
tb.addTarget(self, action: #selector(flashlightAction), for: .touchUpInside)
tb.setTitleColor(UIColor(red: 85 / 255, green: 215 / 255, blue: 130 / 250, alpha: 1.0), for: .normal)
tb.setTitleColor(.black, for: .highlighted)
tb.setTitleColor(.darkGray, for: .disabled)
tb.titleLabel?.font = UIFont(name: "Okomito-Medium", size: 29 / 2)
return tb
}()
let copyButton: UIButton = {
let tb = UIButton()
tb.falseAutoResizingMaskTranslation()
tb.contentMode = .scaleAspectFit
tb.setImage(UIImage(named: "clipboard"), for: .normal)
// tb.setTitle("Play", for: .normal)
tb.addTarget(self, action: #selector(copyText), for: .touchUpInside)
tb.setTitleColor(UIColor(red: 85 / 255, green: 215 / 255, blue: 130 / 250, alpha: 1.0), for: .normal)
tb.setTitleColor(.black, for: .highlighted)
tb.setTitleColor(.darkGray, for: .disabled)
tb.titleLabel?.font = UIFont(name: "Okomito-Medium", size: 29 / 2)
return tb
}()
lazy var selectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 467 / 2, height: 52 / 2)
layout.minimumLineSpacing = 0
let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: 467 / 2, height: 188 / 2), collectionViewLayout: layout)
cv.falseAutoResizingMaskTranslation()
cv.backgroundColor = UIColor(red: 23 / 255.0, green: 23 / 255.0, blue: 23 / 255.0, alpha: 1.0)
// cv.isScrollEnabled = false
cv.layer.cornerRadius = 1.5
cv.clipsToBounds = true
cv.dataSource = self
cv.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: -4, right: 0)
cv.register(SelectionCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
customView.backgroundColor = UIColor.darkGray
customView.addSubview(selectionButton)
NSLayoutConstraint.activate([
selectionButton.leadingAnchor.constraint(equalTo: customView.leadingAnchor, constant: 5),
selectionButton.trailingAnchor.constraint(equalTo: customView.trailingAnchor, constant: -5),
selectionButton.topAnchor.constraint(equalTo: customView.topAnchor, constant: 5),
selectionButton.bottomAnchor.constraint(equalTo: customView.bottomAnchor, constant: -5),
])
sectionOneText.inputAccessoryView = customView
view.backgroundColor = UIColor(red: 14 / 255.0, green: 14 / 255.0, blue: 14 / 255.0, alpha: 1.0)
addSubviews(to: view, views: topBackground, lowerHalfArea)
addSubviews(to: topBackground, views: sectionOneLabel, sectionOneText /* transcribeButton, selectionButton */ )
addSubviews(to: lowerHalfArea, views: sectionTwoLabel, sectionTwoText, playButton, flashButton, copyButton)
addConstraints(
topBackground.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.45),
topBackground.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topBackground.trailingAnchor.constraint(equalTo: view.trailingAnchor),
topBackground.topAnchor.constraint(equalTo: view.topAnchor),
sectionOneText.leadingAnchor.constraint(equalTo: topBackground.leadingAnchor, constant: 42.8),
sectionOneText.trailingAnchor.constraint(equalTo: topBackground.trailingAnchor, constant: -42.8),
sectionOneText.centerYAnchor.constraint(equalTo: topBackground.centerYAnchor),
sectionOneLabel.leadingAnchor.constraint(equalTo: topBackground.leadingAnchor, constant: 42.8),
sectionOneText.heightAnchor.constraint(equalToConstant: 128 / 2),
sectionOneLabel.trailingAnchor.constraint(equalTo: topBackground.trailingAnchor, constant: -42.8),
sectionOneLabel.bottomAnchor.constraint(equalTo: sectionOneText.topAnchor, constant: -8),
// transcribeButton.trailingAnchor.constraint(equalTo: topBackground.trailingAnchor, constant: -42.8),
// transcribeButton.topAnchor.constraint(equalTo: sectionOneText.bottomAnchor, constant: 5),
//
// selectionButton.leadingAnchor.constraint(equalTo: topBackground.leadingAnchor, constant: 42.8),
// selectionButton.topAnchor.constraint(equalTo: sectionOneText.bottomAnchor, constant: 5),
lowerHalfArea.leadingAnchor.constraint(equalTo: view.leadingAnchor),
lowerHalfArea.trailingAnchor.constraint(equalTo: view.trailingAnchor),
lowerHalfArea.bottomAnchor.constraint(equalTo: view.bottomAnchor),
lowerHalfArea.heightAnchor.constraint(equalToConstant: UIScreen.main.bounds.height * 0.55),
sectionTwoText.centerYAnchor.constraint(equalTo: lowerHalfArea.centerYAnchor),
sectionTwoText.leadingAnchor.constraint(equalTo: lowerHalfArea.leadingAnchor, constant: 42.8),
sectionTwoText.trailingAnchor.constraint(equalTo: lowerHalfArea.trailingAnchor, constant: -42.8),
sectionTwoText.heightAnchor.constraint(equalToConstant: 152 / 2),
sectionTwoLabel.bottomAnchor.constraint(equalTo: sectionTwoText.topAnchor, constant: -8),
sectionTwoLabel.leadingAnchor.constraint(equalTo: lowerHalfArea.leadingAnchor, constant: 42.8),
sectionTwoLabel.trailingAnchor.constraint(equalTo: lowerHalfArea.trailingAnchor, constant: -42.8),
playButton.topAnchor.constraint(equalTo: sectionTwoText.bottomAnchor, constant: 72 / 2),
playButton.heightAnchor.constraint(equalToConstant: 20),
playButton.widthAnchor.constraint(equalToConstant: 20.5),
playButton.trailingAnchor.constraint(equalTo: lowerHalfArea.trailingAnchor, constant: -42.8),
flashButton.trailingAnchor.constraint(equalTo: playButton.leadingAnchor, constant: -12.5),
flashButton.centerYAnchor.constraint(equalTo: playButton.centerYAnchor),
flashButton.heightAnchor.constraint(equalToConstant: 20),
flashButton.widthAnchor.constraint(equalToConstant: 12.5),
copyButton.leadingAnchor.constraint(equalTo: lowerHalfArea.leadingAnchor, constant: 42.8),
copyButton.centerYAnchor.constraint(equalTo: flashButton.centerYAnchor),
copyButton.heightAnchor.constraint(equalToConstant: 22.5),
copyButton.widthAnchor.constraint(equalToConstant: 20.5)
)
hideLower()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func touchesBegan(_: Set<UITouch>, with _: UIEvent?) {
view.endEditing(true)
}
// Actions / Targets
@objc func selectionAction() {
transcribeMethodAlert()
}
func transcribe() {
telegram.substitution = .itu
if lowerHalfArea.isHidden {
lowerHalfArea.isHidden = false
switch telegram.method {
case .toPhrase:
presentLowerInState(isToMorse: false)
case .toMorse:
presentLowerInState(isToMorse: true)
}
}
sectionTwoText.text = telegram.translate(text: sectionOneText.text)!
}
@objc func play(_ sender: UIButton) {
if player.items().count == 0 {
let sharedInstance = AVAudioSession.sharedInstance()
// Needs to be active to notice changes in volume
try! sharedInstance.setActive(true)
if AVAudioSession.sharedInstance().outputVolume == 0 {
showWarningMessageOn(view, message: NSLocalizedString("volume-message", comment: ""))
return
}
sender.isEnabled = false
playMorse(sectionTwoText.text)
player.play()
} else {
player.pause()
player.removeAllItems()
}
}
// App Helpers: Play
func playMorse(_ code: String) {
for char in code.characters {
switch String(char) {
case "-":
playSound(fileName: "long", ext: "wav")
case ".":
playSound(fileName: "short", ext: "wav")
case "/":
playSound(fileName: "break", ext: "wav")
default:
continue
// print(char)
// print("Unknown file.")
}
}
playButton.isEnabled = true
}
@objc func copyText() {
showWarningMessageOn(view, message: NSLocalizedString("clipboard-message", comment: ""))
UIPasteboard.general.string = sectionTwoText.text
}
func playSound(fileName name: String, ext: String) {
player.insert(AVPlayerItem(url: Bundle.main.url(forResource: name, withExtension: ext)!), after: player.items().last)
}
@objc func flashlightAction() {
if let text = sectionTwoText.text {
let intervals: [Double] = text.characters.map {
switch String($0) {
case ".":
return 0.25
case "-":
return 0.8
case "/":
return -0.8
default:
return 0
}
}
flashLight(withInterval: intervals)
}
}
func flashLight(withInterval i: [Double]) {
var timeToCome = 0.0
i.forEach { time in
timeToCome += time
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + timeToCome, execute: {
if time > 0 {
self.useFlashlight(turnOn: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
// print("Flashing ", time)
self.useFlashlight(turnOn: false)
}
} else if time < 0 {
self.useFlashlight(turnOn: false)
// print("Pause ", time)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + (time * time).squareRoot()) {
}
}
})
}
}
func useFlashlight(turnOn: Bool) {
if let device = AVCaptureDevice.default(for: AVMediaType.video), device.hasTorch {
do {
try device.lockForConfiguration()
try device.setTorchModeOn(level: 1.0)
if turnOn { device.torchMode = .on } else { device.torchMode = .off }
} catch {
// print("Hello")
}
}
}
func showWarningMessageOn(_ mainView: UIView, message: String) {
let background: UIView = {
let bg = UIView()
bg.backgroundColor = .white
bg.layer.cornerRadius = 16
bg.clipsToBounds = true
bg.translatesAutoresizingMaskIntoConstraints = false
return bg
}()
let warningLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.text = message
label.textColor = .black
label.font = UIFont(name: "Okomito-Bold", size: 29)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
background.addSubview(warningLabel)
mainView.addSubview(background)
NSLayoutConstraint.activate([
background.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
background.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
background.centerXAnchor.constraint(equalTo: view.centerXAnchor),
background.centerYAnchor.constraint(equalTo: view.centerYAnchor),
warningLabel.centerXAnchor.constraint(equalTo: background.centerXAnchor),
warningLabel.centerYAnchor.constraint(equalTo: background.centerYAnchor),
warningLabel.leadingAnchor.constraint(equalTo: background.leadingAnchor, constant: 20),
warningLabel.trailingAnchor.constraint(equalTo: background.trailingAnchor, constant: -20),
background.heightAnchor.constraint(equalTo: warningLabel.heightAnchor, constant: 40),
])
UIView.animate(withDuration: 3, animations: {
background.alpha = 0
})
}
func transcribeMethodAlert() {
let alert = UIAlertController(title: NSLocalizedString("transcribe-alert-title", comment: ""), message: NSLocalizedString("transcribe-alert-message", comment: ""), preferredStyle: .alert)
let a1 = UIAlertAction(title: NSLocalizedString("transcribe-option-to-morse", comment: ""), style: .default) { _ in
self.telegram.method = .toMorse
self.selectionButton.setTitle(NSLocalizedString("transcribe-option-to-morse", comment: ""), for: .normal)
}
let a2 = UIAlertAction(title: NSLocalizedString("transcribe-option-to-phrase", comment: ""), style: .default) { _ in
self.telegram.method = .toPhrase
self.selectionButton.setTitle(NSLocalizedString("transcribe-option-to-phrase", comment: ""), for: .normal)
}
let a3 = UIAlertAction(title: NSLocalizedString("transcribe-option-later", comment: ""), style: .cancel) { _ in
self.dismiss(animated: true, completion: nil)
}
alert.addActions(a1, a2, a3)
present(alert, animated: true, completion: nil)
}
// Hide lower section
func hideLower() {
lowerHalfArea.isHidden = true
}
func presentLowerInState(isToMorse: Bool) {
flashButton.isHidden = !isToMorse
playButton.isHidden = !isToMorse
}
// Helpers
func addSubviews(to parent: UIView, views: UIView...) {
views.forEach { parent.addSubview($0) }
}
func addConstraints(_ consts: NSLayoutConstraint...) {
NSLayoutConstraint.activate(consts)
}
}
extension MainController: UICollectionViewDataSource {
func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SelectionCell
cell.contentLabel.text = substitutions[indexPath.row]
return cell
}
}
extension MainController: UITextViewDelegate {
func textViewDidChange(_: UITextView) {
transcribe()
}
}
extension UIView {
func falseAutoResizingMaskTranslation() {
translatesAutoresizingMaskIntoConstraints = false
}
}
extension UIAlertController {
func addActions(_ actions: UIAlertAction...) {
actions.forEach { self.addAction($0) }
}
}
| apache-2.0 | 0c71e379d14ce1cdd8e77c7c4717f60b | 39.391039 | 195 | 0.626866 | 4.641236 | false | false | false | false |
LQJJ/demo | 86-DZMeBookRead-master/DZMeBookRead/DZMeBookRead/other/global/DZMGlobalMethod.swift | 1 | 6082 | //
// DZMGlobalMethod.swift
// DZMeBookRead
//
// Created by 邓泽淼 on 2017/5/11.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
// MARK: -- 颜色
/// RGB
func RGB(_ r:CGFloat,g:CGFloat,b:CGFloat) -> UIColor {
return RGBA(r, g: g, b: b, a: 1.0)
}
/// RGBA
func RGBA(_ r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat) -> UIColor {
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}
// MARK: -- 尺寸计算 以iPhone6为比例
func DZMSizeW(_ size:CGFloat) ->CGFloat {
return size * (ScreenWidth / 375)
}
func DZMSizeH(_ size:CGFloat) ->CGFloat{
return size * (ScreenHeight / 667)
}
// MARK: 截屏
/// 获得截屏视图(无值获取当前Window)
func ScreenCapture(_ view:UIView? = nil, _ isSave:Bool = false) ->UIImage {
let captureView = (view ?? (UIApplication.shared.keyWindow ?? UIApplication.shared.windows.first))!
UIGraphicsBeginImageContextWithOptions(captureView.frame.size, false, 0.0)
captureView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if isSave { UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil) }
return image!
}
// MARK: -- 创建分割线
/// 给一个视图创建添加一条分割线 高度 : HJSpaceLineHeight
func SpaceLineSetup(view:UIView, color:UIColor? = nil) ->UIView {
let spaceLine = UIView()
spaceLine.backgroundColor = color != nil ? color : UIColor.lightGray
view.addSubview(spaceLine)
return spaceLine
}
// MARK: -- 获取时间
/// 获取当前时间传入 时间格式 "YYYY-MM-dd-HH-mm-ss"
func GetCurrentTimerString(dateFormat:String) ->String {
let dateformatter = DateFormatter()
dateformatter.dateFormat = dateFormat
return dateformatter.string(from: Date())
}
/// 将 时间 根据 类型 转成 时间字符串
func GetTimerString(dateFormat:String, date:Date) ->String {
let dateformatter = DateFormatter()
dateformatter.dateFormat = dateFormat
return dateformatter.string(from: date)
}
/// 获取当前的 TimeIntervalSince1970 时间字符串
func GetCurrentTimeIntervalSince1970String() -> String {
return String(format: "%.0f",Date().timeIntervalSince1970)
}
// MARK: -- 阅读ViewFrame
/// 阅读TableView的位置
func GetReadTableViewFrame() ->CGRect {
if isX {
// Y = 刘海高度 + 状态View高 + 间距
let y = TopLiuHeight + DZMSpace_2 + DZMSpace_6
let bottomHeight = TopLiuHeight
return CGRect(x: DZMSpace_1, y: y, width: ScreenWidth - 2 * DZMSpace_1, height: ScreenHeight - y - bottomHeight)
}else{
// Y = 状态View高 + 间距
let y = DZMSpace_2 + DZMSpace_6
return CGRect(x: DZMSpace_1, y: y, width: ScreenWidth - 2 * DZMSpace_1, height: ScreenHeight - 2 * y)
}
}
// MARK: 阅读视图位置
/* 阅读视图位置
需要做横竖屏的可以在这里修改阅读View的大小
GetReadViewFrame 会使用与 阅读View的Frame 以及计算分页的范围
*/
func GetReadViewFrame() ->CGRect {
return CGRect(x: 0, y: 0, width: GetReadTableViewFrame().width, height: GetReadTableViewFrame().height)
}
// MARK: -- 创建文件夹
/// 创建文件夹 如果存在则不创建
func CreatFilePath(_ filePath:String) ->Bool {
let fileManager = FileManager.default
// 文件夹是否存在
if fileManager.fileExists(atPath: filePath) {
return true
}
do{
try fileManager.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)
return true
}catch{}
return false
}
// MARK: -- 文件链接处理
/// 文件类型
func GetFileExtension(_ url:URL) ->String {
return url.path.pathExtension()
}
/// 文件名称
func GetFileName(_ url:URL) ->String {
return url.path.lastPathComponent().stringByDeletingPathExtension()
}
// MARK: -- 阅读页面获取文件方法
/// 主文件夹名称
private let ReadFolderName:String = "DZMeBookRead"
/// 归档阅读文件文件
func ReadKeyedArchiver(folderName:String,fileName:String,object:AnyObject) {
var path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!) + "/\(ReadFolderName)/\(folderName)"
if (CreatFilePath(path)) { // 创建文件夹成功或者文件夹存在
path = path + "/\(fileName)"
NSKeyedArchiver.archiveRootObject(object, toFile: path)
}
}
/// 解档阅读文件文件
func ReadKeyedUnarchiver(folderName:String,fileName:String) ->AnyObject? {
let path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as String) + "/\(ReadFolderName)/\(folderName)") + "/\(fileName)"
return NSKeyedUnarchiver.unarchiveObject(withFile: path) as AnyObject?
}
/// 删除阅读归档文件
func ReadKeyedRemoveArchiver(folderName:String,fileName:String? = nil) {
var path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as String) + "/\(ReadFolderName)/\(folderName)")
if fileName != nil { path += "/\(fileName!)" }
do{
try FileManager.default.removeItem(atPath: path)
}catch{}
}
/// 是否存在了改归档文件
func ReadKeyedIsExistArchiver(folderName:String,fileName:String? = nil) ->Bool {
var path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as String) + "/\(ReadFolderName)/\(folderName)")
if fileName != nil { path += "/\(fileName!)" }
return FileManager.default.fileExists(atPath: path)
}
| apache-2.0 | 4379024c439d82fcb61d879fde4deaa6 | 25.461905 | 230 | 0.670866 | 3.95516 | false | false | false | false |
allenlinli/Wildlife-League | Wildlife League/GameScene.swift | 1 | 3823 | //
// GameScene.swift
// Wildlife League
//
// Created by allenlin on 7/8/14.
// Copyright (c) 2014 Raccoonism. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
let beedLayer = SKNode()
let TileWidth: CGFloat = 320.0/6.0
let TileHeight: CGFloat = 568.0/2.0/5.0
var board: Board!
var beedToMove :Beed?
var beedMoving :Beed?
var beedSwapped :Beed?
required init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(color: UIColor(red: 0.8, green: 1, blue: 1, alpha: 1), size: CGSizeMake(320, 568))
var point = background.position
background.position = point
addChild(background)
let layerPosition = CGPoint(
x: -TileWidth * CGFloat(NumColumns) / 2,
y: -TileHeight*2 * CGFloat(NumRows) / 2)
beedLayer.position = layerPosition
let backgroundLayer = SKSpriteNode(color: UIColor.grayColor(), size: CGSizeMake(320, 568/2))
point = backgroundLayer.position
point.y = -568/2/2
backgroundLayer.position = point
var mask = SKSpriteNode(color: UIColor.grayColor(), size: CGSizeMake(320, 568/2))
mask.position = point
var cropNode = SKCropNode();
cropNode.addChild(beedLayer)
cropNode.maskNode = mask
background.addChild(backgroundLayer)
background.addChild(cropNode)
}
func roundSpriteBeedNode (color :UIColor, size :CGSize)-> SKNode{
var mask = SKShapeNode(path: CGPathCreateWithRoundedRect(CGRectMake(0, 0, TileWidth, TileHeight), 8.0, 8.0, nil))
var sprite = SKSpriteNode(color: color, size: size)
var cropNode = SKCropNode()
cropNode.addChild(sprite)
cropNode.maskNode = mask
return sprite
}
func addSpritesForBoard(board :Board) {
for beed in board.grid {
if let realBeed = beed{
if (realBeed.beedType==BeedType.BeedTypeEmpty) {
continue
}
let sprite = self.roundSpriteBeedNode(realBeed.beedType.spriteColor, size: CGSizeMake(TileWidth, TileHeight))
sprite.position = pointAtColumn(realBeed.column, row: realBeed.row)
sprite.setScale(0.8)
beedLayer.addChild(sprite)
realBeed.sprite = sprite
}
}
}
func addCopyBeedOnBoard(#beedToCopy :Beed, location :CGPoint) {
beedMoving = beedToCopy.copy()
beedMoving!.sprite!.alpha = 0.7
beedMoving!.sprite!.position = location
beedLayer.addChild(beedMoving!.sprite)
}
func _delay(block :()->(), delayInSeconds :NSTimeInterval) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
block()
})
}
}
extension GameScene {
func convertPointToBoardCoordinate(point :CGPoint) -> (Bool, Int, Int) {
if (point.x >= 0 && point.x < CGFloat(NumColumns)*self.TileWidth &&
point.y >= 0 && point.y < CGFloat(NumRows)*self.TileHeight) {
return (true, Int(point.x/TileWidth), NumRows - Int(point.y/TileHeight) - 1)
}
else {
return (false, 0, 0)
}
}
func pointAtColumn(column: Int, row: Int) -> CGPoint {
return CGPoint (x: CGFloat(column)*TileWidth + TileWidth/2, y: CGFloat(NumRows-1) * TileHeight - CGFloat(row)*TileHeight + TileHeight/2)
}
}
| apache-2.0 | 07b604becb55be58c897fd164dc846a0 | 32.831858 | 144 | 0.595082 | 4.019979 | false | false | false | false |
EdwinSaenz/GraphingCalculator | StanfordCalculator/CalculatorBrain.swift | 1 | 5830 | //
// CalculatorBrain.swift
// StanfordCalculator
//
// Created by Edwin Aaron Saenz on 2/18/15.
// Copyright (c) 2015 Edwin Aaron Saenz. All rights reserved.
//
import Foundation
class CalculatorBrain {
private enum Op: CustomStringConvertible {
case Operand(Double)
case UnaryOperation(String, Double -> Double)
case BinaryOperation(String, Int, (Double, Double) -> Double)
case Constant(String, Double)
case Variable(String)
var description: String {
get {
switch self {
case .Operand(let operand):
return "\(operand)"
case .UnaryOperation(let symbol, _):
return symbol
case .BinaryOperation(let symbol, _, _):
return symbol
case .Constant(let symbol, _):
return "\(symbol)"
case .Variable(let symbol):
return "\(symbol)"
}
}
}
}
var variableValues = Dictionary<String,Double>()
private var opStack = [Op]()
private var knownOps = [String:Op]()
init() {
func learnOp(op: Op) {
knownOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", Int.max, *))
learnOp(Op.BinaryOperation("÷", Int.max) { $1 / $0 })
learnOp(Op.BinaryOperation("+", 1, +))
learnOp(Op.BinaryOperation("-", 1) { $1 - $0 })
learnOp(Op.UnaryOperation("√", sqrt))
learnOp(Op.UnaryOperation("sin", sin))
learnOp(Op.UnaryOperation("cos", cos))
learnOp(Op.UnaryOperation("ᐩ/-") { $0 * -1 })
learnOp(Op.Constant("π", M_PI))
}
var description: String {
get {
var description = ""
var evaluation = evaluateDescription(opStack)
while(evaluation.result != "?") {
description = "\(evaluation.result), \(description)"
evaluation = evaluateDescription(evaluation.remainingOps)
}
let lastIndex = advance(description.endIndex, -2)
return description[description.startIndex..<lastIndex]
}
}
func clear() {
opStack = [Op]()
variableValues = Dictionary<String,Double>()
}
func evaluate() -> Double? {
let (result, remainder) = evaluate(opStack)
print("\(opStack) = \(result) with \(remainder) left over")
return result
}
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.Operand(operand))
return evaluate()
}
func pushOperand(symbol: String) -> Double? {
opStack.append(Op.Variable(symbol))
return evaluate()
}
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let operand):
return (operand, remainingOps)
case .UnaryOperation(_, let operation):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
return (operation(operand), operandEvaluation.remainingOps)
}
case .BinaryOperation(_, _, let operation):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
case .Constant(_, let constant):
return (constant, remainingOps)
case .Variable(let symbol):
let value = variableValues[symbol]
return (value, remainingOps)
}
}
return (nil, ops)
}
private func evaluateDescription(ops: [Op]) -> (result: String, opPrecedence: Int, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .UnaryOperation(let symbol, _):
let description = evaluateDescription(remainingOps)
return ("\(symbol)(\(description.result))", Int.max, description.remainingOps)
case .BinaryOperation(let symbol, let precedence, _):
let evaluation = evaluateDescription(remainingOps)
let evaluation2 = evaluateDescription(evaluation.remainingOps)
let evaluationsPrecedenceIsLower = evaluation.opPrecedence < precedence
if evaluationsPrecedenceIsLower {
return ("\(evaluation2.result) " + symbol + " (\(evaluation.result))", precedence, evaluation2.remainingOps)
} else {
return ("\(evaluation2.result) " + symbol + " \(evaluation.result)", precedence, evaluation2.remainingOps)
}
case .Operand(let operand):
return ("\(operand)", Int.max, remainingOps)
case .Constant(let constant, _):
return ("\(constant)", Int.max, remainingOps)
case .Variable(let variable):
return ("\(variable)", Int.max, remainingOps)
}
}
return ("?", Int.max, ops)
}
} | mit | d7af79399beecc418089d04eec5a02c2 | 34.950617 | 128 | 0.53615 | 4.985445 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Permission/MicrophonePrompting.swift | 1 | 2297 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Localization
import PlatformKit
import ToolKit
public protocol MicrophonePrompting: AnyObject {
var permissionsRequestor: PermissionsRequestor { get set }
var microphonePromptingDelegate: MicrophonePromptingDelegate? { get set }
func checkMicrophonePermissions()
func willUseMicrophone()
}
extension MicrophonePrompting {
public func checkMicrophonePermissions() {
permissionsRequestor.requestPermissions([.microphone]) { [weak self] in
guard let self = self else { return }
self.microphonePromptingDelegate?.onMicrophonePromptingComplete()
}
}
public func willUseMicrophone() {
guard PermissionsRequestor.shouldDisplayMicrophonePermissionsRequest() else {
microphonePromptingDelegate?.onMicrophonePromptingComplete()
return
}
microphonePromptingDelegate?.promptToAcceptMicrophonePermissions(confirmHandler: checkMicrophonePermissions)
}
}
public protocol MicrophonePromptingDelegate: AnyObject {
var analyticsRecorder: AnalyticsEventRecorderAPI { get }
func onMicrophonePromptingComplete()
func promptToAcceptMicrophonePermissions(confirmHandler: @escaping (() -> Void))
}
extension MicrophonePromptingDelegate {
public func promptToAcceptMicrophonePermissions(confirmHandler: @escaping (() -> Void)) {
let okay = AlertAction(style: .confirm(LocalizationConstants.okString))
let notNow = AlertAction(style: .default(LocalizationConstants.KYC.notNow))
let model = AlertModel(
headline: LocalizationConstants.KYC.allowMicrophoneAccess,
body: LocalizationConstants.KYC.enableMicrophoneDescription,
actions: [okay, notNow]
)
let alert = AlertView.make(with: model) { output in
switch output.style {
case .confirm,
.default:
self.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreMicApprove)
confirmHandler()
case .dismiss:
self.analyticsRecorder.record(event: AnalyticsEvents.Permission.permissionPreMicDecline)
}
}
alert.show()
}
}
| lgpl-3.0 | 39ec10e29e7f5ca394bac84c14957781 | 36.032258 | 116 | 0.706446 | 5.30254 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressStatsWidgets/Views/StatsWidgetsView.swift | 2 | 4788 | import SwiftUI
import WidgetKit
struct StatsWidgetsView: View {
@Environment(\.widgetFamily) var family: WidgetFamily
let timelineEntry: StatsWidgetEntry
@ViewBuilder
var body: some View {
switch timelineEntry {
case .loggedOut(let widgetKind):
UnconfiguredView(widgetKind: widgetKind)
.widgetURL(nil)
// This seems to prevent a bug where the URL for subsequent widget
// types is being triggered if one isn't specified here.
case .noData:
UnconfiguredView(widgetKind: .noStats)
.widgetURL(nil)
case .siteSelected(let content, _):
if let viewData = makeGroupedViewData(from: content) {
switch family {
case .systemSmall:
SingleStatView(viewData: viewData)
.widgetURL(viewData.statsURL)
.padding()
case .systemMedium:
MultiStatsView(viewData: viewData)
.widgetURL(viewData.statsURL)
.padding()
default:
Text("View is unavailable")
}
}
if let viewData = makeListViewData(from: content) {
let padding: CGFloat = family == .systemLarge ? 22 : 16
ListStatsView(viewData: viewData)
.widgetURL(viewData.statsURL)
.padding(.all, padding)
}
}
}
}
// MARK: - Helper methods
private extension StatsWidgetsView {
func makeGroupedViewData(from widgetData: HomeWidgetData) -> GroupedViewData? {
if let todayWidgetData = widgetData as? HomeWidgetTodayData {
return GroupedViewData(widgetTitle: LocalizableStrings.todayWidgetTitle,
siteName: todayWidgetData.siteName,
upperLeftTitle: LocalizableStrings.viewsTitle,
upperLeftValue: todayWidgetData.stats.views,
upperRightTitle: LocalizableStrings.visitorsTitle,
upperRightValue: todayWidgetData.stats.visitors,
lowerLeftTitle: LocalizableStrings.likesTitle,
lowerLeftValue: todayWidgetData.stats.likes,
lowerRightTitle: LocalizableStrings.commentsTitle,
lowerRightValue: todayWidgetData.stats.comments,
statsURL: todayWidgetData.statsURL)
}
if let allTimeWidgetData = widgetData as? HomeWidgetAllTimeData {
return GroupedViewData(widgetTitle: LocalizableStrings.allTimeWidgetTitle,
siteName: allTimeWidgetData.siteName,
upperLeftTitle: LocalizableStrings.viewsTitle,
upperLeftValue: allTimeWidgetData.stats.views,
upperRightTitle: LocalizableStrings.visitorsTitle,
upperRightValue: allTimeWidgetData.stats.visitors,
lowerLeftTitle: LocalizableStrings.postsTitle,
lowerLeftValue: allTimeWidgetData.stats.posts,
lowerRightTitle: LocalizableStrings.bestViewsTitle,
lowerRightValue: allTimeWidgetData.stats.bestViews,
statsURL: allTimeWidgetData.statsURL)
}
return nil
}
func makeListViewData(from widgetData: HomeWidgetData) -> ListViewData? {
guard let thisWeekWidgetData = widgetData as? HomeWidgetThisWeekData else {
return nil
}
return ListViewData(widgetTitle: LocalizableStrings.thisWeekWidgetTitle,
siteName: thisWeekWidgetData.siteName,
items: thisWeekWidgetData.stats.days,
statsURL: thisWeekWidgetData.statsURL)
}
}
private extension HomeWidgetTodayData {
static let statsUrl = "https://wordpress.com/stats/day/"
var statsURL: URL? {
URL(string: Self.statsUrl + "\(siteID)?source=widget")
}
}
private extension HomeWidgetAllTimeData {
static let statsUrl = "https://wordpress.com/stats/insights/"
var statsURL: URL? {
URL(string: Self.statsUrl + "\(siteID)?source=widget")
}
}
private extension HomeWidgetThisWeekData {
static let statsUrl = "https://wordpress.com/stats/week/"
var statsURL: URL? {
URL(string: Self.statsUrl + "\(siteID)?source=widget")
}
}
| gpl-2.0 | 88ece41de90cba1f07152c231bec2efd | 37.304 | 86 | 0.562657 | 5.361702 | false | false | false | false |
coinbase/coinbase-ios-sdk | Tests/UnitTests/PaginationParametersSpec.swift | 1 | 7965 | //
// PaginationParametersSpec.swift
// Coinbase
//
// Copyright © 2018 Coinbase, Inc. All rights reserved.
//
@testable import CoinbaseSDK
import Quick
import Nimble
class PaginationParametersSpec: QuickSpec {
override func spec() {
describe("PaginationParameters") {
context("init(uri)") {
var uri: String? = ""
let pagination = specVar { Pagination(limit: 10, order: .desc, previousURI: uri, nextURI: uri) }
let model = specVar { PaginationParameters.nextPage(from: pagination()) }
context("with all options uri") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?limit=10&starting_after=other_id&order=desc"
}
it("create model with all parameters") {
expect(model()).notTo(beNil())
expect(model()?.limit).notTo(beNil())
expect(model()?.order).notTo(beNil())
expect(model()?.cursor).notTo(beNil())
}
}
context("with nil uri") {
beforeEach {
uri = nil
}
it("returns nil") {
expect(model()).to(beNil())
}
}
context("with not parameter") {
beforeEach {
uri = "/v2/accounts/some_id/transactions"
}
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.limit).to(beNil())
expect(model()?.order).to(beNil())
expect(model()?.cursor).to(beNil())
}
}
context("with order parameter") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?order=desc"
}
context("desc") {
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.order).to(equal(ListOrder.desc))
}
}
context("asc") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?order=asc"
}
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.order).to(equal(ListOrder.asc))
}
}
context("unparsable") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?order=other"
}
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.order).to(beNil())
}
}
}
context("with limit parameter") {
context("as number") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?limit=10"
}
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.limit).to(equal(10))
}
}
context("unparsable") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?limit=sfds"
}
it("create model") {
expect(model()).notTo(beNil())
expect(model()?.limit).to(beNil())
}
}
}
context("with ending_before parameter") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?ending_before=some_id"
}
it("create model") {
expect(model()).notTo(beNil())
expect({
guard case .some(.endingBefore(let id)) = model()?.cursor else {
return .failed(reason: "wrong enum case")
}
expect(id).to(equal("some_id"))
return .succeeded
}).to(succeed())
}
}
context("with starting_after parameter") {
beforeEach {
uri = "/v2/accounts/some_id/transactions?starting_after=some_id"
}
it("create model") {
expect(model()).notTo(beNil())
expect({
guard case .some(.startingAfter(let id)) = model()?.cursor else {
return .failed(reason: "wrong enum case")
}
expect(id).to(equal("some_id"))
return .succeeded
}).to(succeed())
}
}
}
context("dictinary") {
context("empty model") {
it("retrun empty dictinary") {
let model = PaginationParameters()
expect(model.parameters).to(beEmpty())
}
}
context("full model") {
it("retrun full dictinary") {
let model = PaginationParameters(limit: 10, order: .desc, cursor: .endingBefore(id: "some_id"))
expect(model.parameters).notTo(beEmpty())
expect(model.parameters["limit"]).notTo(beEmpty())
expect(model.parameters["order"]).notTo(beEmpty())
expect(model.parameters["ending_before"]).notTo(beEmpty())
expect(model.parameters["starting_after"]).to(beNil())
}
}
context("model with limit") {
it("retrun dictinary") {
let model = PaginationParameters(limit: 10)
expect(model.parameters["limit"]).to(equal("10"))
}
}
context("model with order") {
context("desc") {
it("retrun dictinary") {
let model = PaginationParameters(order: .desc)
expect(model.parameters["order"]).to(equal("desc"))
}
}
context("asc") {
it("retrun dictinary") {
let model = PaginationParameters(order: .asc)
expect(model.parameters["order"]).to(equal("asc"))
}
}
}
context("model with startingAfter") {
it("retrun dictinary") {
let model = PaginationParameters(cursor: .startingAfter(id: "id1"))
expect(model.parameters["starting_after"]).to(equal("id1"))
}
}
context("model with startingAfter") {
it("retrun dictinary") {
let model = PaginationParameters(cursor: .endingBefore(id: "id1"))
expect(model.parameters["ending_before"]).to(equal("id1"))
}
}
}
}
}
}
| apache-2.0 | 1f5894c6db4ba772883cf070da00e272 | 42.519126 | 119 | 0.381341 | 5.847283 | false | false | false | false |
jeroendesloovere/examples-swift | Swift-Playgrounds/Enumerations.playground/section-1.swift | 1 | 2213 | // Enumerations
// An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
enum CompassPoint {
case North
case South
case East
case West
}
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
var directionToHead = CompassPoint.West
directionToHead = .East
// Matching Enumeration Values with a Switch Statement
directionToHead = .South
switch directionToHead {
case .North:
println("Lots of planets have a north")
case .South:
println("Watch out for penguins")
case .East:
println("Where the sun rises")
case .West:
println("Where the skies are blue")
}
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
println("Mostly Harmless")
default:
println("Not a safe place for humans")
}
// Associated Values
enum Barcode {
case UPCA(Int, Int, Int)
case QRCode(String)
}
var productBarcode = Barcode.UPCA(8, 85909_51226, 3)
productBarcode = .QRCode("ABCDEFGHIJKLMNOP")
switch productBarcode {
case .UPCA(let numberSystem, let identifier, let check):
println("UPC-A with value of \(numberSystem), \(identifier), \(check)")
case .QRCode(let productCode):
println("QR code with value of \(productCode).")
}
productBarcode = Barcode.UPCA(8, 85909_51226, 3)
switch productBarcode {
case let .UPCA(numberSystem, identifier, check):
println("UPC-A with value of \(numberSystem), \(identifier), \(check)")
case let .QRCode(productCode):
println("QR code with value of \(productCode).")
}
// Raw Values
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
enum PlanetRaw: Int {
case Mercury = 1, Venuc, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
let earthsOrder = PlanetRaw.Earth.rawValue
let possiblePlanet = PlanetRaw(rawValue: 7)
let positionToFind = 9
if let somePlanet = PlanetRaw(rawValue: positionToFind) {
switch somePlanet {
case .Earth:
println("Mostly harmless")
default:
println("Not a safe place for humans")
}
} else {
println("There isn't a planet at position \(positionToFind)")
}
| mit | 9999d05f97c781337faa47844fb6f59b | 22.542553 | 149 | 0.702666 | 3.868881 | false | false | false | false |
danlozano/Requestr | Example/TinyApiClientExample/RemotelyService.swift | 1 | 3337 | //
// RemotelyService.swift
// TinyApiClientExample
//
// Created by Daniel Lozano Valdés on 11/29/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Foundation
import TinyAPIClient
public protocol RemotelyService {
func me(completion: @escaping (RemotelyResult<User>) -> Void)
func user(userId: String, completion: @escaping (RemotelyResult<User>) -> Void)
func users(completion: @escaping (RemotelyResult<[User]>) -> Void)
func userEvents(completion: @escaping (RemotelyResult<[Event]>) -> Void)
}
public enum RemotelyResult<T> {
case success(resource: T, metadata: RemotelyMetadata)
case error(message: String)
}
public struct RemotelyMetadata {
let pagination: PaginationInfo?
}
public class RemotelyAPIService: RemotelyService {
let apiClient: ApiClient
init(apiClient: ApiClient) {
self.apiClient = apiClient
}
}
public extension RemotelyAPIService {
func me(completion: @escaping (RemotelyResult<User>) -> Void) {
let endpoint = Endpoints.me
apiClient.GET(endpoint.fullPath) { (result: ApiResult<User>) in
completion(self.remotelyResultFor(apiResult: result))
}
}
func user(userId: String, completion: @escaping (RemotelyResult<User>) -> Void) {
let endpoint = Endpoints.user(userId: userId)
apiClient.GET(endpoint.fullPath) { (result: ApiResult<User>) in
completion(self.remotelyResultFor(apiResult: result))
}
}
func users(completion: @escaping (RemotelyResult<[User]>) -> Void) {
let usersEndpoint = Endpoints.users
apiClient.GET(usersEndpoint.fullPath, rootKey: usersEndpoint.rootKey!) { (apiResult: ApiResult<[User]>) in
completion(self.remotelyResultFor(apiResult: apiResult))
}
}
func userEvents(completion: @escaping (RemotelyResult<[Event]>) -> Void) {
let endpoint = Endpoints.userEvents
apiClient.GET(endpoint.fullPath, rootKey: endpoint.rootKey!) { (result: ApiResult<[Event]>) in
completion(self.remotelyResultFor(apiResult: result))
}
}
}
private extension RemotelyAPIService {
func remotelyResultFor<T>(apiResult: ApiResult<T>) -> RemotelyResult<T> {
switch apiResult {
case .success(let resource, let meta):
let pagination = meta.pagination
let metadata = RemotelyMetadata(pagination: pagination)
return .success(resource: resource, metadata: metadata)
case .cancelled:
return .error(message: "cancelled")
case .clientError(let errorCode):
return .error(message: "client error = \(errorCode)")
case .serverError(let errorCode):
return .error(message: "server error = \(errorCode)")
case .error(let error):
return .error(message: "error = \(error)")
case .invalidCredentials:
return .error(message: "invalid credentials")
case .invalidToken:
return .error(message: "invalid token")
case .notFound:
return .error(message: "not found")
case .unexpectedResponse(let response):
return .error(message: "unexpected response \(response)")
case .unknownError:
return .error(message: "unkown error")
}
}
}
| mit | 477c4181c5c9e39b97799bffc81a6478 | 30.761905 | 114 | 0.653373 | 4.34811 | false | false | false | false |
turingcorp/gattaca | Pods/GifHero/gifhero/Source/Model/GifModelFrame.swift | 1 | 765 | import UIKit
class GifModelFrame
{
let image:UIImage
private let duration:TimeInterval
private var sum:TimeInterval
init(image:UIImage, duration:TimeInterval)
{
self.image = image
self.duration = duration
sum = 0
}
//MARK: internal
func deltaTime(currentTimestamp:TimeInterval) -> TimeInterval
{
let delta:TimeInterval = currentTimestamp - sum
return delta
}
func updateTime(timestamp:TimeInterval, delta:TimeInterval)
{
let time:TimeInterval
if delta > 1
{
time = timestamp
}
else
{
time = timestamp - delta
}
sum = duration + time
}
}
| mit | 45ff8e121f98b7298ac51cb42b5fd185 | 18.125 | 65 | 0.545098 | 5.275862 | false | false | false | false |
vashimbogom/ghrFinder | GithubLangF/app/Tools/ImgDownloader.swift | 1 | 1498 | //
// ImgDownloader.swift
// GithubLangF
//
// Created by Jose Lopez on 2/17/16.
// Copyright © 2016 Jose Lopez. All rights reserved.
//
import UIKit
import Alamofire
class ImgDownloader: NSObject {
static var imageCache = NSCache()
class func downloadImageTo(view: UIImageView, fromURL: String){
view.image = UIImage(named: "github_cat")
if let imgData = self.imageCache.objectForKey(fromURL) as? NSData {
let image = UIImage(data: imgData)
view.image = image
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let request = NSURLRequest(URL: NSURL(string: fromURL)!)
Alamofire.request(request).response { (request, response, data, error) -> Void in
if data != nil {
self.imageCache.setObject(data!, forKey: fromURL)
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue()) {
view.image = image
}
}else {
dispatch_async(dispatch_get_main_queue()) {
view.image = UIImage(named: "github_cat")
}
}
}
})
}
}
}
| mit | a047eb447bdfc0aefe05376ec031c889 | 30.1875 | 105 | 0.474282 | 5.109215 | false | false | false | false |
apple/swift | test/IDE/print_clang_objc_async.swift | 5 | 8438 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -print-module -print-implicit-attrs -source-filename %s -module-to-print=ObjCConcurrency -function-definitions=false -enable-experimental-concurrency -enable-experimental-feature SendableCompletionHandlers > %t/ObjCConcurrency.printed.txt
// RUN: %FileCheck -input-file %t/ObjCConcurrency.printed.txt %s
// REQUIRES: objc_interop
// REQUIRES: concurrency
// REQUIRES: asserts
import _Concurrency
// CHECK-LABEL: class SlowServer : NSObject, ServiceProvider {
// CHECK: @available(*, renamed: "doSomethingSlow(_:)")
// CHECK-NEXT: func doSomethingSlow(_ operation: String, completionHandler handler: @escaping @Sendable (Int) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func doSomethingSlow(_ operation: String) async -> Int
// CHECK: @available(*, renamed: "doSomethingDangerous(_:)")
// CHECK-NEXT: func doSomethingDangerous(_ operation: String, completionHandler handler: (@Sendable (String?, Error?) -> Void)? = nil)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func doSomethingDangerous(_ operation: String) async throws -> String
// CHECK: @available(*, renamed: "doSomethingReckless(_:)")
// CHECK-NEXT: func doSomethingReckless(_ operation: String, completionHandler handler: ((String?, Error?) -> Void)? = nil)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func doSomethingReckless(_ operation: String) async throws -> String
// CHECK: @available(*, renamed: "checkAvailability()")
// CHECK-NEXT: func checkAvailability(completionHandler: @escaping @Sendable (Bool) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func checkAvailability() async -> Bool
// CHECK: @available(*, renamed: "anotherExample()")
// CHECK-NEXT: func anotherExample(completionBlock block: @escaping @Sendable (String) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func anotherExample() async -> String
// CHECK: @available(*, renamed: "finalExample()")
// CHECK-NEXT: func finalExampleWithReply(to block: @escaping @Sendable (String) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func finalExample() async -> String
// CHECK: @available(*, renamed: "replyingOperation(_:)")
// CHECK-NEXT: func replyingOperation(_ operation: String, replyTo block: @escaping @Sendable (String) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func replyingOperation(_ operation: String) async -> String
// CHECK: @available(*, renamed: "findAnswer()")
// CHECK-NEXT: func findAnswer(completionHandler handler: @escaping @Sendable (String?, Error?) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findAnswer() async throws -> String
// CHECK: @available(*, renamed: "findAnswerFailingly()")
// CHECK-NEXT: func findAnswerFailingly(completionHandler handler: @escaping @Sendable (String?, Error?) -> Void) throws
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findAnswerFailingly() async throws -> String
// CHECK: @available(*, renamed: "findQAndA()")
// CHECK-NEXT: func findQAndA(completionHandler handler: @escaping @Sendable (String?, String?, Error?) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findQAndA() async throws -> (String?, String)
// CHECK: @available(*, renamed: "findQuestionableAnswers()")
// CHECK-NEXT: func findQuestionableAnswers(completionHandler handler: @escaping CompletionHandler)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findQuestionableAnswers() async throws -> (String, String?)
// CHECK: @available(*, renamed: "findAnswerableQuestions()")
// CHECK-NEXT: func findAnswerableQuestions(completionHandler handler: @escaping @Sendable (String?, String?, Error?) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findAnswerableQuestions() async throws -> (String, String?)
// CHECK: @available(*, renamed: "findUnanswerableQuestions()")
// CHECK-NEXT: func findUnanswerableQuestions(completionHandler handler: @escaping NonsendableCompletionHandler)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func findUnanswerableQuestions() async throws -> (String, String?)
// CHECK: @available(*, renamed: "doSomethingFun(_:)")
// CHECK-NEXT: func doSomethingFun(_ operation: String, then completionHandler: @escaping @Sendable () -> Void)
// CHECK-NEXT: func doSomethingFun(_ operation: String) async
// CHECK: @available(*, renamed: "doSomethingConflicted(_:)")
// CHECK-NEXT: func doSomethingConflicted(_ operation: String, completionHandler handler: @escaping @Sendable (Int) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func doSomethingConflicted(_ operation: String) async -> Int
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func doSomethingConflicted(_ operation: String) -> Int
// CHECK: func dance(_ step: String) async -> String
// CHECK: func __leap(_ height: Int) async -> String
// CHECK: @available(*, renamed: "runOnMainThread()")
// CHECK-NEXT: func runOnMainThread(completionHandler completion: (@MainActor (String) -> Void)? = nil)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func runOnMainThread() async -> String
// CHECK: @available(*, renamed: "asyncImportSame(_:)")
// CHECK-NEXT: func asyncImportSame(_ operation: String, completionHandler handler: @escaping @Sendable (Int) -> Void)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: func asyncImportSame(_ operation: String) async -> Int
// CHECK-NEXT: func asyncImportSame(_ operation: String, replyTo handler: @escaping (Int) -> Void)
// CHECK-NOT: func asyncImportSame(_ operation: String) async -> Int
// CHECK: {{^[}]$}}
// CHECK-LABEL: protocol RefrigeratorDelegate
// CHECK-NEXT: func someoneDidOpenRefrigerator(_ fridge: Any)
// CHECK-NEXT: func refrigerator(_ fridge: Any, didGetFilledWithItems items: [Any])
// CHECK-NEXT: {{^}} @objc func refrigerator(_ fridge: Any, didGetFilledWithIntegers items: UnsafeMutablePointer<Int>, count: Int)
// CHECK-NEXT: {{^}} @objc func refrigerator(_ fridge: Any, willAddItem item: Any)
// CHECK-NEXT: @discardableResult
// CHECK-NEXT: {{^}} @objc func refrigerator(_ fridge: Any, didRemoveItem item: Any) -> Bool
// CHECK-NEXT: {{^[}]$}}
// CHECK-LABEL: protocol ProtocolWithSwiftAttributes {
// CHECK-NEXT: nonisolated func independentMethod()
// CHECK-NEXT: nonisolated func nonisolatedMethod()
// CHECK-NEXT: {{^}} @MainActor @objc func mainActorMethod()
// CHECK-NEXT: {{^}} @MainActor @objc func uiActorMethod()
// CHECK-NEXT: {{^}} @objc optional func missingAtAttributeMethod()
// CHECK-NEXT: {{^[}]$}}
// CHECK: {{^}}nonisolated var MAGIC_NUMBER: Int32 { get }
// CHECK: func doSomethingConcurrently(_ block: @Sendable () -> Void)
// CHECK: @MainActor @objc protocol TripleMainActor {
// CHECK-LABEL: class NXSender :
// CHECK: func sendAny(_ obj: Sendable) -> Sendable
// CHECK: func sendOptionalAny(_ obj: Sendable?) -> Sendable?
// CHECK: func sendSendable(_ sendable: SendableClass & Sendable) -> SendableClass & Sendable
// CHECK: func sendSendableSubclasses(_ sendableSubclass: NonSendableClass & Sendable) -> NonSendableClass & Sendable
// CHECK: func sendProto(_ obj: LabellyProtocol & Sendable) -> LabellyProtocol & Sendable
// CHECK: func sendProtos(_ obj: LabellyProtocol & ObjCClub & Sendable) -> LabellyProtocol & ObjCClub & Sendable
// CHECK: func sendAnyArray(_ array: [Sendable]) -> [Sendable]
// CHECK: func sendGeneric(_ generic: GenericObject<SendableClass> & Sendable) -> GenericObject<SendableClass> & Sendable
// CHECK: func sendPtr(_ val: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer
// CHECK: func sendStringArray(_ obj: [String]) -> [String]
// CHECK: func sendAnyTypedef(_ obj: Sendable) -> Sendable
// CHECK: func sendAnyTypedefs(_ objs: [Sendable]) -> [Sendable]
// CHECK: func sendBlockTypedef(_ block: @escaping @Sendable (Any) -> Void) -> @Sendable (Any) -> Void
// CHECK: func sendBlockTypedefs(_ blocks: [@Sendable @convention(block) (Any) -> Void]) -> [@Sendable @convention(block) (Any) -> Void]
// CHECK: func sendUnbound(_ array: [Sendable]) -> [Sendable]
// CHECK: var sendableProp: Sendable
// CHECK: }
// CHECK: func NXSendFunc(_ arg: Sendable) -> Sendable
// CHECK: var NXSendGlobal: Sendable
// CHECK-LABEL: struct StructWithSendableContents
// FIXME: `Unmanaged` should support `AnyObject & Sendable`.
// CHECK: var sendableField: Unmanaged<AnyObject>
// FIXME: Should be imported as Unmanaged!
// CHECK: var sendableIndirectField: Sendable & AnyObject
// CHECK: var sendableComputed: Sendable { get }
| apache-2.0 | 60b0a0aea43710620b5f794e4f6b2940 | 53.089744 | 300 | 0.72849 | 4.023844 | false | false | false | false |
alltheflow/copypasta | Carthage/Checkouts/VinceRP/vincerp/Common/Threading/DynamicVariable.swift | 1 | 989 | //
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
// Inspired by
// http://www.scala-lang.org/api/2.11.5/index.html#scala.util.DynamicVariable
// and
// https://searchcode.com/codesearch/view/18473763/
// and
// http://scalageek.blogspot.hu/2013/02/when-to-use-dynamic-variables.html?m=1
public class DynamicVariable<T> {
private let threadLocal: ThreadLocal<T>
public var value: T? {
set {
threadLocal.value = newValue
}
get {
return threadLocal.value
}
}
public init(_ value: T?) {
self.threadLocal = ThreadLocal(value: value, key: "DynamicVariable")
}
public func withValue<S>(newval: T, @noescape _ thunk: () -> S) -> S {
let oldval = value
// set the context
self.value = newval
let result = thunk()
// restore the context
self.value = oldval
return result
}
}
| mit | 6a7b9c1e7839d2041ba70404c2d78fda | 22 | 78 | 0.598584 | 3.622711 | false | false | false | false |
smartystreets/smartystreets-ios-sdk | Sources/SmartyStreets/USExtract/USExtractClient.swift | 1 | 2372 | import Foundation
@objcMembers public class USExtractClient: NSObject {
// It is recommended to instantiate this class using SSClientBuilder
var sender:SmartySender
var serializer:SmartySerializer
init(sender:Any, serializer:SmartySerializer) {
self.sender = sender as! SmartySender
self.serializer = serializer
}
@objc public func sendLookup(lookup: UnsafeMutablePointer<USExtractLookup>, error: UnsafeMutablePointer<NSError?>) -> Bool {
// Sends a Lookup object to the US Extract Code API and stores the result in the Lookup's result field.
// It also returns the result directly.
if let text = lookup.pointee.text {
if text.count == 0 {
let details = [NSLocalizedDescriptionKey:"sendLookup requires a Lookup with the 'text' field set"]
error.pointee = NSError(domain: SmartyErrors().SSErrorDomain, code: SmartyErrors.SSErrors.FieldNotSetError.rawValue, userInfo: details)
return false
}
let request = buildRequest(lookup: lookup.pointee)
let response = self.sender.sendRequest(request: request, error: &error.pointee)
if error.pointee != nil { return false }
let result = self.serializer.Deserialize(payload: response?.payload, error: &error.pointee) as! NSDictionary
if error.pointee != nil { return false }
lookup.pointee.result = USExtractResult(dictionary: result)
return true
}
return false
}
func buildRequest(lookup:USExtractLookup) -> SmartyRequest {
let request = SmartyRequest()
request.method = "POST"
request.contentType = "text/plain"
let payload = lookup.text?.data(using: .utf8)
request.payload = payload
request.setValue(value: String(lookup.isHtml()), HTTPParameterField: "html")
request.setValue(value: String(lookup.isAggressive()), HTTPParameterField: "aggressive")
request.setValue(value: "\(lookup.addressesHaveLineBreaks ?? false)", HTTPParameterField: "addr_line_breaks")
request.setValue(value: "\(lookup.addressesPerLine ?? 0)", HTTPParameterField: "addr_per_line")
return request
}
}
| apache-2.0 | a4cde94a18927edd397cf6e34f4419ab | 42.925926 | 151 | 0.634486 | 4.870637 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/Utility/ContextManager+ErrorHandling.swift | 1 | 7181 | import CoreData
// Imported from CoreData.CoreDataErrors
private let coreDataKnownErrorCodes = [
NSCoreDataError: "General Core Data error",
NSEntityMigrationPolicyError: "Migration failed during processing of the entity migration policy ",
NSExternalRecordImportError: "General error encountered while importing external records",
NSInferredMappingModelError: "Inferred mapping model creation error",
NSManagedObjectConstraintMergeError: "Merge policy failed - unable to complete merging due to multiple conflicting constraint violations",
NSManagedObjectConstraintValidationError: "One or more uniqueness constraints were violated",
NSManagedObjectContextLockingError: "Can't acquire a lock in a managed object context",
NSManagedObjectExternalRelationshipError: "An object being saved has a relationship containing an object from another store",
NSManagedObjectMergeError: "Merge policy failed - unable to complete merging",
NSManagedObjectReferentialIntegrityError: "Attempt to fire a fault pointing to an object that does not exist (we can see the store, we can't see the object)",
NSManagedObjectValidationError: "Generic validation error",
NSMigrationCancelledError: "Migration failed due to manual cancellation",
NSMigrationConstraintViolationError: "Migration failed due to a violated uniqueness constraint",
NSMigrationError: "General migration error",
NSMigrationManagerDestinationStoreError: "Migration failed due to a problem with the destination data store",
NSMigrationManagerSourceStoreError: "Migration failed due to a problem with the source data store",
NSMigrationMissingMappingModelError: "Migration failed due to missing mapping model",
NSMigrationMissingSourceModelError: "Migration failed due to missing source data model",
NSPersistentHistoryTokenExpiredError: "The history token passed to NSPersistentChangeRequest was invalid",
NSPersistentStoreCoordinatorLockingError: "Can't acquire a lock in a persistent store coordinator",
NSPersistentStoreIncompatibleSchemaError: "Store returned an error for save operation (database level errors ie missing table, no permissions)",
NSPersistentStoreIncompatibleVersionHashError: "Entity version hashes incompatible with data model",
NSPersistentStoreIncompleteSaveError: "One or more of the stores returned an error during save (stores/objects that failed will be in userInfo)",
NSPersistentStoreInvalidTypeError: "Unknown persistent store type/format/version",
NSPersistentStoreOpenError: "An error occurred while attempting to open the persistent store",
NSPersistentStoreOperationError: "The persistent store operation failed",
NSPersistentStoreSaveConflictsError: "An unresolved merge conflict was encountered during a save. userInfo has NSPersistentStoreSaveConflictsErrorKey",
NSPersistentStoreSaveError: "Unclassified save error - something we depend on returned an error",
NSPersistentStoreTimeoutError: "Failed to connect to the persistent store within the specified timeout (see NSPersistentStoreTimeoutOption)",
NSPersistentStoreTypeMismatchError: "Returned by persistent store coordinator if a store is accessed that does not match the specified type",
NSPersistentStoreUnsupportedRequestTypeError: "An NSPersistentStore subclass was passed an NSPersistentStoreRequest that it did not understand",
NSSQLiteError: "General SQLite error ",
NSValidationDateTooLateError: "Some date value is too late",
NSValidationDateTooSoonError: "Some date value is too soon",
NSValidationInvalidDateError: "Some date value fails to match date pattern",
NSValidationInvalidURIError: "Some URI value cannot be represented as a string",
NSValidationMissingMandatoryPropertyError: "Non-optional property with a nil value",
NSValidationMultipleErrorsError: "Generic message for error containing multiple validation errors",
NSValidationNumberTooLargeError: "Some numerical value is too large",
NSValidationNumberTooSmallError: "Some numerical value is too small",
NSValidationRelationshipDeniedDeleteError: "Some relationship with NSDeleteRuleDeny is non-empty",
NSValidationRelationshipExceedsMaximumCountError: "Bounded, to-many relationship with too many destination objects",
NSValidationRelationshipLacksMinimumCountError: "To-many relationship with too few destination objects",
NSValidationStringPatternMatchingError: "Some string value fails to match some pattern",
NSValidationStringTooLongError: "Some string value is too long",
NSValidationStringTooShortError: "Some string value is too short",
]
private extension NSExceptionName {
static let coreDataSaveMainException = NSExceptionName("Unresolved Core Data save error (Main Context)")
static let coreDataSaveDerivedException = NSExceptionName("Unresolved Core Data save error (Derived Context)")
}
extension ContextManager {
@objc(handleSaveError:inContext:)
func handleSaveError(_ error: NSError, in context: NSManagedObjectContext) {
let isMainContext = context == mainContext
let exceptionName: NSExceptionName = isMainContext ? .coreDataSaveMainException : .coreDataSaveDerivedException
let reason = reasonForError(error)
DDLogError("Unresolved Core Data save error: \(error)")
DDLogError("Generating exception with reason:\n\(reason)")
// Sentry is choking when userInfo is too big and not sending crash reports
// For debugging we can still see the userInfo details since we're logging the full error above
let exception = NSException(name: exceptionName, reason: reason, userInfo: nil)
exception.raise()
}
}
private extension ContextManager {
func reasonForError(_ error: NSError) -> String {
if error.code == NSValidationMultipleErrorsError {
guard let errors = error.userInfo[NSDetailedErrorsKey] as? [NSError] else {
return "Multiple errors without details"
}
return reasonForMultipleErrors(errors)
} else {
return reasonForIndividualError(error)
}
}
func reasonForMultipleErrors(_ errors: [NSError]) -> String {
return "Multiple errors:\n" + errors.enumerated().map({ (index, error) in
return " \(index + 1): " + reasonForIndividualError(error)
}).joined(separator: "\n")
}
func reasonForIndividualError(_ error: NSError) -> String {
let entity = entityName(for: error) ?? "null"
let property = propertyName(for: error) ?? "null"
let message = coreDataKnownErrorCodes[error.code] ?? "Unknown error (domain: \(error.domain) code: \(error.code), \(error.localizedDescription)"
return "\(message) on \(entity).\(property)"
}
func entityName(for error: NSError) -> String? {
guard let managedObject = error.userInfo[NSValidationObjectErrorKey] as? NSManagedObject else {
return nil
}
return managedObject.entity.name
}
func propertyName(for error: NSError) -> String? {
return error.userInfo[NSValidationKeyErrorKey] as? String
}
}
| gpl-2.0 | 3bb4ba09f2d37566083498f3cf7bee6e | 64.880734 | 162 | 0.766049 | 5.295723 | false | false | false | false |
swiftingio/architecture-wars-mvc | MyCards/MyCards/PhotoCaptureViewController.swift | 1 | 6820 | //
// PhotoCaptureViewController.swift
// MyCards
//
// Created by Maciej Piotrowski on 22/11/16.
//
import UIKit
import AVFoundation
protocol PhotoCaptureViewControllerDelegate: class {
func photoCaptureViewController(_ viewController: PhotoCaptureViewController, didTakePhoto
photo: UIImage, for side: Card.Side)
}
final class PhotoCaptureViewController: LightStatusBarViewController {
weak var delegate: PhotoCaptureViewControllerDelegate?
fileprivate let side: Card.Side
fileprivate lazy var previewView: PreviewView = PreviewView().with {
$0.session = self.session
$0.captureButton.tapped = { [unowned self] in self.takePhoto() }
$0.closeButton.tapped = { [unowned self] in self.dismiss() }
$0.controlsAlpha = 0.0
//display preview items in landscape right
$0.captureButton.transform = .rotateRight
$0.closeButton.transform = .rotateRight
}
// MARK: AVFoundation components
fileprivate let output = AVCapturePhotoOutput().with {
$0.isHighResolutionCaptureEnabled = true
$0.isLivePhotoCaptureEnabled = false
}
fileprivate let session = AVCaptureSession()
fileprivate let queue = DispatchQueue(label: "AV Session Queue", attributes: [], target: nil)
fileprivate var authorizationStatus: AVAuthorizationStatus {
return AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
}
init(side: Card.Side) {
self.side = side
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureViews()
configureConstraints()
requestAuthorizationIfNeeded()
configureSession()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startSession()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.25) {
self.previewView.controlsAlpha = 1.0
}
}
override func viewWillDisappear(_ animated: Bool) {
stopSession()
super.viewWillDisappear(animated)
}
}
extension PhotoCaptureViewController {
fileprivate func configureViews() {
view.addSubview(previewView)
view.backgroundColor = .black
}
fileprivate func configureConstraints() {
view.subviews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false }
let constraints: [NSLayoutConstraint] = NSLayoutConstraint.filledInSuperview(previewView)
NSLayoutConstraint.activate(constraints)
}
fileprivate func requestAuthorizationIfNeeded() {
guard .notDetermined == authorizationStatus else { return }
queue.suspend()
AVCaptureDevice.requestAccess(for: AVMediaType.video) { [unowned self] granted in
guard granted else { return }
self.queue.resume()
}
}
fileprivate enum Error: Swift.Error {
case noCamera
case cannotAddInput
}
fileprivate func configureSession() {
queue.async {
guard .authorized == self.authorizationStatus else { return }
guard let camera: AVCaptureDevice = AVCaptureDevice.backVideoCamera else { return }
defer { self.session.commitConfiguration() }
self.session.beginConfiguration()
self.session.sessionPreset = AVCaptureSession.Preset.photo
do {
let input = try AVCaptureDeviceInput(device: camera)
guard self.session.canAddInput(input) else { return }
self.session.addInput(input)
} catch { return }
guard self.session.canAddOutput(self.output) else { return }
self.session.addOutput(self.output)
}
}
fileprivate func takePhoto() {
queue.async { [unowned self] in
let photoSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
photoSettings.flashMode = .auto
photoSettings.isHighResolutionPhotoEnabled = true
self.output.capturePhoto(with: photoSettings, delegate: self)
}
}
fileprivate func startSession() {
queue.async {
guard self.authorizationStatus == .authorized else { return }
guard !self.session.isRunning else { return }
self.session.startRunning()
}
}
fileprivate func stopSession() {
queue.async {
guard self.authorizationStatus == .authorized else { return }
guard self.session.isRunning else { return }
self.session.stopRunning()
}
}
}
extension PhotoCaptureViewController: AVCapturePhotoCaptureDelegate {
// codebeat:disable[ARITY]
public func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photo: AVCapturePhoto,
error: Swift.Error?) {
guard error == nil,
let data = photo.fileDataRepresentation(),
let photo = process(data)
else { print("Error capturing photo: \(String(describing: error))"); return }
delegate?.photoCaptureViewController(self, didTakePhoto: photo, for: side)
}
// codebeat:enable[ARITY]
private func process(_ data: Data) -> UIImage? {
guard let image = UIImage(data: data)?.cgImage else { return nil }
let outline = previewView.outline.frame
let outputRect = previewView.videoPreviewLayer.metadataOutputRectConverted(fromLayerRect: outline)
return cropp(image, to: outline, with: outputRect)
}
func cropp(_ image: CGImage, to outline: CGRect, with metadataOutputRect: CGRect) -> UIImage? {
let originalSize: CGSize = CGSize(width: image.width, height: image.height)
//NOTE: Scale using corresponding CGRect from AVCaptureVideoPreviewLayer
let scaledOutline: CGSize = CGSize(width:
originalSize.width * metadataOutputRect.width,
height: CGFloat(image.height) * metadataOutputRect.height)
//NOTE: Calculate card outline offset (x,y)
let x: CGFloat = originalSize.width * metadataOutputRect.origin.x
let y: CGFloat = originalSize.height * metadataOutputRect.origin.y
let rect = CGRect(x: x,
y: y,
width: scaledOutline.width,
height: scaledOutline.height)
guard let cropped = image.cropping(to: rect) else { return nil }
let photo = UIImage(cgImage: cropped, scale: 1, orientation: .up)
return photo
}
}
| mit | cd428d5e000c5934abad5a0ce32551b7 | 33.1 | 106 | 0.64868 | 5.174507 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Home/ComposeViewController.swift | 1 | 5936 | //
// ComposeViewController.swift
// AYWeibo
//
// Created by Jinyong on 16/7/23.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController {
/// 工具条底部约束
private var toolbarBottomConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
// 1.添加子控件
setupUI()
// 2.布局子控件
setupConstraints()
// 3.注册通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
// 4.将文本视图传递给toolbar
toolbar.textView = textView
toolbar.keyboardView = keyboardEmoticomViewController.view
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
textView.resignFirstResponder()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - 内部控制方法
func setupUI() {
// 1.添加导航栏按钮
let leftItem = UIBarButtonItem(title: "关闭", style: .Done, target: self, action: #selector(self.leftBarButtonClick))
let rightItem = UIBarButtonItem(title: "发送", style: .Done, target: self, action: #selector(self.rightBarButtonClick))
// 1.1.添加左侧导航按钮
self.navigationItem.leftBarButtonItem = leftItem
// 1.2.添加右侧导航按钮
self.navigationItem.rightBarButtonItem = rightItem
self.navigationItem.rightBarButtonItem?.enabled = false
// 1.3.添加导航标题
let titleView = JYTitleView(frame: CGRectMake(0, 0, 100, 40))
titleView.backgroundColor = self.navigationController?.navigationBar.backgroundColor
self.navigationItem.titleView = titleView
// 2.添加文本视图
self.view.addSubview(textView)
textView.delegate = self
// 3.添加工具条
self.view.addSubview(toolbar)
// 4.添加表情键盘控制器
self.addChildViewController(keyboardEmoticomViewController)
}
private func setupConstraints() {
textView.translatesAutoresizingMaskIntoConstraints = false
toolbar.translatesAutoresizingMaskIntoConstraints = false
// 文本视图布局
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[textView]-0-|", options: .DirectionMask, metrics: nil, views: ["textView": textView]))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[textView]-0-|", options: .DirectionMask, metrics: nil, views: ["textView": textView]))
// 工具条布局
toolbar.addConstraint(NSLayoutConstraint(item: toolbar, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 0.0, constant: 44.0))
toolbarBottomConstraint = NSLayoutConstraint(item: toolbar, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: .DirectionMask, metrics: nil, views: ["toolbar": toolbar]))
self.view.addConstraint(toolbarBottomConstraint!)
}
// 左侧导航按钮监听
@objc private func leftBarButtonClick() {
QL2("")
self.dismissViewControllerAnimated(true, completion: nil)
}
// 右侧导航按钮监听
@objc private func rightBarButtonClick() {
QL2("")
let text = textView.text
NetWorkTools.shareIntance.sendStatus(text) { (data, error) in
if error != nil {
QL3("发送失败")
return
}
self.dismissViewControllerAnimated(true, completion: nil)
}
}
// 通知中心键盘监听方法
@objc private func keyboardWillChange(notification: NSNotification) {
// 1.获取弹出键盘的frame
let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
// 2.获取屏幕的高度
let height = UIScreen.mainScreen().bounds.height
// 3.计算需要移动的距离
let offsetY = rect.origin.y - height
// 4.获取弹出键盘的节奏
let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// 5.计算弹出键盘的持续时间
let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
// 5.修改工具条底部约束
UIView.animateWithDuration(duration) {
self.toolbarBottomConstraint?.constant = offsetY
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
self.view.layoutIfNeeded()
}
}
// MARK: - 懒加载
private lazy var textView: UITextView = {
let tv = JYTextView(frame: CGRectZero, textContainer: nil)
tv.font = UIFont.systemFontOfSize(14)
return tv
}()
private lazy var toolbar: ComposeToolbar = {
let tb = NSBundle.mainBundle().loadNibNamed("ComposeToolbar", owner: nil, options: nil).last as! ComposeToolbar
return tb
}()
private lazy var keyboardEmoticomViewController: JYKeyboardEmoticonViewController = JYKeyboardEmoticonViewController()
}
// MARK: - UITextViewDelegate
extension ComposeViewController: UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
}
}
| apache-2.0 | 78ed4acfd9ae62842641702b96038601 | 34.44586 | 177 | 0.649416 | 5.0271 | false | false | false | false |
clwm01/RTKit | RTKit/RTWindow.swift | 1 | 1126 | //
// RTWindow.swift
// RTKit
//
// Created by Rex Tsao on 10/4/2016.
// Copyright © 2016 rexcao.net. All rights reserved.
//
import Foundation
import UIKit
public class RTTopWindow: UIWindow {
public init() {
super.init(frame: UIScreen.mainScreen().bounds)
self.hidden = false
self.windowLevel = UIWindowLevelAlert
self.backgroundColor = nil
self.rootViewController = UIViewController()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func revoke() {
self.windowLevel = UIWindowLevelAlert - 1
self.removeFromSuperview()
}
}
public class RTWindow {
public class func keyWindow() -> UIWindow? {
return UIApplication.sharedApplication().keyWindow
}
public class func sharedTopWindow() -> RTTopWindow {
var sharedTopWindow: RTTopWindow?
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken, {
sharedTopWindow = RTTopWindow()
})
return sharedTopWindow!
}
} | apache-2.0 | d74c5a4688e08aa0e7b094dfc2d1d943 | 22.458333 | 59 | 0.627556 | 4.44664 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Pods/Charts/Charts/Classes/Components/ChartLimitLine.swift | 6 | 2082 | //
// ChartLimitLine.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// The limit line is an additional feature for all Line, Bar and ScatterCharts.
/// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis).
open class ChartLimitLine: ChartComponentBase
{
@objc(ChartLimitLabelPosition)
public enum LabelPosition: Int
{
case leftTop
case leftBottom
case rightTop
case rightBottom
}
/// limit / maximum (the y-value or xIndex)
open var limit = Double(0.0)
private var _lineWidth = CGFloat(2.0)
open var lineColor = NSUIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0)
open var lineDashPhase = CGFloat(0.0)
open var lineDashLengths: [CGFloat]?
open var valueTextColor = NSUIColor.black
open var valueFont = NSUIFont.systemFont(ofSize: 13.0)
open var label = ""
open var drawLabelEnabled = true
open var labelPosition = LabelPosition.rightTop
public override init()
{
super.init()
}
public init(limit: Double)
{
super.init()
self.limit = limit
}
public init(limit: Double, label: String)
{
super.init()
self.limit = limit
self.label = label
}
/// set the line width of the chart (min = 0.2, max = 12); default 2
open var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if (newValue < 0.2)
{
_lineWidth = 0.2
}
else if (newValue > 12.0)
{
_lineWidth = 12.0
}
else
{
_lineWidth = newValue
}
}
}
}
| mit | 1c1746195ebb58f7f6349c8afb770990 | 23.209302 | 138 | 0.571566 | 4.231707 | false | false | false | false |
zapdroid/RXWeather | Pods/Nimble/Sources/Nimble/DSL+Wait.swift | 1 | 4354 | import Dispatch
import Foundation
private enum ErrorResult {
case exception(NSException)
case error(Error)
case none
}
/// Only classes, protocols, methods, properties, and subscript declarations can be
/// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style
/// asynchronous waiting logic so that it may be called from Objective-C and Swift.
internal class NMBWait: NSObject {
internal class func until(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) -> Void) {
return throwableUntil(timeout: timeout, file: file, line: line) { done in
action(done)
}
}
// Using a throwable closure makes this method not objc compatible.
internal class func throwableUntil(
timeout: TimeInterval,
file: FileString = #file,
line: UInt = #line,
action: @escaping (@escaping () -> Void) throws -> Void) {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let leeway = timeout / 2.0
let result = awaiter.performBlock { (done: @escaping (ErrorResult) -> Void) throws -> Void in
DispatchQueue.main.async {
let capture = NMBExceptionCapture(
handler: ({ exception in
done(.exception(exception))
}),
finally: ({})
)
capture.tryBlock {
do {
try action {
done(.none)
}
} catch let e {
done(.error(e))
}
}
}
}.timeout(timeout, forcefullyAbortTimeout: leeway).wait("waitUntil(...)", file: file, line: line)
switch result {
case .incomplete: internalError("Reached .incomplete state for waitUntil(...).")
case .blockedRunLoop:
fail(blockedRunLoopErrorMessageFor("-waitUntil()", leeway: leeway),
file: file, line: line)
case .timedOut:
let pluralize = (timeout == 1 ? "" : "s")
fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line)
case let .raisedException(exception):
fail("Unexpected exception raised: \(exception)")
case let .errorThrown(error):
fail("Unexpected error thrown: \(error)")
case let .completed(.exception(exception)):
fail("Unexpected exception raised: \(exception)")
case let .completed(.error(error)):
fail("Unexpected error thrown: \(error)")
case .completed(.none): // success
break
}
}
#if SWIFT_PACKAGE
internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) {
until(timeout: 1, file: file, line: line, action: action)
}
#else
@objc(untilFile:line:action:)
internal class func until(_ file: FileString = #file, line: UInt = #line, action: @escaping (() -> Void) -> Void) {
until(timeout: 1, file: file, line: line, action: action)
}
#endif
}
internal func blockedRunLoopErrorMessageFor(_ fnName: String, leeway: TimeInterval) -> String {
return "\(fnName) timed out but was unable to run the timeout handler because the main thread is unresponsive (\(leeway) seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
}
/// Wait asynchronously until the done closure is called or the timeout has been reached.
///
/// @discussion
/// Call the done() closure to indicate the waiting has completed.
///
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func waitUntil(timeout: TimeInterval = 1, file: FileString = #file, line: UInt = #line, action: @escaping (@escaping () -> Void) -> Void) {
NMBWait.until(timeout: timeout, file: file, line: line, action: action)
}
| mit | 0c38eda128b5b1981911458206935481 | 42.979798 | 381 | 0.603124 | 4.774123 | false | false | false | false |
zpz1237/NirBillBoard | NirBillboard/ProfileViewController.swift | 1 | 3410 | //
// ProfileViewController.swift
// NirBillboard
//
// Created by Nirvana on 7/11/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var buttonImage: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
buttonImage.setImage(UIImage(named: "1430891193_photo-128"), forState: UIControlState.Normal)
assert(buttonImage.imageView?.image != nil)
// Do any additional setup after loading the view.
}
@IBAction func choosePhoto(sender: UIButton) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
let deleteAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in
self.goCamera()
}
let archiveAction = UIAlertAction(title: "从相册选择", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in
self.goImage()
}
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
alertController.addAction(archiveAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func goCamera() {
var sourceType = UIImagePickerControllerSourceType.Camera
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
var picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = sourceType
self.presentViewController(picker, animated: true, completion: nil)
}
func goImage() {
var picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(picker.sourceType)!
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
buttonImage.setImage(image, forState: UIControlState.Normal)
picker.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
picker.dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 36919c84ac8bef6cc0a732b58379d97b | 33.602041 | 139 | 0.669419 | 5.928322 | false | false | false | false |
terryxing/Swift | CoreLocation/CoreLocation/ViewController.swift | 8 | 6899 | //
// ViewController.swift
// CoreLocation
//
// Created by Carlos Butron on 19/12/14.
// Copyright (c) 2015 Carlos Butron. 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
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager: CLLocationManager = CLLocationManager()
var myLatitude: CLLocationDegrees!
var myLongitude: CLLocationDegrees!
var finalLatitude: CLLocationDegrees!
var finalLongitude: CLLocationDegrees!
var distance: CLLocationDistance!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let tap = UITapGestureRecognizer(target: self, action: "action:")
myMap.addGestureRecognizer(tap)
}
func action(gestureRecognizer:UIGestureRecognizer) {
var touchPoint = gestureRecognizer.locationInView(self.myMap)
var newCoord:CLLocationCoordinate2D = myMap.convertPoint(touchPoint, toCoordinateFromView: self.myMap)
var getLat: CLLocationDegrees = newCoord.latitude
var getLon: CLLocationDegrees = newCoord.longitude
//Convert to points to CLLocation. In this way we can measure distanceFromLocation
var newCoord2: CLLocation = CLLocation(latitude: getLat, longitude: getLon)
var newCoord3: CLLocation = CLLocation(latitude: myLatitude, longitude: myLongitude)
finalLatitude = newCoord2.coordinate.latitude
finalLongitude = newCoord2.coordinate.longitude
println("Original Latitude: \(myLatitude)")
println("Original Longitude: \(myLongitude)")
println("Final Latitude: \(finalLatitude)")
println("Final Longitude: \(finalLongitude)")
//distance between our position and the new point created
let distance = newCoord2.distanceFromLocation(newCoord3)
println("Distancia entre puntos: \(distance)")
var newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoord
newAnnotation.title = "My target"
newAnnotation.subtitle = ""
myMap.addAnnotation(newAnnotation)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
} else {
println("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
//get data from placemark
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
myLongitude = (containsPlacemark.location.coordinate.longitude)
myLatitude = (containsPlacemark.location.coordinate.latitude)
// testing show data
println("Locality: \(locality)")
println("PostalCode: \(postalCode)")
println("Area: \(administrativeArea)")
println("Country: \(country)")
println(myLatitude)
println(myLongitude)
//update map with my location
let theSpan:MKCoordinateSpan = MKCoordinateSpanMake(0.1 , 0.1)
let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: myLatitude, longitude: myLongitude)
let theRegion:MKCoordinateRegion = MKCoordinateRegionMake(location, theSpan)
myMap.setRegion(theRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
//distance between two points
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }
func getBearingBetweenTwoPoints1(point1 : CLLocation, point2 : CLLocation) -> Double {
let lat1 = degreesToRadians(point1.coordinate.latitude)
let lon1 = degreesToRadians(point1.coordinate.longitude)
let lat2 = degreesToRadians(point2.coordinate.latitude);
let lon2 = degreesToRadians(point2.coordinate.longitude);
println("Latitud inicial: \(point1.coordinate.latitude)")
println("Longitud inicial: \(point1.coordinate.longitude)")
println("Latitud final: \(point2.coordinate.latitude)")
println("Longitud final: \(point2.coordinate.longitude)")
let dLon = lon2 - lon1;
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x);
return radiansToDegrees(radiansBearing)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 1eda26be06bbeaf5d5395bcf33e6a5ee | 38.198864 | 126 | 0.649659 | 5.510383 | false | false | false | false |
actorapp/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/iOSPhoneBookProvider.swift | 3 | 6837 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import AddressBook
class PhoneBookProvider: NSObject, ACPhoneBookProvider {
func loadPhoneBook(with callback: ACPhoneBookProvider_Callback!) {
dispatchBackgroundDelayed(5.0) {
let rawBook = ABAddressBookCreateWithOptions(nil, nil)
if (rawBook == nil) {
print("Access to AddressBook denied")
callback.onLoaded(withContacts: JavaUtilArrayList())
return
}
let book: ABAddressBook = rawBook!.takeRetainedValue()
// ABAddressBookRequestAccessWithCompletion(book, { (granted: Bool, error: CFError!) -> Void in
// if (!granted) {
// print("Access to AddressBook denied")
// callback.onLoaded(withContacts: JavaUtilArrayList())
// return
// }
//
// autoreleasepool {
// let numbersSet = CharacterSet(charactersIn: "0123456789").inverted
// let contacts = JavaUtilArrayList()
// var index = 1
// let people = ABAddressBookCopyArrayOfAllPeople(book).takeRetainedValue() as [ABRecordRef]
//
// for person in people {
// let firstName = self.extractString(person as ABRecord, propertyName: kABPersonFirstNameProperty)
// let middleName = self.extractString(person as ABRecord, propertyName: kABPersonMiddleNameProperty)
// let lastName = self.extractString(person as ABRecord, propertyName: kABPersonLastNameProperty)
//
// var contactName :String?
//
// //
// // For Performance. LOL.
// //
// if firstName != nil {
// if middleName != nil {
// if lastName != nil {
// contactName = firstName! + " " + middleName! + " " + lastName!
// } else {
// contactName = firstName! + " " + middleName!
// }
// } else {
// if (lastName != nil) {
// contactName = firstName! + " " + lastName!
// } else {
// contactName = firstName
// }
// }
// } else {
// if middleName != nil {
// if lastName != nil {
// contactName = middleName! + " " + lastName!
// } else {
// contactName = middleName
// }
// } else {
// if lastName != nil {
// contactName = lastName
// }
// }
// }
//
// if (firstName == "Name not specified") {
// contactName = nil
// }
//
// let contactPhones = JavaUtilArrayList()
// let contactEmails = JavaUtilArrayList()
// let contact = ACPhoneBookContact(long: jlong(index), with: contactName, with: contactPhones, with: contactEmails)
// index += 1
// if let phones: ABMultiValueRef =
// self.extractProperty(person as ABRecord, propertyName: kABPersonPhoneProperty) as ABMultiValueRef? {
// for i in 0...ABMultiValueGetCount(phones) {
// var phoneStr = self.extractString(phones, index: i)
// if (phoneStr == nil || phoneStr!.trim().isEmpty) {
// continue
// }
// phoneStr = phoneStr!.strip(numbersSet)
// let phoneVal = Int64(phoneStr!)// numberFormatter.numberFromString(phoneStr!)?.longLongValue
// if (phoneVal != nil) {
// contactPhones.addWithId(ACPhoneBookPhone(long: jlong(index), withLong: jlong(phoneVal!)))
// index += 1
// }
// }
// }
//
// if let emails: ABMultiValueRef =
// self.extractProperty(person as ABRecord, propertyName: kABPersonEmailProperty) as ABMultiValueRef? {
// for i in 0...ABMultiValueGetCount(emails) {
// let emailStr = self.extractString(emails, index: i)
// if (emailStr == nil || emailStr!.trim().isEmpty) {
// continue
// }
// contactEmails.addWithId(ACPhoneBookEmail(long: jlong(index), with: emailStr!))
// index += 1
// }
// }
//
// if (contactPhones.size() != 0 || contactEmails.size() != 0) {
// contacts.addWithId(contact)
// }
// }
//
// callback.onLoaded(withContacts: contacts)
// }
// })
}
}
fileprivate func extractString(_ record: ABRecord, propertyName : ABPropertyID) -> String? {
return extractProperty(record, propertyName: propertyName)
}
fileprivate func extractProperty<T>(_ record: ABRecord, propertyName : ABPropertyID) -> T? {
//the following is two-lines of code for a reason. Do not combine (compiler optimization problems)
let value: AnyObject? = ABRecordCopyValue(record, propertyName)?.takeRetainedValue()
return value as? T
}
fileprivate func extractString(_ record: ABMultiValue, index: Int) -> String? {
let value: AnyObject? = ABMultiValueCopyValueAtIndex(record, index)?.takeRetainedValue()
return value as? String
}
}
| agpl-3.0 | 20480aef4908728cae322ea2c2527738 | 50.406015 | 139 | 0.419336 | 5.888889 | false | false | false | false |
JohnEstropia/GCDKit | Package.swift | 1 | 1540 | //
// Package.swift
// GCDKit
//
// Copyright © 2016 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import PackageDescription
let targets: [Target]
#if os(iOS)
targets = [Target(name: "GCDKit iOS")]
#elseif os(OSX)
targets = [Target(name: "GCDKit OSX")]
#elseif os(watchOS)
targets = [Target(name: "GCDKit watchOS")]
#elseif os(tvOS)
targets = [Target(name: "GCDKit tvOS")]
#else
targets = []
#endif
let package = Package(
name: "GCDKit",
targets: targets
)
| mit | 93426f0ac1365898b43aca43823f7a06 | 33.977273 | 82 | 0.731644 | 3.936061 | false | false | false | false |
Kalvin126/BatteryNotifier | iOS Battery Notifier/Services/NotificationsHandler.swift | 1 | 6618 | //
// NotificationsHandler.swift
// BatteryNotifier
//
// Created by Kalvin Loc on 10/14/19.
// Copyright © 2019 Red Panda. All rights reserved.
//
import Cocoa
final class NotificationsHandler: NSObject {
private var deviceNotificationTimers: [Device.SerialNumber: Timer] = [:]
private var devices: Set<Device> = []
private let userDefaults = UserDefaults.standard
private lazy var queue: DispatchQueue = DispatchQueue(label: "com.redpanda.NotificationsHandler",
qos: .default,
target: .global())
// MARK: Notification Thresholds
private var batteryThreshold: Int { userDefaults.integer(forKey: .batteryThreshold) }
private var snoozeInterval: Int { userDefaults.integer(forKey: "SnoozeInterval") }
// MARK: Init
override init() {
super.init()
UserDefaults.standard.addObserver(self,
forKeyPath: ConfigKey.lowBatteryNotificationsOn.id,
options: .new,
context: nil)
}
deinit {
UserDefaults.standard.removeObserver(self,
forKeyPath: ConfigKey.lowBatteryNotificationsOn.id)
}
// MARK: NSKeyValueObserving
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
if keyPath == ConfigKey.lowBatteryNotificationsOn.id {
// Remove all pending notifications if turned off, notifications re-enabled upon device re-connection
if let newChange = change?[.newKey] as? Int,
newChange == 0 {
queue.async {
self.removeAllNotificationTimers()
}
}
}
}
}
// MARK: - Actions
extension NotificationsHandler {
private func removeLowBatteryNotification(for serial: Device.SerialNumber) {
deviceNotificationTimers[serial]?.invalidate()
deviceNotificationTimers.removeValue(forKey: serial)
}
private func removeAllNotificationTimers() {
deviceNotificationTimers.keys.forEach {
removeLowBatteryNotification(for: $0)
}
}
private func snoozeDevice(_ device: Device) {
guard deviceNotificationTimers.keys.contains(device.serialNumber) else { return }
removeLowBatteryNotification(for: device.serialNumber)
let deadline = DispatchTime.now() + .seconds(snoozeInterval*60)
// dispatch re-enabling of notification timer after snooze interval
queue.asyncAfter(deadline: deadline) {
self.updateLowBatteryNotificationTimer(for: device)
}
}
private func updateLowBatteryNotification(for device: Device) {
guard !device.isBatteryCharging ||
device.currentBatteryCapacity <= batteryThreshold else {
removeLowBatteryNotification(for: device.serialNumber)
return
}
guard deviceNotificationTimers[device.serialNumber] == nil,
device.currentBatteryCapacity <= userDefaults.integer(forKey: .batteryThreshold),
userDefaults.bool(forKey: .lowBatteryNotificationsOn) else { return }
updateLowBatteryNotificationTimer(for: device)
}
private func updateLowBatteryNotificationTimer(for device: Device) {
guard !device.isBatteryCharging else { return }
guard deviceNotificationTimers[device.serialNumber] == nil else { return }
let interval = userDefaults.double(forKey: .notificationInterval)*60.0
let timer = Timer.scheduledTimer(timeInterval: interval,
target: self,
selector: #selector(sendLowBatteryNotification(timer:)),
userInfo: device.serialNumber,
repeats: true)
timer.fire()
deviceNotificationTimers[device.serialNumber] = timer
}
@objc private func sendLowBatteryNotification(timer: Timer) {
guard let deviceSerialNumber = timer.userInfo as? String,
let device = devices.first(where: { $0.serialNumber == deviceSerialNumber }) else { return }
let userInfo = ["deviceSerialNumber": deviceSerialNumber]
let notification = NSUserNotification()
notification.title = "Low Battery: \(device.name)"
notification.subtitle = "\(device.currentBatteryCapacity)% of battery remaining"
notification.soundName = NSUserNotificationDefaultSoundName
notification.userInfo = userInfo
// Private
notification.actionButtonTitle = "Snooze"
notification.setValue(true, forKey: "_showsButtons")
notification.setValue(NSImage(named: "lowBattery"), forKey: "_identityImage")
notification.setValue(false, forKey: "_identityImageHasBorder")
NSUserNotificationCenter.default.deliver(notification)
}
}
// MARK: - Events
extension NotificationsHandler { }
// MARK: - DeviceObserver
extension NotificationsHandler: DeviceObserver {
func deviceManager(_ manager: DeviceManager, didFetch devices: Set<Device>) {
queue.async {
devices.forEach { self.devices.update(with: $0) }
}
}
func deviceManager(_ manager: DeviceManager, didExpire device: Device) {
queue.async {
_ = self.devices.remove(device)
self.removeLowBatteryNotification(for: device.serialNumber)
}
}
}
// MARK: - NSUserNotificationCenterDelegate
extension NotificationsHandler: NSUserNotificationCenterDelegate {
func userNotificationCenter(_ center: NSUserNotificationCenter,
shouldPresent notification: NSUserNotification) -> Bool {
return true
}
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
switch notification.activationType {
case .actionButtonClicked:
guard let deviceSerialNumber = notification.userInfo?["deviceSerialNumber"] as? String,
let device = devices.first(where: { $0.serialNumber == deviceSerialNumber }) else { return }
queue.async {
self.snoozeDevice(device)
}
default:
break
}
}
}
| gpl-3.0 | dd80c8a6c578f778f9328de472740da8 | 34.575269 | 115 | 0.625057 | 5.555835 | false | false | false | false |
aiqiuqiu/Tuan | Tuan/HMSearchViewController.swift | 2 | 5097 | //
// HMSearchViewController.swift
// Tuan
//
// Created by nero on 15/6/1.
// Copyright (c) 2015年 nero. All rights reserved.
//
import UIKit
class HMSearchViewController: HMDealListViewController {
var selectedCity:HMCity?
var lastParam:HMFindDealsParam?
var totalCount = 0
var footer:MJRefreshFooterView!
var searchBar:UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
/**
* 设置导航栏的内容
*/
func setupNav(){
// 左边的返回
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "icon_back", highImageName: "icon_back_highlighted", target: self, action: Selector("back"))
// 中间的搜索框
let titleView = UIView(frame: CGRectZero)
titleView.height = 30
titleView.width = 400
navigationItem.titleView = titleView
searchBar = UISearchBar()
searchBar.backgroundImage = UIImage(named: "bg_login_textfield")
titleView.addSubview(searchBar)
searchBar.delegate = self
searchBar.placeholder = "请输入关键词"
searchBar.autoPinEdgesToSuperviewEdgesWithInsets( UIEdgeInsetsZero)
}
func setupRefresh(){
footer = MJRefreshFooterView.footer()
self.footer.scrollView = self.collectionView
self.footer.delegate = self
}
setupNav()
setupRefresh()
}
func back(){
self.footer = nil
dismissViewControllerAnimated(true, completion: nil)
}
func loadMoreDeals(){
self.searchBar.userInteractionEnabled = false
// // // 1.请求参数
let param = HMFindDealsParam()
// // 关键词
param.keyword = searchBar.text
var x = 0
let operantion:String?
// = operantion.lastPathComponent
// // 城市
param.city = self.selectedCity?.name
// // 页码
param.page = NSNumber(int: self.lastParam!.page.intValue + 1)
HMDealTool.findDeals(param, success: { (result) -> Void in
self.totalCount = result.deals.count
for deal in result.deals {
self.deals.append(deal as! HMDeal)
}
self.collectionView?.reloadData()
self.footer.endRefreshing()
self.searchBar.userInteractionEnabled = true
}) { (error) -> Void in
MBProgressHUD.showError("加载团购失败,请稍后再试")
self.footer.endRefreshing()
param.page = NSNumber(int: self.lastParam!.page.intValue - 1)
self.searchBar.userInteractionEnabled = true
}
// // 3.设置请求参数
lastParam = param
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func emptyIcon() -> String {
return "icon_deals_empty"
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.footer.hidden = self.deals.count == totalCount
return super.collectionView(collectionView, numberOfItemsInSection: section)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.footer = nil
}
}
extension HMSearchViewController:UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.endEditing(true)
MBProgressHUD.showMessage("正在搜索团购", toView: navigationController?.view)
// // 1.请求参数
let param = HMFindDealsParam()
// // 关键词
param.keyword = searchBar.text
// // 城市
param.city = self.selectedCity?.name
// // 页码
param.page = NSNumber(integer: 1)
//
// // 2.搜索
HMDealTool.findDeals(param, success: { (result) -> Void in
self.deals.removeAll(keepCapacity: false)
for deal in result.deals {
self.deals.append(deal as! HMDeal)
}
self.collectionView?.reloadData()
MBProgressHUD.hideHUDForView(self.navigationController?.view, animated: true)
}) { (error) -> Void in
MBProgressHUD.hideHUDForView(self.navigationController?.view, animated: true)
MBProgressHUD.showError("加载团购失败,请稍后再试")
}
lastParam = param
}
}
extension HMSearchViewController:MJRefreshBaseViewDelegate {
func refreshViewBeginRefreshing(refreshView: MJRefreshBaseView!) {
self.loadMoreDeals()
}
}
| mit | c22f7bdbd6ce9e19af72f0ebb4c03843 | 31.833333 | 166 | 0.580914 | 5 | false | false | false | false |
superk589/DereGuide | DereGuide/Common/CloudKitSync/FavoriteCardUploader.swift | 2 | 2596 | //
// FavoriteCardUploader.swift
// DereGuide
//
// Created by zzk on 2017/7/27.
// Copyright © 2017 zzk. All rights reserved.
//
import CoreData
/// use local favorite card to create remote favorite card
final class FavoriteCardUploader: ElementChangeProcessor {
typealias Element = FavoriteCard
var remote: FavoriteCardsRemote
init(remote: FavoriteCardsRemote) {
self.remote = remote
}
var elementsInProgress = InProgressTracker<FavoriteCard>()
func setup(for context: ChangeProcessorContext) {
// no-op
}
func processChangedLocalElements(_ objects: [FavoriteCard], in context: ChangeProcessorContext) {
processInsertedFavoriteCards(objects, in: context)
}
func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], in context: ChangeProcessorContext, completion: () -> ()) {
completion()
}
func fetchLatestRemoteRecords(in context: ChangeProcessorContext) {
// no-op
}
var predicateForLocallyTrackedElements: NSPredicate {
return FavoriteCard.waitingForUploadPredicate
}
}
extension FavoriteCardUploader {
fileprivate func processInsertedFavoriteCards(_ insertions: [FavoriteCard], in context: ChangeProcessorContext) {
remote.upload(insertions) { (remoteFavoriteCards, error) in
context.perform {
guard !(error?.isPermanent ?? false) else {
// Since the error was permanent, delete these objects:
insertions.forEach { $0.markForLocalDeletion() }
self.elementsInProgress.markObjectsAsComplete(insertions)
return
}
// currently not retry for temporarily error
// set unit remote id
for favoriteCard in insertions {
guard let remoteFavoriteCard = remoteFavoriteCards.first(where: { favoriteCard.createdAt == $0.localCreatedAt }) else { continue }
favoriteCard.creatorID = remoteFavoriteCard.creatorID
favoriteCard.remoteIdentifier = remoteFavoriteCard.id
}
context.delayedSaveOrRollback()
if Config.cloudKitDebug && insertions.count > 0 {
print("favorite card uploader: upload \(insertions.count) success \(insertions.filter { $0.remoteIdentifier != nil }.count)")
}
self.elementsInProgress.markObjectsAsComplete(insertions)
}
}
}
}
| mit | 1638afe60ed066fbe001aa4cf9e70310 | 34.547945 | 150 | 0.625434 | 5.242424 | false | false | false | false |
thoughtworks/dancing-glyphs | Library/MetalScreenSaverView.swift | 1 | 4621 | /*
* Copyright 2016 Erik Doernenburg
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use these files 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 ScreenSaver
import Metal
import IOKit.ps
class MetalScreenSaverView : ScreenSaverView
{
var device: MTLDevice!
var displayLink: CVDisplayLink!
var outputTime: Double = 0
// init and deinit
override init?(frame: NSRect, isPreview: Bool)
{
super.init(frame: frame, isPreview: isPreview)
device = selectMetalDevice()
wantsLayer = true;
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
CVDisplayLinkStop(displayLink!)
}
private func selectMetalDevice() -> MTLDevice
{
var device: MTLDevice?
var message: String
if IOPSGetTimeRemainingEstimate() == kIOPSTimeRemainingUnlimited {
device = MTLCreateSystemDefaultDevice()
message = "Connected to power, using default video device"
} else {
for d in MTLCopyAllDevices() {
device = d
if d.isLowPower && !d.isHeadless {
message = "On battery, using low power video device"
break
}
}
message = "On battery, using video device"
}
if let name = device?.name {
NSLog("TWGlyphSaver: \(message) \(name)")
} else {
NSLog("TWGlyphSaver: No or unknown video device. Screen saver might not work.")
}
return device!
}
// deferred initialisations that require access to the window
override func viewDidMoveToSuperview()
{
super.viewDidMoveToSuperview()
if let window = superview?.window {
layer = makeMetalLayer(window: window, device:device)
displayLink = makeDisplayLink(window: window)
}
}
private func makeMetalLayer(window: NSWindow, device: MTLDevice) -> CAMetalLayer
{
let metalLayer = CAMetalLayer()
metalLayer.device = device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = true
metalLayer.contentsScale = window.backingScaleFactor
metalLayer.isOpaque = true
return metalLayer
}
private func makeDisplayLink(window: NSWindow) -> CVDisplayLink
{
func displayLinkOutputCallback(_ displayLink: CVDisplayLink, _ nowPtr: UnsafePointer<CVTimeStamp>, _ outputTimePtr: UnsafePointer<CVTimeStamp>, _ flagsIn: CVOptionFlags, _ flagsOut: UnsafeMutablePointer<CVOptionFlags>, _ displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn {
let _self: MetalScreenSaverView = unsafeBitCast(displayLinkContext, to: MetalScreenSaverView.self)
let outputTime = outputTimePtr.pointee
_self.outputTime = Double(outputTime.videoTime) / Double(outputTime.videoTimeScale)
_self.animateOneFrame()
return kCVReturnSuccess
}
var link: CVDisplayLink?
let ddDictionary = Dictionary(uniqueKeysWithValues: window.screen!.deviceDescription.map {key, value in (key.rawValue, value)})
let screensID = UInt32(ddDictionary["NSScreenNumber"] as! Int)
CVDisplayLinkCreateWithCGDisplay(screensID, &link)
CVDisplayLinkSetOutputCallback(link!, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
return link!
}
// screen saver api
override class func backingStoreType() -> NSWindow.BackingStoreType
{
return NSWindow.BackingStoreType.nonretained
}
override func startAnimation()
{
// we're not calling super because we need to set up our own timer for the animation
CVDisplayLinkStart(displayLink!)
}
override func stopAnimation()
{
// we're not calling super because we didn't do it in startAnimation()
CVDisplayLinkStop(displayLink!)
}
override var isAnimating: Bool
{
get
{
return CVDisplayLinkIsRunning(displayLink!)
}
}
}
| apache-2.0 | 4065cd0fda9f18f9db70d1906c041113 | 30.868966 | 288 | 0.650941 | 4.974166 | false | false | false | false |
sarvex/SwiftRecepies | Cloud/Retrieving Data with CloudKit/Retrieving Data with CloudKit/ViewController.swift | 1 | 7027 | //
// ViewController.swift
// Retrieving Data with CloudKit
//
// Created by vandad on 197//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import UIKit
import CloudKit
class ViewController: UIViewController {
let database = CKContainer.defaultContainer().privateCloudDatabase
/* Defines our car types */
enum CarType: String{
case Estate = "Estate"
func zoneId() -> CKRecordZoneID{
let zoneId = CKRecordZoneID(zoneName: self.rawValue,
ownerName: CKOwnerDefaultName)
return zoneId
}
}
/* Checks if the user has logged into her iCloud account or not */
func isIcloudAvailable() -> Bool{
if let token = NSFileManager.defaultManager().ubiquityIdentityToken{
return true
} else {
return false
}
}
/* This method generates a record ID and keeps it in the system defaults
so that the second time it is called, it will generate the exact same record
ID like before which we can use to find the stored record in the database */
func recordId() -> CKRecordID{
/* The key into NSUserDefaults */
let key = "recordId"
var recordName =
NSUserDefaults.standardUserDefaults().stringForKey(key)
func createNewRecordName(){
println("No record name was previously generated")
println("Creating a new one...")
recordName = NSUUID().UUIDString
NSUserDefaults.standardUserDefaults().setValue(recordName, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
if let name = recordName{
if count(name) == 0{
createNewRecordName()
} else {
println("The previously generated record ID was recovered")
}
} else {
createNewRecordName()
}
return CKRecordID(recordName: recordName, zoneID: CarType.Estate.zoneId())
}
func saveRecordWithCompletionHandler(completionHandler:
(succeeded: Bool, error: NSError!) -> Void){
/* Store information about a Volvo V50 car */
let volvoV50 = CKRecord(recordType: "MyCar", recordID: recordId())
volvoV50.setObject("Volvo", forKey: "maker")
volvoV50.setObject("V50", forKey: "model")
volvoV50.setObject(5, forKey: "numberOfDoors")
volvoV50.setObject(2015, forKey: "year")
/* Save this record publicly */
database.saveRecord(volvoV50, completionHandler: {
(record: CKRecord!, error: NSError!) in
completionHandler(succeeded: (error == nil), error: error)
})
}
/* 1 */
// override func viewDidAppear(animated: Bool) {
// super.viewDidAppear(animated)
//
// if isIcloudAvailable(){
// displayAlertWithTitle("iCloud", message: "iCloud is not available." +
// " Please sign into your iCloud account and restart this app")
// return
// }
//
// println("Fetching the record to see if it exists already...")
//
// /* Attempt to find the record if we have saved it already */
// database.fetchRecordWithID(recordId(), completionHandler:{[weak self]
// (record: CKRecord!, error: NSError!) in
//
// if error != nil{
// println("An error occurred")
//
// if error.code == CKErrorCode.UnknownItem.rawValue{
// println("This error means that the record was not found.")
// println("Saving the record...")
//
// self!.saveRecordWithCompletionHandler{
// (succeeded: Bool, error: NSError!) in
//
// if succeeded{
// println("Successfully saved the record")
// } else {
// println("Failed to save the record. Error = \(error)")
// }
//
// }
//
// } else {
// println("I don't understand this error. Error = \(error)")
// }
//
// } else {
// println("Seems like we had previously stored the record. Great!")
// println("Retrieved record = \(record)")
// }
//
// })
//
// }
/* 2 */
enum Color : String{
case Red = "Red"
case Blue = "Blue"
case Green = "Green"
case Yellow = "Yellow"
static let allColors = [Red, Blue, Green, Yellow]
static func randomColor() -> Color{
let colorIndex = Int(arc4random_uniform(UInt32(allColors.count)))
return Color.allColors[colorIndex]
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if isIcloudAvailable(){
displayAlertWithTitle("iCloud", message: "iCloud is not available." +
" Please sign into your iCloud account and restart this app")
return
}
println("Fetching the record to see if it exists already...")
/* Attempt to find the record if we have saved it already */
database.fetchRecordWithID(recordId(), completionHandler:{[weak self]
(record: CKRecord!, error: NSError!) in
if error != nil{
println("An error occurred")
if error.code == CKErrorCode.UnknownItem.rawValue{
println("This error means that the record was not found.")
println("Saving the record...")
self!.saveRecordWithCompletionHandler{
(succeeded: Bool, error: NSError!) in
if succeeded{
println("Successfully saved the record")
} else {
println("Failed to save the record. Error = \(error)")
}
}
} else {
println("I don't understand this error. Error = \(error)")
}
} else {
println("Seems like we had previously stored the record. Great!")
println("Retrieved record = \(record)")
/* Now make your changes to the record */
let colorKey = "color"
let newColor = Color.randomColor().rawValue
var oldColor = record.valueForKey(colorKey) as? String
if oldColor == nil{
oldColor = "Unknown"
}
println("Changing the car color from \(oldColor) to \(newColor)")
record.setValue(newColor, forKey:colorKey)
self!.database.saveRecord(record, completionHandler:
{(record:CKRecord!, error: NSError!) in
if error == nil{
println("Successfully modified the record")
} else {
println("Failed to modify the record. Error = \(error)")
}
})
}
})
}
/* Just a little method to help us display alert dialogs to the user */
func displayAlertWithTitle(title: String, message: String){
let controller = UIAlertController(title: title,
message: message,
preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK",
style: .Default,
handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
}
| isc | af685a09ea4ad22afc62b669146c2359 | 28.775424 | 79 | 0.590152 | 4.725622 | false | false | false | false |
MrAlek/JSQDataSourcesKit | Example/Example/FetchedCollectionViewController.swift | 1 | 6194 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://jessesquires.com/JSQDataSourcesKit
//
//
// GitHub
// https://github.com/jessesquires/JSQDataSourcesKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import UIKit
import CoreData
import JSQDataSourcesKit
class FetchedCollectionViewController: UICollectionViewController {
// MARK: properties
let stack = CoreDataStack()
typealias ThingCellFactory = CellFactory<Thing, CollectionViewCell>
typealias ThingSupplementaryViewFactory = ComposedCollectionSupplementaryViewFactory<Thing>
var dataSourceProvider: CollectionViewFetchedResultsDataSourceProvider<ThingCellFactory, ThingSupplementaryViewFactory>?
var delegateProvider: CollectionViewFetchedResultsDelegateProvider<ThingCellFactory>?
// MARK: view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView(collectionView!)
collectionView!.allowsMultipleSelection = true
let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
layout.footerReferenceSize = CGSize(width: collectionView!.frame.size.width, height: 25)
// 1. create cell factory
let cellFactory = CellFactory(reuseIdentifier: CellId) { (cell, model: Thing, collectionView, indexPath) -> CollectionViewCell in
cell.label.text = model.displayName
cell.label.textColor = UIColor.whiteColor()
cell.backgroundColor = model.displayColor
return cell
}
// 2. create supplementary view factory
let headerFactory = TitledCollectionReusableViewFactory(
dataConfigurator: { (header, item: Thing?, kind, collectionView, indexPath) -> TitledCollectionReusableView in
header.label.text = "\(item?.colorName) (header \(indexPath.section))"
header.label.textColor = item?.displayColor
return header
},
styleConfigurator: { (header) -> Void in
header.backgroundColor = .darkGrayColor()
})
let footerFactory = TitledCollectionReusableViewFactory(
dataConfigurator: { (footer, item: Thing?, kind, collectionView, indexPath) -> TitledCollectionReusableView in
footer.label.text = "\(item?.colorName) (footer \(indexPath.section))"
footer.label.textColor = item?.displayColor
return footer
},
styleConfigurator: { (footer) -> Void in
footer.backgroundColor = .lightGrayColor()
footer.label.font = .preferredFontForTextStyle(UIFontTextStyleFootnote)
footer.label.textAlignment = .Center
})
let composedFactory = ComposedCollectionSupplementaryViewFactory(headerViewFactory: headerFactory, footerViewFactory: footerFactory)
// 3. create fetched results controller
let frc = thingFRCinContext(stack.context)
// 4. create delegate provider
delegateProvider = CollectionViewFetchedResultsDelegateProvider(collectionView: collectionView!,
cellFactory: cellFactory,
fetchedResultsController: frc)
// 5. create data source provider
dataSourceProvider = CollectionViewFetchedResultsDataSourceProvider(fetchedResultsController: frc,
cellFactory: cellFactory,
supplementaryViewFactory: composedFactory,
collectionView: collectionView)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
fetchData()
}
// MARK: Helpers
private func fetchData() {
do {
try dataSourceProvider?.fetchedResultsController.performFetch()
} catch {
print("Fetch error = \(error)")
}
}
// MARK: Actions
@IBAction func didTapActionButton(sender: UIBarButtonItem) {
UIAlertController.showActionAlert(self, addNewAction: {
self.addNewThing()
}, deleteAction: {
self.deleteSelected()
}, changeNameAction: {
self.changeNameSelected()
}, changeColorAction: {
self.changeColorSelected()
}, changeAllAction: {
self.changeAllSelected()
})
}
func addNewThing() {
collectionView!.deselectAllItems()
let newThing = Thing.newThing(stack.context)
stack.saveAndWait()
fetchData()
if let indexPath = dataSourceProvider?.fetchedResultsController.indexPathForObject(newThing) {
collectionView!.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .CenteredVertically)
}
}
func deleteSelected() {
let indexPaths = collectionView!.indexPathsForSelectedItems()
dataSourceProvider?.fetchedResultsController.deleteThingsAtIndexPaths(indexPaths)
stack.saveAndWait()
fetchData()
collectionView!.reloadData()
}
func changeNameSelected() {
let indexPaths = collectionView!.indexPathsForSelectedItems()
dataSourceProvider?.fetchedResultsController.changeThingNamesAtIndexPaths(indexPaths)
stack.saveAndWait()
fetchData()
}
func changeColorSelected() {
let indexPaths = collectionView!.indexPathsForSelectedItems()
dataSourceProvider?.fetchedResultsController.changeThingColorsAtIndexPaths(indexPaths)
stack.saveAndWait()
fetchData()
}
func changeAllSelected() {
let indexPaths = collectionView!.indexPathsForSelectedItems()
dataSourceProvider?.fetchedResultsController.changeThingsAtIndexPaths(indexPaths)
stack.saveAndWait()
fetchData()
}
}
| mit | dec6b053be552b7749fac6270d44ba0c | 36.083832 | 140 | 0.638947 | 6.186813 | false | false | false | false |
cnbin/MarkdownTextView | MarkdownTextView/TextUtilities.swift | 1 | 1291 | //
// TextUtilities.swift
// MarkdownTextView
//
// Created by Indragie on 4/28/15.
// Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//
import UIKit
public typealias TextAttributes = [String: AnyObject]
internal func fontWithTraits(traits: UIFontDescriptorSymbolicTraits, font: UIFont) -> UIFont {
let combinedTraits = UIFontDescriptorSymbolicTraits(font.fontDescriptor().symbolicTraits.rawValue | (traits.rawValue & 0xFFFF))
if let descriptor = font.fontDescriptor().fontDescriptorWithSymbolicTraits(combinedTraits) {
return UIFont(descriptor: descriptor, size: font.pointSize)
}
return font
}
internal func regexFromPattern(pattern: String) -> NSRegularExpression {
var error: NSError?
if let regex = NSRegularExpression(pattern: pattern, options: .AnchorsMatchLines, error: &error) {
return regex
} else {
fatalError("Failed to initialize regular expression with pattern \(pattern): \(error)")
}
}
internal func enumerateMatches(regex: NSRegularExpression, string: String, block: NSTextCheckingResult -> Void) {
let range = NSRange(location: 0, length: (string as NSString).length)
regex.enumerateMatchesInString(string, options: nil, range: range) { (result, _, _) in
block(result)
}
}
| mit | 48afab135084b4d3a7918da3a3a1419a | 35.885714 | 131 | 0.728118 | 4.513986 | false | false | false | false |
andreipitis/ASPCircleChart | Example/ASPCircleChart/ViewController.swift | 1 | 1910 | //
// ViewController.swift
// ASPCircleChart
//
// Created by Andrei-Sergiu Pitis on 06/17/2016.
// Copyright (c) 2016 Andrei-Sergiu Pitis. All rights reserved.
//
import UIKit
import ASPCircleChart
class ViewController: UIViewController {
@IBOutlet weak var circleChart: ASPCircleChart!
let dataSource = DataSource()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
circleChart.lineCapStyle = .round
circleChart.latestSliceOnTop = false
circleChart.dataSource = dataSource
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var numberOfSlices = 2
while numberOfSlices <= 2 {
numberOfSlices = Int(arc4random()) % 8
}
var values = [Double]()
for _ in 0..<numberOfSlices {
let randomNumber = Double(arc4random() % 100)
values.append(randomNumber)
}
dataSource.items = values
circleChart.reloadData()
}
}
class DataSource: ASPCircleChartDataSource {
var items: [Double] = [44, 10, 134]
@objc func numberOfDataPoints() -> Int {
return items.count
}
@objc func dataPointsSum() -> Double {
return items.reduce(0.0, { (initial, new) -> Double in
return initial + new
})
}
@objc func dataPointAtIndex(_ index: Int) -> Double {
return items[index]
}
@objc func colorForDataPointAtIndex(_ index: Int) -> UIColor {
switch index {
case 0:
return UIColor(red: 205/255.0, green: 213/255.0, blue: 66/255.0, alpha: 1.0)
case 1:
return UIColor(red: 242/255.0, green: 115/255.0, blue: 82/255.0, alpha: 1.0)
case 2:
return UIColor(red: 83/255.0, green: 158/255.0, blue: 55/255.0, alpha: 1.0)
default:
return UIColor(red: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), green: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), blue: CGFloat(Float(arc4random()) / Float(UINT32_MAX)), alpha: 1.0)
}
}
}
| mit | aa7de938509893980b592ea37aeeb10b | 23.805195 | 197 | 0.682723 | 3.210084 | false | false | false | false |
EasySwift/EasySwift | EasySwift_iOS/Core/EZExtend+Bond.swift | 2 | 9591 | //
// EZBond.swift
// medical
//
// Created by zhuchao on 15/4/27.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Bond
import TTTAttributedLabel
import Kingfisher_iOS
import ReactiveKit
@objc class TapGestureDynamicHelper: NSObject
{
weak var view: UIView?
let sink: (UITapGestureRecognizer) -> Void
init(view: UIView, number: NSInteger, sink: @escaping ((UITapGestureRecognizer) -> Void)) {
self.view = view
self.sink = sink
super.init()
view.addTapGesture(number, target: self, action: #selector(TapGestureDynamicHelper.tapHandle(_:)))
}
func tapHandle(_ gesture: UITapGestureRecognizer) {
sink(gesture)
}
}
@objc class PanGestureDynamicHelper: NSObject {
weak var view: UIView?
let sink: (UIPanGestureRecognizer) -> Void
init(view: UIView, number: NSInteger, sink: @escaping ((UIPanGestureRecognizer) -> Void)) {
self.view = view
self.sink = sink
super.init()
view.addPanGesture(self, action: #selector(PanGestureDynamicHelper.panHandle(_:)))
}
func panHandle(_ gestureRecognizer: UIPanGestureRecognizer) {
sink(gestureRecognizer)
}
}
@objc class SwipeGestureDynamicHelper: NSObject
{
weak var view: UIView?
let sink: ((UISwipeGestureRecognizer) -> Void)
var number: NSInteger = 1
init(view: UIView, number: NSInteger, sink: @escaping ((UISwipeGestureRecognizer) -> Void)) {
self.view = view
self.number = number
self.sink = sink
super.init()
view.addSwipeGesture(UISwipeGestureRecognizerDirection.right, numberOfTouches: number, target: self, action: #selector(SwipeGestureDynamicHelper.swipeRightHandle(_:)))
view.addSwipeGesture(UISwipeGestureRecognizerDirection.up, numberOfTouches: number, target: self, action: #selector(SwipeGestureDynamicHelper.swipeUpHandle(_:)))
view.addSwipeGesture(UISwipeGestureRecognizerDirection.down, numberOfTouches: number, target: self, action: #selector(SwipeGestureDynamicHelper.swipeDownHandle(_:)))
view.addSwipeGesture(UISwipeGestureRecognizerDirection.left, numberOfTouches: number, target: self, action: #selector(SwipeGestureDynamicHelper.swipeLeftHandle(_:)))
}
func swipeRightHandle(_ gestureRecognizer: UISwipeGestureRecognizer) {
sink(gestureRecognizer)
}
func swipeUpHandle(_ gestureRecognizer: UISwipeGestureRecognizer) {
sink(gestureRecognizer)
}
func swipeDownHandle(_ gestureRecognizer: UISwipeGestureRecognizer) {
sink(gestureRecognizer)
}
func swipeLeftHandle(_ gestureRecognizer: UISwipeGestureRecognizer) {
sink(gestureRecognizer)
}
}
extension UIView {
fileprivate struct AssociatedKeys {
static var PanGestureEventKey = "bnd_PanGestureEventKey"
static var PanGestureEventHelperKey = "bnd_PanGestureEventHelperKey"
static var SwipeGestureEventKey = "bnd_SwipeGestureEventKey"
static var SwipeGestureEventHelperKey = "bnd_SwipeGestureEventHelperKey"
static var TapGestureEventKey = "bnd_TapGestureEventKey"
static var TapGestureEventHelperKey = "bnd_TapGestureEventHelperKey"
}
// public func bnd_swipeGestureEvent(_ number: NSInteger) -> EventProducer<UISwipeGestureRecognizer> {
// if let bnd_swipeGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.SwipeGestureEventKey) as AnyObject? {
// return bnd_swipeGestureEvent as! EventProducer<UISwipeGestureRecognizer>
// } else {
// var capturedSink: ((UISwipeGestureRecognizer) -> ())! = nil
// let bnd_swipeGestureEvent = EventProducer<UISwipeGestureRecognizer> { sink in
// capturedSink = sink
// return nil
// }
// let controlHelper = SwipeGestureDynamicHelper(view: self, number: number, sink: capturedSink)
// objc_setAssociatedObject(self, &AssociatedKeys.SwipeGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// objc_setAssociatedObject(self, &AssociatedKeys.SwipeGestureEventKey, bnd_swipeGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return bnd_swipeGestureEvent
// }
// }
//
// public func bnd_tapGestureEvent(_ number: NSInteger) -> EventProducer<UITapGestureRecognizer> {
// if let bnd_tapGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.TapGestureEventKey) as AnyObject? {
// return bnd_tapGestureEvent as! EventProducer<UITapGestureRecognizer>
// } else {
// var capturedSink: ((UITapGestureRecognizer) -> ())! = nil
// let bnd_tapGestureEvent = EventProducer<UITapGestureRecognizer> { sink in
// capturedSink = sink
// return nil
// }
// let controlHelper = TapGestureDynamicHelper(view: self, number: number, sink: capturedSink)
// objc_setAssociatedObject(self, &AssociatedKeys.TapGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// objc_setAssociatedObject(self, &AssociatedKeys.TapGestureEventKey, bnd_tapGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return bnd_tapGestureEvent
// }
// }
//
// public var bnd_panGestureEvent: EventProducer<UIPanGestureRecognizer> {
// if let bnd_panGestureEvent: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.PanGestureEventKey) as AnyObject? {
// return bnd_panGestureEvent as! EventProducer<UIPanGestureRecognizer>
// } else {
// var capturedSink: ((UIPanGestureRecognizer) -> ())! = nil
// let bnd_panGestureEvent = EventProducer<UIPanGestureRecognizer> { sink in
// capturedSink = sink
// return nil
// }
// let controlHelper = PanGestureDynamicHelper(view: self, number: 1, sink: capturedSink)
// objc_setAssociatedObject(self, &AssociatedKeys.PanGestureEventHelperKey, controlHelper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// objc_setAssociatedObject(self, &AssociatedKeys.PanGestureEventKey, bnd_panGestureEvent, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return bnd_panGestureEvent
// }
// }
}
//extension UIImageView {
// fileprivate struct AssociatedKeys {
// static var UrlImageDynamicHandleUIImageView = "UrlImageDynamicHandleUIImageView"
// }
// public var bnd_URLImage: Observable<URL?> {
// if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.UrlImageDynamicHandleUIImageView) as AnyObject? {
// return (d as? Observable<URL?>)!
// } else {
// let d = Observable<URL?>(URL())
// d.observe { [weak self] v in if let s = self {
// if v != nil {
// s.kf_setImageWithURL(v!)
// }
// } }
// objc_setAssociatedObject(self, &AssociatedKeys.UrlImageDynamicHandleUIImageView, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return d
// }
// }
//}
extension TTTAttributedLabel {
fileprivate struct AssociatedKeys {
static var textDynamicHandleTTTAttributeLabel = "textDynamicHandleTTTAttributeLabel"
static var attributedTextDynamicHandleTTTAttributeLabel = "attributedTextDynamicHandleTTTAttributeLabel"
static var dataDynamicHandleTTTAttributeLabel = "dataDynamicHandleTTTAttributeLabel"
}
public var dynTTText: Observable<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.textDynamicHandleTTTAttributeLabel) as AnyObject? {
return (d as? Observable<String>)!
} else {
let d = Observable<String>(self.text ?? "")
d.observe { [weak self] v in if let s = self {
s.setText(v)
} }
objc_setAssociatedObject(self, &AssociatedKeys.textDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
// public var dynTTTData: Observable<Data> {
// if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.dataDynamicHandleTTTAttributeLabel) as AnyObject? {
// return (d as? Observable<Data>)!
// } else {
// let d = Observable<Data>(Data())
// d.observe { [weak self] v in if let s = self {
// s.setText(NSAttributedString(fromHTMLData: v, attributes: ["dict": s.tagProperty.style]))
// } }
// objc_setAssociatedObject(self, &AssociatedKeys.dataDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// return d
// }
// }
public var dynTTTAttributedText: Observable<NSAttributedString> {
if let d: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.attributedTextDynamicHandleTTTAttributeLabel) as AnyObject? {
return (d as? Observable<NSAttributedString>)!
} else {
let d = Observable<NSAttributedString>(self.attributedText ?? NSAttributedString(string: ""))
d.observe { [weak self] v in if let s = self {
s.setText(v) } }
objc_setAssociatedObject(self, &AssociatedKeys.attributedTextDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
}
| apache-2.0 | 88e61ee37729fbc5ee61c182c5a45f4d | 47.18593 | 175 | 0.680884 | 4.799299 | false | false | false | false |
zhaobin19918183/zhaobinCode | FamilyShop/FamilyShop/CoreData/BaseDAO.swift | 1 | 1453 | //
// BaseDAO.swift
// FamilyShop
//
// Created by Zhao.bin on 16/9/26.
// Copyright © 2016年 Zhao.bin. All rights reserved.
//
import UIKit
import CoreData
class BaseDAO: NSObject
{
static let managedObjectModel : NSManagedObjectModel =
{
let modelURL = Bundle.main.url(forResource: "FamilyShopModel", withExtension: "momd")
return NSManagedObjectModel(contentsOf: modelURL!)!
}()
static let persistentStoreCoordinator : NSPersistentStoreCoordinator =
{
let sqliteURL = URL(fileURLWithPath: kPathSQLITE)
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: BaseDAO.managedObjectModel)
do
{
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: sqliteURL, options: nil)
print("Initial persistent store coordinator success")
}catch
{
print("Initial persistent store coordinator failed - \(error)")
abort()
}
return persistentStoreCoordinator
}()
static let mainMOC : NSManagedObjectContext =
{
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = BaseDAO.persistentStoreCoordinator
return moc
}()
}
| gpl-3.0 | 8bc864f5706cd026d93224124598ee68 | 30.521739 | 145 | 0.631034 | 6.170213 | false | false | false | false |
BeezleLabs/HackerTracker-iOS | hackertracker/AnonymousSession.swift | 1 | 4541 | //
// AnonymousSession.swift
// hackertracker
//
// Created by Christopher Mays on 7/8/19.
// Copyright © 2019 Beezle Labs. All rights reserved.
//
import Firebase
import FirebaseStorage
import Foundation
class AnonymousSession {
typealias FavoritesUpdater = (Result<[Bookmark], Error>) -> Void
struct WeakContainer<T: AnyObject> {
weak var content: T?
}
private(set) static var shared: AnonymousSession! // swiftlint:disable:this implicitly_unwrapped_optional
private static var conferencesToken: UpdateToken?
private var bookmarksToken: UpdateToken?
private var bookmarks: [Bookmark]?
var currentConference: ConferenceModel {
didSet {
setupConference()
}
}
var currentFavoritesUpdates: [WeakContainer<UpdateToken>] = []
var user: User?
static func initialize(conCode: String, completion: @escaping (AnonymousSession?) -> Void) {
Auth.auth().signInAnonymously { authResult, error in
if error != nil {
completion(nil)
return
}
self.conferencesToken = FSConferenceDataController.shared.requestConferenceByCode(forCode: conCode) { result in
switch result {
case .success(let con):
shared = AnonymousSession(conference: con)
shared.user = authResult?.user
shared.setupConference()
completion(shared)
case .failure:
completion(nil)
}
}
}
}
init(conference: ConferenceModel) {
currentConference = conference
}
func setupConference() {
self.currentFavoritesUpdates = []
self.bookmarksToken = warmFavoritesCache(forConference: currentConference) { result in
switch result {
case .success(let bookmarks):
self.bookmarks = bookmarks
case .failure:
NSLog("failure")
}
for weakContainer in self.currentFavoritesUpdates {
if let updateToken = weakContainer.content, let block = updateToken.collectionValue as? FavoritesUpdater {
block(result)
}
}
}
DateFormatterUtility.shared.update(identifier: currentConference.timeZone)
let fileManager = FileManager.default
let docDir = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let storageRef = FSConferenceDataController.shared.storage.reference()
for map in currentConference.maps {
let path = "\(currentConference.code)/\(map.file)"
let mRef = storageRef.child(path)
let mLocal = docDir.appendingPathComponent(path)
if fileManager.fileExists(atPath: mLocal.path) {
// TODO: Add logic to check md5 hash and re-update if it has changed
// NSLog("Map file (\(path)) already exists")
} else {
_ = mRef.write(toFile: mLocal) { _, error in
if let error = error {
NSLog("Error \(error) retrieving \(path)")
} else {
NSLog("Got map \(path)")
}
}
}
}
}
func warmFavoritesCache(forConference conference: ConferenceModel,
updateHandler: @escaping (Result<[Bookmark], Error>) -> Void) -> UpdateToken? {
guard let user = user else {
return nil
}
let query = document(forConference: conference).collection("users").document(user.uid).collection("bookmarks")
let bookmarks = Collection<Bookmark>(query: query)
bookmarks.listen { _ in
updateHandler(Result<[Bookmark], Error>.success(bookmarks.items))
}
return UpdateToken(bookmarks)
}
func requestFavorites(updateHandler: @escaping (Result<[Bookmark], Error>) -> Void) -> UpdateToken? {
if let bookmarks = self.bookmarks {
updateHandler(Result<[Bookmark], Error>.success(bookmarks))
}
let updateToken = UpdateToken(updateHandler)
currentFavoritesUpdates.append(WeakContainer(content: updateToken))
return updateToken
}
private func document(forConference conference: ConferenceModel) -> DocumentReference {
return Firestore.firestore().collection("conferences").document(conference.code)
}
}
| gpl-2.0 | 31a1a6e29da5650064ec3b70046d2a1e | 34.193798 | 123 | 0.596035 | 5.2124 | false | false | false | false |
PureSwift/Predicate | Sources/Compound.swift | 1 | 4292 | //
// Compound.swift
// Predicate
//
// Created by Alsey Coleman Miller on 4/2/17.
// Copyright © 2017 PureSwift. All rights reserved.
//
/// Predicate type used to represent logical “gate” operations (AND/OR/NOT) and comparison operations.
public indirect enum Compound: Equatable, Hashable {
case and([Predicate])
case or([Predicate])
case not(Predicate)
}
// MARK: - Accessors
public extension Compound {
var type: LogicalType {
switch self {
case .and: return .and
case .or: return .or
case .not: return .not
}
}
var subpredicates: [Predicate] {
switch self {
case let .and(subpredicates): return subpredicates
case let .or(subpredicates): return subpredicates
case let .not(subpredicate): return [subpredicate]
}
}
}
// MARK: - Supporting Types
public extension Compound {
/// Possible Compund Predicate types.
enum LogicalType: String, Codable {
/// A logical NOT predicate.
case not = "NOT"
/// A logical AND predicate.
case and = "AND"
/// A logical OR predicate.
case or = "OR"
}
}
// MARK: - CustomStringConvertible
extension Compound: CustomStringConvertible {
public var description: String {
guard subpredicates.isEmpty == false else {
return "(Empty \(type) predicate)"
}
var text = ""
for (index, predicate) in subpredicates.enumerated() {
let showType: Bool
if index == 0 {
showType = subpredicates.count == 1
} else {
showType = true
text += " "
}
if showType {
text += type.rawValue + " "
}
let includeBrackets: Bool
switch predicate {
case .compound:
includeBrackets = true
case .comparison,
.value:
includeBrackets = false
}
text += includeBrackets ? "(" + predicate.description + ")" : predicate.description
}
return text
}
}
// MARK: - Codable
extension Compound: Codable {
internal enum CodingKeys: String, CodingKey {
case type
case predicates
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(Compound.LogicalType.self, forKey: .type)
switch type {
case .and:
let predicates = try container.decode([Predicate].self, forKey: .predicates)
self = .and(predicates)
case .or:
let predicates = try container.decode([Predicate].self, forKey: .predicates)
self = .or(predicates)
case .not:
let predicate = try container.decode(Predicate.self, forKey: .predicates)
self = .not(predicate)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
switch self {
case let .and(predicates):
try container.encode(predicates, forKey: .predicates)
case let .or(predicates):
try container.encode(predicates, forKey: .predicates)
case let .not(predicate):
try container.encode(predicate, forKey: .predicates)
}
}
}
// MARK: - Predicate Operators
public func && (lhs: Predicate, rhs: Predicate) -> Predicate {
return .compound(.and([lhs, rhs]))
}
public func && (lhs: Predicate, rhs: [Predicate]) -> Predicate {
return .compound(.and([lhs] + rhs))
}
public func || (lhs: Predicate, rhs: Predicate) -> Predicate {
return .compound(.or([lhs, rhs]))
}
public func || (lhs: Predicate, rhs: [Predicate]) -> Predicate {
return .compound(.or([lhs] + rhs))
}
public prefix func ! (rhs: Predicate) -> Predicate {
return .compound(.not(rhs))
}
| mit | 5b70fdd6c6c6fd577282b7504f7a3adf | 24.634731 | 102 | 0.547769 | 4.683807 | false | false | false | false |
SwiftFS/Swift-FS-China | Sources/SwiftFSChina/router/Handlers.swift | 1 | 4478 | //
// Handlers.swift
// PerfectChina
//
// Created by mubin on 2017/7/25.
//
//
import Foundation
import PerfectHTTP
import PerfectLib
class Handlers {
static func topics_category_handler(current_category:Int,request:HTTPRequest,response:HTTPResponse) {
var context: [String : Any] = [:]
do{
let user_count = try UserServer.get_total_count()
context["user_count"] = user_count[0].count
let topic_count = try TopicServer.get_total_count()
context["topic_count"] = topic_count[0].count
let comment_count = try CommentServer.get_total_count()
context["comment_count"] = comment_count[0].count
let (diff,diff_days) = Utils.days_after_registry(req: request)
context["diff"] = diff
context["diff_days"] = diff_days
context["current_category"] = current_category
}catch{
}
response.render(template: "index",context: context)
}
static func settings(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
guard let user:[String:Any] = request.session?.data["user"] as? [String : Any] else{
response.render(template: "error", context: ["errMsg":"cannot find user, please login."])
return
}
guard let userId = user["userid"] else {
response.render(template: "error", context: ["errMsg":"cannot find user, please login."])
return
}
do{
let user = try UserServer.query_by_id(id: "\(userId)".int!)
let encoded = try? encoder.encode(user)
if encoded != nil {
if let json = encodeToString(data: encoded!){
if let decoded = try json.jsonDecode() as? [String:Any] {
response.render(template: "user/settings", context: ["user":decoded])
}
}
}
}catch{
response.render(template: "error", context: ["errMsg":"error to find user."])
}
}
}
static func index(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let current_category = 0
if let loginType:String = request.session?.data["loginType"] as? String{
if loginType == "github" {
}
}
Handlers.topics_category_handler(current_category: current_category,request: request,response:response)
}
}
static func share(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let current_category = 1
Handlers.topics_category_handler(current_category: current_category,request: request,response:response)
}
}
static func ask(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let current_category = 2
Handlers.topics_category_handler(current_category: current_category,request: request,response:response)
}
}
static func login(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
response.render(template: "login")
}
}
static func register(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let name = request.session?.data["name"] ?? ""
let email = request.session?.data["email"] ?? ""
let picture_url = request.session?.data["picture"] ?? ""
let login = request.session?.data["login"] ?? ""
let content:[String:Any] = ["name":name,"email":email,"picture_url":picture_url,"login":login]
response.render(template: "register",context: content)
}
}
static func about(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
response.render(template: "about")
}
}
}
| mit | f30bcc5363398cc1918bf1b7e4ad2143 | 32.17037 | 115 | 0.513176 | 4.893989 | false | false | false | false |
keyfun/DeviceStatusSample | DeviceStatusSample/BluetoothHelper.swift | 1 | 3282 | //
// BluetoothHelper.swift
// DeviceStatusSample
//
// Created by Hui Key on 6/2/2016.
// Copyright © 2016 KeyFun. All rights reserved.
//
import Foundation
import CoreBluetooth
import SwiftFlux
class BluetoothHelper: NSObject, CBPeripheralManagerDelegate {
enum BluetoothStatus: Int {
case PoweredOn = 0
case PoweredOff
case Unauthorized
case Unsupported
var description: String {
switch self {
case .PoweredOn: return "PoweredOn"
case .PoweredOff: return "PoweredOff"
case .Unauthorized: return "Unauthorized"
case .Unsupported: return "Unsupported"
}
}
}
typealias Status = BluetoothStatus
static let sharedInstance:BluetoothHelper = BluetoothHelper()
private var manager:CBPeripheralManager?
var state:CBPeripheralManagerState? // raw state
var status:BluetoothStatus? // general state
override init() {
super.init()
}
func startListen() {
if(manager == nil) {
manager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
}
self.manager?.delegate = self
}
func stopListen() {
self.manager?.delegate = nil
}
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
// print("[BluetoothHelper] \(__FUNCTION__)")
self.state = peripheral.state
switch(peripheral.state) {
case .PoweredOn:
print("[BluetoothHelper] PoweredOn Broadcasting...")
status = BluetoothStatus.PoweredOn
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: true, status: status!.rawValue)))
break
case .PoweredOff:
print("[BluetoothHelper] PoweredOff")
status = BluetoothStatus.PoweredOff
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: false, status: status!.rawValue)))
break
case .Unauthorized:
print("[BluetoothHelper] Unauthorized")
status = BluetoothStatus.Unauthorized
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: false, status: status!.rawValue)))
break
case .Unsupported:
print("[BluetoothHelper] Unsupported")
status = BluetoothStatus.Unsupported
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: false, status: status!.rawValue)))
break
case .Unknown:
print("[BluetoothHelper] Unknown")
status = BluetoothStatus.Unsupported
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: false, status: status!.rawValue)))
break
case .Resetting:
print("[BluetoothHelper] Resetting")
status = BluetoothStatus.PoweredOff
ActionCreator.invoke(DeviceStatusAction.UpdateBluetoothStatus(value: StatusPayload(value: false, status: status!.rawValue)))
break
}
}
}
| mit | 3223c3330aabd489d00fd1ee9d230865 | 33.536842 | 136 | 0.627248 | 5.42314 | false | false | false | false |
Imgur/Hermes | Hermes/HermesDefaultNotificationView.swift | 1 | 3356 | import UIKit
extension UIImageView {
func h_setImage(url url: NSURL) {
// Using NSURLSession API to fetch image
// TODO: maybe change NSURLConfiguration to add things like timeouts and cellular configuration
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration)
// NSURLRequest Object
let request = NSURLRequest(URL: url)
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if error == nil {
// Set whatever image attribute to the returned data
self.image = UIImage(data: data!)!
} else {
print(error)
}
})
// Start the data task
dataTask.resume()
}
}
class HermesDefaultNotificationView: HermesNotificationView {
override var notification: HermesNotification? {
didSet {
textLabel.attributedText = notification?.attributedText
imageView.backgroundColor = notification?.color
colorView.backgroundColor = notification?.color
imageView.image = notification?.image
if let imageURL = notification?.imageURL {
imageView.h_setImage(url: imageURL)
}
layoutSubviews()
}
}
var style: HermesStyle = .Dark {
didSet {
textLabel.textColor = style == .Light ? .darkGrayColor() : .whiteColor()
}
}
private var imageView = UIImageView()
private var textLabel = UILabel()
private var colorView = UIView()
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
imageView.contentMode = .Center
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 5
textLabel.textColor = .whiteColor()
textLabel.font = UIFont(name: "HelveticaNeue", size: 14)
textLabel.numberOfLines = 3
addSubview(imageView)
addSubview(textLabel)
addSubview(colorView)
}
convenience init(notification: HermesNotification) {
self.init(frame: CGRectZero)
self.notification = notification
}
override func layoutSubviews() {
let margin: CGFloat = 4
let colorHeight: CGFloat = 4
imageView.hidden = notification?.image == nil && notification?.imageURL == nil
imageView.frame = CGRectMake(margin * 2, 0, 34, 34)
imageView.center.y = CGRectGetMidY(bounds) - colorHeight
var leftRect = CGRect()
var rightRect = CGRect()
CGRectDivide(bounds, &leftRect, &rightRect, CGRectGetMaxX(imageView.frame), .MinXEdge)
let space: CGFloat = 20
let constrainedSize = CGRectInset(rightRect, (space + margin) * 0.5, 0).size
textLabel.frame.size = textLabel.sizeThatFits(constrainedSize)
textLabel.frame.origin.x = CGRectGetMaxX(imageView.frame) + space
textLabel.center.y = CGRectGetMidY(bounds) - colorHeight
colorView.frame = CGRectMake(margin, bounds.size.height - colorHeight, bounds.size.width - 2 * margin, colorHeight)
// This centers the text across the whole view, unless that would cause it to block the imageView
textLabel.center.x = CGRectGetMidX(bounds)
let leftBound = CGRectGetMaxX(imageView.frame) + space
if textLabel.frame.origin.x < leftBound {
textLabel.frame.origin.x = leftBound
}
}
}
| mit | 94b90404d0b0122d81a972b5149a5876 | 32.227723 | 119 | 0.690703 | 4.767045 | false | true | false | false |
Nirma/Attributed | Attributed/Attributes.swift | 1 | 9307 | //
// Attributes.swift
//
// Copyright (c) 2016-2019 Nicholas Maccharoli
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public struct Attributes {
public let dictionary: [NSAttributedString.Key: Any]
public init() {
dictionary = [:]
}
public init(_ attributesBlock: (Attributes) -> Attributes) {
self = attributesBlock(Attributes())
}
internal init(dictionary: [NSAttributedString.Key: Any]) {
self.dictionary = dictionary
}
public func font(_ font: UIFont) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.font: font])
}
public func kerning(_ kerning: Double) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.kern: NSNumber(floatLiteral: kerning)])
}
public func strikeThroughStyle(_ strikeThroughStyle: NSUnderlineStyle) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.strikethroughStyle: strikeThroughStyle.rawValue, NSAttributedString.Key.baselineOffset : NSNumber(floatLiteral: 1.5)])
}
public func underlineStyle(_ underlineStyle: NSUnderlineStyle) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.underlineStyle: underlineStyle.rawValue])
}
public func strokeColor(_ strokeColor: UIColor) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.strokeColor: strokeColor])
}
public func strokeWidth(_ strokewidth: Double) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.strokeWidth: NSNumber(floatLiteral: strokewidth)])
}
public func foreground(color: UIColor) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.foregroundColor: color])
}
public func background(color: UIColor) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.backgroundColor: color])
}
public func paragraphStyle(_ paragraphStyle: NSParagraphStyle) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func shadow(_ shadow: NSShadow) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.shadow: shadow])
}
public func obliqueness(_ value: CGFloat) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.obliqueness: value])
}
public func link(_ link: String) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.link: link])
}
public func baselineOffset(_ offset: NSNumber) -> Attributes {
return self + Attributes(dictionary: [NSAttributedString.Key.baselineOffset: offset])
}
}
// MARK: NSParagraphStyle related
extension Attributes {
public func lineSpacing(_ lineSpacing: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.lineSpacing = lineSpacing
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func paragraphSpacing(_ paragraphSpacing: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.paragraphSpacing = paragraphSpacing
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func alignment(_ alignment: NSTextAlignment) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.alignment = alignment
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func firstLineHeadIndent(_ firstLineHeadIndent: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.firstLineHeadIndent = firstLineHeadIndent
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func headIndent(_ headIndent: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.headIndent = headIndent
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func tailIndent(_ tailIndent: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.tailIndent = tailIndent
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func lineBreakMode(_ lineBreakMode: NSLineBreakMode) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = lineBreakMode
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func minimumLineHeight(_ minimumLineHeight: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.minimumLineHeight = minimumLineHeight
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func maximumLineHeight(_ maximumLineHeight: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.maximumLineHeight = maximumLineHeight
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func uniformLineHeight(_ uniformLineHeight: CGFloat) -> Attributes {
return maximumLineHeight(uniformLineHeight).minimumLineHeight(uniformLineHeight)
}
public func baseWritingDirection(_ baseWritingDirection: NSWritingDirection) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.baseWritingDirection = baseWritingDirection
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func lineHeightMultiple(_ lineHeightMultiple: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.lineHeightMultiple = lineHeightMultiple
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func paragraphSpacingBefore(_ paragraphSpacingBefore: CGFloat) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.paragraphSpacingBefore = paragraphSpacingBefore
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
public func hyphenationFactor(_ hyphenationFactor: Float) -> Attributes {
let paragraphStyle = (dictionary[NSAttributedString.Key.paragraphStyle] ?? NSMutableParagraphStyle.default.mutableCopy()) as! NSMutableParagraphStyle
paragraphStyle.hyphenationFactor = hyphenationFactor
return self + Attributes(dictionary: [NSAttributedString.Key.paragraphStyle: paragraphStyle])
}
}
| mit | 0995fcb398d1bd4d71f3d3483f4992c9 | 50.705556 | 187 | 0.751048 | 5.737978 | false | false | false | false |
Fenrikur/ef-app_ios | EurofurenceTests/Presenter Tests/Map Detail/Test Doubles/FakeMapDetailInteractor.swift | 1 | 1598 | @testable import Eurofurence
import EurofurenceModel
import EurofurenceModelTestDoubles
import Foundation
class FakeMapDetailInteractor: MapDetailInteractor {
private let expectedMapIdentifier: MapIdentifier
init(expectedMapIdentifier: MapIdentifier = .random) {
self.expectedMapIdentifier = expectedMapIdentifier
}
let viewModel = FakeMapDetailViewModel()
func makeViewModelForMap(identifier: MapIdentifier, completionHandler: @escaping (MapDetailViewModel) -> Void) {
guard identifier == expectedMapIdentifier else { return }
completionHandler(viewModel)
}
}
class FakeMapDetailViewModel: MapDetailViewModel {
var mapImagePNGData: Data = .random
var mapName: String = .random
private(set) var positionToldToShowMapContentsFor: (x: Float, y: Float)?
fileprivate var contentsVisitor: MapContentVisitor?
func showContentsAtPosition(x: Float, y: Float, describingTo visitor: MapContentVisitor) {
positionToldToShowMapContentsFor = (x: x, y: y)
contentsVisitor = visitor
}
}
extension FakeMapDetailViewModel {
func resolvePositionalContent(with position: MapCoordinate) {
contentsVisitor?.visit(position)
}
func resolvePositionalContent(with content: MapInformationContextualContent) {
contentsVisitor?.visit(content)
}
func resolvePositionalContent(with dealer: DealerIdentifier) {
contentsVisitor?.visit(dealer)
}
func resolvePositionalContent(with mapContents: MapContentOptionsViewModel) {
contentsVisitor?.visit(mapContents)
}
}
| mit | 7490e024b3e736a041a2df163aaf5e21 | 28.592593 | 116 | 0.74781 | 4.88685 | false | false | false | false |
ivanbruel/SwipeIt | SwipeIt/Protocols/ViewControllers/AlerteableViewController.swift | 1 | 2630 | //
// AlerteableViewController.swift
// Reddit
//
// Created by Ivan Bruel on 26/04/16.
// Copyright © 2016 Faber Ventures. All rights reserved.
//
import UIKit
import RxSwift
protocol AlerteableViewController {
func presentAlert(title: String?,
message: String?,
textField: AlertTextField?,
buttonTitle: String?,
cancelButtonTitle: String?,
alertClicked: ((AlertButtonClicked) -> Void)?)
}
extension AlerteableViewController where Self: UIViewController {
func presentAlert(title: String? = nil,
message: String? = nil,
textField: AlertTextField? = nil,
buttonTitle: String? = nil,
cancelButtonTitle: String? = nil,
alertClicked: ((AlertButtonClicked) -> Void)? = nil) {
let alertController = UIAlertController(title: title, message: message,
preferredStyle: .Alert)
if let cancelButtonTitle = cancelButtonTitle {
let dismissAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { _ in
alertClicked?(.Cancel)
}
alertController.addAction(dismissAction)
}
if let textFieldConfig = textField {
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = textFieldConfig.placeholder
textField.text = textFieldConfig.text
if let buttonTitle = buttonTitle {
let buttonAction = UIAlertAction(title: buttonTitle, style: .Default) { _ in
alertClicked?(.ButtonWithText(textField.text))
}
alertController.addAction(buttonAction)
}
}
} else {
if let buttonTitle = buttonTitle {
let buttonAction = UIAlertAction(title: buttonTitle, style: .Default) { _ in
alertClicked?(.Button)
}
alertController.addAction(buttonAction)
}
}
self.presentViewController(alertController, animated: true, completion: nil)
}
}
enum AlertButtonClicked {
case Button
case ButtonWithText(String?)
case Cancel
}
func == (lhs: AlertButtonClicked, rhs: AlertButtonClicked) -> Bool {
switch (lhs, rhs) {
case (.Button, .Button):
return true
case (.ButtonWithText, .ButtonWithText):
return true
case (.Cancel, .Cancel):
return true
default:
return false
}
}
struct AlertTextField {
let text: String?
let placeholder: String?
init(text: String?, placeholder: String?) {
self.text = text
self.placeholder = placeholder
}
}
| mit | f67e59823bb320249c14534f48f36f76 | 27.268817 | 88 | 0.625713 | 5.026769 | false | false | false | false |
hilen/TSWeChat | TSWeChat/General/TSProgressHUD.swift | 1 | 2509 | //
// TSProgressHUD.swift
// TSWeChat
//
// Created by Hilen on 11/11/15.
// Copyright © 2015 Hilen. All rights reserved.
//
/// 对 HUD 层进行一次封装
import Foundation
import SVProgressHUD
class TSProgressHUD: NSObject {
class func ts_initHUD() {
SVProgressHUD.setBackgroundColor(UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 ))
SVProgressHUD.setForegroundColor(UIColor.white)
SVProgressHUD.setFont(UIFont.systemFont(ofSize: 14))
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.none)
}
//成功
class func ts_showSuccessWithStatus(_ string: String) {
self.TSProgressHUDShow(.success, status: string)
}
//失败 ,NSError
class func ts_showErrorWithObject(_ error: NSError) {
self.TSProgressHUDShow(.errorObject, status: nil, error: error)
}
//失败,String
class func ts_showErrorWithStatus(_ string: String) {
self.TSProgressHUDShow(.errorString, status: string)
}
//转菊花
class func ts_showWithStatus(_ string: String) {
self.TSProgressHUDShow(.loading, status: string)
}
//警告
class func ts_showWarningWithStatus(_ string: String) {
self.TSProgressHUDShow(.info, status: string)
}
//dismiss消失
class func ts_dismiss() {
SVProgressHUD.dismiss()
}
//私有方法
fileprivate class func TSProgressHUDShow(_ type: HUDType, status: String? = nil, error: NSError? = nil) {
switch type {
case .success:
SVProgressHUD.showSuccess(withStatus: status)
break
case .errorObject:
guard let newError = error else {
SVProgressHUD.showError(withStatus: "Error:出错拉")
return
}
if newError.localizedFailureReason == nil {
SVProgressHUD.showError(withStatus: "Error:出错拉")
} else {
SVProgressHUD.showError(withStatus: error!.localizedFailureReason)
}
break
case .errorString:
SVProgressHUD.showError(withStatus: status)
break
case .info:
SVProgressHUD.showInfo(withStatus: status)
break
case .loading:
SVProgressHUD.show(withStatus: status)
break
}
}
fileprivate enum HUDType: Int {
case success, errorObject, errorString, info, loading
}
}
| mit | 24994fd2a65e2894b78d5a412b1513c1 | 27.729412 | 109 | 0.603604 | 4.669216 | false | false | false | false |
zvonicek/SpriteKit-Pong | TDT4240-pong/SKTUtils/CGFloat+Extensions.swift | 15 | 3136 | /*
* Copyright (c) 2013-2014 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import CoreGraphics
/** The value of π as a CGFloat */
let π = CGFloat(M_PI)
public extension CGFloat {
/**
* Converts an angle in degrees to radians.
*/
public func degreesToRadians() -> CGFloat {
return π * self / 180.0
}
/**
* Converts an angle in radians to degrees.
*/
public func radiansToDegrees() -> CGFloat {
return self * 180.0 / π
}
/**
* Ensures that the float value stays between the given values, inclusive.
*/
public func clamped(v1: CGFloat, _ v2: CGFloat) -> CGFloat {
let min = v1 < v2 ? v1 : v2
let max = v1 > v2 ? v1 : v2
return self < min ? min : (self > max ? max : self)
}
/**
* Ensures that the float value stays between the given values, inclusive.
*/
public mutating func clamp(v1: CGFloat, _ v2: CGFloat) -> CGFloat {
self = clamped(v1, v2)
return self
}
/**
* Returns 1.0 if a floating point value is positive; -1.0 if it is negative.
*/
public func sign() -> CGFloat {
return (self >= 0.0) ? 1.0 : -1.0
}
/**
* Returns a random floating point number between 0.0 and 1.0, inclusive.
*/
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
/**
* Returns a random floating point number in the range min...max, inclusive.
*/
public static func random(#min: CGFloat, max: CGFloat) -> CGFloat {
assert(min < max)
return CGFloat.random() * (max - min) + min
}
/**
* Randomly returns either 1.0 or -1.0.
*/
public static func randomSign() -> CGFloat {
return (arc4random_uniform(2) == 0) ? 1.0 : -1.0
}
}
/**
* Returns the shortest angle between two angles. The result is always between
* -π and π.
*/
public func shortestAngleBetween(angle1: CGFloat, angle2: CGFloat) -> CGFloat {
let twoπ = π * 2.0
var angle = (angle2 - angle1) % twoπ
if (angle >= π) {
angle = angle - twoπ
}
if (angle <= -π) {
angle = angle + twoπ
}
return angle
}
| mit | 83992245b3dbec68797405609d2ba8c6 | 29.028846 | 80 | 0.658021 | 3.841328 | false | false | false | false |
ahoppen/swift | test/SILGen/synthesized_conformance_struct.swift | 9 | 6257 | // RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 -enable-library-evolution | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s
struct Struct<T> {
var x: T
}
// CHECK-LABEL: struct Struct<T> {
// CHECK: @_hasStorage var x: T { get set }
// CHECK: enum CodingKeys : CodingKey {
// CHECK: case x
// CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Struct<T>.CodingKeys, _ b: Struct<T>.CodingKeys) -> Bool
// CHECK-RESILIENT: static func == (a: Struct<T>.CodingKeys, b: Struct<T>.CodingKeys) -> Bool
// CHECK: func hash(into hasher: inout Hasher)
// CHECK: init?(stringValue: String)
// CHECK: init?(intValue: Int)
// CHECK: var hashValue: Int { get }
// CHECK: var intValue: Int? { get }
// CHECK: var stringValue: String { get }
// CHECK: }
// CHECK: init(x: T)
// CHECK: }
// CHECK-LABEL: extension Struct : Equatable where T : Equatable {
// CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_struct_equals(_ a: Struct<T>, _ b: Struct<T>) -> Bool
// CHECK-RESILIENT: static func == (a: Struct<T>, b: Struct<T>) -> Bool
// CHECK: }
// CHECK-LABEL: extension Struct : Hashable where T : Hashable {
// CHECK: func hash(into hasher: inout Hasher)
// CHECK: var hashValue: Int { get }
// CHECK: }
// CHECK-LABEL: extension Struct : Decodable & Encodable where T : Decodable, T : Encodable {
// CHECK: func encode(to encoder: Encoder) throws
// CHECK: init(from decoder: Decoder) throws
// CHECK: }
extension Struct: Equatable where T: Equatable {}
// CHECK-FRAGILE-LABEL: // static Struct<A>.__derived_struct_equals(_:_:)
// CHECK-FRAGILE-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Struct<T>, @in_guaranteed Struct<T>, @thin Struct<T>.Type) -> Bool {
// CHECK-RESILIENT-LABEL: // static Struct<A>.== infix(_:_:)
// CHECK-RESILIENT-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Struct<T>, @in_guaranteed Struct<T>, @thin Struct<T>.Type) -> Bool {
extension Struct: Hashable where T: Hashable {}
// CHECK-LABEL: // Struct<A>.hash(into:)
// CHECK-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Struct<T>) -> () {
// CHECK-LABEL: // Struct<A>.hashValue.getter
// CHECK-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Struct<T>) -> Int {
extension Struct: Codable where T: Codable {}
// CHECK-LABEL: // Struct<A>.encode(to:)
// CHECK-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASeRzSERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Decodable, T : Encodable> (@in_guaranteed Encoder, @in_guaranteed Struct<T>) -> @error Error {
// CHECK-LABEL: // Struct<A>.init(from:)
// CHECK-NEXT: sil hidden [ossa] @$s30synthesized_conformance_struct6StructVAASeRzSERzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable, T : Encodable> (@in Decoder, @thin Struct<T>.Type) -> (@out Struct<T>, @error Error)
// Witness tables
// CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct {
// CHECK-NEXT: method #Equatable."==": <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$s30synthesized_conformance_struct6StructVyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Struct<A>
// CHECK-NEXT: conditional_conformance (T: Equatable): dependent
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Struct<T>: Hashable module synthesized_conformance_struct {
// CHECK-DAG: base_protocol Equatable: <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct
// CHECK-DAG: method #Hashable.hashValue!getter: <Self where Self : Hashable> (Self) -> () -> Int : @$s30synthesized_conformance_struct6StructVyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Struct<A>
// CHECK-DAG: method #Hashable.hash: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$s30synthesized_conformance_struct6StructVyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Struct<A>
// CHECK-DAG: method #Hashable._rawHashValue: <Self where Self : Hashable> (Self) -> (Int) -> Int : @$s30synthesized_conformance_struct6StructVyxGSHAASHRzlSH13_rawHashValue4seedS2i_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Struct<A>
// CHECK-DAG: conditional_conformance (T: Hashable): dependent
// CHECK: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Decodable module synthesized_conformance_struct {
// CHECK-NEXT: method #Decodable.init!allocator: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$s30synthesized_conformance_struct6StructVyxGSeAASeRzSERzlSe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Struct<A>
// CHECK-NEXT: conditional_conformance (T: Decodable): dependent
// CHECK-NEXT: conditional_conformance (T: Encodable): dependent
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Encodable module synthesized_conformance_struct {
// CHECK-NEXT: method #Encodable.encode: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$s30synthesized_conformance_struct6StructVyxGSEAASeRzSERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Struct<A>
// CHECK-NEXT: conditional_conformance (T: Decodable): dependent
// CHECK-NEXT: conditional_conformance (T: Encodable): dependent
// CHECK-NEXT: }
| apache-2.0 | 2b6ff0458db51ccfc818fac20e5e3132 | 75.304878 | 284 | 0.718076 | 3.476111 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/Policy.swift | 3 | 46338 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The return type of functions that don't explicitly specify a return type;
/// an empty tuple (i.e., `()`).
///
/// When declaring a function or method, you don't need to specify a return
/// type if no value will be returned. However, the type of a function,
/// method, or closure always includes a return type, which is `Void` if
/// otherwise unspecified.
///
/// Use `Void` or an empty tuple as the return type when declaring a
/// closure, function, or method that doesn't return a value.
///
/// // No return type declared:
/// func logMessage(s: String) {
/// print("Message: \(s)")
/// }
///
/// let logger: String -> Void = logMessage
/// logger("This is a void function")
/// // Prints "Message: This is a void function"
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
///
/// When you create a constant or variable using one of the Boolean literals
/// `true` or `false`, the resulting type is determined by the
/// `BooleanLiteralType` alias. For example:
///
/// let isBool = true
/// print("isBool is a '\(isBool.dynamicType)'")
/// // Prints "isBool is a 'Bool'"
///
/// The type aliased by `BooleanLiteralType` must conform to the
/// `BooleanLiteralConvertible` protocol.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
// Integer literals are limited to 2048 bits.
// The intent is to have arbitrary-precision literals, but implementing that
// requires more work.
//
// Rationale: 1024 bits are enough to represent the absolute value of min/max
// IEEE Binary64, and we need 1 bit to represent the sign. Instead of using
// 1025, we use the next round number -- 2048.
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
#if !os(Windows) && (arch(i386) || arch(x86_64))
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
/// The protocol to which all types implicitly conform.
///
/// The `Any` protocol can be used as the concrete type for an instance of any
/// type in Swift: a class, struct, or enumeration; a metatype, such as
/// `Int.self`; a tuple with any types of components; or a closure or function
/// type.
///
/// Casting Any Instances to a Known Type
/// =====================================
///
/// When you use `Any` as a concrete type, you must cast your instance back to
/// a known type before you can access its properties or methods. Instances
/// with a concrete type of `Any` maintain their original dynamic type and can
/// be cast to that type using one of the type-cast operators (`as`, `as?`, or
/// `as!`).
///
/// For example, use `as?` to conditionally downcast the first object
/// in a heterogeneous array to a `String`.
///
/// let mixed: [Any] = ["one", "two", 3, true, {(x: Int) -> Int in x * 2 }]
///
/// let first = = numberObjects.firstObject
/// if let first = mixed.first as? String {
/// print("The first item, '\(first)', is a String")
/// }
/// // Prints("The first item, 'one', is a String")
///
/// If you have prior knowledge that an `Any` instance is an instance of
/// a particular type, you can use the `as!` operator to unconditionally
/// downcast. Performing an invalid cast results in a runtime error.
///
/// let second = mixed[1] as! String
/// print("'\(second)' is also a String")
/// // Prints "'two' is also a String"
///
/// In a `switch` statement, a value is cast to a type only when pattern
/// matching with that type succeeds. For that reason, you use the `as`
/// operator instead of the conditional `as?` or unconditional `as!`
/// operators.
///
/// for item in mixed {
/// switch item {
/// case let s as String:
/// print("String: \(s)")
/// case let i as Int:
/// print("Integer: \(i)")
/// case let b as Bool:
/// print("Bool: \(b)")
/// case let f as Int -> Int:
/// print("Function: 2 * 5 = \(f(5))")
/// default:
/// print("Unrecognized type")
/// }
/// }
/// // Prints "String: one"
/// // Prints "String: two"
/// // Prints "Integer: 3"
/// // Prints "Bool: true"
/// // Prints "Function: 2 * 5 = 10"
///
/// - SeeAlso: `AnyObject`, `AnyClass`
public typealias Any = protocol<>
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// You use `AnyObject` when you need the flexibility of an untyped object or
/// when you use bridged Objective-C methods and properties that return an
/// untyped result. `AnyObject` can be used as the concrete type for an
/// instance of any class, class type, or class-only protocol. For example:
///
/// class FloatRef {
/// let value: Float
/// init(_ value: Float) {
/// self.value = value
/// }
/// }
///
/// let x = FloatRef(2.3)
/// let y: AnyObject = x
/// let z: AnyObject = FloatRef.self
///
/// `AnyObject` can also be used as the concrete type for an instance of a type
/// that bridges to an Objective-C class. Many value types in Swift bridge to
/// Objective-C counterparts, like `String` and `Int`.
///
/// let s: AnyObject = "This is a bridged string."
/// print(s is NSString)
/// // Prints "true"
///
/// let v: AnyObject = 100
/// print(v.dynamicType)
/// // Prints "__NSCFNumber"
///
/// The flexible behavior of the `AnyObject` protocol is similar to
/// Objective-C's `id` type. For this reason, imported Objective-C types
/// frequently use `AnyObject` as the type for properties, method parameters,
/// and return values.
///
/// Casting AnyObject Instances to a Known Type
/// ===========================================
///
/// Objects with a concrete type of `AnyObject` maintain a specific dynamic
/// type and can be cast to that type using one of the type-cast operators
/// (`as`, `as?`, or `as!`).
///
/// In the code samples that follow, the elements of the `NSArray` instance
/// `numberObjects` have `AnyObject` as their type. The first example uses the
/// conditional downcast operator (`as?`) to conditionally cast the first
/// object in the `numberObjects` array to an instance of Swift's `String`
/// type.
///
/// let numberObjects: NSArray = ["one", "two", 3, 4]
///
/// let first: AnyObject = numberObjects[0]
/// if let first = first as? String {
/// print("The first object, '\(first)', is a String")
/// }
/// // Prints("The first object, 'one', is a String")
///
/// If you have prior knowledge that an `AnyObject` instance has a particular
/// type, you can use the unconditional downcast operator (`as!`). Performing
/// an invalid cast triggers a runtime error.
///
/// let second = numberObjects.object(at: 1) as! String
/// print("'\(second)' is also a String")
/// // Prints "'two' is also a String"
///
/// let badCase = numberObjects.object(at: 2) as! NSDate
/// // Runtime error
///
/// Casting is always safe in the context of a `switch` statement.
///
/// for object in numberObjects {
/// switch object {
/// case let x as String:
/// print("'\(x)' is a String")
/// default:
/// print("'\(object)' is not a String")
/// }
/// }
/// // Prints "'one' is a String"
/// // Prints "'two' is a String"
/// // Prints "'3' is not a String"
/// // Prints "'4' is not a String"
///
/// You can call a method that takes an `AnyObject` parameter with an instance
/// of any class, `@objc` protocol, or type that bridges to Objective-C. In
/// the following example, the `toFind` constant is of type `Int`, which
/// bridges to `NSNumber` when passed to an `NSArray` method that expects an
/// `AnyObject` parameter:
///
/// let toFind = 3
/// let i = numberObjects.index(of: toFind)
/// if i != NSNotFound {
/// print("Found '\(numberObjects[i])' at index \(i)")
/// } else {
/// print("Couldn't find \(toFind)")
/// }
/// // Prints "Found '3' at index 2"
///
/// Accessing Objective-C Methods and Properties
/// ============================================
///
/// When you use `AnyObject` as a concrete type, you have at your disposal
/// every `@objc` method and property---that is, methods and properties
/// imported from Objective-C or marked with the `@objc` attribute. Because
/// Swift can't guarantee at compile time that these methods and properties
/// are actually available on an `AnyObject` instance's underlying type, these
/// `@objc` symbols are available as implicitly unwrapped optional methods and
/// properties, respectively.
///
/// This example defines an `IntegerRef` type with an `@objc` method named
/// `getIntegerValue`.
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// @objc func getIntegerValue() -> Int {
/// return value
/// }
/// }
///
/// func getObject() -> AnyObject {
/// return IntegerRef(100)
/// }
///
/// let x: AnyObject = getObject()
///
/// In the example, `x` has a static type of `AnyObject` and a dynamic type of
/// `IntegerRef`. You can use optional chaining to call the `@objc` method
/// `getIntegerValue()` on `x` safely. If you're sure of the dynamic type of
/// `x`, you can call `getIntegerValue()` directly.
///
/// let possibleValue = x.getIntegerValue?()
/// print(possibleValue)
/// // Prints "Optional(100)"
///
/// let certainValue = x.getIntegerValue()
/// print(certainValue)
/// // Prints "100"
///
/// If the dynamic type of `x` doesn't implement a `getIntegerValue()` method,
/// the system returns a runtime error when you initialize `certainValue`.
///
/// Alternatively, if you need to test whether `x.getValue()` exists, use
/// optional binding before calling the method.
///
/// if let f = x.getIntegerValue {
/// print("The value of 'x' is \(f())")
/// } else {
/// print("'x' does not have a 'getIntegerValue()' method")
/// }
/// // Prints "The value of 'x' is 100"
///
/// - SeeAlso: `AnyClass`, `Any`
@objc
public protocol AnyObject : class {}
#else
/// The protocol to which all classes implicitly conform.
///
/// - SeeAlso: `AnyClass`
public protocol AnyObject : class {}
#endif
// Implementation note: the `AnyObject` protocol *must* not have any method or
// property requirements.
// FIXME: AnyObject should have an alternate version for non-objc without
// the @objc attribute, but AnyObject needs to be not be an address-only
// type to be able to be the target of castToNativeObject and an empty
// non-objc protocol appears not to be. There needs to be another way to make
// this the right kind of object.
/// The protocol to which all class types implicitly conform.
///
/// You can use the `AnyClass` protocol as the concrete type for an instance of
/// any class. When you do, all known `@objc` class methods and properties are
/// available as implicitly unwrapped optional methods and properties,
/// respectively. For example:
///
/// class IntegerRef {
/// @objc class func getDefaultValue() -> Int {
/// return 42
/// }
/// }
///
/// func getDefaultValue(_ c: AnyClass) -> Int? {
/// return c.getDefaultValue?()
/// }
///
/// The `getDefaultValue(_:)` function uses optional chaining to safely call
/// the implicitly unwrapped class method on `c`. Calling the function with
/// different class types shows how the `getDefaultValue()` class method is
/// only conditionally available.
///
/// print(getDefaultValue(IntegerRef.self))
/// // Prints "Optional(42)"
///
/// print(getDefaultValue(NSString.self))
/// // Prints "nil"
///
/// - SeeAlso: `AnyObject`, `Any`
public typealias AnyClass = AnyObject.Type
/// Returns `true` iff `lhs` and `rhs` are references to the same object
/// instance (in other words, are identical pointers).
///
/// - SeeAlso: `Equatable`, `==`
public func === (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return Bool(Builtin.cmp_eq_RawPointer(
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(l)),
Builtin.bridgeToRawPointer(Builtin.castToNativeObject(r))
))
case (nil, nil):
return true
default:
return false
}
}
public func !== (lhs: AnyObject?, rhs: AnyObject?) -> Bool {
return !(lhs === rhs)
}
//
// Equatable
//
/// A type that can be compared for value equality.
///
/// Types that conform to the `Equatable` protocol can be compared for equality
/// using the is-equal-to operator (`==`) or inequality using the
/// is-not-equal-to operator (`!=`). Most basic types in the Swift standard
/// library conform to `Equatable`.
///
/// Some sequence and collection operations can be used more simply when the
/// elements conform to `Equatable`. For example, to check whether an array
/// contains a particular value, you can pass the value itself to the
/// `contains(_:)` method when the array's element conforms to `Equatable`
/// instead of providing a closure that determines equivalence. The following
/// example shows how the `contains(_:)` method can be used with an array of
/// strings.
///
/// let students = ["Nora", "Fern", "Ryan", "Rainer"]
///
/// let nameToCheck = "Ryan"
/// if students.contains(nameToCheck) {
/// print("\(nameToCheck) is signed up!")
/// } else {
/// print("No record of \(nameToCheck).")
/// }
/// // Prints "Ryan is signed up!"
///
/// Conforming to the Equatable Protocol
/// ====================================
///
/// Adding `Equatable` conformance to your custom types means that you can use
/// more convenient APIs when searching for particular instances in a
/// collection. `Equatable` is also the base protocol for the `Hashable` and
/// `Comparable` protocols, which allow more uses of your custom type, such as
/// constructing sets or sorting the elements of a collection.
///
/// To adopt the `Equatable` protocol, implement the "is equal to" operator
/// (`==`). The standard library provides an implementation for the "is not
/// equal to" operator (`!=`) for any `Equatable` type, which calls the custom
/// `==` function and negates its result.
///
/// As an example, consider a `StreetAddress` structure that holds the parts of
/// a street address: a house or building number, the street name, and an
/// optional unit number. Here's the initial declaration of the
/// `StreetAddress` type:
///
/// struct StreetAddress {
/// let number: String
/// let street: String
/// let unit: String?
///
/// init(_ number: String, _ street: String, unit: String? = nil) {
/// self.number = number
/// self.street = street
/// self.unit = unit
/// }
/// }
///
/// Now suppose you have an array of addresses that you need to check for a
/// particular address. To use the `contains(_:)` method without including a
/// closure in each call, extend the `StreetAddress` type to conform to
/// `Equatable`.
///
/// extension StreetAddress: Equatable { }
/// func ==(lhs: StreetAddress, rhs: StreetAddress) -> Bool {
/// return
/// lhs.number == rhs.number &&
/// lhs.street == rhs.street &&
/// lhs.unit == rhs.unit
/// }
///
/// The `StreetAddress` type now conforms to `Equatable`. You can use `==` to
/// check for equality between any two instances or call the
/// `Equatable`-constrained `contains(_:)` method.
///
/// let addresses = [StreetAddress("1490", "Grove Street"),
/// StreetAddress("2119", "Maple Avenue"),
/// StreetAddress("1400", "16th Street")]
/// let home = StreetAddress("1400", "16th Street")
///
/// print(addresses[0] == home)
/// // Prints "false"
/// print(addresses.contains(home))
/// // Prints "true"
///
/// Equality implies substitutability---any two instances that compare equally
/// can be used interchangeably in any code that depends on their values. To
/// maintain substitutability, the `==` operator should take into account all
/// visible aspects of an `Equatable` type. Exposing nonvalue aspects of
/// `Equatable` types other than class identity is discouraged, and any that
/// *are* exposed should be explicitly pointed out in documentation.
///
/// Since equality between instances of `Equatable` types is an equivalence
/// relation, any of your custom types that conform to `Equatable` must
/// satisfy three conditions, for any values `a`, `b`, and `c`:
///
/// - `a == a` is always `true` (Reflexivity)
/// - `a == b` implies `b == a` (Symmetry)
/// - `a == b` and `b == c` implies `a == c` (Transitivity)
///
/// Moreover, inequality is the inverse of equality, so any custom
/// implementation of the `!=` operator must guarantee that `a != b` implies
/// `!(a == b)`. The default implementation of the `!=` operator function
/// satisfies this requirement.
///
/// Equality is Separate From Identity
/// ----------------------------------
///
/// The identity of a class instance is not part of an instance's value.
/// Consider a class called `IntegerRef` that wraps an integer value. Here's
/// the definition for `IntegerRef` and the `==` function that makes it
/// conform to `Equatable`:
///
/// class IntegerRef: Equatable {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
/// }
///
/// func ==(lhs: IntegerRef, rhs: IntegerRef) -> Bool {
/// return lhs.value == rhs.value
/// }
///
/// The implementation of the `==` function returns the same value whether
/// its two arguments are the same instance or are two different instances
/// with the same integer stored in their `value` properties. For example:
///
/// let a = IntegerRef(100)
/// let b = IntegerRef(100)
///
/// print(a == a, a == b, separator: ", ")
/// // Prints "true, true"
///
/// Class instance identity, on the other hand, is compared using the
/// triple-equals "is identical to" operator (`===`). For example:
///
/// let c = a
/// print(a === c, b === c, separator: ", ")
/// // Prints "true, false"
public protocol Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
func == (lhs: Self, rhs: Self) -> Bool
}
/// Returns a Boolean value indicating whether two values are not equal.
///
/// Inequality is the inverse of equality. For any values `a` and `b`, `a != b`
/// implies that `a == b` is `false`.
///
/// This is the default implementation of the is-not-equal-to operator (`!=`)
/// for any type that conforms to `Equatable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public func != <T : Equatable>(lhs: T, rhs: T) -> Bool {
return !(lhs == rhs)
}
//
// Comparable
//
/// Returns a Boolean value indicating whether the value of the first argument
/// is greater than that of the second argument.
///
/// This is the default implementation of the greater-than operator (`>`) for
/// any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public func > <T : Comparable>(lhs: T, rhs: T) -> Bool {
return rhs < lhs
}
/// Returns a Boolean value indicating whether the value of the first argument
/// is less than or equal to that of the second argument.
///
/// This is the default implementation of the less-than-or-equal-to
/// operator (`<=`) for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public func <= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(rhs < lhs)
}
/// Returns a Boolean value indicating whether the value of the first argument
/// is greater than or equal to that of the second argument.
///
/// This is the default implementation of the greater-than-or-equal-to operator
/// (`>=`) for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Returns: `true` if `lhs` is greater than or equal to `rhs`; otherwise,
/// `false`.
public func >= <T : Comparable>(lhs: T, rhs: T) -> Bool {
return !(lhs < rhs)
}
/// A type that can be compared using the relational operators `<`, `<=`, `>=`,
/// and `>`.
///
/// The `Comparable` protocol is used for types that have an inherent order,
/// such as numbers and strings. Many types in the standard library already
/// conform to the `Comparable` protocol. Add `Comparable` conformance to your
/// own custom types when you want to be able to compare instances using
/// relational operators or use standard library methods that are designed for
/// `Comparable` types.
///
/// The most familiar use of relational operators is to compare numbers, as in
/// the following example:
///
/// let currentTemp = 73
///
/// if currentTemp >= 90 {
/// print("It's a scorcher!")
/// } else if currentTemp < 65 {
/// print("Might need a sweater today.")
/// } else {
/// print("Seems like picnic weather!")
/// }
/// // Prints "Seems like picnic weather!"
///
/// You can use special versions of some sequence and collection operations
/// when working with a `Comparable` type. For example, if your array's
/// elements conform to `Comparable`, you can call the `sort()` method without
/// using arguments to sort the elements of your array in ascending order.
///
/// var measurements = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2]
/// measurements.sort()
/// print(measurements)
/// // Prints "[1.1, 1.2, 1.2, 1.3, 1.5, 1.5, 2.9]"
///
/// Conforming to the Comparable Protocol
/// =====================================
///
/// Types with Comparable conformance implement the less-than operator (`<`)
/// and the is-equal-to operator (`==`). These two operations impose a strict
/// total order on the values of a type, in which exactly one of the following
/// must be true for any two values `a` and `b`:
///
/// - `a == b`
/// - `a < b`
/// - `b < a`
///
/// In addition, the following conditions must hold:
///
/// - `a < a` is always `false` (Irreflexivity)
/// - `a < b` implies `!(b < a)` (Asymmetry)
/// - `a < b` and `b < c` implies `a < c` (Transitivity)
///
/// To add `Comparable` conformance to your custom types, define the `<` and
/// `==` operators. The `==` operator is a requirement of the `Equatable`
/// protocol, which `Comparable` extends---see that protocol's documentation
/// for more information about equality in Swift. Because default
/// implementations of the remainder of the relational operators are provided
/// by the standard library, you'll be able to use `!=`, `>`, `<=`, and `>=`
/// with instances of your type without any further code.
///
/// As an example, here's an implementation of a `Date` structure that stores
/// the year, month, and day of a date:
///
/// struct Date {
/// let year: Int
/// let month: Int
/// let day: Int
/// }
///
/// To add `Comparable` conformance to `Date`, first declare conformance to
/// `Comparable` and implement the `<` operator function.
///
/// extension Date: Comparable { }
///
/// func <(lhs: Date, rhs: Date) -> Bool {
/// if lhs.year != rhs.year {
/// return lhs.year < rhs.year
/// } else if lhs.month != rhs.month {
/// return lhs.month < rhs.month
/// } else {
/// return lhs.day < rhs.day
/// }
/// }
///
/// This function uses the least specific nonmatching property of the date to
/// determine the result of the comparison. For example, if the two `year`
/// properties are equal but the two `month` properties are not, the date with
/// the lesser value for `month` is the lesser of the two dates.
///
/// Next, implement the `==` operator function, the requirement inherited from
/// the `Equatable` protocol.
///
/// func ==(lhs: Date, rhs: Date) -> Bool {
/// return lhs.year == rhs.year && lhs.month == rhs.month
/// && lhs.day == rhs.day
/// }
///
/// Two `Date` instances are equal if each of their corresponding properties is
/// equal.
///
/// Now that `Date` conforms to `Comparable`, you can compare instances of the
/// type with any of the relational operators. The following example compares
/// the date of the first moon landing with the release of David Bowie's song
/// "Space Oddity":
///
/// let spaceOddity = Date(year: 1969, month: 7, day: 11) // July 11, 1969
/// let moonLanding = Date(year: 1969, month: 7, day: 20) // July 20, 1969
/// if moonLanding > spaceOddity {
/// print("Major Tom stepped through the door first.")
/// } else {
/// print("David Bowie was following in Neil Armstrong's footsteps.")
/// }
/// // Prints "Major Tom stepped through the door first."
///
/// Note that the `>` operator provided by the standard library is used in this
/// example, not the `<` operator implemented above.
///
/// - Note: A conforming type may contain a subset of values which are treated
/// as exceptional---that is, values that are outside the domain of
/// meaningful arguments for the purposes of the `Comparable` protocol. For
/// example, the special not-a-number (`FloatingPoint.nan`) value for
/// floating-point types compares as neither less than, greater than, nor
/// equal to any normal floating-point value. Exceptional values need not
/// take part in the strict total order.
public protocol Comparable : Equatable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
func < (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
func <= (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
func >= (lhs: Self, rhs: Self) -> Bool
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
func > (lhs: Self, rhs: Self) -> Bool
}
/// A type that supports standard bitwise arithmetic operators.
///
/// Types that conform to the `BitwiseOperations` protocol implement operators
/// for bitwise arithmetic. The integer types in the standard library all
/// conform to `BitwiseOperations` by default. When you use bitwise operators
/// with an integer, you perform operations on the raw data bits that store
/// the integer's value.
///
/// In the following examples, the binary representation of any values are
/// shown in a comment to the right, like this:
///
/// let x: UInt8 = 5 // 0b00000101
///
/// Here are the required operators for the `BitwiseOperations` protocol:
///
/// - The bitwise OR operator (`|`) returns a value that has each bit set to
/// `1` where *one or both* of its arguments had that bit set to `1`. This
/// is equivalent to the union of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
///
/// Performing a bitwise OR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x | .allZeros) // 0b00000101
/// // Prints "5"
///
/// - The bitwise AND operator (`&`) returns a value that has each bit set to
/// `1` where *both* of its arguments had that bit set to `1`. This is
/// equivalent to the intersection of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
///
/// Performing a bitwise AND operation with a value and `allZeros` always
/// returns `allZeros`.
///
/// print(x & .allZeros) // 0b00000000
/// // Prints "0"
///
/// - The bitwise XOR operator (`^`), or exclusive OR operator, returns a value
/// that has each bit set to `1` where *one or the other but not both* of
/// its operators has that bit set to `1`. This is equivalent to the
/// symmetric difference of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
///
/// Performing a bitwise XOR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x ^ .allZeros) // 0b00000101
/// // Prints "5"
///
/// - The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// where all the bits of its argument are flipped: Bits that are `1` in the
/// argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on `allZeros` returns a value with
/// every bit set to `1`.
///
/// let allOnes = ~UInt8.allZeros // 0b11111111
///
/// The `OptionSet` protocol uses a raw value that conforms to
/// `BitwiseOperations` to provide mathematical set operations like
/// `union(_:)`, `intersection(_:)` and `contains(_:)` with O(1) performance.
///
/// Conforming to the BitwiseOperations Protocol
/// ============================================
///
/// To make your custom type conform to `BitwiseOperations`, add a static
/// `allZeros` property and declare the four required operator functions. Any
/// type that conforms to `BitwiseOperations`, where `x` is an instance of the
/// conforming type, must satisfy the following conditions:
///
/// - `x | Self.allZeros == x`
/// - `x ^ Self.allZeros == x`
/// - `x & Self.allZeros == .allZeros`
/// - `x & ~Self.allZeros == x`
/// - `~x == x ^ ~Self.allZeros`
///
/// - SeeAlso: `OptionSet`
public protocol BitwiseOperations {
/// Returns the intersection of bits set in the two arguments.
///
/// The bitwise AND operator (`&`) returns a value that has each bit set to
/// `1` where *both* of its arguments had that bit set to `1`. This is
/// equivalent to the intersection of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
///
/// Performing a bitwise AND operation with a value and `allZeros` always
/// returns `allZeros`.
///
/// print(x & .allZeros) // 0b00000000
/// // Prints "0"
///
/// - Complexity: O(1).
func & (lhs: Self, rhs: Self) -> Self
/// Returns the union of bits set in the two arguments.
///
/// The bitwise OR operator (`|`) returns a value that has each bit set to
/// `1` where *one or both* of its arguments had that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
///
/// Performing a bitwise OR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x | .allZeros) // 0b00000101
/// // Prints "5"
///
/// - Complexity: O(1).
func | (lhs: Self, rhs: Self) -> Self
/// Returns the bits that are set in exactly one of the two arguments.
///
/// The bitwise XOR operator (`^`), or exclusive OR operator, returns a value
/// that has each bit set to `1` where *one or the other but not both* of
/// its operators has that bit set to `1`. This is equivalent to the
/// symmetric difference of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
///
/// Performing a bitwise XOR with a value and `allZeros` always returns the
/// same value:
///
/// print(x ^ .allZeros) // 0b00000101
/// // Prints "5"
///
/// - Complexity: O(1).
func ^ (lhs: Self, rhs: Self) -> Self
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in the
/// argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on `allZeros` returns a value with
/// every bit set to `1`.
///
/// let allOnes = ~UInt8.allZeros // 0b11111111
///
/// - Complexity: O(1).
prefix func ~ (x: Self) -> Self
/// The empty bitset.
///
/// The `allZeros` static property is the [identity element][] for bitwise OR
/// and XOR operations and the [fixed point][] for bitwise AND operations.
/// For example:
///
/// let x: UInt8 = 5 // 0b00000101
///
/// // Identity
/// x | .allZeros // 0b00000101
/// x ^ .allZeros // 0b00000101
///
/// // Fixed point
/// x & .allZeros // 0b00000000
///
/// [identity element]:http://en.wikipedia.org/wiki/Identity_element
/// [fixed point]:http://en.wikipedia.org/wiki/Fixed_point_(mathematics)
static var allZeros: Self { get }
}
/// Calculates the union of bits sets in the two arguments and stores the result
/// in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the union of bits set in the two arguments.
/// - rhs: Another value.
public func |= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs | rhs
}
/// Calculates the intersections of bits sets in the two arguments and stores
/// the result in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the intersections of bits set in the two
/// arguments.
/// - rhs: Another value.
public func &= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs & rhs
}
/// Calculates the bits that are set in exactly one of the two arguments and
/// stores the result in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the bits that are set in exactly one of the
/// two arguments.
/// - rhs: Another value.
public func ^= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs ^ rhs
}
/// A type that provides an integer hash value.
///
/// You can use any type that conforms to the `Hashable` protocol in a set or
/// as a dictionary key. Many types in the standard library conform to
/// `Hashable`: strings, integers, floating-point and Boolean values, and even
/// sets provide a hash value by default. Your own custom types can be
/// hashable as well. When you define an enumeration without associated
/// values, it gains `Hashable` conformance automatically, and you can add
/// `Hashable` conformance to your other custom types by adding a single
/// `hashValue` property.
///
/// A hash value, provided by a type's `hashValue` property, is an integer that
/// is the same for any two instances that compare equally. That is, for two
/// instances `a` and `b` of the same type, if `a == b` then
/// `a.hashValue == b.hashValue`. The reverse is not true: Two instances with
/// equal hash values are not necessarily equal to each other.
///
/// - Important: Hash values are not guaranteed to be equal across different
/// executions of your program. Do not save hash values to use during a
/// future execution.
///
/// Conforming to the Hashable Protocol
/// ===================================
///
/// To use your own custom type in a set or as the key type of a dictionary,
/// add `Hashable` conformance to your type by providing a `hashValue`
/// property. The `Hashable` protocol inherits from the `Equatable` protocol,
/// so you must also add an is-equal-to operator (`==`) function for your
/// custom type.
///
/// As an example, consider a `GridPoint` type that describes a location in a
/// grid of buttons. Here's the initial declaration of the `GridPoint` type:
///
/// /// A point in an x-y coordinate system.
/// struct GridPoint {
/// var x: Int
/// var y: Int
/// }
///
/// You'd like to create a set of the grid points where a user has already
/// tapped. Because the `GridPoint` type is not hashable yet, it can't be used
/// as the `Element` type for a set. To add `Hashable` conformance, provide an
/// `==` operator function and a `hashValue` property.
///
/// func ==(lhs: GridPoint, rhs: GridPoint) -> Bool {
/// return lhs.x == rhs.x && lhs.y == rhs.y
/// }
///
/// extension GridPoint: Hashable {
/// var hashValue: Int {
/// return x.hashValue ^ y.hashValue
/// }
/// }
///
/// The `hashValue` property in this example combines the hash values of a grid
/// point's `x` and `y` values using the bitwise XOR operator (`^`). The `^`
/// operator is one way to combine two integer values into a single value.
///
/// - Note: Set and dictionary performance depends on hash values that minimize
/// collisions for their associated element and key types, respectively.
///
/// Now that `GridPoint` conforms to the `Hashable` protocol, you can create a
/// set of previously tapped grid points.
///
/// var tappedPoints: Set = [GridPoint(x: 2, y: 3), GridPoint(x: 4, y: 1)]
/// let nextTap = GridPoint(x: 0, y: 1)
/// if tappedPoints.contains(nextTap) {
/// print("Already tapped at (\(nextTap.x), \(nextTap.y)).")
/// } else {
/// tappedPoints.insert(nextTap)
/// print("New tap detected at (\(nextTap.x), \(nextTap.y)).")
/// }
/// // Prints "New tap detected at (0, 1).")
public protocol Hashable : Equatable {
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
var hashValue: Int { get }
}
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
// Equatable types can be matched in patterns by value equality.
@_transparent
public func ~= <T : Equatable> (a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++ {}
postfix operator -- {}
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator ! {}
// Standard prefix operators.
prefix operator ++ {}
prefix operator -- {}
prefix operator ! {}
prefix operator ~ {}
prefix operator + {}
prefix operator - {}
// Standard infix operators.
// "Exponentiative"
infix operator << { associativity none precedence 160 }
infix operator >> { associativity none precedence 160 }
// "Multiplicative"
infix operator * { associativity left precedence 150 }
infix operator &* { associativity left precedence 150 }
infix operator / { associativity left precedence 150 }
infix operator % { associativity left precedence 150 }
infix operator & { associativity left precedence 150 }
// "Additive"
infix operator + { associativity left precedence 140 }
infix operator &+ { associativity left precedence 140 }
infix operator - { associativity left precedence 140 }
infix operator &- { associativity left precedence 140 }
infix operator | { associativity left precedence 140 }
infix operator ^ { associativity left precedence 140 }
// FIXME: is this the right precedence level for "..." ?
infix operator ... { associativity none precedence 135 }
infix operator ..< { associativity none precedence 135 }
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as { associativity none precedence 132 }
// "Coalescing"
infix operator ?? { associativity right precedence 131 }
// "Comparative"
infix operator < { associativity none precedence 130 }
infix operator <= { associativity none precedence 130 }
infix operator > { associativity none precedence 130 }
infix operator >= { associativity none precedence 130 }
infix operator == { associativity none precedence 130 }
infix operator != { associativity none precedence 130 }
infix operator === { associativity none precedence 130 }
infix operator !== { associativity none precedence 130 }
// FIXME: ~= will be built into the compiler.
infix operator ~= { associativity none precedence 130 }
// "Conjunctive"
infix operator && { associativity left precedence 120 }
// "Disjunctive"
infix operator || { associativity left precedence 110 }
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : { associativity right precedence 100 }
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator = { associativity right precedence 90 }
// Compound
infix operator *= { associativity right precedence 90 assignment }
infix operator /= { associativity right precedence 90 assignment }
infix operator %= { associativity right precedence 90 assignment }
infix operator += { associativity right precedence 90 assignment }
infix operator -= { associativity right precedence 90 assignment }
infix operator <<= { associativity right precedence 90 assignment }
infix operator >>= { associativity right precedence 90 assignment }
infix operator &= { associativity right precedence 90 assignment }
infix operator ^= { associativity right precedence 90 assignment }
infix operator |= { associativity right precedence 90 assignment }
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~> { associativity left precedence 255 }
@available(*, unavailable, renamed: "BitwiseOperations")
public typealias BitwiseOperationsType = BitwiseOperations
| apache-2.0 | b82d8c8133b7e29bc357c4e89b77d12f | 38.037911 | 81 | 0.620031 | 4.143981 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Controllers/UI/MapContainer/MapViewController.swift | 1 | 3359 | //
// TTMapViewController.swift
// TrolleyTracker
//
// Created by Ryan Poolos on 6/16/15.
// Copyright (c) 2015 Code For Greenville. All rights reserved.
//
import UIKit
import MapKit
import os.log
// TODO: Add tracking button that toggles MKUserTrackingMode like native maps
protocol MapVCDelegate: class {
func viewAppeared()
func viewDisappeared()
func locateMeButtonTapped()
}
class MapViewController: UIViewController {
typealias ViewControllerDependencies = ApplicationController
//==========================================================================
// MARK: - API
//==========================================================================
func dimTrolleysOtherThan(_ trolleyToSkip: Trolley) {
guard let trolleyView = mapView.view(for: trolleyToSkip) else { return }
mapView.dimTrolleyAnnotationsExcept(trolleyView)
}
//==================================================================
// MARK: - Properties
//==================================================================
weak var delegate: MapVCDelegate?
let mapView: MKMapView = {
let v = MKMapView().useAutolayout()
return v
}()
let locateMeButton: UIButton = {
let b = UIButton().useAutolayout()
b.setImage(#imageLiteral(resourceName: "LocateMe"), for: .normal)
b.backgroundColor = UIColor.ttAlternateTintColor()
b.tintColor = UIColor.ttTintColor()
b.layer.cornerRadius = 5
b.addTarget(self,
action: #selector(handleLocateMeButton(_:)),
for: .touchUpInside)
return b
}()
//==================================================================
// MARK: - Lifecycle
//==================================================================
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
delegate?.viewAppeared()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
delegate?.viewDisappeared()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.default
}
@objc private func handleLocateMeButton(_ sender: UIButton) {
delegate?.locateMeButtonTapped()
}
//==========================================================================
// MARK: - Views
//==========================================================================
private func setupViews() {
view.addSubview(mapView)
mapView.edgeAnchors == view.edgeAnchors
let effect = UIBlurEffect(style: .light)
let statusBarBlur = UIVisualEffectView(effect: effect).useAutolayout()
view.addSubview(statusBarBlur)
statusBarBlur.horizontalAnchors == view.horizontalAnchors
statusBarBlur.topAnchor == view.topAnchor
statusBarBlur.bottomAnchor == topLayoutGuide.bottomAnchor
view.addSubview(locateMeButton)
locateMeButton.trailingAnchor == view.trailingAnchor - 12
locateMeButton.bottomAnchor == bottomLayoutGuide.topAnchor - 12
locateMeButton.widthAnchor == 44
locateMeButton.heightAnchor == 44
}
}
| mit | 4d16459a9a263c2d956cb3df855a454d | 30.990476 | 80 | 0.538851 | 5.924162 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/Autocomplete/IssueCommentAutocomplete.swift | 1 | 2941 | //
// IssueCommentAutocomplete.swift
// Freetime
//
// Created by Ryan Nystrom on 7/23/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
protocol IssueCommentAutocompleteDelegate: class {
func didChangeStore(autocomplete: IssueCommentAutocomplete)
func didFinish(autocomplete: IssueCommentAutocomplete, hasResults: Bool)
}
final class IssueCommentAutocomplete {
let cellHeight = Styles.Sizes.tableCellHeight
private weak var delegate: IssueCommentAutocompleteDelegate?
private let identifier = "identifier"
private var map: [String: AutocompleteType]
init(autocompletes: [AutocompleteType]) {
var map = [String: AutocompleteType]()
for autocomplete in autocompletes {
map[autocomplete.prefix] = autocomplete
}
self.map = map
}
// MARK: Public APIs
func add(_ autocomplete: AutocompleteType) {
map[autocomplete.prefix] = autocomplete
delegate?.didChangeStore(autocomplete: self)
}
func configure(tableView: UITableView, delegate: IssueCommentAutocompleteDelegate) {
self.delegate = delegate
tableView.register(AutocompleteCell.self, forCellReuseIdentifier: identifier)
}
var prefixes: [String] {
return map.map { $0.key }
}
func highlightAttributes(prefix: String) -> [NSAttributedStringKey: Any]? {
return map[prefix]?.highlightAttributes
}
func resultCount(prefix: String?) -> Int {
guard let prefix = prefix, let autocomplete = map[prefix] else { return 0 }
return autocomplete.resultsCount
}
func resultHeight(prefix: String?) -> CGFloat {
return CGFloat(resultCount(prefix: prefix)) * cellHeight
}
func didChange(tableView: UITableView, prefix: String?, word: String) {
guard let prefix = prefix, let autocomplete = map[prefix] else {
delegate?.didFinish(autocomplete: self, hasResults: false)
return
}
autocomplete.search(word: word) { hasResults in
self.delegate?.didFinish(autocomplete: self, hasResults: hasResults)
}
}
func cell(tableView: UITableView, prefix: String?, indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
if let cell = cell as? AutocompleteCell,
let prefix = prefix,
let autocomplete = map[prefix] {
autocomplete.configure(cell: cell, index: indexPath.item)
}
return cell
}
func accept(prefix: String?, indexPath: IndexPath) -> String? {
guard let prefix = prefix, let autocomplete = map[prefix] else {
return nil
}
return autocomplete.accept(index: indexPath.item)
}
var copy: IssueCommentAutocomplete {
return IssueCommentAutocomplete(autocompletes: Array(map.values))
}
}
| mit | 8b1d65fc0aa7d722829680aa900eedf8 | 29.625 | 97 | 0.668027 | 4.843493 | false | false | false | false |
rockbruno/swiftshield | Sources/SwiftShieldCore/Interactor/SwiftShieldInteractor.swift | 1 | 1996 | import Foundation
final class SwiftShieldInteractor: SwiftShieldInteractorProtocol {
weak var delegate: SwiftShieldInteractorDelegate?
let schemeInfoProvider: SchemeInfoProviderProtocol
let logger: LoggerProtocol
let obfuscator: ObfuscatorProtocol
init(
schemeInfoProvider: SchemeInfoProviderProtocol,
logger: LoggerProtocol,
obfuscator: ObfuscatorProtocol
) {
self.schemeInfoProvider = schemeInfoProvider
self.logger = logger
self.obfuscator = obfuscator
obfuscator.delegate = self
}
func getModulesFromProject() throws -> [Module] {
try schemeInfoProvider.getModulesFromProject()
}
func obfuscate(modules: [Module]) throws -> ConversionMap {
try modules.forEach(obfuscator.registerModuleForObfuscation)
return try obfuscator.obfuscate()
}
func markProjectsAsObfuscated() throws {
let contents = try schemeInfoProvider.markProjectsAsObfuscated()
try contents.forEach {
if let error = delegate?.interactor(self, didPrepare: $0.key, withContents: $0.value) {
throw error
}
}
}
func prepare(map: ConversionMap, date: Date) throws {
let outputPrefix = schemeInfoProvider.schemeName
let projectPath = schemeInfoProvider.projectFile.path
let finalMapPath = map.outputPath(
projectPath: projectPath,
date: date,
filePrefix: outputPrefix
)
let mapFile = File(path: finalMapPath)
let content = map.toString(info: outputPrefix)
if let error = delegate?.interactor(self, didPrepare: mapFile, withContents: content) {
throw error
}
}
}
extension SwiftShieldInteractor: ObfuscatorDelegate {
func obfuscator(_: ObfuscatorProtocol, didObfuscateFile file: File, newContents: String) -> Error? {
delegate?.interactor(self, didPrepare: file, withContents: newContents)
}
}
| gpl-3.0 | 1ae6c993e8fc8d7c297c12b6a52b7cb6 | 32.830508 | 104 | 0.675852 | 4.809639 | false | false | false | false |
kusl/swift | validation-test/compiler_crashers_fixed/1052-swift-genericsignature-get.swift | 12 | 831 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension Array {
typealias R = a<T.Element>(Any) {
return self.Generator..E == "](((b(bytes: S<T : C> a {
extension NSData {
struct e {
}
func d: (2, y: NSObject {
}
func f() -> Any {
public var e> {
}
return g: Any, AnyObject) -> {
}
}
struct c {
}("""foo")
func e> T -> Any) -> {
}
return { _, AnyObject)-> String {
A? = b: a {
}
}
}
for (A>) -> {
extension String {
typealias e == { c<T {
class A>) -> A : T, x }
}
}
protocol a {
extension NSData {
}
}
typealias A {
protocol A {
static let v: b = b({
}
i<T>, "")
}
}
}
let h : A where T, AnyObject.A, f(n: AnyObject) -> {
typealias B == true }
}
func d<b: d wh
| apache-2.0 | 5223758632bb36c2967b188d0af4c2c8 | 15.294118 | 87 | 0.598075 | 2.77 | false | false | false | false |
tensorflow/swift-models | Examples/Fractals/JuliaSet.swift | 1 | 2831 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import ArgumentParser
import Foundation
import TensorFlow
struct ComplexConstant {
let real: Float
let imaginary: Float
}
func juliaSet(
iterations: Int, constant: ComplexConstant, tolerance: Float, region: ComplexRegion,
imageSize: ImageSize, device: Device
) -> Tensor<Float> {
let xs = Tensor<Float>(
linearSpaceFrom: region.realMinimum, to: region.realMaximum, count: imageSize.width, on: device
).broadcasted(to: [imageSize.width, imageSize.height])
let ys = Tensor<Float>(
linearSpaceFrom: region.imaginaryMaximum, to: region.imaginaryMinimum, count: imageSize.height,
on: device
).expandingShape(at: 1).broadcasted(to: [imageSize.width, imageSize.height])
var Z = ComplexTensor(real: xs, imaginary: ys)
let C = ComplexTensor(
real: Tensor<Float>(repeating: constant.real, shape: xs.shape, on: device),
imaginary: Tensor<Float>(repeating: constant.imaginary, shape: xs.shape, on: device))
var divergence = Tensor<Float>(repeating: Float(iterations), shape: xs.shape, on: device)
// We'll make sure the initialization of these tensors doesn't carry
// into the trace for the first iteration.
LazyTensorBarrier()
let start = Date()
var firstIteration = Date()
for iteration in 0..<iterations {
Z = Z * Z + C
let aboveThreshold = abs(Z) .> tolerance
divergence = divergence.replacing(
with: min(divergence, Float(iteration)), where: aboveThreshold)
// We're cutting the trace to be a single iteration.
LazyTensorBarrier()
if iteration == 1 {
firstIteration = Date()
}
}
print(
"Total calculation time: \(String(format: "%.3f", Date().timeIntervalSince(start))) seconds")
print(
"Time after first iteration: \(String(format: "%.3f", Date().timeIntervalSince(firstIteration))) seconds"
)
return divergence
}
extension ComplexConstant: ExpressibleByArgument {
init?(argument: String) {
let subArguments = argument.split(separator: ",").compactMap { Float(String($0)) }
guard subArguments.count >= 2 else { return nil }
self.real = subArguments[0]
self.imaginary = subArguments[1]
}
var defaultValueDescription: String {
"\(self.real),\(self.imaginary)"
}
}
| apache-2.0 | 105b90646819a5df0c1aaaaab41af8af | 33.108434 | 109 | 0.713882 | 3.998588 | false | false | false | false |
radazzouz/firefox-ios | UITests/AuthenticationTests.swift | 2 | 6032 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import EarlGrey
class AuthenticationTests: KIFTestCase {
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
webRoot = SimplePageServer.start()
BrowserUtils.dismissFirstRunUI()
}
override func tearDown() {
BrowserUtils.resetToAboutHome(tester())
BrowserUtils.clearPrivateData(tester: tester())
super.tearDown()
}
/**
* Tests HTTP authentication credentials and auto-fill.
*/
func testAuthentication() {
loadAuthPage()
// Make sure that 3 invalid credentials result in authentication failure.
enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "foo", password: "bar")
enterCredentials(usernameValue: "foo", passwordValue: "•••", username: "foo2", password: "bar2")
enterCredentials(usernameValue: "foo2", passwordValue: "••••", username: "foo3", password: "bar3")
// Use KIFTest framework for checking elements within webView
tester().waitForWebViewElementWithAccessibilityLabel("auth fail")
// Enter valid credentials and ensure the page loads.
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reload")).perform(grey_tap())
enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass")
tester().waitForWebViewElementWithAccessibilityLabel("logged in")
// Save the credentials.
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Save Login"))
.inRoot(grey_kindOfClass(NSClassFromString("Client.SnackButton")))
.perform(grey_tap())
logOut()
loadAuthPage()
// Make sure the credentials were saved and auto-filled.
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Log in"))
.inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")))
.perform(grey_tap())
tester().waitForWebViewElementWithAccessibilityLabel("logged in")
// Add a private tab.
EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("Menu")).perform(grey_tap())
EarlGrey.select(elementWithMatcher:grey_accessibilityLabel("New Private Tab"))
.inRoot(grey_kindOfClass(NSClassFromString("Client.MenuItemCollectionViewCell")))
.perform(grey_tap())
loadAuthPage()
// Make sure the auth prompt is shown.
// Note that in the future, we might decide to auto-fill authentication credentials in private browsing mode,
// but that's not currently supported. We assume the username and password fields are empty.
enterCredentials(usernameValue: "Username", passwordValue: "Password", username: "user", password: "pass")
tester().waitForWebViewElementWithAccessibilityLabel("logged in")
}
fileprivate func loadAuthPage() {
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\(webRoot!)/auth.html\n"))
}
fileprivate func logOut() {
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\(webRoot!)/auth.html?logout=1\n"))
// Wait until the dialog shows up
let dialogAppeared = GREYCondition(name: "Wait the login dialog to appear", block: { _ in
var errorOrNil: NSError?
let matcher = grey_allOfMatchers([grey_accessibilityLabel("Cancel"),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher!)
.inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")))
.assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil == nil
return success
}).wait(withTimeout: 20)
GREYAssertTrue(dialogAppeared, reason: "Failed to display login dialog")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Cancel"))
.inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")))
.perform(grey_tap())
}
fileprivate func enterCredentials(usernameValue: String, passwordValue: String, username: String, password: String) {
// Wait until the dialog shows up
let dialogAppeared = GREYCondition(name: "Wait the login dialog to appear", block: { () -> Bool in
var errorOrNil: NSError?
let matcher = grey_allOfMatchers([grey_accessibilityValue(usernameValue),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher!).assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil == nil
return success
})
let success = dialogAppeared?.wait(withTimeout: 20)
GREYAssertTrue(success!, reason: "Failed to display login dialog")
let usernameField = EarlGrey.select(elementWithMatcher: grey_accessibilityValue(usernameValue))
let passwordField = EarlGrey.select(elementWithMatcher: grey_accessibilityValue(passwordValue))
if usernameValue != "Username" {
usernameField.perform(grey_doubleTap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Select All"))
.inRoot(grey_kindOfClass(NSClassFromString("UICalloutBarButton")))
.perform(grey_tap())
}
usernameField.perform(grey_typeText(username))
passwordField.perform(grey_typeText(password))
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Log in"))
.inRoot(grey_kindOfClass(NSClassFromString("_UIAlertControllerActionView")))
.perform(grey_tap())
}
}
| mpl-2.0 | 509747d3f03dbbf9ed358e1fdc703397 | 45.292308 | 135 | 0.690927 | 5.134812 | false | true | false | false |
Floater-ping/DYDemo | DYDemo/DYDemo/Classes/Home/View/RecommendGameView.swift | 1 | 2016 | //
// RecommendGameView.swift
// DYDemo
//
// Created by ZYP-MAC on 2017/8/9.
// Copyright © 2017年 ZYP-MAC. All rights reserved.
//
import UIKit
fileprivate let pGameCellID = "pGameCellID"
class RecommendGameView: UIView {
//MARK:- 控件属性
@IBOutlet weak var collectionView: UICollectionView!
//MARK:- 定义数据的属性
var groups : [AnchorGroupModel]? {
didSet {
groups?.removeFirst()
groups?.removeFirst()
let moreGroup = AnchorGroupModel()
moreGroup.tag_name = "更多"
groups?.append(moreGroup)
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
/// 注册cell
collectionView.register(UINib(nibName: "GameCollectionCell", bundle: nil), forCellWithReuseIdentifier: pGameCellID)
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: pGameCellID)
}
}
//MARK:- 快速创建方法
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView
}
}
//MARK:- UICollectionViewDelegate
extension RecommendGameView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pGameCellID, for: indexPath) as! GameCollectionCell
/// 强制解包
cell.anchor = groups![indexPath.item];
return cell
}
}
//MARK:- UICollectionViewDelegate
extension RecommendGameView : UICollectionViewDelegate {
}
| mit | e2c4f24fc2fce8a3dc0c0c0f2dd0b97c | 26.647887 | 126 | 0.669384 | 5.305405 | false | false | false | false |
garygriswold/Bible.js | Plugins/VideoPlayer/src/ios/VideoPlayer/AVPlayerViewControllerExtension.swift | 1 | 7382 | /**
* AVPlayerViewControllerExtension.swift
* VideoPlayer
*
* Created by Gary Griswold on 1/27/17.
* Copyright © 2017 ShortSands. All rights reserved.
*/
import AVKit
import UIKit
import CoreMedia
import Utility
extension AVPlayerViewController {
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.landscapeRight
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscape
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("\n********** VIEW DID APPEAR ***** in AVPlayerViewController \(animated)")
sendVideoAnalytics(isStart: true, isDone: false)
// Init notifications after analytics is started so that it does not get any false ends.
initNotifications()
//initDebugNotifications()
}
/**
* This method is called when the Done button on the video player is clicked.
* Video State is saved in this method.
*/
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("\n********** VIEW DID DISAPPEAR ***** in AVPlayerViewController \(animated)")
sendVideoAnalytics(isStart: false, isDone: false)
if let position = self.player?.currentTime() {
MediaPlayState.video.update(position: position)
}
releaseVideoPlayer()
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("\n*********** DID RECEIVE MEMORY WARNING **** in AVPlayerViewController")
}
func initNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidPlayToEndTime(note:)),
name: .AVPlayerItemDidPlayToEndTime,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemFailedToPlayToEndTime(note:)),
name: .AVPlayerItemFailedToPlayToEndTime,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemPlaybackStalled(note:)),
name: .AVPlayerItemPlaybackStalled,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemNewErrorLogEntry(note:)),
name: .AVPlayerItemNewErrorLogEntry,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(applicationWillResignActive(note:)),
name: UIApplication.willResignActiveNotification,
object: nil)
}
func initDebugNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemNewAccessLogEntry(note:)),
name: .AVPlayerItemNewAccessLogEntry,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemTimeJumped(note:)),
name: .AVPlayerItemTimeJumped,
object: nil)
}
func removeNotifications() {
print("\n ***** INSIDE REMOVE NOTIFICATIONS")
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemFailedToPlayToEndTime, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemPlaybackStalled, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemNewErrorLogEntry, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
}
func removeDebugNotifications() {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemNewAccessLogEntry, object: nil)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemTimeJumped, object: nil)
}
@objc func playerItemDidPlayToEndTime(note:Notification) {
print("\n** DID PLAY TO END \(String(describing: note.object))")
self.dismiss(animated: false) // move this till after??
sendVideoAnalytics(isStart: false, isDone: true)
MediaPlayState.video.delete()
}
@objc func playerItemFailedToPlayToEndTime(note:Notification) {
print("\n********* FAILED TO PLAY TO END *********\(String(describing: note.object))")
}
@objc func playerItemTimeJumped(note:Notification) {
print("\n****** TIME JUMPED \(String(describing: note.object))")
}
@objc func playerItemPlaybackStalled(note:Notification) {
print("\n****** PLAYBACK STALLED \(String(describing: note.object))")
}
@objc func playerItemNewAccessLogEntry(note:Notification) {
print("\n****** ACCESS LOG ENTRY \(String(describing: note.object))\n\(String(describing: self.player?.currentItem?.accessLog()))")
}
@objc func playerItemNewErrorLogEntry(note:Notification) {
print("\n****** ERROR LOG ENTRY \(String(describing: note.object))\n\(String(describing: self.player?.currentItem?.errorLog()))")
}
/**
* This method is called when the Home button is clicked or double clicked.
* VideoState is saved in this method
*/
@objc func applicationWillResignActive(note:Notification) {
print("\n******* APPLICATION WILL RESIGN ACTIVE *** in AVPlayerViewController")
sendVideoAnalytics(isStart: false, isDone: false)
if let position = self.player?.currentTime() {
MediaPlayState.video.update(position: position)
}
}
private func releaseVideoPlayer() {
print("\n******* INSIDE RELEASE PLAYER ")
removeNotifications()
removeDebugNotifications()
if (self.delegate != nil) {
let videoDelegate = self.delegate as? VideoViewControllerDelegate
videoDelegate?.completionHandler?(nil)
}
}
private func sendVideoAnalytics(isStart: Bool, isDone: Bool) {
print("\n*********** INSIDE SAVE ANALYTICS \(isDone)")
let currTime = (self.player != nil) ? self.player!.currentTime() : CMTime.zero
if (self.delegate != nil) {
let videoDelegate = self.delegate as? VideoViewControllerDelegate
if (isStart) {
videoDelegate?.videoAnalytics?.playStarted(position: currTime)
} else {
videoDelegate?.videoAnalytics?.playEnded(position: currTime, completed: isDone)
videoDelegate?.videoAnalytics = nil // prevent sending duplicate messages
}
}
}
}
| mit | 4d028ccaa7add38ab2078dc4ebbdc7b8 | 48.871622 | 139 | 0.608319 | 5.682063 | false | false | false | false |
compudds/WarrantyLocker | AddViewController.swift | 1 | 24859 | //
// SecondViewController.swift
// Warranty Wallet
// Created by Eric Cook on 10/23/14.
// Copyright (c) 2014 Better Search, LLC. All rights reserved.
//
import UIKit
//import CoreData
//import Parse
import Firebase
import FirebaseDatabase
import FirebaseFirestoreSwift
var id = String()
var newItemItem = [String]()
var modelItem = [String]()
var serialItem = [String]()
var boughtItem = [String]()
var priceItem = [String]()
var phoneItem = [String]()
var purchaseDateItem = [String]()
var endDateItem = [String]()
var warrantyItem = [Data]() //[PFFile]()
var receiptItem = [Data]() //[PFFile]()
var notesItem = [String]()
var productSearch = [String]()
//var imageW = UIImage()
//var imageR = UIImage()
var picId = String()
class AddViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var imageWarranty = UIImagePickerController()
var imageReceipt = UIImagePickerController()
var imagePicked = 0
var imageDataReceipt = Data()
var imageDataWarranty = Data()
var imageDataReceiptLength = 0
var imageDataWarrantyLength = 0
@IBOutlet var barCode: UIImageView!
var photoSelected:Bool = false
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var notes: UITextView!
@IBOutlet var newItem: UITextField!
@IBOutlet var phone: UITextField!
@IBOutlet var endDate: UITextField!
@IBOutlet var purchaseDate: UITextField!
@IBOutlet var bought: UITextField!
@IBOutlet var price: UITextField!
@IBOutlet var serial: UITextField!
@IBOutlet var model: UITextField!
@IBOutlet var profileR: UIImageView!
@IBOutlet var profileW: UIImageView!
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
@IBAction func addToHome(_ sender: AnyObject) {
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.style = UIActivityIndicatorView.Style.large
self.view.addSubview(activityIndicator)
activityIndicator.startAnimating()
self.view.isUserInteractionEnabled = false
picId = ""
performSegue(withIdentifier: "addToHome", sender: self)
}
@IBAction func addToEdit(_ sender: AnyObject) {
picId = ""
performSegue(withIdentifier: "addToEdit", sender: self)
}
@IBAction func cameraReceipt(_ sender: AnyObject) {
let vc = UIImagePickerController()
vc.sourceType = .camera
vc.allowsEditing = true
imagePicked = sender.tag
vc.delegate = self
present(vc, animated: true)
}
@IBAction func cameraWarranty(_ sender: AnyObject) {
let vc = UIImagePickerController()
vc.sourceType = .camera
vc.allowsEditing = true
imagePicked = sender.tag
vc.delegate = self
present(vc, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true)
guard let image = info[.editedImage] as? UIImage else {
print("No image found")
return
}
print("Image selected")
if imagePicked == 1 {
profileR.image = image
profileR.alpha = 1
imageDataReceiptLength = 1
} else if imagePicked == 2 {
profileW.image = image
profileW.alpha = 1
imageDataWarrantyLength = 1
}
photoSelected = true
}
func uploadReceiptPic() {
let storage = Storage.storage()
let storageRef = storage.reference()
// Data in memory
let data = imageDataReceipt //Data()
// Create a reference to the file you want to upload
let receiptRef = storageRef.child("receipt/\(picId)-receipt.png")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = receiptRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// Metadata contains file metadata such as size, content-type.
/*let size = metadata.size
// You can also access to download URL after upload.
receiptRef.downloadURL { (url, error) in
guard url != nil else {
// Uh-oh, an error occurred!
print("Error occured in uploading image!")
return
}
}*/
}
}
func uploadWarrantyPic() {
let storage = Storage.storage()
let storageRef = storage.reference()
// Data in memory
let data = imageDataWarranty //Data()
// Create a reference to the file you want to upload
let warrantyRef = storageRef.child("warranty/\(picId)-warranty.png")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = warrantyRef.putData(data, metadata: nil) { (metadata, error) in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
print("Error occured in uploading image!")
return
}
// Metadata contains file metadata such as size, content-type.
/*let size = metadata.size
// You can also access to download URL after upload.
warrantyRef.downloadURL { (url, error) in
guard url != nil else {
// Uh-oh, an error occurred!
print("Error occured in downloading image!")
return
}
}*/
}
}
func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}
@IBAction func buttonPressed(_ sender: AnyObject) {
picId = randomString(length: 12)
let dataToSave: [String:Any] =
["product" : newItem.text!,
"productSearch" : newItem.text!.lowercased(),
"model" : model.text!,
"serial" : serial.text!,
"price" : price.text!,
"bought" : bought.text!,
"phone" : phone.text!,
"purchaseDate" : purchaseDate.text!,
"endDate" : endDate.text!,
"notes" : notes.text!,
"userId" : currentUserId,
"objectId": picId,
"pushSent": "no",
"newObjectId" : currentUserEmail
]
if newItem.text == "" {
let alert = UIAlertController(title: "Product field can not be blank", message: "Please try again.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
} else {
/*var stringts = phone.text as NSMutableString
if(phone.text.isEmpty){
} else {
stringts.insertString("(", atIndex: 0)
stringts.insertString(")", atIndex: 4)
stringts.insertString(" ", atIndex: 5)
stringts.insertString("-", atIndex: 9)
phone.text = stringts as String
}*/
//for(var i=0; i <= 1; i += 1){
//if i == 0 {
if imageDataReceiptLength == 1 {
var image1 = UIImage()
image1 = profileR.image!
let newSize:CGSize = CGSize(width: 850,height: 850)
let rect = CGRect(x: 0,y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image1.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageDataReceipt = newImage!.pngData()!
} else {
imageDataReceiptLength = 0
let image3 = UIImage(named: "[email protected]")
imageDataReceipt = image3!.pngData()!
}
//} else {
if imageDataWarrantyLength == 1 {
var image2 = UIImage()
image2 = profileW.image!
let newSize:CGSize = CGSize(width: 850,height: 850)
let rect = CGRect(x: 0,y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image2.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageDataWarranty = newImage!.pngData()!
} else {
imageDataWarrantyLength = 0
let image3 = UIImage(named: "[email protected]")
imageDataWarranty = image3!.pngData()!
}
//}
//}
if imageDataWarrantyLength == 1 && imageDataReceiptLength == 1 {
print(imageDataReceipt.count)
print(imageDataWarranty.count)
let ref = db.collection("Warranties")
ref.addDocument(data: dataToSave)
{ err in
if let err = err {
print("Error adding document: \(err)")
} else {
//print("Document added with ID: \(ref.documentID)")
print("New Warranty successfully added with warranty and receipt pictures!")
//id = "\(ref.documentID)"
self.uploadWarrantyPic()
self.uploadReceiptPic()
}
}
/*let warranty = PFObject(className:"Warranties")
warranty["product"] = newItem.text
warranty["productSearch"] = newItem.text?.lowercased()
warranty["model"] = model.text
warranty["serial"] = serial.text
warranty["price"] = price.text
warranty["bought"] = bought.text
warranty["phone"] = phone.text
warranty["purchaseDate"] = purchaseDate.text
warranty["endDate"] = endDate.text
warranty["notes"] = notes.text
warranty["receipt"] = PFFile(name:"receipt.png", data:imageDataReceipt)
warranty["warranty"] = PFFile(name:"warranty.png", data:imageDataWarranty)
warranty["userId"] = PFUser.current()!.objectId!
warranty["newUserId"] = currentUserEmail
warranty.saveInBackground {
(success: Bool, error: Error?) in
//(success, error) in
if (success) {
print("New warranty saved.")
id = warranty.objectId!
} else {
print(error!)
}
//id = warranty.objectId!
}*/
} else {
if imageDataWarrantyLength == 0 && imageDataReceiptLength == 0 {
print(imageDataReceipt.count)
print(imageDataWarranty.count)
//var ref: DatabaseReference!
let ref = db.collection("Warranties")
ref.addDocument(data: dataToSave)
{ err in
if let err = err {
print("Error adding document: \(err)")
} else {
//print("Document added with ID: \(ref!.documentID)")
print("New Warranty successfully added without and pictures!")
//id = "\(ref!.documentID)"
//self.uploadWarrantyPic()
//self.uploadReceiptPic()
}
}
/*let warranty = PFObject(className:"Warranties")
warranty["product"] = newItem.text
warranty["productSearch"] = newItem.text?.lowercased()
warranty["model"] = model.text
warranty["serial"] = serial.text
warranty["price"] = price.text
warranty["bought"] = bought.text
warranty["phone"] = phone.text
warranty["purchaseDate"] = purchaseDate.text
warranty["endDate"] = endDate.text
warranty["notes"] = notes.text
warranty["receipt"] = PFFile(name:"receipt.png", data:imageDataReceipt)
warranty["warranty"] = PFFile(name:"warranty.png", data:imageDataWarranty)
warranty["userId"] = PFUser.current()!.objectId!
warranty["newUserId"] = currentUserEmail
warranty.saveInBackground {
(success: Bool, error: Error?) in
//(success, error) in
if (success) {
print("New warranty saved.")
id = warranty.objectId!
} else {
print(error!)
}
//id = warranty.objectId!
}*/
}
if imageDataWarrantyLength == 1 && imageDataReceiptLength == 0 {
print(imageDataReceipt.count)
print(imageDataWarranty.count)
let ref = db.collection("Warranties")
ref.addDocument(data: dataToSave)
{ err in
if let err = err {
print("Error adding document: \(err)")
} else {
//print("Document added with ID: \(ref!.documentID)")
print("New Warranty successfully added with warranty picture!")
//id = "\(ref!.documentID)"
self.uploadWarrantyPic()
//self.uploadReceiptPic()
}
}
/*let warranty = PFObject(className:"Warranties")
warranty["product"] = newItem.text
warranty["productSearch"] = newItem.text?.lowercased()
warranty["model"] = model.text
warranty["serial"] = serial.text
warranty["price"] = price.text
warranty["bought"] = bought.text
warranty["phone"] = phone.text
warranty["purchaseDate"] = purchaseDate.text
warranty["endDate"] = endDate.text
warranty["notes"] = notes.text
warranty["receipt"] = PFFile(name:"receipt.png", data:imageDataReceipt)
warranty["warranty"] = PFFile(name:"warranty.png", data:imageDataWarranty)
warranty["userId"] = PFUser.current()!.objectId!
warranty["newUserId"] = currentUserEmail
warranty.saveInBackground {
(success: Bool, error: Error?) in
//(success, error) in
if (success) {
print("New warranty saved.")
id = warranty.objectId!
} else {
print(error!)
}
//id = warranty.objectId!
}*/
}
if imageDataWarrantyLength == 0 && imageDataReceiptLength == 1 {
print(imageDataReceipt.count)
print(imageDataWarranty.count)
let ref = db.collection("Warranties")
ref.addDocument(data: dataToSave)
{ err in
if let err = err {
print("Error adding document: \(err)")
} else {
//print("Document added with ID: \(ref!.documentID)")
print("New Warranty successfully added with receipt picture!")
//id = "\(ref!.documentID)"
//self.uploadWarrantyPic()
self.uploadReceiptPic()
}
}
/*let warranty = PFObject(className:"Warranties")
warranty["product"] = newItem.text
warranty["productSearch"] = newItem.text?.lowercased()
warranty["model"] = model.text
warranty["serial"] = serial.text
warranty["price"] = price.text
warranty["bought"] = bought.text
warranty["phone"] = phone.text
warranty["purchaseDate"] = purchaseDate.text
warranty["endDate"] = endDate.text
warranty["notes"] = notes.text
warranty["receipt"] = PFFile(name:"receipt.png", data:imageDataReceipt)
warranty["warranty"] = PFFile(name:"warranty.png", data:imageDataWarranty)
warranty["userId"] = PFUser.current()!.objectId!
warranty["newUserId"] = currentUserEmail
warranty.saveInBackground {
(success: Bool, error: Error?) in
//(success, error) in
if (success) {
print("New warranty saved.")
id = warranty.objectId!
} else {
print(error!)
}
//id = warranty.objectId!
}*/
}
}
let alert = UIAlertController(title: "Warranty Successfully Added!", message: "", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
newItem.text = ""
model.text = ""
serial.text = ""
bought.text = ""
price.text = ""
purchaseDate.text = ""
endDate.text = ""
phone.text = ""
notes.text = ""
imagePicked = 0
profileR.alpha = 0
profileW.alpha = 0
imageDataReceiptLength = 0
imageDataWarrantyLength = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
scrollView.isScrollEnabled = true
scrollView.contentSize.height = 1006
scrollView.contentSize.width = 291
//self.scrollView.delegate = self
}
func noInternetConnection() {
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
print(userEmail)
} else {
print("Internet connection FAILED")
let alert = UIAlertController(title: "Sorry, no internet connection found.", message: "Warranty Locker requires an internet connection.", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Try Again?", style: .default, handler: { action in
alert.dismiss(animated: true, completion: nil)
self.noInternetConnection()
}))
self.present(alert, animated: true, completion: nil)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//setBarcode()
}
override func viewDidAppear(_ animated: Bool) {
noInternetConnection()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
newItem.resignFirstResponder()
return true
}
}
| gpl-3.0 | 42bf108afd2439e7adeba3b47759391d | 35.611193 | 196 | 0.437709 | 6.30779 | false | false | false | false |
wrld3d/wrld-example-app | ios/Include/WrldSDK/iphoneos12.0/WrldNav.framework/Headers/WRLDNavLocation.swift | 6 | 1111 | import Foundation
import CoreLocation
/**
This type is used to describe a location on the map, primarily this is used for the start and end
locations of a route.
*/
@objc
public class WRLDNavLocation: NSObject
{
@objc public init(name name_: String,
latLon latLon_: CLLocationCoordinate2D,
indoorID indoorID_: String? = nil,
floorID floorID_: Int = 0)
{
name = name_
latLon = latLon_
indoorID = indoorID_
floorID = floorID_
}
/**
The name of this location, this is what should be displayed in a search text box.
*/
@objc(name) public let name: String
/**
Latitude and Longitude of the location.
*/
@objc(latLon) public let latLon: CLLocationCoordinate2D
/**
The name of the building that this location is within, or nil if this is not applicable.
*/
@objc(indoorID) public let indoorID: String?
/**
The floor that this location is on or 0 if not applicable.
*/
@objc(floorID) public let floorID: Int
}
| bsd-2-clause | fc9f84369783fec4df26319044179ca2 | 26.097561 | 98 | 0.605761 | 4.176692 | false | false | false | false |
gtcode/GTMetronome | GTMetronome/MainViewController.swift | 1 | 3636 | //
// MainViewController.swift
// GTMetronome
//
// Created by Paul Lowndes on 8/3/17.
// Copyright © 2017 Paul Lowndes. All rights reserved.
//
import UIKit
import AVFoundation
class MainViewController:
UIViewController
, UITextFieldDelegate
, SequencePlayerControllerDelegate
{
//MARK: Properties
// @IBOutlet weak var playButton: PlayButton!
// @IBOutlet weak var rateKnob: GreenControlKnob!
// @IBOutlet weak var playLabel: UILabel!
//
// @IBOutlet var panKnobs: [ControlKnob]!
// @IBOutlet var volumeKnobs: [ControlKnob]!
@IBOutlet weak var appNameLabel: UILabel!
@IBOutlet weak var tempoTextField: UITextField!
@IBOutlet weak var barTextField: UITextField!
@IBOutlet weak var beatTextField: UITextField!
@IBOutlet weak var toggleMetronomeButton: UIButton!
@IBOutlet weak var subdivisionControl: UISegmentedControl!
@IBOutlet weak var photoImageView: UIImageView!
let audioSession: AVAudioSession! = AVAudioSession.sharedInstance()
let controller = SequencePlayerController()
override func viewDidLoad() {
super.viewDidLoad()
controller.delegate = self
}
func handleMediaServicesWereReset(_ notification: NSNotification) {
do {
try audioSession.setActive(
true
);
} catch {
print("FAILED!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateTempoAndTempoTextField(newTempoString: textField.text)
}
//MARK: Actions
@IBAction func startStopButton(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if controller.play() {
initTempoField()
}
}
@IBAction func subdivisionControlAction(_ sender: UISegmentedControl) {
// TODO: remove this UI control
// controller.updateSubdivisions(selectedSegmentIndex: sender.selectedSegmentIndex)
}
//MARK: Helpers
func initTempoField() {
tempoTextField.text
= NSString.localizedStringWithFormat("%.2f", controller.sequencePlayer.tempoBPM) as String
}
func updateTempoAndTempoTextField(newTempoString: String!) {
let newTempo = Float32(newTempoString)!
if (newTempo >= Float32(10.0) && newTempo <= Float32(240.0)) {
// TODO: tempo control
//controller.setTempo(newTempo)
}
initTempoField()
}
// MARK: SequencePlayerControllerDelegate handlers
// TODO: complete these
func playbackBegan() {
//playButton.isSelected = true
//playLabel.text = NSLocalizedString("Stop", comment: "")
}
func playbackStopped() {
//playButton.isSelected = false
//playLabel.text = NSLocalizedString("Play", comment: "")
}
// MARK: MetronomeDelegate handler
func metronomeTicking(_ metronome: Metronome, bar: String, beat: String) {
// see more here: https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html
// qos levels: https://developer.apple.com/documentation/dispatch/dispatchqos.qosclass
// some shortcuts here: https://github.com/hyperoslo/SwiftSnippets
// let _ = {
// self.barTextField.text = bar
// self.beatTextField.text = beat
// }()
//DispatchQueue.main.async(qos: .background) {
DispatchQueue.main.async() {
self.barTextField.text = bar
self.beatTextField.text = beat
}
}
}
| mit | 4cc63cd61a3c4753dd5243c423f92ae3 | 26.537879 | 145 | 0.69381 | 4.460123 | false | false | false | false |
AimobierCocoaPods/OddityUI | Classes/DetailAndCommitViewController/DetailViewController/Extension/WebViewExtenion.swift | 1 | 13230 | //
// DetailViewControllerWebViewExtenion.swift
// Journalism
//
// Created by Mister on 16/5/31.
// Copyright © 2016年 aimobier. All rights reserved.
//
import UIKit
import WebKit
extension DetailViewController:WKNavigationDelegate{
/**
主要是为了针对于党图片延时加载之后的webvView高度问题
- parameter scrollView: 滑动视图
*/
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let height = UIScreen.main.bounds.height+scrollView.contentOffset.y
let jsStr = "scrollMethod(\(height))"
self.webView.evaluateJavaScript(jsStr, completionHandler: { (body, error) in
})
self.adaptionWebViewHeightMethod()
}
/**
当滑动视图停止,记录滑动到达的位置 用来记录用户的赏赐查看位置
- parameter scrollView: 滑动视图
*/
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
new?.getNewContentObject()?.scroffY(scrollView.contentOffset.y)
}
/**
整合方法
完成webview的初始化
完成新闻详情页面的加载方法
监听字体变化的方法
*/
func integrationMethod(){
self.initWebViewInit()
self.loadContentObjects()
/**
* 该方法会检测用户设置字体大小的方法
* 当用户设置字体后,会发起该通知。
*
* @param FONTMODALSTYLEIDENTIFITER 用户发起的通知的名称
* @param nil 所携带的数据
* @param NSOperationQueue.mainQueue 需要执行接下来操作的县城
*
* @return 所需要完成的操作
*/
// NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: FONTMODALSTYLEIDENTIFITER), object: nil, queue: OperationQueue.main) { (_) in
//
// self.tableView.reloadData()
//
// let jsStr = "document.getElementById('body_section').style.fontSize=\(UIFont.a_font3.pointSize);document.getElementById('subtitle').style.fontSize=\(UIFont.a_font8.pointSize);document.getElementById('title').style.fontSize=\(UIFont.a_font9.pointSize);"
//
// self.webView.evaluateJavaScript(jsStr, completionHandler: { (body, error) in
//
// self.adaptionWebViewHeightMethod()
// })
// }
}
/**
初始化 WKWebView
设置webview可以使用javascript
设置webview播放视频时可以使用html5 自带的播放器,播放
设置webview的JSBridge对象
- returns: null
*/
func initWebViewInit(){
let configuration = WKWebViewConfiguration()
configuration.userContentController.add(self, name: "JSBridge")
// configuration.allowsInlineMediaPlayback = true
self.webView = WKWebView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 600, height: 1000)), configuration: configuration)
self.webView.isHidden = true
self.webView.navigationDelegate = self
self.webView.scrollView.isScrollEnabled = false
self.webView.scrollView.scrollsToTop = false
self.webView.scrollView.bounces = false
self.tableView.tableHeaderView = self.webView
self.showWaitLoadView()
self.tableView.sectionFooterHeight = 0
}
/**
读取新闻详情对象
经过改版后。原方法在数据库中直接获取详情的代码已经被删除。
主要是为了针对新闻发生品论或者新欢收藏后,完成新闻内容的及时刷新
*/
func loadContentObjects(){
if let n = new {
self.ShowNewCOntentInWebView(newCon)
NewAPI.GetnewContent(n.nid, finish: { (newCon) in
self.newCon = newCon
self.ShowNewCOntentInWebView(newCon)
}, fail: {
self.waitView.setNoNetWork {
self.loadContentObjects()
}
})
}
}
/**
根据用户提供的新闻详情,进行网页上新闻详情的展示
在这例用户可以提供一个不存在的新闻详情,这个主要是为了针对当用户刚进入页面或者没有网络的时候进行数据加载的情况
- parameter newContent: 新闻详情 NewContent 类型
*/
func ShowNewCOntentInWebView(_ newContent:NewContent?=nil){
if let newCon = newContent {
self.webView.loadHTMLString(newCon.getHtmlResourcesString(), baseURL: Bundle.OddityBundle().bundleURL)
}
}
/**
当调用到这个方法的时候,WkWebView将会调用Javascript的方法,来以此获取新闻展示页面所需要的高度
获取高度完成之后就进行页面的重新布局以加入到tableView的表头中作为一个详情展示页
*/
func adaptionWebViewHeightMethod(_ height:CGFloat = -1){
self.webView.evaluateJavaScript("document.getElementById('section').offsetHeight") { (data, _) in
if let height = data as? CGFloat{
if self.webView.frame.size.height != height+35 {
self.webView.layoutIfNeeded()
self.webView.frame.size.height = height+35
self.tableView.tableHeaderView = self.webView
}
}
}
}
/**
当webview全部加载完成之后
完成之后,设置webview的高度。让其适配于页面
之后显示webview并且将正在加载的等待视图进行隐藏
- parameter webView: webview
- parameter navigation: 什么玩意?
*/
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.adaptionWebViewHeightMethod()
self.webView.isHidden = false
self.tableView.setContentOffset(CGPoint(x: 0,y: 1), animated: false)
if let off = self.new?.getNewContentObject()?.scroffY {
self.tableView.setContentOffset(CGPoint(x: 0, y: CGFloat(off)), animated: false)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(0.6 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {
self.hiddenWaitLoadView() // 隐藏加载视图
})
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
self.waitView.setNoNetWork {
self.loadContentObjects()
}
}
/**
当webview中发生了一些链接的变化 将会调用该方法
该方法主要针对于用户点击了页面中的超链接后。将会交由另一个webview进行处理,不再本webview中直接展示。为了布局
- parameter webView: webview
- parameter navigationAction: 发生的链接变化
- parameter decisionHandler: 处理方式
*/
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == WKNavigationType.linkActivated {
if let urlStr = navigationAction.request.url?.absoluteString {
self.oddityDelegate?.clickHyperlinkAction?(viewController: self, urlString: urlStr)
}
return decisionHandler(WKNavigationActionPolicy.cancel)
}
return decisionHandler(WKNavigationActionPolicy.allow)
}
}
import PINCache
import PINRemoteImage
extension String {
fileprivate func DownloadImageByUrl(_ progress:@escaping (Int) -> Void,finish:@escaping (String) -> Void){
if let str = PINCache.shared().object(forKey: "hanle\(self)") as? String {
return finish(str)
}
guard let url = URL(string: self) else { return }
PINRemoteImageManager.shared().downloadImage(with: url, options: PINRemoteImageManagerDownloadOptions(), progressDownload: { (min, max) in
if url.absoluteString.hasSuffix(".gif") {
let process = Int(CGFloat(min)/CGFloat(max)*100)
progress((process-5 < 0 ? 0 : process-5))
}
}) { (result) in
self.HandlePinDownLoadResult(finish,result:result)
}
}
/**
处理PINRemoteImage下载完成的结果哦
- parameter finish: 处理完成化后的回调
- parameter result: Result to PINRemoteImageManagerResult
*/
fileprivate func HandlePinDownLoadResult(_ finish:@escaping (String) -> Void,result:PINRemoteImageManagerResult){
/// 含有静态图片
if let img = result.image ,let base64 = UIImageJPEGRepresentation(img, 0.9)?.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0)){
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
let string = "data:image/jpeg;base64,\(base64)".replaceRegex("<", with: "").replaceRegex(">", with: "")
DispatchQueue.main.async(execute: {
finish(string)
PINCache.shared().setObject(string as NSCoding, forKey: "hanle\(self)")
})
})
}
/// 含有动态图片
if let img = result.animatedImage {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: {
let base64 = img.data.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let string = "data:image/gif;base64,\(base64)".replaceRegex("<", with: "").replaceRegex(">", with: "")
DispatchQueue.main.async(execute: {
finish(string)
PINCache.shared().setObject(string as NSCoding, forKey: "hanle\(self)")
})
})
}
}
}
extension DetailViewController :WKScriptMessageHandler{
/**
当客户端即收到来自于javascript的消息请求之后,将会调用到该方法。
比如用户点击图片之后所调用的方法
比如图片加载完成后展示将会调用该方法
- parameter userContentController: userContentController
- parameter message: javascript 所发出的消息体
*/
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let bodyData = message.body as? Dictionary<String,AnyObject> else { return }
guard let type = bodyData["type"] as? Int else{return}
if type == 0 { return self.adaptionWebViewHeightMethod() }
if type == 3 {
if let url = bodyData["url"] as? String,let index = bodyData["index"] as? Int {
self.HandleUrlAndIndex(url, index: index)
}
}
if type == 1 {
if let index = bodyData["index"] as? Int,let res = new?.getNewContentObject()?.allImagesArray() {
self.oddityDelegate?.clickNewContentImageAction?(viewController: self, newContent: self.newCon, imgIndex: index,imgArray: res)
}
}
}
/**
根据提供的 URL 和 需要加载完成的 Index
- parameter url: 图片URL
- parameter index: 图片所在的Index
*/
fileprivate func HandleUrlAndIndex(_ url:String,index:Int){
url.DownloadImageByUrl({ (pro) in
DispatchQueue.main.async(execute: {
let jsStr = "$(\"div .customProgressBar\").eq(\(index)).css(\"width\",\"\(pro)%\")"
self.webView.evaluateJavaScript(jsStr, completionHandler: nil)
})
}, finish: { (base64) in
let jsStr = "$(\"img\").eq(\(index)).attr(\"src\",\"\(base64)\")"
self.webView.evaluateJavaScript(jsStr, completionHandler: nil)
if url.hasSuffix(".gif") {
let display = "$(\"div .progress\").eq(\(index)).css(\"visibility\",\"hidden\")"
self.webView.evaluateJavaScript(display, completionHandler: nil)
}
})
}
}
| mit | 36081124a633fd54ebe5e102eec56ad2 | 31.539726 | 266 | 0.563274 | 4.756508 | false | false | false | false |
Aaron-zheng/yugioh | yugioh/DOFavoriteButton.swift | 1 | 15971 | //
// DOFavoriteButton.swift
// yugioh
//
// Created by Aaron on 13/8/2017.
// Copyright © 2017 sightcorner. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class DOFavoriteButton: UIButton {
fileprivate var imageShape: CAShapeLayer!
@IBInspectable open var image: UIImage! {
didSet {
createLayers(image: image)
}
}
@IBInspectable open var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (isSelected) {
imageShape.fillColor = imageColorOn.cgColor
}
}
}
@IBInspectable open var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!isSelected) {
imageShape.fillColor = imageColorOff.cgColor
}
}
}
fileprivate var circleShape: CAShapeLayer!
fileprivate var circleMask: CAShapeLayer!
@IBInspectable open var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.cgColor
}
}
fileprivate var lines: [CAShapeLayer]!
@IBInspectable open var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for line in lines {
line.strokeColor = lineColor.cgColor
}
}
}
fileprivate let circleTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
fileprivate let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
fileprivate let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
fileprivate let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable open var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override open var isSelected : Bool {
didSet {
if (isSelected != oldValue) {
if isSelected {
imageShape.fillColor = imageColorOn.cgColor
} else {
deselect()
}
}
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
public override convenience init(frame: CGRect) {
self.init(frame: frame, image: UIImage())
}
public init(frame: CGRect, image: UIImage!) {
super.init(frame: frame)
self.image = image
createLayers(image: image)
addTargets()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
createLayers(image: UIImage())
addTargets()
}
fileprivate func createLayers(image: UIImage!) {
self.layer.sublayers = nil
let imageFrame = CGRect(x: frame.size.width / 2 - frame.size.width / 4, y: frame.size.height / 2 - frame.size.height / 4, width: frame.size.width / 2, height: frame.size.height / 2)
let imgCenterPoint = CGPoint(x: imageFrame.midX, y: imageFrame.midY)
let lineFrame = CGRect(x: imageFrame.origin.x - imageFrame.width / 4, y: imageFrame.origin.y - imageFrame.height / 4 , width: imageFrame.width * 1.5, height: imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalIn: imageFrame).cgPath
circleShape.fillColor = circleColor.cgColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = CAShapeLayerFillRule.evenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArc(withCenter: imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
circleMask.path = maskPath.cgPath
//===============
// line layer
//===============
lines = []
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.cgColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGMutablePath()
path.move(to: CGPoint(x: lineFrame.midX, y: lineFrame.midY))
path.addLine(to: CGPoint(x: lineFrame.origin.x + lineFrame.width / 2, y: lineFrame.origin.y))
return path
}()
line.lineCap = CAShapeLayerLineCap.round
line.lineJoin = CAShapeLayerLineJoin.round
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(Double.pi) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).cgPath
imageShape.fillColor = imageColorOff.cgColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
imageShape.mask = CALayer()
imageShape.mask!.contents = image.cgImage
imageShape.mask!.bounds = imageFrame
imageShape.mask!.position = imgCenterPoint
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(caTransform3D: CATransform3DIdentity), // 0/10
NSValue(caTransform3D: CATransform3DIdentity), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(caTransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(caTransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(caTransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
fileprivate func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: #selector(DOFavoriteButton.touchDown(_:)), for: UIControl.Event.touchDown)
self.addTarget(self, action: #selector(DOFavoriteButton.touchUpInside(_:)), for: UIControl.Event.touchUpInside)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragExit(_:)), for: UIControl.Event.touchDragExit)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragEnter(_:)), for: UIControl.Event.touchDragEnter)
self.addTarget(self, action: #selector(DOFavoriteButton.touchCancel(_:)), for: UIControl.Event.touchCancel)
}
@objc func touchDown(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
@objc func touchUpInside(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
@objc func touchDragExit(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
@objc func touchDragEnter(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
@objc func touchCancel(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
open func selectWithNoCATransaction() {
isSelected = true
imageShape.fillColor = imageColorOn.cgColor
}
open func select() {
isSelected = true
imageShape.fillColor = imageColorOn.cgColor
CATransaction.begin()
circleShape.add(circleTransform, forKey: "transform")
circleMask.add(circleMaskTransform, forKey: "transform")
imageShape.add(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].add(lineStrokeStart, forKey: "strokeStart")
lines[i].add(lineStrokeEnd, forKey: "strokeEnd")
lines[i].add(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
open func deselect() {
isSelected = false
imageShape.fillColor = imageColorOff.cgColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
| agpl-3.0 | 973acf7235b7038f29afcb05721fec46 | 38.825436 | 190 | 0.525611 | 3.935436 | false | false | false | false |
lemberg/connfa-ios | Connfa/Classes/Events/List Base/ViewData/EventsViewModelsTransformer.swift | 1 | 3117 | //
// EventsViewModelsTransformer.swift
// Connfa
//
// Created by Volodymyr Hyrka on 11/28/17.
// Copyright © 2017 Lemberg Solution. All rights reserved.
//
import Foundation
import SwiftDate
class EventsViewModelsTransformer {
static var `default`: EventsViewModelsTransformer {
var fullFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: Configurations().timeZoneIdentifier)
formatter.dateFormat = "EEEE - MMMM d, yyyy"
return formatter
}
let confifuration = Configurations()
var dayFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: confifuration.timeZoneIdentifier)
formatter.dateFormat = "d"
return formatter
}
var slotFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(identifier: confifuration.timeZoneIdentifier)
formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "HH:mm", options: 0, locale: Locale.autoupdatingCurrent)
return formatter
}
return EventsViewModelsTransformer(day: dayFormatter, slot: slotFormatter, full: fullFormatter)
}
private var dayFormatter: DateFormatter
private var fullFormatter: DateFormatter
private var slotFormatter: DateFormatter
init(day: DateFormatter, slot: DateFormatter, full: DateFormatter) {
self.dayFormatter = day
self.fullFormatter = full
self.slotFormatter = slot
}
public func transform(_ events: [EventModel]) -> [ProgramListDayViewData : DayList] {
var tmpList = [ProgramListDayViewData : DayList]()
let now = Date()
events.forEach { (event) in
let day = ProgramListDayViewData(event.fromDate, dayFormatter: self.dayFormatter, fullFormatter: self.fullFormatter)
let slot = ProgramListSlotViewData(start: self.slotFormatter.string(from: event.fromDate), end: self.slotFormatter.string(from: event.toDate), marker: marker(forStart: event.fromDate, end: event.toDate, now: now))
let levelImageName = event.experienceLevel >= 0 ? ExperienceLevel(rawValue: event.experienceLevel)!.imageName : nil
let speakers = event.speakersJoinedFullNames
let item = ProgramListViewData(eventId: event.id, name: event.name, isSelectable: event.isSelectable, place: event.place, levelImageName: levelImageName, type: event.type, speakers: speakers, track: event.track)
if tmpList[day] == nil {
tmpList[day] = [slot:[item]]
} else if tmpList[day]?[slot] == nil {
tmpList[day]![slot] = [item]
} else {
tmpList[day]![slot]!.append(item)
}
}
var sortedList: [ProgramListDayViewData : DayList] = [:]
tmpList.forEach { (key, value) in
sortedList[key] = value.mapValues{ $0.sorted{ $0.name < $1.name } }
}
return sortedList
}
//MARK: - private
private func marker(forStart start: Date, end: Date, now: Date) -> ProgramListSlotViewData.Marker {
if end < now {
return .none
} else if start > now {
return .upcoming
}
return .going
}
}
| apache-2.0 | 3c67e207b2835251091bece4a9578ffe | 37.95 | 219 | 0.700578 | 4.216509 | false | false | false | false |
ejeinc/MetalScope | Sources/PlayerRenderer.swift | 1 | 2538 | //
// PlayerRenderer.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/01/17.
// Copyright © 2017 eje Inc. All rights reserved.
//
#if (arch(arm) || arch(arm64)) && os(iOS)
import Metal
import AVFoundation
public final class PlayerRenderer {
private let currentItemObserver: KeyValueObserver
public var player: AVPlayer? {
willSet {
if let player = player {
unbind(player)
}
}
didSet {
if let player = player {
bind(player)
}
}
}
public var device: MTLDevice {
return itemRenderer.device
}
public let itemRenderer: PlayerItemRenderer
public init(itemRenderer: PlayerItemRenderer) {
self.itemRenderer = itemRenderer
currentItemObserver = KeyValueObserver { change in
itemRenderer.playerItem = change?[.newKey] as? AVPlayerItem
}
}
public convenience init(device: MTLDevice) {
let itemRenderer = PlayerItemRenderer(device: device)
self.init(itemRenderer: itemRenderer)
}
public convenience init(device: MTLDevice, outputSettings: [String: Any]) throws {
let itemRenderer = try PlayerItemRenderer(device: device, outputSettings: outputSettings)
self.init(itemRenderer: itemRenderer)
}
deinit {
if let player = player {
unbind(player)
}
}
private func bind(_ player: AVPlayer) {
itemRenderer.playerItem = player.currentItem
player.addObserver(currentItemObserver, forKeyPath: "currentItem", options: [.new], context: nil)
}
private func unbind(_ player: AVPlayer) {
player.removeObserver(currentItemObserver, forKeyPath: "currentItem")
itemRenderer.playerItem = nil
}
public func hasNewPixelBuffer(atItemTime time: CMTime) -> Bool {
return itemRenderer.hasNewPixelBuffer(atItemTime: time)
}
public func render(atItemTime time: CMTime, to texture: MTLTexture, commandBuffer: MTLCommandBuffer) throws {
try itemRenderer.render(atItemTime: time, to: texture, commandBuffer: commandBuffer)
}
public func hasNewPixelBuffer(atHostTime time: TimeInterval) -> Bool {
return itemRenderer.hasNewPixelBuffer(atHostTime: time)
}
public func render(atHostTime time: TimeInterval, to texture: MTLTexture, commandBuffer: MTLCommandBuffer) throws {
try itemRenderer.render(atHostTime: time, to: texture, commandBuffer: commandBuffer)
}
}
#endif
| mit | 16578850ab06476fa6d763e3ed327ad2 | 28.16092 | 119 | 0.661017 | 4.64652 | false | false | false | false |
redlock/SwiftyDeepstream | SwiftyDeepstream/Classes/deepstream/message/Message.swift | 1 | 2299 | //
// Message.swift
// deepstreamSwiftTest
//
// Created by Redlock on 4/5/17.
// Copyright © 2017 JiblaTech. All rights reserved.
//
import JAYSON
import Foundation
class Message {
let raw: String
let topic: Topic
let action: Actions
let data: [String]
let messageData:MessageData?
static var messageCount:NSHashTable<Message> = NSHashTable<Message>(options: .weakMemory)
init(raw: String, topic: Topic, action: Actions, data: [String]) {
self.raw = raw
self.topic = topic
self.action = action
self.data = data
if data.count == 4 && action == .PATCH {
self.messageData = try! MessageData(data: data)
}else{
self.messageData = nil
}
// Message.messageCount.add(self)
}
func toString() -> String {
return self.raw
}
deinit {
// Message.messageCount.remove(self)
// Message.messageCount -= 1
// print("[\(Message.messageCount.count)] I AM DEAD!")
}
}
class MessageData {
let record:String
let version:Int
let path:String
let type:Types
// let pathType:UtilJSONPath
let rawValue:Any?
let value:JAYSON?
init(data:[String]) throws {
self.record = data[0]
let (type, rawData) = try MessageParser.convertTyped(value: data[3])
self.type = type
self.rawValue = rawData
guard let newVersion = Int(data[1]) else {
throw DeepstreamError(message: "Error: can't get new version from message")
}
self.version = newVersion
if type == Types.UNDEFINED {
self.value = nil
} else if type == Types.OBJECT {
self.value = rawData as? JAYSON //JSON(rawData as! JSON)
// print(data)
}else{
self.value = JAYSON(rawData)
}
// if let d = rawData.data(using: .utf8) {
//
// self.value = JSON(data: d)
// }
self.path = data[2]
// self.pathType = JSON.toSubscriptType(path: self.path )
}
}
| mit | 110d8a2749e83f564aa38a2f2d247aac | 21.752475 | 93 | 0.518277 | 4.216514 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Style/ShorthandOperatorRule.swift | 1 | 2911 | import SwiftSyntax
struct ShorthandOperatorRule: ConfigurationProviderRule, SwiftSyntaxRule {
var configuration = SeverityConfiguration(.error)
init() {}
static let description = RuleDescription(
identifier: "shorthand_operator",
name: "Shorthand Operator",
description: "Prefer shorthand operators (+=, -=, *=, /=) over doing the operation and assigning.",
kind: .style,
nonTriggeringExamples: allOperators.flatMap { operation in
[
Example("foo \(operation)= 1"),
Example("foo \(operation)= variable"),
Example("foo \(operation)= bar.method()"),
Example("self.foo = foo \(operation) 1"),
Example("foo = self.foo \(operation) 1"),
Example("page = ceilf(currentOffset \(operation) pageWidth)"),
Example("foo = aMethod(foo \(operation) bar)"),
Example("foo = aMethod(bar \(operation) foo)")
]
} + [
Example("var helloWorld = \"world!\"\n helloWorld = \"Hello, \" + helloWorld"),
Example("angle = someCheck ? angle : -angle"),
Example("seconds = seconds * 60 + value")
],
triggeringExamples: allOperators.flatMap { operation in
[
Example("↓foo = foo \(operation) 1\n"),
Example("↓foo = foo \(operation) aVariable\n"),
Example("↓foo = foo \(operation) bar.method()\n"),
Example("↓foo.aProperty = foo.aProperty \(operation) 1\n"),
Example("↓self.aProperty = self.aProperty \(operation) 1\n")
]
} + [
Example("↓n = n + i / outputLength"),
Example("↓n = n - i / outputLength")
]
)
fileprivate static let allOperators = ["-", "/", "+", "*"]
func preprocess(syntaxTree: SourceFileSyntax) -> SourceFileSyntax? {
syntaxTree.folded()
}
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension ShorthandOperatorRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: InfixOperatorExprSyntax) {
guard node.operatorOperand.is(AssignmentExprSyntax.self),
let rightExpr = node.rightOperand.as(InfixOperatorExprSyntax.self),
let binaryOperatorExpr = rightExpr.operatorOperand.as(BinaryOperatorExprSyntax.self),
ShorthandOperatorRule.allOperators.contains(binaryOperatorExpr.operatorToken.withoutTrivia().text),
node.leftOperand.withoutTrivia().description == rightExpr.leftOperand.withoutTrivia().description
else {
return
}
violations.append(node.leftOperand.positionAfterSkippingLeadingTrivia)
}
}
}
| mit | 9bbdd76537974b25fb38367475df44a4 | 40.985507 | 117 | 0.586469 | 5.154804 | false | false | false | false |
saagarjha/iina | iina/DurationDisplayTextField.swift | 1 | 3071 | //
// DurationDisplayView.swift
// iina
//
// Created by Christophe Laprun on 26/01/2017.
// Copyright © 2017 lhc. All rights reserved.
//
import Foundation
class DurationDisplayTextField: NSTextField {
enum DisplayMode {
case current
case duration // displays the duration of the movie
case remaining // displays the remaining time in the movie
}
static var precision : UInt = UInt(Preference.integer(for: .timeDisplayPrecision))
var mode: DisplayMode = .duration { didSet { updateText() } }
var duration: VideoTime = .zero
var current: VideoTime = .zero
/** Switches the display mode between duration and remaining time */
private func switchMode() {
switch mode {
case .duration:
mode = .remaining
default:
mode = .duration
}
}
func updateText(with duration: VideoTime, given current: VideoTime) {
self.duration = duration
self.current = current
updateText()
}
private func updateText() {
let precision = DurationDisplayTextField.precision
let stringValue: String
switch mode {
case .current:
stringValue = current.stringRepresentationWithPrecision(precision)
case .duration:
stringValue = duration.stringRepresentationWithPrecision(precision)
case .remaining:
var remaining = (duration - current)
if remaining.second < 0 {
remaining = VideoTime.zero
}
stringValue = "-\(remaining.stringRepresentationWithPrecision(precision))"
}
self.stringValue = stringValue
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
guard mode != .current else { return }
self.switchMode()
Preference.set(mode == .remaining, for: .showRemainingTime)
}
override func scrollWheel(with event: NSEvent) {
return
}
override func rightMouseDown(with event: NSEvent) {
let precision = DurationDisplayTextField.precision
let menu = NSMenu(title: "Time label settings")
menu.addItem(withTitle: NSLocalizedString("osc.precision", comment: "Precision"))
["1s", "100ms", "10ms", "1ms"].enumerated().forEach { (index, key) in
menu.addItem(withTitle: NSLocalizedString("osc.\(key)", comment: ""),
action: #selector(self.setPrecision(_:)),
target: self, tag: index,
stateOn: precision == index)
}
NSMenu.popUpContextMenu(menu, with: event, for: self)
}
override func touchesBegan(with event: NSEvent) {
// handles the remaining time text field in the touch bar
super.touchesBegan(with: event)
guard mode != .current else { return }
self.switchMode()
Preference.set(mode == .remaining, for: .touchbarShowRemainingTime)
}
@objc func setPrecision(_ sender: NSMenuItem) {
let precision = UInt(sender.tag)
DurationDisplayTextField.precision = precision
Preference.set(Int(precision), for: .timeDisplayPrecision)
PlayerCore.playerCores.forEach { core in
if core.syncPlayTimeTimer != nil {
core.createSyncUITimer()
}
}
}
}
| gpl-3.0 | e8174fc38bc0d8b2631e8a62d82fdbe1 | 29.39604 | 85 | 0.676873 | 4.462209 | false | false | false | false |
younata/RSSClient | Tethys/Feeds/Viewing Feeds/FeedTableCell.swift | 1 | 5103 | import UIKit
import PureLayout
import TethysKit
public final class FeedTableCell: UITableViewCell {
public var feed: Feed? = nil {
didSet {
if let f = feed {
self.nameLabel.text = f.displayTitle
self.summaryLabel.text = f.displaySummary
self.unreadCounter.unread = f.unreadCount
let unreadCountString = String.localizedStringWithFormat(NSLocalizedString(
"FeedsTableViewController_Accessibility_Cell_UnreadArticles",
comment: ""
), f.unreadCount)
self.accessibilityValue = "\(f.displayTitle). \(unreadCountString)"
} else {
self.nameLabel.text = ""
self.summaryLabel.text = ""
self.unreadCounter.unread = 0
}
if let image = feed?.image {
self.iconView.image = image
let scaleRatio = 60 / image.size.width
self.iconWidth.constant = 60
self.iconHeight.constant = image.size.height * scaleRatio
} else {
self.iconView.image = nil
self.iconWidth.constant = 45
self.iconHeight.constant = 0
}
}
}
public let nameLabel = UILabel(forAutoLayout: ())
public let summaryLabel = UILabel(forAutoLayout: ())
public let unreadCounter = UnreadCounter(frame: CGRect.zero)
public let iconView = UIImageView(forAutoLayout: ())
fileprivate let backgroundColorView = UIView()
public private(set) var iconWidth: NSLayoutConstraint!
public private(set) var iconHeight: NSLayoutConstraint!
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.nameLabel.numberOfLines = 0
self.nameLabel.font = UIFont.preferredFont(forTextStyle: .headline)
self.summaryLabel.numberOfLines = 0
self.summaryLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
self.iconView.contentMode = .scaleAspectFit
self.unreadCounter.hideUnreadText = false
self.unreadCounter.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.nameLabel)
self.contentView.addSubview(self.summaryLabel)
self.contentView.addSubview(self.iconView)
self.contentView.addSubview(self.unreadCounter)
self.nameLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 4)
self.nameLabel.autoPinEdge(toSuperviewEdge: .left, withInset: 8)
self.nameLabel.autoPinEdge(.right, to: .left, of: self.iconView, withOffset: -8)
self.summaryLabel.autoPinEdge(toSuperviewEdge: .bottom, withInset: 4, relation: .greaterThanOrEqual)
self.summaryLabel.autoPinEdge(toSuperviewEdge: .left, withInset: 8)
self.summaryLabel.autoPinEdge(.right, to: .left, of: self.iconView, withOffset: -8)
self.summaryLabel.autoPinEdge(.top, to: .bottom, of: self.nameLabel, withOffset: 8,
relation: .greaterThanOrEqual)
self.iconView.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual)
self.iconView.autoPinEdge(toSuperviewEdge: .right)
self.iconView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual)
self.iconView.autoAlignAxis(toSuperviewAxis: .horizontal)
self.iconWidth = self.iconView.autoSetDimension(.width, toSize: 45, relation: .lessThanOrEqual)
self.iconHeight = self.iconView.autoSetDimension(.height, toSize: 0, relation: .lessThanOrEqual)
self.unreadCounter.autoPinEdge(toSuperviewEdge: .top)
self.unreadCounter.autoPinEdge(toSuperviewEdge: .right)
self.unreadCounter.autoSetDimension(.height, toSize: 45)
self.unreadCounter.autoMatch(.width, to: .height, of: self.unreadCounter)
self.unreadCounter.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual)
self.selectedBackgroundView = self.backgroundColorView
self.isAccessibilityElement = true
self.accessibilityIdentifier = "FeedList_Cell"
self.accessibilityLabel = NSLocalizedString("FeedsTableViewController_Accessibility_Cell_Label", comment: "")
self.accessibilityTraits = [.button]
self.applyTheme()
}
public required init?(coder aDecoder: NSCoder) { fatalError() }
private func applyTheme() {
self.nameLabel.textColor = Theme.textColor
self.summaryLabel.textColor = Theme.textColor
self.backgroundColorView.backgroundColor = Theme.overlappingBackgroundColor
self.unreadCounter.triangleColor = Theme.highlightColor
self.backgroundColor = Theme.backgroundColor
}
public override func prepareForReuse() {
super.prepareForReuse()
self.nameLabel.text = ""
self.summaryLabel.text = ""
self.unreadCounter.unread = 0
self.iconView.image = nil
self.accessibilityValue = nil
}
}
| mit | 220d234c49a68dc4b7b96c0a4a047628 | 41.525 | 117 | 0.673917 | 5.123494 | false | false | false | false |
mohamede1945/quran-ios | Quran/AyahBookmarkDataSource.swift | 1 | 2953 | //
// AyahBookmarkDataSource.swift
// Quran
//
// Created by Mohamed Afifi on 11/1/16.
//
// 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 Foundation
import GenericDataSources
class AyahBookmarkDataSource: BaseBookmarkDataSource<AyahBookmark, BookmarkTableViewCell> {
let ayahCache: Cache<AyahNumber, String> = {
let cache = Cache<AyahNumber, String>()
cache.countLimit = 30
return cache
}()
let numberFormatter = NumberFormatter()
let ayahPersistence: AyahTextPersistence
init(persistence: BookmarksPersistence, ayahPersistence: AyahTextPersistence) {
self.ayahPersistence = ayahPersistence
super.init(persistence: persistence)
}
override func ds_collectionView(_ collectionView: GeneralCollectionView,
configure cell: BookmarkTableViewCell,
with item: AyahBookmark,
at indexPath: IndexPath) {
cell.iconImage.image = #imageLiteral(resourceName: "bookmark-filled").withRenderingMode(.alwaysTemplate)
cell.iconImage.tintColor = .bookmark()
cell.descriptionLabel.text = item.creationDate.bookmarkTimeAgo()
cell.startPage.text = numberFormatter.format(NSNumber(value: item.page))
let name: String
// get from cache
if let text = ayahCache.object(forKey: item.ayah) {
name = text
} else {
do {
// get from persistence
let text = try self.ayahPersistence.getAyahTextForNumber(item.ayah)
// save to cache
self.ayahCache.setObject(text, forKey: item.ayah)
// update the UI
name = text
} catch {
name = item.ayah.localizedName
Crash.recordError(error, reason: "AyahTextPersistence.getAyahTextForNumber", fatalErrorOnDebug: false)
}
}
cell.name.text = name
}
func reloadData() {
DispatchQueue.default
.promise2(execute: self.persistence.retrieveAyahBookmarks)
.then(on: .main) { items -> Void in
self.items = items
self.ds_reusableViewDelegate?.ds_reloadSections(IndexSet(integer: 0), with: .automatic)
}.cauterize(tag: "BookmarksPersistence.retrieveAyahBookmarks")
}
}
| gpl-3.0 | fc5240ea472976eac488b85141275d50 | 36.858974 | 118 | 0.640704 | 4.809446 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Search/SearchVideoViewController.swift | 1 | 2371 | //
// SearchVideoViewController.swift
// MusicApp
//
// Created by Hưng Đỗ on 7/11/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import XLPagerTabStrip
import RxSwift
import RxCocoa
import RxDataSources
import NSObject_Rx
class SearchVideoViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchController: UISearchController!
var store: SearchStore!
var action: SearchAction!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
bindStore()
bindAction()
}
fileprivate lazy var dataSource: RxTableViewSectionedReloadDataSource<SectionModel<String, Video>> = {
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Video>>()
dataSource.configureCell = { dataSource, tableView, indexPath, video in
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: VideoItemCell.self), for: indexPath)
if let cell = cell as? VideoItemCell {
cell.configure(name: video.name, singer: video.singer, image: video.avatar)
}
return cell
}
return dataSource
}()
}
extension SearchVideoViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
extension SearchVideoViewController: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return "Video"
}
}
extension SearchVideoViewController {
func bindStore() {
store.videos.asObservable()
.filter { $0.count > 0 }
.map { videos in [SectionModel(model: "Videos", items: videos)] }
.bind(to: tableView.rx.items(dataSource: dataSource))
.addDisposableTo(rx_disposeBag)
}
}
extension SearchVideoViewController {
func bindAction() {
tableView.rx.modelSelected(Video.self)
.subscribe(onNext: { [weak self] video in
self?.searchController.setInactive()
self?.action.videoDidSelect.execute(video)
})
.addDisposableTo(rx_disposeBag)
}
}
| mit | 763dadae4c741a524c2837dc8ddf4a81 | 25.886364 | 124 | 0.648352 | 5.222958 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.