repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tdscientist/ShelfView-iOS | Example/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift | 1 | 3229 | //
// ImageDataProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/11.
//
// Copyright (c) 2018年 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
private let sharedProcessingQueue: CallbackQueue =
.dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process"))
// Handles image processing work on an own process queue.
class ImageDataProcessor {
let data: Data
let callbacks: [SessionDataTask.TaskCallback]
let queue: CallbackQueue
// Note: We have an optimization choice there, to reduce queue dispatch by checking callback
// queue settings in each option...
let onImageProcessed = Delegate<(Result<Image, KingfisherError>, SessionDataTask.TaskCallback), Void>()
init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) {
self.data = data
self.callbacks = callbacks
self.queue = processingQueue ?? sharedProcessingQueue
}
func process() {
queue.execute(doProcess)
}
private func doProcess() {
var processedImages = [String: Image]()
for callback in callbacks {
let processor = callback.options.processor
var image = processedImages[processor.identifier]
if image == nil {
image = processor.process(item: .data(data), options: callback.options)
processedImages[processor.identifier] = image
}
let result: Result<Image, KingfisherError>
if let image = image {
let imageModifier = callback.options.imageModifier
var finalImage = imageModifier.modify(image)
if callback.options.backgroundDecode {
finalImage = finalImage.kf.decoded
}
result = .success(finalImage)
} else {
let error = KingfisherError.processorError(
reason: .processingFailed(processor: processor, item: .data(data)))
result = .failure(error)
}
onImageProcessed.call((result, callback))
}
}
}
| mit | 6c81e89c592cbeabf033246030805145 | 40.371795 | 107 | 0.673381 | 4.838081 | false | false | false | false |
cpascoli/WeatherHype | WeatherHype/Classes/API/DataTransformer/SearchResultsTransformer.swift | 1 | 800 | //
// SearchResultsTransformer.swift
// WeatherHype
//
// Created by Carlo Pascoli on 27/09/2016.
// Copyright © 2016 Carlo Pascoli. All rights reserved.
//
import UIKit
import SwiftyJSON
class SearchResultsTransformer: NSObject {
func parse(json:JSON) -> SearchResults {
var results = [City]()
let list = json["list"].arrayValue
for item in list {
let cityId = item["id"].stringValue
let name = item["name"].stringValue
let country = item["sys"]["country"].stringValue
let city = City(cityId: cityId, name: name, country: country)
results.append(city)
}
let searchReults = SearchResults(results:results)
return searchReults
}
}
| apache-2.0 | 9f4c9c80a7afafb9fc834a3cec63a735 | 22.5 | 73 | 0.585732 | 4.463687 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Flows/PaymentFlow/PXPaymentFlowModel.swift | 1 | 6669 | import Foundation
final class PXPaymentFlowModel: NSObject {
var amountHelper: PXAmountHelper?
var checkoutPreference: PXCheckoutPreference?
let paymentPlugin: PXSplitPaymentProcessor?
let mercadoPagoServices: MercadoPagoServices
var paymentResult: PaymentResult?
var instructionsInfo: PXInstruction?
var pointsAndDiscounts: PXPointsAndDiscounts?
var businessResult: PXBusinessResult?
var productId: String?
var shouldSearchPointsAndDiscounts: Bool = true
var postPaymentStatus: PostPaymentStatus?
let ESCBlacklistedStatus: [String]?
init(paymentPlugin: PXSplitPaymentProcessor?, mercadoPagoServices: MercadoPagoServices, ESCBlacklistedStatus: [String]?) {
self.paymentPlugin = paymentPlugin
self.mercadoPagoServices = mercadoPagoServices
self.ESCBlacklistedStatus = ESCBlacklistedStatus
}
enum Steps: String {
case createPaymentPlugin
case createDefaultPayment
case goToPostPayment
case getPointsAndDiscounts
case createPaymentPluginScreen
case finish
}
func nextStep() -> Steps {
if needToCreatePaymentForPaymentPlugin() {
return .createPaymentPlugin
} else if needToShowPaymentPluginScreenForPaymentPlugin() {
return .createPaymentPluginScreen
} else if needToCreatePayment() {
return .createDefaultPayment
} else if needToGoToPostPayment() {
return .goToPostPayment
} else if needToGetPointsAndDiscounts() {
return .getPointsAndDiscounts
} else {
return .finish
}
}
func needToCreatePaymentForPaymentPlugin() -> Bool {
if paymentPlugin == nil {
return false
}
if !needToCreatePayment() {
return false
}
if hasPluginPaymentScreen() {
return false
}
assignToCheckoutStore()
paymentPlugin?.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance)
if let shouldSupport = paymentPlugin?.support() {
return shouldSupport
}
return false
}
func needToCreatePayment() -> Bool {
return paymentResult == nil && businessResult == nil
}
func needToGoToPostPayment() -> Bool {
let hasPostPaymentFlow = postPaymentStatus?.isPending ?? false
let paymentResultIsApproved = paymentResult?.isApproved() == true
let isBusinessApproved = businessResult?.isApproved() == true
let isBusinessAccepted = businessResult?.isAccepted() == true
let businessResultIsApprovedAndAccepted = isBusinessApproved && isBusinessAccepted
return hasPostPaymentFlow && (paymentResultIsApproved || businessResultIsApprovedAndAccepted)
}
func needToGetPointsAndDiscounts() -> Bool {
if postPaymentStatus == .continuing && shouldSearchPointsAndDiscounts {
return true
}
if let paymentResult = paymentResult,
shouldSearchPointsAndDiscounts,
(paymentResult.isApproved() || needToGetInstructions()) {
return true
} else if let businessResult = businessResult,
shouldSearchPointsAndDiscounts,
businessResult.isApproved(),
businessResult.isAccepted() {
return true
}
return false
}
func needToGetInstructions() -> Bool {
guard let paymentResult = self.paymentResult else {
return false
}
guard !String.isNullOrEmpty(paymentResult.paymentId) else {
return false
}
return isOfflinePayment() && instructionsInfo == nil
}
func needToShowPaymentPluginScreenForPaymentPlugin() -> Bool {
if !needToCreatePayment() {
return false
}
return hasPluginPaymentScreen()
}
func isOfflinePayment() -> Bool {
guard let paymentTypeId = amountHelper?.getPaymentData().paymentMethod?.paymentTypeId else {
return false
}
let id = amountHelper?.getPaymentData().paymentMethod?.id
return !PXPaymentTypes.isOnlineType(paymentTypeId: paymentTypeId, paymentMethodId: id)
}
func assignToCheckoutStore(programId: String? = nil) {
if let amountHelper = amountHelper {
PXCheckoutStore.sharedInstance.paymentDatas = [amountHelper.getPaymentData()]
if let splitAccountMoney = amountHelper.splitAccountMoney {
PXCheckoutStore.sharedInstance.paymentDatas.append(splitAccountMoney)
}
}
PXCheckoutStore.sharedInstance.validationProgramId = programId
PXCheckoutStore.sharedInstance.checkoutPreference = checkoutPreference
}
func cleanData() {
paymentResult = nil
businessResult = nil
instructionsInfo = nil
}
}
extension PXPaymentFlowModel {
func hasPluginPaymentScreen() -> Bool {
guard let paymentPlugin = paymentPlugin else {
return false
}
assignToCheckoutStore()
paymentPlugin.didReceive?(checkoutStore: PXCheckoutStore.sharedInstance)
let processorViewController = paymentPlugin.paymentProcessorViewController()
return processorViewController != nil
}
}
// MARK: Manage ESC
extension PXPaymentFlowModel {
func handleESCForPayment(status: String, statusDetails: String, errorPaymentType: String?) {
guard let token = amountHelper?.getPaymentData().getToken() else {
return
}
if let paymentStatus = PXPaymentStatus(rawValue: status),
paymentStatus == PXPaymentStatus.APPROVED {
// If payment was approved
if let esc = token.esc {
PXConfiguratorManager.escProtocol.saveESC(config: PXConfiguratorManager.escConfig, token: token, esc: esc)
}
} else {
guard let errorPaymentType = errorPaymentType else { return }
// If it has error Payment Type, check if the error was from a card
if let isCard = PXPaymentTypes(rawValue: errorPaymentType)?.isCard(), isCard {
if let ESCBlacklistedStatus = ESCBlacklistedStatus, ESCBlacklistedStatus.contains(statusDetails) {
PXConfiguratorManager.escProtocol.deleteESC(config: PXConfiguratorManager.escConfig, token: token, reason: .REJECTED_PAYMENT, detail: statusDetails)
}
}
}
}
}
extension PXPaymentFlowModel {
func generateIdempotecyKey() -> String {
return String(arc4random()) + String(Date().timeIntervalSince1970)
}
}
| mit | 1cbc49cb1f28f6659aba2761e7c4fdeb | 33.376289 | 168 | 0.659919 | 5.297061 | false | false | false | false |
abaca100/Nest | iOS-NestDK/ConditionCell.swift | 1 | 4977 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ConditionCell` displays characteristic and location conditions.
*/
import UIKit
import HomeKit
/// A `UITableViewCell` subclass that displays a trigger condition.
class ConditionCell: UITableViewCell {
/// A static, short date formatter.
static let dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .ShortStyle
dateFormatter.locale = NSLocale.currentLocale()
return dateFormatter
}()
/// Ignores the passed-in style and overrides it with .Subtitle.
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Subtitle, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
detailTextLabel?.textColor = UIColor.lightGrayColor()
accessoryType = .None
}
/// Required because we overwrote a designated initializer.
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
Sets the cell's text to represent a characteristic and target value.
For example, "Brightness → 60%"
Sets the subtitle to the service and accessory that this characteristic represents.
- parameter characteristic: The characteristic this cell represents.
- parameter targetValue: The target value from this action.
*/
func setCharacteristic(characteristic: HMCharacteristic, targetValue: AnyObject) {
let targetDescription = "\(characteristic.localizedDescription) → \(characteristic.localizedDescriptionForValue(targetValue))"
textLabel?.text = targetDescription
let contextDescription = NSLocalizedString("%@ in %@", comment: "Service in Accessory")
if let service = characteristic.service, accessory = service.accessory {
detailTextLabel?.text = String(format: contextDescription, service.name, accessory.name)
}
else {
detailTextLabel?.text = NSLocalizedString("Unknown Characteristic", comment: "Unknown Characteristic")
}
}
/**
Sets the cell's text to represent an ordered time with a set context string.
- parameter order: A `TimeConditionOrder` which will map to a localized string.
- parameter timeString: The localized time string.
- parameter contextString: A localized string describing the time type.
*/
private func setOrder(order: TimeConditionOrder, timeString: String, contextString: String) {
let formatString: String
switch order {
case .Before:
formatString = NSLocalizedString("Before %@", comment: "Before Time")
case .After:
formatString = NSLocalizedString("After %@", comment: "After Time")
case .At:
formatString = NSLocalizedString("At %@", comment: "At Time")
}
textLabel?.text = String(format: formatString, timeString)
detailTextLabel?.text = contextString
}
/**
Sets the cell's text to represent an exact time condition.
- parameter order: A `TimeConditionOrder` which will map to a localized string.
- parameter dateComponents: The date components of the exact time.
*/
func setOrder(order: TimeConditionOrder, dateComponents: NSDateComponents) {
let date = NSCalendar.currentCalendar().dateFromComponents(dateComponents)
let timeString = ConditionCell.dateFormatter.stringFromDate(date!)
setOrder(order, timeString: timeString, contextString: NSLocalizedString("Relative to Time", comment: "Relative to Time"))
}
/**
Sets the cell's text to represent a solar event time condition.
- parameter order: A `TimeConditionOrder` which will map to a localized string.
- parameter sunState: A `TimeConditionSunState` which will map to localized string.
*/
func setOrder(order: TimeConditionOrder, sunState: TimeConditionSunState) {
let timeString: String
switch sunState {
case .Sunrise:
timeString = NSLocalizedString("Sunrise", comment: "Sunrise")
case .Sunset:
timeString = NSLocalizedString("Sunset", comment: "Sunset")
}
setOrder(order, timeString: timeString , contextString: NSLocalizedString("Relative to sun", comment: "Relative to Sun"))
}
/// Sets the cell's text to indicate the given condition is not handled by the app.
func setUnknown() {
let unknownString = NSLocalizedString("Unknown Condition", comment: "Unknown Condition")
detailTextLabel?.text = unknownString
textLabel?.text = unknownString
}
}
| apache-2.0 | dbb211ff1f97dfe0161b333592eb787e | 41.853448 | 134 | 0.662442 | 5.597973 | false | false | false | false |
DarlingXIe/WeiBoProject | WeiBo/WeiBo/Classes/View/Main/XDLTabBar.swift | 1 | 2710 | //
// XDLTabBar.swift
// WeiBo
//
// Created by DalinXie on 16/9/11.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
class XDLTabBar: UITabBar {
//
var composeButtonClosure:(()->())?
override init(frame:CGRect){
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
backgroundImage = #imageLiteral(resourceName: "tabbar_background")
addSubview(composeButton)
}
override func layoutSubviews() {
super.layoutSubviews()
//set composeButton Width
composeButton.center = CGPoint(x: self.bounds.size.width * 0.5, y: self.bounds.size.height * 0.5)
//set index to change x of subviews
var index = 0
//calculate all subviews button's itemW
let itemW = UIScreen.main.bounds.size.width/5
//for in function--- to set postion of subviews
for subview in self.subviews{
//judge that the value of subview is "UITabBarButton"
if subview.isKind(of: NSClassFromString("UITabBarButton")!){
// according to index to calculate each button width
let itemX = CGFloat(index) * itemW
// update values of each button frame
subview.frame.origin.x = itemX
subview.frame.size.width = itemW
// index +1
index = index + 1
if index == 2{
index = index + 1
}
}
}
}
lazy var composeButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for:.highlighted)
button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
button.sizeToFit()
return button
}()
@objc private func composeButtonClick(){
composeButtonClosure?()
}
}
| mit | 43099964d712c6cfac5401eaa4d10b3e | 24.780952 | 118 | 0.527521 | 5.38171 | false | false | false | false |
sebastianludwig/Koloda | Pod/Classes/KolodaView/KolodaView.swift | 2 | 18197 | //
// KolodaView.swift
// TinderCardsSwift
//
// Created by Eugene Andreyev on 4/24/15.
// Copyright (c) 2015 Eugene Andreyev. All rights reserved.
//
import UIKit
import pop
public enum SwipeResultDirection {
case None
case Left
case Right
}
//Default values
private let defaultCountOfVisibleCards = 3
private let backgroundCardsTopMargin: CGFloat = 4.0
private let backgroundCardsScalePercent: CGFloat = 0.95
private let backgroundCardsLeftMargin: CGFloat = 8.0
private let backgroundCardFrameAnimationDuration: NSTimeInterval = 0.2
//Opacity values
private let alphaValueOpaque: CGFloat = 1.0
private let alphaValueTransparent: CGFloat = 0.0
private let alphaValueSemiTransparent: CGFloat = 0.7
//Animations constants
private let revertCardAnimationName = "revertCardAlphaAnimation"
private let revertCardAnimationDuration: NSTimeInterval = 1.0
private let revertCardAnimationToValue: CGFloat = 1.0
private let revertCardAnimationFromValue: CGFloat = 0.0
private let kolodaAppearScaleAnimationName = "kolodaAppearScaleAnimation"
private let kolodaAppearScaleAnimationFromValue = CGPoint(x: 0.1, y: 0.1)
private let kolodaAppearScaleAnimationToValue = CGPoint(x: 1.0, y: 1.0)
private let kolodaAppearScaleAnimationDuration: NSTimeInterval = 0.8
private let kolodaAppearAlphaAnimationName = "kolodaAppearAlphaAnimation"
private let kolodaAppearAlphaAnimationFromValue: CGFloat = 0.0
private let kolodaAppearAlphaAnimationToValue: CGFloat = 1.0
private let kolodaAppearAlphaAnimationDuration: NSTimeInterval = 0.8
public protocol KolodaViewDataSource:class {
func kolodaNumberOfCards(koloda: KolodaView) -> UInt
func kolodaViewForCardAtIndex(koloda: KolodaView, index: UInt) -> UIView
func kolodaViewForCardOverlayAtIndex(koloda: KolodaView, index: UInt) -> OverlayView?
}
public protocol KolodaViewDelegate:class {
func kolodaDidSwipedCardAtIndex(koloda: KolodaView,index: UInt, direction: SwipeResultDirection)
func kolodaDidRunOutOfCards(koloda: KolodaView)
func kolodaDidSelectCardAtIndex(koloda: KolodaView, index: UInt)
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool
}
public class KolodaView: UIView, DraggableCardDelegate {
public weak var dataSource: KolodaViewDataSource! {
didSet {
setupDeck()
}
}
public weak var delegate: KolodaViewDelegate?
private(set) public var currentCardNumber = 0
private(set) public var countOfCards = 0
var countOfVisibleCards = defaultCountOfVisibleCards
private var visibleCards = [DraggableCardView]()
private var animating = false
private var configured = false
//MARK: Lifecycle
override public func layoutSubviews() {
super.layoutSubviews()
if !self.configured {
if self.visibleCards.isEmpty {
reloadData()
} else {
layoutDeck()
}
self.configured = true
}
}
private func setupDeck() {
countOfCards = Int(dataSource!.kolodaNumberOfCards(self))
if countOfCards - currentCardNumber > 0 {
let countOfNeededCards = min(countOfVisibleCards, countOfCards - currentCardNumber)
for index in 0..<countOfNeededCards {
if let nextCardContentView = dataSource?.kolodaViewForCardAtIndex(self, index: UInt(index)) {
let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index)))
nextCardView.delegate = self
nextCardView.alpha = index == 0 ? alphaValueOpaque : alphaValueSemiTransparent
nextCardView.userInteractionEnabled = index == 0
let overlayView = overlayViewForCardAtIndex(UInt(index))
nextCardView.configure(nextCardContentView, overlayView: overlayView!)
visibleCards.append(nextCardView)
index == 0 ? addSubview(nextCardView) : insertSubview(nextCardView, belowSubview: visibleCards[index - 1])
}
}
}
}
private func layoutDeck() {
for (index, card) in enumerate(self.visibleCards) {
card.frame = frameForCardAtIndex(UInt(index))
}
}
//MARK: Frames
private func frameForCardAtIndex(index: UInt) -> CGRect {
let bottomOffset:CGFloat = 0
let topOffset = backgroundCardsTopMargin * CGFloat(self.countOfVisibleCards - 1)
let xOffset = backgroundCardsLeftMargin * CGFloat(index)
let scalePercent = backgroundCardsScalePercent
let width = CGRectGetWidth(self.frame) * pow(scalePercent, CGFloat(index))
let height = (CGRectGetHeight(self.frame) - bottomOffset - topOffset) * pow(scalePercent, CGFloat(index))
let multiplier: CGFloat = index > 0 ? 1.0 : 0.0
let previousCardFrame = index > 0 ? frameForCardAtIndex(max(index - 1, 0)) : CGRectZero
let yOffset = (CGRectGetHeight(previousCardFrame) - height + previousCardFrame.origin.y + backgroundCardsTopMargin) * multiplier
let frame = CGRect(x: xOffset, y: yOffset, width: width, height: height)
return frame
}
private func moveOtherCardsWithFinishPercent(percent: CGFloat) {
if visibleCards.count > 1 {
for index in 1..<visibleCards.count {
let previousCardFrame = frameForCardAtIndex(UInt(index - 1))
var frame = frameForCardAtIndex(UInt(index))
let distanceToMoveY: CGFloat = (frame.origin.y - previousCardFrame.origin.y) * (percent / 100)
frame.origin.y -= distanceToMoveY
let distanceToMoveX: CGFloat = (previousCardFrame.origin.x - frame.origin.x) * (percent / 100)
frame.origin.x += distanceToMoveX
let widthScale = (previousCardFrame.size.width - frame.size.width) * (percent / 100)
let heightScale = (previousCardFrame.size.height - frame.size.height) * (percent / 100)
frame.size.width += widthScale
frame.size.height += heightScale
let card = visibleCards[index]
card.frame = frame
card.layoutIfNeeded()
//For fully visible next card, when moving top card
if index == 1 {
card.alpha = alphaValueOpaque
}
}
}
}
//MARK: Animations
public func applyAppearAnimation() {
userInteractionEnabled = false
animating = true
let kolodaAppearScaleAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
kolodaAppearScaleAnimation.duration = kolodaAppearScaleAnimationDuration
kolodaAppearScaleAnimation.fromValue = NSValue(CGPoint: kolodaAppearScaleAnimationFromValue)
kolodaAppearScaleAnimation.toValue = NSValue(CGPoint: kolodaAppearScaleAnimationToValue)
kolodaAppearScaleAnimation.completionBlock = {
(_, _) in
self.userInteractionEnabled = true
self.animating = false
}
let kolodaAppearAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
kolodaAppearAlphaAnimation.fromValue = NSNumber(float: Float(kolodaAppearAlphaAnimationFromValue))
kolodaAppearAlphaAnimation.toValue = NSNumber(float: Float(kolodaAppearAlphaAnimationToValue))
kolodaAppearAlphaAnimation.duration = kolodaAppearAlphaAnimationDuration
pop_addAnimation(kolodaAppearAlphaAnimation, forKey: kolodaAppearAlphaAnimationName)
pop_addAnimation(kolodaAppearScaleAnimation, forKey: kolodaAppearScaleAnimationName)
}
func applyRevertAnimation(card: DraggableCardView) {
animating = true
let firstCardAppearAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
firstCardAppearAnimation.toValue = NSNumber(float: Float(revertCardAnimationToValue))
firstCardAppearAnimation.fromValue = NSNumber(float: Float(revertCardAnimationFromValue))
firstCardAppearAnimation.duration = revertCardAnimationDuration
firstCardAppearAnimation.completionBlock = {
(_, _) in
self.animating = false
}
card.pop_addAnimation(firstCardAppearAnimation, forKey: revertCardAnimationName)
}
//MARK: DraggableCardDelegate
func cardDraggedWithFinishPercent(card: DraggableCardView, percent: CGFloat) {
animating = true
moveOtherCardsWithFinishPercent(percent)
}
func cardSwippedInDirection(card: DraggableCardView, direction: SwipeResultDirection) {
swipedAction(direction)
}
func cardWasReset(card: DraggableCardView) {
if visibleCards.count > 1 {
UIView.animateWithDuration(0.2,
delay: 0.0,
options: .CurveLinear,
animations: {
self.moveOtherCardsWithFinishPercent(0)
},
completion: {
_ in
self.animating = false
for index in 1..<self.visibleCards.count {
let card = self.visibleCards[index]
card.alpha = alphaValueSemiTransparent
}
})
} else {
animating = false
}
}
func cardTapped(card: DraggableCardView) {
let index = currentCardNumber + find(visibleCards, card)!
delegate?.kolodaDidSelectCardAtIndex(self, index: UInt(index))
}
//MARK: Private
private func clear() {
currentCardNumber = 0
for card in visibleCards {
card.removeFromSuperview()
}
visibleCards.removeAll(keepCapacity: true)
}
private func overlayViewForCardAtIndex(index: UInt) -> OverlayView? {
return dataSource.kolodaViewForCardOverlayAtIndex(self, index: index)
}
//MARK: Actions
private func swipedAction(direction: SwipeResultDirection) {
animating = true
visibleCards.removeAtIndex(0)
currentCardNumber++
let shownCardsCount = currentCardNumber + countOfVisibleCards
if shownCardsCount - 1 < countOfCards {
if let dataSource = self.dataSource {
let lastCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(shownCardsCount - 1))
let lastCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(shownCardsCount - 1))
let lastCardFrame = frameForCardAtIndex(UInt(currentCardNumber + visibleCards.count))
let lastCardView = DraggableCardView(frame: lastCardFrame)
lastCardView.hidden = true
lastCardView.userInteractionEnabled = true
lastCardView.configure(lastCardContentView, overlayView: lastCardOverlayView)
lastCardView.delegate = self
insertSubview(lastCardView, belowSubview: visibleCards.last!)
visibleCards.append(lastCardView)
}
}
if !visibleCards.isEmpty {
for (index, currentCard) in enumerate(visibleCards) {
let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame)
frameAnimation.duration = backgroundCardFrameAnimationDuration
if index != 0 {
currentCard.alpha = alphaValueSemiTransparent
} else {
frameAnimation.completionBlock = {(_, _) in
self.visibleCards.last?.hidden = false
self.animating = false
self.delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(self.currentCardNumber - 1), direction: direction)
}
currentCard.alpha = alphaValueOpaque
}
currentCard.userInteractionEnabled = index == 0
frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index)))
currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation")
}
} else {
delegate?.kolodaDidSwipedCardAtIndex(self, index: UInt(currentCardNumber - 1), direction: direction)
animating = false
self.delegate?.kolodaDidRunOutOfCards(self)
}
}
public func revertAction() {
if currentCardNumber > 0 && animating == false {
if countOfCards - currentCardNumber >= countOfVisibleCards {
if let lastCard = visibleCards.last {
lastCard.removeFromSuperview()
visibleCards.removeLast()
}
}
currentCardNumber--
if let dataSource = self.dataSource {
let firstCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber))
let firstCardOverlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber))
let firstCardView = DraggableCardView()
firstCardView.alpha = alphaValueTransparent
firstCardView.configure(firstCardContentView, overlayView: firstCardOverlayView)
firstCardView.delegate = self
addSubview(firstCardView)
visibleCards.insert(firstCardView, atIndex: 0)
firstCardView.frame = frameForCardAtIndex(0)
applyRevertAnimation(firstCardView)
}
for index in 1..<visibleCards.count {
let currentCard = visibleCards[index]
let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame)
frameAnimation.duration = backgroundCardFrameAnimationDuration
currentCard.alpha = alphaValueSemiTransparent
frameAnimation.toValue = NSValue(CGRect: frameForCardAtIndex(UInt(index)))
currentCard.userInteractionEnabled = false
currentCard.pop_addAnimation(frameAnimation, forKey: "frameAnimation")
}
}
}
private func loadMissingCards(missingCardsCount: Int) {
if missingCardsCount > 0 {
let cardsToAdd = min(missingCardsCount, countOfCards - currentCardNumber)
for index in 1...cardsToAdd {
let nextCardIndex = countOfVisibleCards - cardsToAdd + index - 1
let nextCardView = DraggableCardView(frame: frameForCardAtIndex(UInt(index)))
nextCardView.alpha = alphaValueSemiTransparent
nextCardView.delegate = self
visibleCards.append(nextCardView)
insertSubview(nextCardView, belowSubview: visibleCards[index - 1])
}
}
reconfigureCards()
}
private func reconfigureCards() {
for index in 0..<visibleCards.count {
if let dataSource = self.dataSource {
let currentCardContentView = dataSource.kolodaViewForCardAtIndex(self, index: UInt(currentCardNumber + index))
let overlayView = dataSource.kolodaViewForCardOverlayAtIndex(self, index: UInt(currentCardNumber + index))
let currentCard = visibleCards[index]
currentCard.configure(currentCardContentView, overlayView: overlayView)
}
}
}
public func reloadData() {
countOfCards = Int(dataSource!.kolodaNumberOfCards(self))
let missingCards = min(countOfVisibleCards - visibleCards.count, countOfCards - (currentCardNumber + 1))
if countOfCards == 0 {
return
}
if currentCardNumber == 0 {
clear()
}
if countOfCards - (currentCardNumber + visibleCards.count) > 0 {
if !visibleCards.isEmpty {
loadMissingCards(missingCards)
} else {
setupDeck()
layoutDeck()
if let shouldApply = delegate?.kolodaShouldApplyAppearAnimation(self) where shouldApply == true {
applyAppearAnimation()
}
}
} else {
reconfigureCards()
}
}
public func swipe(direction: SwipeResultDirection) {
if (animating == false) {
if let frontCard = visibleCards.first {
animating = true
switch direction {
case SwipeResultDirection.None:
return
case SwipeResultDirection.Left:
frontCard.swipeLeft()
case SwipeResultDirection.Right:
frontCard.swipeRight()
}
if visibleCards.count > 1 {
let nextCard = visibleCards[1]
nextCard.alpha = alphaValueOpaque
}
}
}
}
public func resetCurrentCardNumber() {
clear()
reloadData()
}
}
| mit | 16fc1c9fd5e842ea4324f300c7d0160a | 36.989562 | 136 | 0.59823 | 6.24897 | false | false | false | false |
Tantalum73/PermissionController | PermissionController/PermissionController.swift | 1 | 12904 | //
// PermissionController.swift
// ClubNews
//
// Created by Andreas Neusüß on 28.04.15.
// Copyright (c) 2015 Cocoawah. All rights reserved.
//
import UIKit
import MapKit
import EventKit
import UserNotifications
/**
Enum to express types of permission in that you are interested in.
- Location: Location permission
- Calendar: Calendar permission
- Notification: Notification permission
*/
public enum PermissionInterestedIn {
case location, calendar, notification
}
/// Exposes the interface for persenting the permission dialog and handles the actions.
open class PermissionController: NSObject, CLLocationManagerDelegate {
fileprivate var locationManager : CLLocationManager?
fileprivate var eventStore : EKEventStore?
fileprivate var currentViewControllerView: UIView?
fileprivate var calendarSuccessBlock : (()->())?
fileprivate var calendarFailureBlock: (()->())?
fileprivate var successBlock : (()->())?
fileprivate var failureBlock: (()->())?
/**
Use this method to present the permission view.
The user will be asked to give permissions by a dialog.
When the user already granted a permission, the button is not enabled and a checkmark reflects it.
By specifying a `interestedInPermission` you register the completion and failure blocks to be executed when the user finfished the interaction with the dialog. If the operation you want to start depends on a permission, you can continue or cancel it in those blocks if you registered in that permission.
- returns: Bool that is true, when requested permission is already granted.
If other permissions are missing, the PermissionView will be displayed and false is returned.
- parameter viewController: The UIViewController on which the PermissionView shall be presented.
- parameter interestedInPermission: Indicates in which action the reuest is interested in. This value decides, whether the permission requesting was successful or not and therefore which completion block will be called. If you are only interested in the location permission to continue an operation, you can rely on the successBlock/failureBlock to be executed after the user was asked and continue or cancel the operation.
- parameter successBlock: This block will be executed on the main thread if the user dismissed the PermissionView and gave the desired permission.
- parameter failureBlock: This block will be executed on the main thread if the user dismissed the PermissionView and did not gave the desired permission.
*/
open func presentPermissionViewIfNeededInViewController(_ viewController: UIViewController, interestedInPermission: PermissionInterestedIn?, successBlock: (()->())?, failureBlock: (()->())? ) -> Bool {
let status = stateOfPermissions()
let allPermissionsGranted = status.permissionLocationGranted && status.permissionCalendarGranted && status.permissionNotificationGranted
self.successBlock = successBlock
self.failureBlock = failureBlock
self.locationManager = CLLocationManager()
self.locationManager?.delegate = self
if !allPermissionsGranted {
//presenting
let explanationViewController = ModalExplanationViewController()
explanationViewController.permissionActionHandler = self
explanationViewController.presentExplanationViewControllerOnViewController(viewController, nameOfNibs: ["PermissionView"], completion: { (_: Bool) -> () in
if let interest = interestedInPermission {
let currentState = self.stateOfPermissions()
DispatchQueue.main.async(execute: {
//TODO: maybe in the future: accept more than one desiredPermission
switch interest {
case .location :
if currentState.permissionLocationGranted {
successBlock?()
}
else {
failureBlock?()
}
break
case .calendar:
if currentState.permissionCalendarGranted {
successBlock?()
}
else {
failureBlock?()
}
break
case .notification:
if currentState.permissionNotificationGranted {
successBlock?()
}
else {
failureBlock?()
}
break
}
})
}
})
//return something so that the calling code an continue.
return false
}
successBlock?()
return true
}
//MARK: - CLLocationManagerDelegate
/**
Receives CLLocationManagerDelegate authorization calls and writes them to the `NSUserDefaults`. Then, a notification is posted that tells the displayed dialog to update the UI accordingly.
*/
open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
let defaults = UserDefaults.standard
switch status {
case .authorizedAlways:
defaults.set(true, forKey: "LocationPermission")
defaults.set(false, forKey: "LocationPermissionAskedOnce")
break
case .authorizedWhenInUse:
defaults.set(false, forKey: "LocationPermission")
defaults.set(false, forKey: "LocationPermissionAskedOnce")
break
case .denied:
defaults.set(false, forKey: "LocationPermission")
defaults.set(true, forKey: "LocationPermissionAskedOnce")
break
case .notDetermined:
defaults.set(false, forKey: "LocationPermission")
defaults.set(false, forKey: "LocationPermissionAskedOnce")
break
case .restricted:
defaults.set(false, forKey: "LocationPermission")
defaults.set(true, forKey: "LocationPermissionAskedOnce")
break
}
defaults.synchronize()
NotificationCenter.default.post(name: Notification.Name(rawValue: "LocalizationAuthorizationStatusChanged"), object: manager)
NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil)
}
/**
Open the Settings.app on the users device because he already declined the permission and it needs to be changed from there.
*/
fileprivate func sendUserToSettings() {
let url = URL(string: UIApplicationOpenSettingsURLString)!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
}
extension PermissionController: PermissionAskingProtocol {
func stateOfPermissions() -> StatusOfPermissions {
var status = StatusOfPermissions()
let defaults = UserDefaults.standard
if defaults.bool(forKey: "LocationPermission") == true || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways {
status.permissionLocationGranted = true
}
if UserDefaults.standard.bool(forKey: "CalendarPermission") == true || EKEventStore.authorizationStatus(for: EKEntityType.event) == EKAuthorizationStatus.authorized {
status.permissionCalendarGranted = true
}
let registeredNotificationSettigns = UIApplication.shared.currentUserNotificationSettings
if registeredNotificationSettigns?.types.rawValue != 0 || defaults.bool(forKey: "NotificationPermission") == true {
//Some notifications are registered or already asked (probably both)
status.permissionNotificationGranted = true
}
return status
}
func permissionButtonLocationPressed() {
let status = CLLocationManager.authorizationStatus()
let userWasAskedOnce = UserDefaults.standard.bool(forKey: "LocationPermissionAskedOnce")
if userWasAskedOnce && status != CLAuthorizationStatus.authorizedAlways && status != CLAuthorizationStatus.authorizedWhenInUse {
sendUserToSettings()
return
}
self.locationManager?.requestAlwaysAuthorization()
}
func permissionButtonCalendarPressed() {
let status = EKEventStore.authorizationStatus(for: EKEntityType.event)
if status == EKAuthorizationStatus.denied {
sendUserToSettings()
return
}
UserDefaults.standard.set(true, forKey: "CalendarPermissionWasAskedOnce")
self.eventStore = EKEventStore()
let accessCompletionHandler : EKEventStoreRequestAccessCompletionHandler = {(granted:Bool , error: Error?) in
let defaults = UserDefaults.standard
if granted {
defaults.set(true, forKey: "CalendarPermission")
}
else {
defaults.set(false, forKey: "CalendarPermission")
}
defaults.synchronize()
DispatchQueue.main.async(execute: {
NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil)
})
}
self.eventStore?.requestAccess(to: .event, completion: accessCompletionHandler)
}
func permissionButtonNotificationPressed() {
// NSNotificationCenter.defaultCenter().postNotificationName("AuthorizationStatusChanged", object: nil)
let defaults = UserDefaults.standard
let registeredNotificationSettigns = UIApplication.shared.currentUserNotificationSettings
if registeredNotificationSettigns?.types.rawValue == 0 && defaults.bool(forKey: "NotificationPermissionWasAskedOnce") == true {
//Some notifications are registered or already asked (probably both)
sendUserToSettings()
return
}
defaults.set(true, forKey: "NotificationPermissionWasAskedOnce")
//iOS 10 changed this a little
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted, error) in
if(granted){
let defaults = UserDefaults.standard
defaults.set(true, forKey: "NotificationPermission")
}
DispatchQueue.main.async(execute: {
NotificationCenter.default.post(name: Notification.Name(rawValue: "AuthorizationStatusChanged"), object: nil)
})
}
} else {
let desiredNotificationSettigns = UIUserNotificationSettings(types: [UIUserNotificationType.alert, .badge, .sound] , categories: nil)
UIApplication.shared.registerUserNotificationSettings(desiredNotificationSettigns)
}
}
}
extension UIColor {
/**
returns UIColor from given hex value.
- parameter hex: the hex value to be converted to uicolor
- parameter alpha: the alpha value of the color
- returns: the UIColor corresponding to the given hex and alpha value
*/
class func colorFromHex (_ hex: Int, alpha: Double = 1.0) -> UIColor {
let red = Double((hex & 0xFF0000) >> 16) / 255.0
let green = Double((hex & 0xFF00) >> 8) / 255.0
let blue = Double((hex & 0xFF)) / 255.0
let color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) )
return color
}
/**
returns UIColor from rgb value.
- parameter red: the r value
- parameter green: the g value
- parameter blue: the b value
*/
class func colorFromRGB (_ red: Int, green: Int, blue: Int) -> UIColor {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
return self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
}
| mit | 1f69707ef9bc51e03c3e887bf6cc359b | 39.829114 | 423 | 0.621454 | 5.832731 | false | false | false | false |
harenbrs/swix | swixUseCases/swix-OSX/swix/matrix/helper-functions.swift | 2 | 2334 | //
// helper-functions.swift
// swix
//
// Created by Scott Sievert on 8/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
func println(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
print(prefix)
var suffix = ", "
var pre:String
var post:String
var printedSpacer = false
for i in 0..<x.shape.0{
// pre and post nice -- internal variables
if i==0 {pre = ""}
else {pre = " "}
if i==x.shape.0-1{post=""}
else {post = "],\n"}
if printWholeMatrix || x.shape.0 < 16 || i<4-1 || i>x.shape.0-4{
print(x[i, 0..<x.shape.1], prefix:pre, postfix:post, format: format, printWholeMatrix:printWholeMatrix)
}
else if printedSpacer==false{
printedSpacer=true
println(" ...,")
}
}
print(postfix)
print(newline)
}
func print(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printWholeMatrix:printWholeMatrix)
}
func argwhere(idx: matrix) -> ndarray{
return argwhere(idx.flat)
}
func flipud(x:matrix)->matrix{
var y = x.copy()
CVWrapper.flip(!x, into:!y, how:"ud", m:x.shape.0.cint, n:x.shape.1.cint)
return y
}
func fliplr(x:matrix)->matrix{
var y = x.copy()
CVWrapper.flip(!x, into:!y, how:"lr", m:x.shape.0.cint, n:x.shape.1.cint)
return y
}
func transpose (x: matrix) -> matrix{
var m = x.shape.1
var n = x.shape.0
var y = zeros((m, n))
vDSP_mtransD(!x, 1.cint, !y, 1.cint, vDSP_Length(m), vDSP_Length(n))
return y
}
func write_csv(x:matrix, #filename:String, prefix:String=S2_PREFIX){
var seperator=","
var str = ""
for i in 0..<x.shape.0{
for j in 0..<x.shape.1{
seperator = j == x.shape.1-1 ? "" : ","
str += String(format: "\(x[i, j])"+seperator)
}
str += "\n"
}
var error:NSError?
str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding, error: &error)
if let error=error{
println("File probably wasn't recognized \n\(error)")
}
}
| mit | 4acf4c5b017b08fb48259ea1ed0c3956 | 30.972603 | 143 | 0.584833 | 3.232687 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Rows/Common/DecimalFormatter.swift | 1 | 1295 | //
// DecimalFormatter.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright © 2016 Xmartlabs. All rights reserved.
//
import Foundation
open class DecimalFormatter : NumberFormatter, FormatterProtocol {
public override init() {
super.init()
locale = .current
numberStyle = .decimal
minimumFractionDigits = 2
maximumFractionDigits = 2
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
guard obj != nil else { return }
let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
}
open func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.position(from: position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position
}
}
| mit | 8e4f2478428356a6f72aa35e95da0db0 | 37.058824 | 167 | 0.681607 | 4.757353 | false | false | false | false |
authme-org/authme | authme-iphone/AuthMe/Src/MasterPassword.swift | 1 | 25117 | /*
*
* Copyright 2015 Berin Lautenbach
*
* 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.
*
*/
//
// MasterPassword.swift
// AuthMe
//
// Created by Berin Lautenbach on 2/03/2015.
// Copyright (c) 2015 Berin Lautenbach. All rights reserved.
//
import Foundation
import CoreData
import UIKit
import LocalAuthentication
// MARK: Callback protocol
protocol MasterPasswordCallback {
func onServiceInitialised()
func onServiceDeinitialised()
}
class MasterPassword : NSObject {
let _AUTHME_DEVICE_RSA_KEY_TAG = "com.authme.iphone.new2"
let _AUTHME_DEVICE_PASSWORD_TAG = "com.authme.iphone.password"
let _AUTHME_RSA_KEY_LENGTH : Int32 = 256 /* Key size in bytes. 256 = 2048 bit key */
let masterPasswordSalt : [UInt8] = [0x56, 0x14, 0x4f, 0x01, 0x5b, 0x8d, 0x44, 0x23] as [UInt8]
let configCheckArray : [UInt8] = [0x6a, 0x6a, 0x6a] as [UInt8]
enum PasswordState : Int {
case open_STORE
case create_PASS1
case create_PASS2
}
let logger = Log()
var managedObjectContext: NSManagedObjectContext? = nil
var cachedConfig: Configuration?
var passwordState = PasswordState.open_STORE
var passwordFirstPass = ""
var storePassword = ""
var useTouchID = false
var RSAGenAlert: UIAlertController? = nil
var serviceActive = false
var callbacks : [MasterPasswordCallback] = []
// Keys
var deviceRSAKey : RSAKey? = nil
var storeKey : AESKey? = nil
var serviceKey : AESKey? = nil
var serviceKeyPair : RSAKey? = nil
var authController: AuthListController? = nil
override init() {
logger.log(.debug, message: "Master Password initialising")
}
// MARK: Startup loading
func requestStorePassword(_ prompt: String) {
// Use an alert dialog to get password
let alert = UIAlertController(title: "Master Password",
message: prompt, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(UIAlertAction) in
self.passwordEntered((alert.textFields![0] as UITextField).text!)
}))
alert.addTextField(configurationHandler: {(textField: UITextField) in
textField.placeholder = "Password"
})
UIApplication.shared.keyWindow!.rootViewController!.present(alert, animated: true, completion: nil)
}
func startup() {
logger.log(.debug, message: "Master password commencing load")
/* Open the master key data */
// First load the Store Check Value so we can validate the password
let request = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName: "Configuration", in: managedObjectContext!)
request.entity = entity
// Fetch
var fetchResult : [AnyObject] = []
do {
fetchResult = try managedObjectContext!.fetch(request) as [AnyObject]!
}
catch _ {
}
/* Can we fetch the required class from the store? */
if fetchResult.count == 0 {
// Oh dear - need to create from scratch
logger.log(.info, message: "Creating default configuration")
cachedConfig = NSEntityDescription.insertNewObject(forEntityName: "Configuration", into: managedObjectContext!) as? Configuration
do {
try managedObjectContext?.save()
} catch _ {
}
}
else {
cachedConfig = (fetchResult[0] as! Configuration)
}
// Load the configuration up
AppConfiguration.getInstance().managedObjectContext = managedObjectContext
// Find out if we have a TouchID that we want to enable
let context = LAContext()
let haveTouchId = context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil)
// Now load the password
if (cachedConfig!.checkString != nil) {
passwordState = .open_STORE
if haveTouchId && (cachedConfig!.useTouchID == NSNumber(value: 1 as Int32)) {
requestTouchIDPassword()
}
else {
requestStorePassword("Open Store - Enter Password")
}
}
else {
passwordState = .create_PASS1
if haveTouchId {
requestTouchIDSetup()
}
else {
requestStorePassword("Initialise Store - Enter Password")
}
}
}
func requestTouchIDSetup() {
// Use an alert dialog to ask the user whether to use TouchID
let alert = UIAlertController(title: "Use Touch ID?",
message: "Touch ID is active on this device. Do you wish to use your fingerprint to secure this app?\n\nNOTE: You will still enter a password that can also be used in an emergency.",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(UIAlertAction) in
self.useTouchID = true
self.requestStorePassword("Initialise Store - Enter Password")
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: {(UIAlertAction) in
self.requestStorePassword("Initialise Store - Enter Password")
}))
UIApplication.shared.keyWindow!.rootViewController!.present(alert, animated: true, completion: nil)
}
func storePasswordToTouchID() {
let keyChainStore = KeyChainPassword(identifier: _AUTHME_DEVICE_PASSWORD_TAG)
keyChainStore?.setPassword(storePassword)
if !(keyChainStore?.storeKey())! {
logger.log(.warn, message: "Error storing password to keychain")
useTouchID = false
}
}
func requestTouchIDPassword() {
let keyChainStore = KeyChainPassword(identifier: _AUTHME_DEVICE_PASSWORD_TAG)
if (keyChainStore?.loadKey())! {
storePassword = (keyChainStore?.getPassword())!
logger.log(.debug, message: "Got Key: \(storePassword)")
if !checkStore() {
// We failed to get the correct password!
// Invalidate current keys and reset
//memset(key, 0, _AUTHME_ENCRYPT_KEY_LENGTH);
storePassword = ""
requestStorePassword("Touch ID failed to load - Enter Password")
return
}
startInit()
}
else {
logger.log(.warn, message: "Error loading password from Touch ID")
requestStorePassword("Open Store - Enter Password")
}
}
func passwordEntered(_ password: String) {
logger.log(.finest, message: "Password = \(password)")
// First of all - did someone type "RESET!" to get this to reset?
if password == "RESET!" {
logger.log(.debug, message: "User requested database reset")
if let persistentStoreCoordinator = managedObjectContext?.persistentStoreCoordinator {
// Do the shut down of the store
var errorCode : NSError?
if let store = persistentStoreCoordinator.persistentStores.last as NSPersistentStore? {
do {
try persistentStoreCoordinator.remove(store)
logger.log(.debug, message: "Store removed OK")
} catch let error as NSError {
errorCode = error
logger.log(.debug, message: "Store removal Error: \(errorCode as Optional), \(errorCode?.userInfo as Optional)");
}
// Now delete the file
// FIXME: dirty. If there are many stores...
// Delete file
if FileManager.default.fileExists(atPath: store.url!.path) {
do {
try FileManager.default.removeItem(atPath: store.url!.path)
logger.log(.debug, message:"Unresolved error \(errorCode as Optional), \(errorCode?.userInfo as Optional)")
} catch let error as NSError {
errorCode = error
logger.log(.debug, message: "Store file deleted OK")
}
}
}
}
abort();
}
// Is this first entry or later?
switch passwordState {
case .create_PASS1:
passwordFirstPass = password
// Now load password screen again
requestStorePassword("Initialise Store - Repeat Password")
passwordState = .create_PASS2
return
case .create_PASS2:
// This is second time entered - check and done!
if passwordFirstPass == password {
storePassword = password
logger.log(.debug, message: "Initial entry of password succeeded")
if useTouchID {
logger.log(.debug, message: "Storing password to keychain")
storePasswordToTouchID()
}
// Use the password to build the
createStore()
return
}
else {
logger.log(.debug, message: "Initial entry of password failed")
passwordFirstPass = ""
passwordState = .create_PASS1
requestStorePassword("Initialise Mismatch - Enter Password")
return
}
case .open_STORE:
storePassword = password
// Now validate
if !checkStore() {
// We failed to get the correct password!
// Invalidate current keys and reset
//memset(key, 0, _AUTHME_ENCRYPT_KEY_LENGTH);
storePassword = ""
requestStorePassword("Incorrect Password - Enter Password")
return
}
}
startInit()
}
// MARK: Store management
@objc func createStoreWorker() {
/* Used to generate the RSA key in the background and then switch back to the
* main thread to close the alert window
*/
logger.log(.debug, message:"rsaGEnThreadMain now generating keys")
if deviceRSAKey != nil {
deviceRSAKey!.destroy(true)
deviceRSAKey = nil;
}
deviceRSAKey = RSAKey(identifier: _AUTHME_DEVICE_RSA_KEY_TAG)
if !deviceRSAKey!.generate(_AUTHME_RSA_KEY_LENGTH * 8) {
logger.log(.warn, message: "Error generating RSA key");
return;
}
logger.log(.debug, message: "ceateStoreWorker creating configuration");
/* Create the AES wrapper using the password */
let pwKey = AESKey()
pwKey.setKeyFromPassword(storePassword, withSalt: Data(bytes: UnsafePointer<UInt8>(masterPasswordSalt), count: 8), ofLength: 8)
/* Create the store key */
storeKey = AESKey()
if !storeKey!.generateKey() {
logger.log(.warn, message: "Error generating store key")
return
}
/* Encrypt the check value, RSA Key pair and the store key to save */
let encodedCheckValue = storeKey!.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3)
let rawStoreKey = Data(bytes: UnsafePointer<UInt8>(storeKey!.key), count: 32)
let encryptedStoreKey = pwKey.encrypt(rawStoreKey, plainLength: 32)
let rawPublicKey = deviceRSAKey?.getPublicKey()
let rawPrivateKey = deviceRSAKey?.getPrivateKey()
let encryptedPrivateKey = storeKey!.encrypt(rawPrivateKey)
let checkStringRSA = deviceRSAKey?.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3)
// Take the encoded result and store
cachedConfig!.checkString = encodedCheckValue
cachedConfig!.nextId = NSNumber(value: 1 as Int32)
cachedConfig!.storeKey = encryptedStoreKey
cachedConfig!.deviceKeyPrivate = encryptedPrivateKey
cachedConfig!.deviceKeyPublic = rawPublicKey
cachedConfig!.checkStringRSA = checkStringRSA
cachedConfig!.useTouchID = NSNumber(value: useTouchID ? 1 : 0 as Int32)
cachedConfig!.deviceUUID = UIDevice.current.identifierForVendor!.uuidString
do {
try managedObjectContext!.save()
} catch _ {
logger.log(.error, message:"Problem saving the configuration")
abort();
}
logger.log(.debug, message: "createStoreWorker finalising");
UIApplication.shared.keyWindow!.rootViewController!.dismiss(animated: true, completion: nil)
DispatchQueue.main.async(execute: {self.startInit()} )
}
func startInit() {
// Only get here if things are OK
let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
let initialiser = AuthMeServiceInitialiser()
initialiser.doInit()
}
func createStore() {
/* This takes a lot of CPU so we put up a message with and delay the work
* while it goes up */
//[self performSelector:@selector(createStoreWorker) withObject:nil afterDelay:.5];
logger.log(.debug, message: "Starting RSA")
RSAGenAlert = UIAlertController(title: "Generating Key",
message: "Generating RSA Key\nPlease wait...", preferredStyle: UIAlertControllerStyle.alert)
let alertFrame = RSAGenAlert!.view.frame
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
activityIndicator.frame = CGRect(x: 125,y: alertFrame.size.height+115, width: 30,height: 30);
activityIndicator.isHidden = false;
activityIndicator.contentMode = UIViewContentMode.center
activityIndicator.startAnimating()
RSAGenAlert!.view.addSubview(activityIndicator)
UIApplication.shared.keyWindow!.rootViewController!.present(RSAGenAlert!, animated: true, completion: nil)
let createStoreWorkerThread = Thread(target: self, selector: #selector(MasterPassword.createStoreWorker), object: nil)
createStoreWorkerThread.start()
}
func checkStore() -> Bool {
/* Know we have all the basic store values - need to validate them using the entered password */
let pwKey = AESKey()
pwKey.setKeyFromPassword(storePassword, withSalt: Data(bytes: UnsafePointer<UInt8>(masterPasswordSalt), count: 8), ofLength: 8)
/* Can we load the store key? */
if let decryptedStoreKey = pwKey.decrypt(cachedConfig!.storeKey!, cipherLength: 0) {
// Decrypt worked for store Key
storeKey = AESKey()
if storeKey!.loadKey(decryptedStoreKey as Data!) {
// Key loaded OK - check the check value
if let decryptedCheckValue = storeKey?.decrypt(cachedConfig!.checkString!, cipherLength: 0) {
var good = true
let checkBytes = decryptedCheckValue.bytes.bindMemory(to: UInt8.self, capacity: decryptedCheckValue.length)
for i in 0..<configCheckArray.count {
if configCheckArray[i] != checkBytes[i] {
good = false
}
}
if good {
// Load the RSA Key
logger.log(.debug, message:"Loading RSA ley")
if deviceRSAKey != nil {
deviceRSAKey!.destroy(true)
deviceRSAKey = nil;
}
deviceRSAKey = RSAKey(identifier: _AUTHME_DEVICE_RSA_KEY_TAG)
// This is an internal test - we don't want the keys persisting
// in the keychain
if deviceRSAKey!.loadKeysFromKeychain() {
// Want to make sure this *NEVER* happens
logger.log(.error, message: "Error KEY FOUND IN KEY CHAIN");
abort();
//return false
}
// Now do decrypts against check values and then do an
// encrypt/decrypt to see it works
good = false
if let decryptedPrivateKey = storeKey?.decrypt(cachedConfig!.deviceKeyPrivate!, cipherLength: 0) {
if deviceRSAKey!.loadPrivateKey(NSString(data: decryptedPrivateKey as Data, encoding: String.Encoding.utf8.rawValue)! as String) {
if deviceRSAKey!.loadPublicKey(cachedConfig!.deviceKeyPublic) {
logger.log(.debug, message: "RSA Key loaded")
// Quick internal tests
if let decRSACheck = deviceRSAKey?.decrypt(cachedConfig!.checkStringRSA) {
let decRSACheckBytes = (decRSACheck as NSData).bytes.bindMemory(to: UInt8.self, capacity: decRSACheck.count)
let encTest = deviceRSAKey?.encrypt(Data(bytes: UnsafePointer<UInt8>(configCheckArray), count: 3), plainLength: 3)
if let decTest = deviceRSAKey?.decrypt(encTest) {
let decTestBytes = (decTest as NSData).bytes.bindMemory(to: UInt8.self, capacity: decTest.count)
good = true
for i in 0..<configCheckArray.count {
if (configCheckArray[i] != checkBytes[i]) ||
(configCheckArray[i] != decRSACheckBytes[i]) ||
(configCheckArray[i] != decTestBytes[i]) {
good = false
}
}
}
else {
good = false
}
}
}
}
}
if !good {
logger.log(.debug, message: "RSA Test failed")
}
else {
logger.log(.debug, message: "All RSA tests passed")
return true
}
}
}
}
}
return false
}
// MARK: Secret wrapping / unwrapping
/*
* A secret is made up of a Base64 encoded byte array
* bytes 1-4 is the length of the encrypted AES key (LEN)
* bytes 5-(5+LEN) is the AES key encrypted in the service public key
* bytes (5+LEN) - (5+LEN+16) is the AES IV - 16 BYTES
* bytes (5+LEN+16) - (END) is the secret we are actually unwrapping encrypted with teh AES key
*/
func unwrapSecret(_ wrappedSecret: String) -> String? {
/* Sanity checks */
if (wrappedSecret == "" || serviceKeyPair == nil) {
return nil
}
/* Have to decode first */
let wrappedLength = wrappedSecret.count
if let rawSecret = Base64().base64decode(wrappedSecret, length: Int32(wrappedLength)) {
let rawBytes = UnsafeMutablePointer<UInt8>(mutating: rawSecret.bytes.bindMemory(to: UInt8.self, capacity: rawSecret.length))
// Size of WrapBufLen
var wrapBufLen = 0
for i in 0..<4 {
wrapBufLen = wrapBufLen << 8
let orVal = rawBytes[i]
wrapBufLen = wrapBufLen | Int(orVal)
}
/* Create the right NSData so we can decrypt using private key */
let wrapBufBytes = UnsafeMutableRawPointer(rawBytes.advanced(by: 4))
if let aesKey = serviceKeyPair?.decryptData(Data(bytesNoCopy: wrapBufBytes, count: wrapBufLen, deallocator: .none)) {
logger.log(.finest, message: "Public key decrypt in unwrap worked");
/* Now get the last part of the buffer */
let aesBytes = UnsafeMutableRawPointer(rawBytes.advanced(by: 4 + wrapBufLen))
let aes = AESKey()
if aes.loadKey(aesKey) {
if let decrypt = aes.decryptData(Data(bytesNoCopy: aesBytes, count: rawSecret.length - 4 - wrapBufLen, deallocator: .none)) {
logger.log(.finest, message: "AES decrypt in unwrap worked");
let ret = Base64().base64encode(decrypt as Data, length: Int32(decrypt.length))
return String(describing: ret)
}
}
}
}
return nil
}
// MARK: Helper functions
func getUniqueDeviceId() -> String {
if cachedConfig?.deviceUUID != nil {
return cachedConfig!.deviceUUID!
}
// This is a fail safe - not a good idea as this can change
return UIDevice.current.identifierForVendor!.uuidString
}
func getDeviceName() -> String {
return UIDevice.current.name
}
// MARK: Service handling
func checkServiceActive(_ callback: MasterPasswordCallback?, registerCallback: Bool) -> Bool {
if registerCallback && callback != nil {
callbacks.append(callback!)
}
return serviceActive
}
// Called by the service initialiser when done
func serviceActivated() {
logger.log(.debug, message: "Service activation completed successfully - starting callbacks")
serviceActive = true
for i in callbacks {
i.onServiceInitialised()
}
}
// If username/password changes
func serviceDeactivated() {
if serviceActive {
logger.log(.debug, message: "Service activation reversed - destroying service details")
serviceActive = false
/* Destroy keys */
serviceKey = nil
if serviceKeyPair != nil {
/* Remove key from key chain as well as deleting our copy */
serviceKeyPair?.destroy(true)
serviceKeyPair = nil
}
/* Tell anyone using service info we're out for the count */
for i in callbacks {
i.onServiceDeinitialised()
}
}
}
// MARK: TouchID KeyChain handling
// MARK: Singleton Handling
class func getInstance() -> MasterPassword {
return sharedInstance
}
class var sharedInstance: MasterPassword {
struct Static {
static let instance: MasterPassword = MasterPassword()
}
return Static.instance
}
}
| apache-2.0 | c8ee95e85c1c26eb46130d462f8467ee | 38.062208 | 195 | 0.546522 | 5.34518 | false | true | false | false |
liuxuan30/SwiftCharts | SwiftCharts/AxisValues/ChartAxisValueFloat.swift | 2 | 1317 | //
// ChartAxisValueFloat.swift
// swift_charts
//
// Created by ischuetz on 15/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartAxisValueFloat: ChartAxisValue {
public let formatter: NSNumberFormatter
let labelSettings: ChartLabelSettings
public var float: CGFloat {
return self.scalar
}
override public var text: String {
return self.formatter.stringFromNumber(self.float)!
}
public init(_ float: CGFloat, formatter: NSNumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
self.formatter = formatter
self.labelSettings = labelSettings
super.init(scalar: float)
}
override public var labels: [ChartAxisLabel] {
let axisLabel = ChartAxisLabel(text: self.text, settings: self.labelSettings)
return [axisLabel]
}
override public func copy(scalar: CGFloat) -> ChartAxisValueFloat {
return ChartAxisValueFloat(scalar, formatter: self.formatter, labelSettings: self.labelSettings)
}
static var defaultFormatter: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
}
| apache-2.0 | 26e1a5d38fab1b40e198c79d25798d7a | 28.266667 | 162 | 0.688686 | 5.353659 | false | false | false | false |
khizkhiz/swift | test/Parse/init_deinit.swift | 8 | 3120 | // RUN: %target-parse-verify-swift
struct FooStructConstructorA {
init // expected-error {{expected '('}}
}
struct FooStructConstructorB {
init() // expected-error {{initializer requires a body}}
}
struct FooStructConstructorC {
init {} // expected-error {{expected '('}}{{8-8=() }}
}
struct FooStructDeinitializerA {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerB {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerC {
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class FooClassDeinitializerA {
deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}}
}
class FooClassDeinitializerB {
deinit { }
}
init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{6-6=() }}
init() // expected-error {{initializers may only be declared within a type}}
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
deinit // expected-error {{expected '{' for deinitializer}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
struct BarStruct {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarStruct {
init(x : Int) {}
// When/if we allow 'var' in extensions, then we should also allow dtors
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
enum BarUnion {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarUnion {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class BarClass {
init() {}
deinit {}
}
extension BarClass {
convenience init(x : Int) { self.init() }
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
protocol BarProtocol {
init() {} // expected-error {{protocol initializers may not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarProtocol {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func fooFunc() {
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func barFunc() {
var x : () = { () -> () in
init() {} // expected-error {{initializers may only be declared within a type}}
return
} ()
var y : () = { () -> () in
deinit {} // expected-error {{deinitializers may only be declared within a class}}
return
} ()
}
// SR-852
class Aaron {
init(x: Int) {}
convenience init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}}
}
class Theodosia: Aaron {
init() {
init(x: 2) // expected-error {{missing 'super.' at initializer invocation}}
}
}
| apache-2.0 | 117aabee79439d1519871bc7cf1c5a90 | 26.610619 | 121 | 0.677244 | 4.051948 | false | false | false | false |
srn214/Floral | Floral/Floral/Classes/Expand/Extensions/Device+Hardware.swift | 1 | 4130 | //
// Device+Hardware.swift
// JianZhongBang
//
// Created by Apple on 2018/8/26.
// Copyright © 2018年 文刂Rn. All rights reserved.
//
import UIKit
import DeviceKit
// MARK: - 手机系列判断
extension Device {
/// 是否是iPhone 4.7系列手机
public static var isPhone4_7Serier: Bool {
return (((Device.current.diagonal ) == 4.7) ? true: false)
}
/// 是否是iPhone 5.5系列手机
public static var isPhone5_5Series: Bool {
return (((Device.current.diagonal ) >= 5.5) ? true: false)
}
/// 是否是iPhone 5 以下 系列手机
public static var isPhone5Earlier: Bool {
return (((Device.current.diagonal ) <= 4.0) ? true: false)
}
/// 是否是iPhone X手机
public static var isPhoneXSerise: Bool {
let device = Device.current
var _bool = false
if Device.allXSeriesDevices.contains(device) {
_bool = true
} else if Device.allSimulatorXSeriesDevices.contains(device) {
_bool = true
}
return _bool
}
}
// MARK: - 手机信息
extension Device {
/// 设备系统名称
public static var deviceSystemName: String {
return UIDevice.current.systemName
}
/// 设备名称
public static var deviceName: String {
return UIDevice.current.name
}
/// 设备版本
public static var deviceSystemVersion: String {
return UIDevice.current.systemVersion
}
/// App版本
public static var appVersion: String {
guard let dict = Bundle.main.infoDictionary else { return "unknown" }
guard let version = dict["CFBundleShortVersionString"] as? String else { return "unknown" }
return version
}
}
extension Device {
/// 设备型号
public static var machineModelName: String {
switch Device.current {
case .iPodTouch5:
return "iPod_Touch_5"
case .iPodTouch6:
return "iPod_Touch_6"
case .iPhone4:
return "iPhone_4"
case .iPhone4s:
return "iPhone_4s"
case .iPhone5:
return "iPhone_5"
case .iPhone5c:
return "iPhone_5c"
case .iPhone5s:
return "iPhone_5s"
case .iPhone6:
return "iPhone_6"
case .iPhone6Plus:
return "iPhone_6_Plus"
case .iPhone6s:
return "iPhone_6s"
case .iPhone6sPlus:
return "iPhone_6s_Plus"
case .iPhone7:
return "iPhone_7"
case .iPhone7Plus:
return "iPhone_7_Plus"
case .iPhoneSE:
return "iPhone_SE"
case .iPhone8:
return "iPhone_8"
case .iPhone8Plus:
return "iPhone_8_Plus"
case .iPhoneX:
return "iPhone_X"
case .iPhoneXS:
return "iPhone_Xs"
case .iPhoneXSMax:
return "iPhone_Xs_Max"
case .iPhoneXR:
return "iPhone_Xr"
case .iPad2:
return "iPad_2"
case .iPad3:
return "iPad_3"
case .iPad4:
return "iPad_4"
case .iPadAir:
return "iPad_Air"
case .iPadAir2:
return "iPad_Air2"
case .iPad5:
return "iPad_5"
case .iPad6:
return "iPad_6"
case .iPadMini:
return "iPad_Mini"
case .iPadMini2:
return "iPad_Mini2"
case .iPadMini3:
return "iPad_Mini3"
case .iPadMini4:
return "iPad_Mini4"
case .iPadPro9Inch:
return "iPad_Pro_9Inch"
case .iPadPro12Inch:
return "iPad_Pro_12Inch"
case .iPadPro12Inch2:
return "iPad_Pro_12Inch2"
case .iPadPro10Inch:
return "iPad_Pro_10Inch"
case .iPadPro11Inch:
return "iPad_Pro_11Inch"
case .iPadPro12Inch3:
return "iPad_Pro_12Inch3"
default:
return "其他型号"
}
}
}
| mit | fce16d7e5381f864389ed99127f1ec35 | 24.310127 | 99 | 0.531133 | 3.951581 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift | 5 | 5637 | //
// GitHubSearchRepositoriesAPI.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
#endif
import struct Foundation.URL
import struct Foundation.Data
import struct Foundation.URLRequest
import struct Foundation.NSRange
import class Foundation.HTTPURLResponse
import class Foundation.URLSession
import class Foundation.NSRegularExpression
import class Foundation.JSONSerialization
import class Foundation.NSString
/**
Parsed GitHub repository.
*/
struct Repository: CustomDebugStringConvertible {
var name: String
var url: URL
init(name: String, url: URL) {
self.name = name
self.url = url
}
}
extension Repository {
var debugDescription: String {
return "\(name) | \(url)"
}
}
enum GitHubServiceError: Error {
case offline
case githubLimitReached
case networkError
}
typealias SearchRepositoriesResponse = Result<(repositories: [Repository], nextURL: URL?), GitHubServiceError>
class GitHubSearchRepositoriesAPI {
// *****************************************************************************************
// !!! This is defined for simplicity sake, using singletons isn't advised !!!
// !!! This is just a simple way to move services to one location so you can see Rx code !!!
// *****************************************************************************************
static let sharedAPI = GitHubSearchRepositoriesAPI(reachabilityService: try! DefaultReachabilityService())
fileprivate let _reachabilityService: ReachabilityService
private init(reachabilityService: ReachabilityService) {
_reachabilityService = reachabilityService
}
}
extension GitHubSearchRepositoriesAPI {
public func loadSearchURL(_ searchURL: URL) -> Observable<SearchRepositoriesResponse> {
return URLSession.shared
.rx.response(request: URLRequest(url: searchURL))
.retry(3)
.observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
.map { pair -> SearchRepositoriesResponse in
if pair.0.statusCode == 403 {
return .failure(.githubLimitReached)
}
let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(pair.0, data: pair.1)
guard let json = jsonRoot as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
let repositories = try Repository.parse(json)
let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(pair.0)
return .success((repositories: repositories, nextURL: nextURL))
}
.retryOnBecomesReachable(.failure(.offline), reachabilityService: _reachabilityService)
}
}
// MARK: Parsing the response
extension GitHubSearchRepositoriesAPI {
private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\""
private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace])
fileprivate static func parseLinks(_ links: String) throws -> [String: String] {
let length = (links as NSString).length
let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length))
var result: [String: String] = [:]
for m in matches {
let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in
let range = m.range(at: rangeIndex)
let startIndex = links.characters.index(links.startIndex, offsetBy: range.location)
let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length)
return String(links[startIndex ..< endIndex])
}
if matches.count != 2 {
throw exampleError("Error parsing links")
}
result[matches[1]] = matches[0]
}
return result
}
fileprivate static func parseNextURL(_ httpResponse: HTTPURLResponse) throws -> URL? {
guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else {
return nil
}
let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks)
guard let nextPageURL = links["next"] else {
return nil
}
guard let nextUrl = URL(string: nextPageURL) else {
throw exampleError("Error parsing next url `\(nextPageURL)`")
}
return nextUrl
}
fileprivate static func parseJSON(_ httpResponse: HTTPURLResponse, data: Data) throws -> AnyObject {
if !(200 ..< 300 ~= httpResponse.statusCode) {
throw exampleError("Call failed")
}
return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject
}
}
extension Repository {
fileprivate static func parse(_ json: [String: AnyObject]) throws -> [Repository] {
guard let items = json["items"] as? [[String: AnyObject]] else {
throw exampleError("Can't find items")
}
return try items.map { item in
guard let name = item["name"] as? String,
let url = item["url"] as? String else {
throw exampleError("Can't parse repository")
}
return Repository(name: name, url: try URL(string: url).unwrap())
}
}
}
| mit | 146599bbf9e65473a6c31cb95986386d | 33.157576 | 172 | 0.624202 | 5.123636 | false | false | false | false |
bugsnag/bugsnag-cocoa | features/fixtures/shared/scenarios/BreadcrumbCallbackCrashScenario.swift | 1 | 1268 | //
// BreadcrumbCallbackCrashScenario.swift
// iOSTestApp
//
// Created by Jamie Lynch on 27/05/2020.
// Copyright © 2020 Bugsnag. All rights reserved.
//
import Foundation
class BreadcrumbCallbackCrashScenario : Scenario {
override func startBugsnag() {
self.config.autoTrackSessions = false;
self.config.enabledBreadcrumbTypes = []
self.config.addOnBreadcrumb { (crumb) -> Bool in
crumb.metadata["addedInCallback"] = true
// throw an exception to crash in the callback
NSException(name: NSExceptionName("BreadcrumbCallbackCrashScenario"),
reason: "Message: BreadcrumbCallbackCrashScenario",
userInfo: nil).raise()
crumb.metadata["shouldNotHappen"] = "it happened"
return true
}
self.config.addOnBreadcrumb { (crumb) -> Bool in
crumb.metadata["secondCallback"] = true
return true
}
super.startBugsnag()
}
override func run() {
Bugsnag.leaveBreadcrumb("Hello World", metadata: ["foo": "bar"], type: .manual)
let error = NSError(domain: "BreadcrumbCallbackCrashScenario", code: 100, userInfo: nil)
Bugsnag.notifyError(error)
}
}
| mit | 2ca76b0f7d194030c225c9e94c89e3bc | 30.675 | 96 | 0.624309 | 4.692593 | false | true | false | false |
brianjmoore/material-components-ios | components/TextFields/examples/TextFieldKitchenSinkExample.swift | 1 | 27340 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// swiftlint:disable file_length
// swiftlint:disable type_body_length
// swiftlint:disable function_body_length
import UIKit
import MaterialComponents.MaterialTextFields
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialTypography
final class TextFieldKitchenSinkSwiftExample: UIViewController {
let scrollView = UIScrollView()
let controlLabel: UILabel = {
let controlLabel = UILabel()
controlLabel.translatesAutoresizingMaskIntoConstraints = false
controlLabel.text = "Options"
controlLabel.font = UIFont.preferredFont(forTextStyle: .headline)
controlLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
return controlLabel
}()
let singleLabel: UILabel = {
let singleLabel = UILabel()
singleLabel.translatesAutoresizingMaskIntoConstraints = false
singleLabel.text = "Single-line Text Fields"
singleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
singleLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
singleLabel.numberOfLines = 0
return singleLabel
}()
let multiLabel: UILabel = {
let multiLabel = UILabel()
multiLabel.translatesAutoresizingMaskIntoConstraints = false
multiLabel.text = "Multi-line Text Fields"
multiLabel.font = UIFont.preferredFont(forTextStyle: .headline)
multiLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
multiLabel.numberOfLines = 0
return multiLabel
}()
let errorLabel: UILabel = {
let errorLabel = UILabel()
errorLabel.translatesAutoresizingMaskIntoConstraints = false
errorLabel.text = "In Error:"
errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
errorLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity())
errorLabel.numberOfLines = 0
return errorLabel
}()
let helperLabel: UILabel = {
let helperLabel = UILabel()
helperLabel.translatesAutoresizingMaskIntoConstraints = false
helperLabel.text = "Show Helper Text:"
helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
helperLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity())
helperLabel.numberOfLines = 0
return helperLabel
}()
var allInputControllers = [MDCTextInputController]()
var allTextFieldControllers = [MDCTextInputController]()
var allMultilineTextFieldControllers = [MDCTextInputController]()
var controllersWithCharacterCount = [MDCTextInputController]()
var controllersFullWidth = [MDCTextInputControllerFullWidth]()
let unstyledTextField = MDCTextField()
let unstyledMultilineTextField = MDCMultilineTextField()
lazy var textInsetsModeButton: MDCButton = self.setupButton()
lazy var characterModeButton: MDCButton = self.setupButton()
lazy var clearModeButton: MDCButton = self.setupButton()
lazy var underlineButton: MDCButton = self.setupButton()
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupExampleViews()
}
func setupFilledTextFields() -> [MDCTextInputControllerFilled] {
let textFieldFilled = MDCTextField()
textFieldFilled.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFilled)
textFieldFilled.delegate = self
let textFieldControllerFilled = MDCTextInputControllerFilled(textInput: textFieldFilled)
textFieldControllerFilled.isFloatingEnabled = false
textFieldControllerFilled.placeholderText = "This is a filled text field"
let textFieldFilledFloating = MDCTextField()
textFieldFilledFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFilledFloating)
textFieldFilledFloating.delegate = self
let textFieldControllerFilledFloating = MDCTextInputControllerFilled(textInput: textFieldFilledFloating)
textFieldControllerFilledFloating.placeholderText = "This is filled and floating"
return [textFieldControllerFilled, textFieldControllerFilledFloating]
}
func setupDefaultTextFields() -> [MDCTextInputControllerDefault] {
let textFieldDefault = MDCTextField()
textFieldDefault.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefault)
textFieldDefault.delegate = self
textFieldDefault.clearButtonMode = .whileEditing
let textFieldControllerDefault = MDCTextInputControllerDefault(textInput: textFieldDefault)
textFieldControllerDefault.isFloatingEnabled = false
let textFieldDefaultPlaceholder = MDCTextField()
textFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefaultPlaceholder)
textFieldDefaultPlaceholder.delegate = self
textFieldDefaultPlaceholder.clearButtonMode = .whileEditing
let textFieldControllerDefaultPlaceholder =
MDCTextInputControllerDefault(textInput: textFieldDefaultPlaceholder)
textFieldControllerDefaultPlaceholder.isFloatingEnabled = false
textFieldControllerDefaultPlaceholder.placeholderText = "This is a text field w/ inline placeholder"
let textFieldDefaultCharMax = MDCTextField()
textFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefaultCharMax)
textFieldDefaultCharMax.delegate = self
textFieldDefaultCharMax.clearButtonMode = .whileEditing
let textFieldControllerDefaultCharMax =
MDCTextInputControllerDefault(textInput: textFieldDefaultCharMax)
textFieldControllerDefaultCharMax.characterCountMax = 50
textFieldControllerDefaultCharMax.isFloatingEnabled = false
textFieldControllerDefaultCharMax.placeholderText = "This is a text field w/ character count"
controllersWithCharacterCount.append(textFieldControllerDefaultCharMax)
return [textFieldControllerDefault, textFieldControllerDefaultPlaceholder,
textFieldControllerDefaultCharMax]
}
func setupFullWidthTextFields() -> [MDCTextInputControllerFullWidth] {
let textFieldFullWidthPlaceholder = MDCTextField()
textFieldFullWidthPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFullWidthPlaceholder)
textFieldFullWidthPlaceholder.delegate = self
textFieldFullWidthPlaceholder.clearButtonMode = .whileEditing
let textFieldControllerFullWidthPlaceholder =
MDCTextInputControllerFullWidth(textInput: textFieldFullWidthPlaceholder)
textFieldControllerFullWidthPlaceholder.placeholderText = "This is a full width text field"
let textFieldFullWidthCharMax = MDCTextField()
textFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFullWidthCharMax)
textFieldFullWidthCharMax.delegate = self
textFieldFullWidthCharMax.clearButtonMode = .whileEditing
let textFieldControllerFullWidthCharMax =
MDCTextInputControllerFullWidth(textInput: textFieldFullWidthCharMax)
textFieldControllerFullWidthCharMax.characterCountMax = 50
textFieldControllerFullWidthCharMax.placeholderText =
"This is a full width text field with character count and a very long placeholder"
controllersWithCharacterCount.append(textFieldControllerFullWidthCharMax)
return [textFieldControllerFullWidthPlaceholder,
textFieldControllerFullWidthCharMax]
}
func setupFloatingTextFields() -> [MDCTextInputControllerDefault] {
let textFieldFloating = MDCTextField()
textFieldFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFloating)
textFieldFloating.delegate = self
textFieldFloating.clearButtonMode = .whileEditing
let textFieldControllerFloating = MDCTextInputControllerDefault(textInput: textFieldFloating)
textFieldControllerFloating.placeholderText = "This is a text field w/ floating placeholder"
let textFieldFloatingCharMax = MDCTextField()
textFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFloatingCharMax)
textFieldFloatingCharMax.delegate = self
textFieldFloatingCharMax.clearButtonMode = .whileEditing
let textFieldControllerFloatingCharMax =
MDCTextInputControllerDefault(textInput: textFieldFloatingCharMax)
textFieldControllerFloatingCharMax.characterCountMax = 50
textFieldControllerFloatingCharMax.placeholderText = "This is floating with character count"
controllersWithCharacterCount.append(textFieldControllerFloatingCharMax)
return [textFieldControllerFloating, textFieldControllerFloatingCharMax]
}
func setupSpecialTextFields() -> [MDCTextInputControllerDefault] {
let textFieldDisabled = MDCTextField()
textFieldDisabled.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDisabled)
textFieldDisabled.delegate = self
textFieldDisabled.isEnabled = false
let textFieldControllerDefaultDisabled =
MDCTextInputControllerDefault(textInput: textFieldDisabled)
textFieldControllerDefaultDisabled.isFloatingEnabled = false
textFieldControllerDefaultDisabled.placeholderText = "This is a disabled text field"
let textFieldCustomFont = MDCTextField()
textFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldCustomFont)
textFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline)
textFieldCustomFont.delegate = self
textFieldCustomFont.clearButtonMode = .whileEditing
let textFieldControllerDefaultCustomFont =
MDCTextInputControllerDefault(textInput: textFieldCustomFont)
textFieldControllerDefaultCustomFont.inlinePlaceholderFont = UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFont.isFloatingEnabled = false
textFieldControllerDefaultCustomFont.placeholderText = "This is a custom font"
let textFieldCustomFontFloating = MDCTextField()
textFieldCustomFontFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldCustomFontFloating)
textFieldCustomFontFloating.font = UIFont.preferredFont(forTextStyle: .headline)
textFieldCustomFontFloating.delegate = self
textFieldCustomFontFloating.clearButtonMode = .whileEditing
textFieldCustomFontFloating.cursorColor = .orange
let textFieldControllerDefaultCustomFontFloating =
MDCTextInputControllerDefault(textInput: textFieldCustomFontFloating)
textFieldControllerDefaultCustomFontFloating.characterCountMax = 40
textFieldControllerDefaultCustomFontFloating.placeholderText = "This is a custom font with the works"
textFieldControllerDefaultCustomFontFloating.helperText = "Custom Font"
textFieldControllerDefaultCustomFontFloating.activeColor = .green
textFieldControllerDefaultCustomFontFloating.normalColor = .purple
textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelTextColor = .cyan
textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelTextColor = .magenta
textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelFont =
UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFontFloating.inlinePlaceholderFont =
UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelFont =
UIFont.preferredFont(forTextStyle: .subheadline)
textFieldCustomFontFloating.clearButton.tintColor = MDCPalette.red.accent400
let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self)
let leadingViewImage = UIImage(named: "ic_search", in: bundle, compatibleWith: nil)!
let textFieldLeadingView = MDCTextField()
textFieldLeadingView.leadingViewMode = .always
textFieldLeadingView.leadingView = UIImageView(image:leadingViewImage)
textFieldLeadingView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeadingView)
textFieldLeadingView.delegate = self
textFieldLeadingView.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeadingView =
MDCTextInputControllerDefault(textInput: textFieldLeadingView)
textFieldControllerDefaultLeadingView.isFloatingEnabled = false
textFieldControllerDefaultLeadingView.placeholderText = "This has a leading view"
let textFieldLeadingViewFloating = MDCTextField()
textFieldLeadingViewFloating.leadingViewMode = .always
textFieldLeadingViewFloating.leadingView = UIImageView(image:leadingViewImage)
textFieldLeadingViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeadingViewFloating)
textFieldLeadingViewFloating.delegate = self
textFieldLeadingViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeadingViewFloating =
MDCTextInputControllerDefault(textInput: textFieldLeadingViewFloating)
textFieldControllerDefaultLeadingViewFloating.placeholderText = "This has a leading view and floats"
let trailingViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)!
let textFieldTrailingView = MDCTextField()
textFieldTrailingView.trailingViewMode = .always
textFieldTrailingView.trailingView = UIImageView(image:trailingViewImage)
textFieldTrailingView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldTrailingView)
textFieldTrailingView.delegate = self
textFieldTrailingView.clearButtonMode = .whileEditing
let textFieldControllerDefaultTrailingView =
MDCTextInputControllerDefault(textInput: textFieldTrailingView)
textFieldControllerDefaultTrailingView.isFloatingEnabled = false
textFieldControllerDefaultTrailingView.placeholderText = "This has a trailing view"
let textFieldTrailingViewFloating = MDCTextField()
textFieldTrailingViewFloating.trailingViewMode = .always
textFieldTrailingViewFloating.trailingView = UIImageView(image:trailingViewImage)
textFieldTrailingViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldTrailingViewFloating)
textFieldTrailingViewFloating.delegate = self
textFieldTrailingViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultTrailingViewFloating =
MDCTextInputControllerDefault(textInput: textFieldTrailingViewFloating)
textFieldControllerDefaultTrailingViewFloating.placeholderText = "This has a trailing view and floats"
let textFieldLeadingTrailingView = MDCTextField()
textFieldLeadingTrailingView.leadingViewMode = .whileEditing
textFieldLeadingTrailingView.leadingView = UIImageView(image: leadingViewImage)
textFieldLeadingTrailingView.trailingViewMode = .unlessEditing
textFieldLeadingTrailingView.trailingView = UIImageView(image:trailingViewImage)
textFieldLeadingTrailingView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeadingTrailingView)
textFieldLeadingTrailingView.delegate = self
textFieldLeadingTrailingView.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeadingTrailingView =
MDCTextInputControllerDefault(textInput: textFieldLeadingTrailingView)
textFieldControllerDefaultLeadingTrailingView.isFloatingEnabled = false
textFieldControllerDefaultLeadingTrailingView.placeholderText =
"This has leading & trailing views and a very long placeholder that should be truncated"
let textFieldLeadingTrailingViewFloating = MDCTextField()
textFieldLeadingTrailingViewFloating.leadingViewMode = .always
textFieldLeadingTrailingViewFloating.leadingView = UIImageView(image: leadingViewImage)
textFieldLeadingTrailingViewFloating.trailingViewMode = .whileEditing
textFieldLeadingTrailingViewFloating.trailingView = UIImageView(image:trailingViewImage)
textFieldLeadingTrailingViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeadingTrailingViewFloating)
textFieldLeadingTrailingViewFloating.delegate = self
textFieldLeadingTrailingViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeadingTrailingViewFloating =
MDCTextInputControllerDefault(textInput: textFieldLeadingTrailingViewFloating)
textFieldControllerDefaultLeadingTrailingViewFloating.placeholderText =
"This has leading & trailing views and floats and a very long placeholder that should be truncated"
unstyledTextField.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(unstyledTextField)
unstyledTextField.placeholder = "This is an unstyled text field (no controller)"
unstyledTextField.leadingUnderlineLabel.text = "Leading label"
unstyledTextField.trailingUnderlineLabel.text = "Trailing label"
unstyledTextField.delegate = self
unstyledTextField.clearButtonMode = .whileEditing
unstyledTextField.leadingView = UIImageView(image: leadingViewImage)
unstyledTextField.leadingViewMode = .always
unstyledTextField.trailingView = UIImageView(image: trailingViewImage)
unstyledTextField.trailingViewMode = .always
return [textFieldControllerDefaultDisabled,
textFieldControllerDefaultCustomFont, textFieldControllerDefaultCustomFontFloating,
textFieldControllerDefaultLeadingView, textFieldControllerDefaultLeadingViewFloating,
textFieldControllerDefaultTrailingView, textFieldControllerDefaultTrailingViewFloating,
textFieldControllerDefaultLeadingTrailingView,
textFieldControllerDefaultLeadingTrailingViewFloating]
}
// MARK: - Multi-line
func setupAreaTextFields() -> [MDCTextInputControllerOutlinedTextArea] {
let textFieldArea = MDCMultilineTextField()
textFieldArea.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldArea)
textFieldArea.textView?.delegate = self
let textFieldControllerArea = MDCTextInputControllerOutlinedTextArea(textInput: textFieldArea)
textFieldControllerArea.placeholderText = "This is a text area"
return [textFieldControllerArea]
}
func setupDefaultMultilineTextFields() -> [MDCTextInputControllerDefault] {
let multilineTextFieldDefault = MDCMultilineTextField()
multilineTextFieldDefault.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefault)
multilineTextFieldDefault.textView?.delegate = self
let multilineTextFieldControllerDefault =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefault)
multilineTextFieldControllerDefault.isFloatingEnabled = false
let multilineTextFieldDefaultPlaceholder = MDCMultilineTextField()
multilineTextFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefaultPlaceholder)
multilineTextFieldDefaultPlaceholder.textView?.delegate = self
let multilineTextFieldControllerDefaultPlaceholder =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultPlaceholder)
multilineTextFieldControllerDefaultPlaceholder.isFloatingEnabled = false
multilineTextFieldControllerDefaultPlaceholder.placeholderText =
"This is a multi-line text field with placeholder"
let multilineTextFieldDefaultCharMax = MDCMultilineTextField()
multilineTextFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefaultCharMax)
multilineTextFieldDefaultCharMax.textView?.delegate = self
let multilineTextFieldControllerDefaultCharMax =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultCharMax)
multilineTextFieldControllerDefaultCharMax.characterCountMax = 140
multilineTextFieldControllerDefaultCharMax.isFloatingEnabled = false
multilineTextFieldControllerDefaultCharMax.placeholderText =
"This is a multi-line text field with placeholder"
controllersWithCharacterCount.append(multilineTextFieldControllerDefaultCharMax)
return [multilineTextFieldControllerDefault, multilineTextFieldControllerDefaultPlaceholder,
multilineTextFieldControllerDefaultCharMax]
}
func setupFullWidthMultilineTextFields() -> [MDCTextInputControllerFullWidth] {
let multilineTextFieldFullWidth = MDCMultilineTextField()
multilineTextFieldFullWidth.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFullWidth)
multilineTextFieldFullWidth.textView?.delegate = self
let multilineTextFieldControllerFullWidth =
MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidth)
multilineTextFieldControllerFullWidth.placeholderText =
"This is a full width multi-line text field"
let multilineTextFieldFullWidthCharMax = MDCMultilineTextField()
multilineTextFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFullWidthCharMax)
multilineTextFieldFullWidthCharMax.textView?.delegate = self
let multilineTextFieldControllerFullWidthCharMax =
MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidthCharMax)
multilineTextFieldControllerFullWidthCharMax.placeholderText =
"This is a full width multi-line text field with character count"
controllersWithCharacterCount.append(multilineTextFieldControllerFullWidthCharMax)
multilineTextFieldControllerFullWidthCharMax.characterCountMax = 140
return [multilineTextFieldControllerFullWidth, multilineTextFieldControllerFullWidthCharMax]
}
func setupFloatingMultilineTextFields() -> [MDCTextInputControllerDefault] {
let multilineTextFieldFloating = MDCMultilineTextField()
multilineTextFieldFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFloating)
multilineTextFieldFloating.textView?.delegate = self
let multilineTextFieldControllerFloating =
MDCTextInputControllerDefault(textInput: multilineTextFieldFloating)
multilineTextFieldControllerFloating.placeholderText =
"This is a multi-line text field with a floating placeholder"
let multilineTextFieldFloatingCharMax = MDCMultilineTextField()
multilineTextFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFloatingCharMax)
multilineTextFieldFloatingCharMax.textView?.delegate = self
let multilineTextFieldControllerFloatingCharMax =
MDCTextInputControllerDefault(textInput: multilineTextFieldFloatingCharMax)
multilineTextFieldControllerFloatingCharMax.placeholderText =
"This is a multi-line text field with a floating placeholder and character count"
controllersWithCharacterCount.append(multilineTextFieldControllerFloatingCharMax)
return [multilineTextFieldControllerFloating, multilineTextFieldControllerFloatingCharMax]
}
func setupSpecialMultilineTextFields() -> [MDCTextInputController] {
let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self)
let trailingViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)!
let multilineTextFieldTrailingView = MDCMultilineTextField()
multilineTextFieldTrailingView.trailingViewMode = .always
multilineTextFieldTrailingView.trailingView = UIImageView(image:trailingViewImage)
multilineTextFieldTrailingView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldTrailingView)
multilineTextFieldTrailingView.textView?.delegate = self
multilineTextFieldTrailingView.clearButtonMode = .whileEditing
let multilineTextFieldControllerDefaultTrailingView =
MDCTextInputControllerDefault(textInput: multilineTextFieldTrailingView)
multilineTextFieldControllerDefaultTrailingView.isFloatingEnabled = false
multilineTextFieldControllerDefaultTrailingView.placeholderText = "This has a trailing view"
let multilineTextFieldCustomFont = MDCMultilineTextField()
multilineTextFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldCustomFont)
let multilineTextFieldControllerDefaultCustomFont =
MDCTextInputControllerDefault(textInput: multilineTextFieldCustomFont)
multilineTextFieldControllerDefaultCustomFont.placeholderText = "This has a custom font"
multilineTextFieldCustomFont.placeholderLabel.font = UIFont.preferredFont(forTextStyle: .headline)
multilineTextFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline)
scrollView.addSubview(unstyledMultilineTextField)
unstyledMultilineTextField.translatesAutoresizingMaskIntoConstraints = false
unstyledMultilineTextField.placeholder =
"This multi-line text field has no controller (unstyled)"
unstyledMultilineTextField.leadingUnderlineLabel.text = "Leading label"
unstyledMultilineTextField.trailingUnderlineLabel.text = "Trailing label"
unstyledMultilineTextField.textView?.delegate = self
return [multilineTextFieldControllerDefaultTrailingView,
multilineTextFieldControllerDefaultCustomFont]
}
@objc func tapDidTouch(sender: Any) {
self.view.endEditing(true)
}
@objc func errorSwitchDidChange(errorSwitch: UISwitch) {
allInputControllers.forEach { controller in
if errorSwitch.isOn {
controller.setErrorText("Uh oh! Try something else.", errorAccessibilityValue: nil)
} else {
controller.setErrorText(nil, errorAccessibilityValue: nil)
}
}
}
@objc func helperSwitchDidChange(helperSwitch: UISwitch) {
allInputControllers.forEach { controller in
controller.helperText = helperSwitch.isOn ? "This is helper text." : nil
}
}
}
extension TextFieldKitchenSinkSwiftExample: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
extension TextFieldKitchenSinkSwiftExample: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
}
}
extension TextFieldKitchenSinkSwiftExample {
@objc func contentSizeCategoryDidChange(notif: Notification) {
controlLabel.font = UIFont.preferredFont(forTextStyle: .headline)
singleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
}
}
| apache-2.0 | b00882825d5e55a7a9b84c3fbbb74153 | 44.415282 | 110 | 0.818178 | 5.902418 | false | false | false | false |
wrld3d/wrld-example-app | ios/Include/WrldSDK/iphoneos12.0/WrldNavWidget.framework/Headers/WRLDNavWidgetTablet.swift | 4 | 12093 | import UIKit
import WrldUtils
import WrldNav
@objc
public class WRLDNavWidgetTablet: WRLDNavWidgetBase
{
@IBOutlet var view: UIView!
//-- Top - Current & Next Instructions ---------------------------------------------------------
@IBOutlet var topPanelView: UIView!
@IBOutlet weak var currentDirectionView: WRLDNavCurrentDirectionView!
@IBOutlet weak var nextDirectionView: WRLDNavNextDirectionView!
@IBOutlet weak var stepByStepDirectionsView: WRLDNavDirectionsView!
//-- Left hand side - Directions ---------------------------------------------------------------
@IBOutlet var leftPanelView: UIView!
@IBOutlet weak var leftInfoViews: UIView!
@IBOutlet weak var directionsStack: UIStackView!
@IBOutlet weak var setupJourneyView: WRLDNavSetupJourneyView!
@IBOutlet weak var leftTimeToDestinationView: WRLDNavTimeToDestinationView!
@IBOutlet weak var directionsView: WRLDNavDirectionsView!
//-- Bottom - Time to Destination --------------------------------------------------------------
@IBOutlet var bottomPanelView: UIView!
@IBOutlet weak var bottomStack: UIStackView!
@IBOutlet weak var bottomTimeToDestinationView: WRLDNavTimeToDestinationView!
var m_bottomPanelHeight: CGFloat = 0
var m_isStepByStepNavListShowing: Bool = false;
var _hideViews: Bool = false
public override init(frame: CGRect)
{
super.init(frame: frame)
initCommon()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initCommon()
}
private func initCommon()
{
observer.registerObserver(observerKey: navModeKeyPath)
let bundle = Bundle(for: WRLDNavWidgetTablet.self)
let nib = UINib(nibName: "WRLDNavWidgetTablet", bundle: bundle)
let view: UIView! = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
applyShadow(view: nextDirectionView)
applyShadow(view: leftInfoViews)
applyShadow(view: directionsView)
applyShadow(view: stepByStepDirectionsView)
leftPanelView.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(leftPanelView)
topPanelView.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(topPanelView)
bottomPanelView.translatesAutoresizingMaskIntoConstraints = true
view.addSubview(bottomPanelView)
m_bottomPanelHeight = bottomPanelView.frame.size.height;
}
func applyShadow(view: UIView)
{
view.layer.shadowColor = UIColor.darkGray.cgColor
view.layer.shadowRadius = 11
view.layer.shadowOffset = CGSize(width: 0, height: 0)
view.layer.shadowOpacity = 0.5
view.layer.masksToBounds = false
}
public override func point(inside point: CGPoint, with event: UIEvent?) -> Bool
{
let leftViewPoint = view.convert(point, to: leftPanelView)
let pointInsideLeftView = (leftInfoViews.frame.contains(leftViewPoint) || directionsView.frame.contains(leftViewPoint))
let bottomViewPoint = view.convert(point, to: bottomPanelView)
let pointInsideBottomView = bottomStack.frame.contains(bottomViewPoint)
let topViewPoint = view.convert(point, to: topPanelView)
let pointInsideTopView = (stepByStepDirectionsView.frame.contains(topViewPoint) || currentDirectionView.frame.contains(topViewPoint) || nextDirectionView.frame.contains(topViewPoint))
return (pointInsideLeftView || pointInsideBottomView || pointInsideTopView);
}
public func modelSet()
{
if let navModel = observer.navModel()
{
setupJourneyView .observer.setNavModel(navModel) //Left
leftTimeToDestinationView .observer.setNavModel(navModel) //Left
directionsView .observer.setNavModel(navModel) //Left
currentDirectionView .observer.setNavModel(navModel) //Top
nextDirectionView .observer.setNavModel(navModel) //Top
stepByStepDirectionsView .observer.setNavModel(navModel) //Top
bottomTimeToDestinationView.observer.setNavModel(navModel) //Bottom
}
updateNavMode(animate: false)
updateBottomStack()
}
public override func eventReceived(key: WRLDNavEvent)
{
if key == .showHideListButtonClicked
{
setStepByStepDirectionsVisibility(visible: !m_isStepByStepNavListShowing, animate: true)
}
super.eventReceived(key: key)
}
func setLeftVisibility(visible: Bool, animate: Bool)
{
let frameWidth: Int = 371
let frameHeight: Int = Int(view.frame.size.height)
let openFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
let closedFrame = CGRect(x: -frameWidth, y: 0, width: frameWidth, height: frameHeight)
let block = {
self.leftPanelView.frame = (visible) ? (openFrame) : (closedFrame)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
};
if(animate == true)
{
UIView.animate(withDuration: 0.3, animations:block)
}
else
{
block()
}
}
func setDirectionsVisibility(visible: Bool, animate: Bool)
{
let frameWidth: Int = Int(directionsView.frame.width)
let frameHeight: Int = Int(directionsView.frame.height)
let yPos = Int(directionsView.frame.minY)
let openFrame = CGRect(x: 0, y: yPos, width: frameWidth, height: frameHeight)
let closedFrame = CGRect(x: -frameWidth, y: yPos, width: frameWidth, height: frameHeight)
let block = {
self.directionsView.frame = (visible) ? (openFrame) : (closedFrame)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
};
if(animate == true)
{
UIView.animate(withDuration: 0.3, animations:block)
}
else
{
block()
}
}
func setTopVisibility(visible: Bool, animate: Bool)
{
let frameWidth: Int = Int(view.frame.size.width)
let frameHeight: Int = Int(view.frame.size.height - bottomStack.frame.size.height)
let openFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
let closedFrame = CGRect(x: 0, y: -(frameHeight+11), width: frameWidth, height: frameHeight)
let block = {
self.topPanelView.frame = (visible) ? (openFrame) : (closedFrame)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.topPanelVisibleHeight = visible ? self.currentDirectionView.bounds.size.height : 0
};
if(animate == true)
{
UIView.animate(withDuration: 0.3, animations:block)
}
else
{
block()
}
}
func setBottomVisibility(visible: Bool, animate: Bool)
{
let ht = Int(view.frame.size.height)
let frameWidth: Int = Int(view.frame.size.width)
let frameHeight: Int = Int(m_bottomPanelHeight)
let openFrame = CGRect(x: 0, y: ht-frameHeight, width: frameWidth, height: frameHeight)
let closedFrame = CGRect(x: 0, y: ht, width: frameWidth, height: frameHeight)
let block = {
self.bottomPanelView.frame = (visible) ? (openFrame) : (closedFrame)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.bottomPanelVisibleHeight = visible ? self.bottomPanelView.bounds.size.height : 0
};
if(animate == true)
{
UIView.animate(withDuration: 0.3, animations:block)
}
else
{
block()
}
}
func setStepByStepDirectionsVisibility(visible: Bool, animate: Bool)
{
m_isStepByStepNavListShowing = visible
nextDirectionView.setShowHideListButtonState(visible)
let frameWidth: Int = Int(stepByStepDirectionsView.frame.width)
let frameHeight: Int = Int(stepByStepDirectionsView.frame.height)
let yPos = Int(nextDirectionView.frame.maxY)
let openFrame = CGRect(x: 0, y: yPos, width: frameWidth, height: frameHeight)
let closedFrame = CGRect(x: 0, y: -frameHeight, width: frameWidth, height: frameHeight)
let block = {
self.stepByStepDirectionsView.frame = (visible) ? (openFrame) : (closedFrame)
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.updateTopPanel()
};
if(animate == true)
{
UIView.animate(withDuration: 0.3, animations:block)
}
else
{
block()
}
}
//This shows/hides the various UI elements based on the current navigation mode.
override open func updateNavMode(animate: Bool)
{
if(_hideViews)
{
setLeftVisibility (visible: false, animate: animate)
setTopVisibility (visible: false, animate: animate)
setBottomVisibility(visible: false, animate: animate)
}
else if let navModel = observer.navModel()
{
switch(navModel.navMode)
{
case .notReady:
setLeftVisibility (visible: true, animate: animate)
setTopVisibility (visible: false, animate: animate)
setBottomVisibility(visible: false, animate: animate)
setDirectionsVisibility(visible: false, animate: animate)
setStepByStepDirectionsVisibility(visible: false, animate: animate)
break;
case .ready,
.readyNoTurnByTurn:
setLeftVisibility (visible: true, animate: animate)
setTopVisibility (visible: false, animate: animate)
setBottomVisibility(visible: false, animate: animate)
setDirectionsVisibility(visible: true, animate: animate)
setStepByStepDirectionsVisibility(visible: false, animate: false)
break;
case .active:
setLeftVisibility (visible: false, animate: animate)
setTopVisibility (visible: true, animate: animate)
setBottomVisibility(visible: true, animate: animate)
setStepByStepDirectionsVisibility(visible: false, animate: false)
break;
}
}
}
//Show/hide the time to destination view when the user clicks the toggle button.
func updateBottomStack()
{
UIView.animate(withDuration: 0.3, animations:
{
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.bottomPanelVisibleHeight = self.bottomStack.bounds.size.height
self.updateTopPanel()
})
}
//Update top panel's size according to bottom stack size change
func updateTopPanel()
{
if m_isStepByStepNavListShowing
{
let bottomHeight = m_bottomPanelHeight
let frameHeight: Int = Int(self.view.frame.size.height - bottomHeight)
let frameWidth: Int = Int(self.view.frame.size.width)
let newFrame = CGRect(x: 0, y: 0, width: frameWidth, height: frameHeight)
self.topPanelView.frame = newFrame
self.topPanelView.setNeedsLayout()
}
}
@objc public override func setViewVisibility(animate: Bool, hideViews: Bool)
{
_hideViews = hideViews
updateNavMode(animate: animate)
}
}
| bsd-2-clause | dce230251d8fa743c5072429519a51fe | 36.672897 | 191 | 0.604978 | 4.654734 | false | false | false | false |
MxABC/oclearning | swiftLearning/Pods/Kingfisher/Kingfisher/UIButton+Kingfisher.swift | 12 | 31710 | //
// UIButton+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/13.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
* Set image to use from web for a specified state.
*/
public extension UIButton {
/**
Set an image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setImage(placeholderImage, forState: state)
kf_setWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
},
completionHandler: {[weak self] image, error, cacheType, imageURL in
dispatch_async_safely_main_queue {
if let sSelf = self {
if imageURL == sSelf.kf_webURLForState(state) && image != nil {
sSelf.setImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
}
)
return task
}
/**
Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastURLKey: Void?
public extension UIButton {
/**
Get the image URL binded to this button for a specified state.
- parameter state: The state that uses the specified image.
- returns: Current URL for image.
*/
public func kf_webURLForState(state: UIControlState) -> NSURL? {
return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_webURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/**
* Set background image to use from web for a specified state.
*/
public extension UIButton {
/**
Set the background image to use for a specified state with a resource.
It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource` and then set it for a button state.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL.
It will ask for Kingfisher's manager to get the image for the URL and then set it for a button state.
The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use.
If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource and a placeholder image.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL and a placeholder image.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image and options.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image and options.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set the background image to use for a specified state with a resource, a placeholder image, options and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(resource, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set the background image to use for a specified state with a resource,
a placeholder image, options progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithResource(resource: Resource,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
setBackgroundImage(placeholderImage, forState: state)
kf_setBackgroundWebURL(resource.downloadURL, forState: state)
let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
},
completionHandler: { [weak self] image, error, cacheType, imageURL in
dispatch_async_safely_main_queue {
if let sSelf = self {
if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil {
sSelf.setBackgroundImage(image, forState: state)
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
}
}
}
)
return task
}
/**
Set the background image to use for a specified state with a URL,
a placeholder image, options progress handler and completion handler.
- parameter URL: The URL of image for specified state.
- parameter state: The state that uses the specified image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
*/
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
forState: state,
placeholderImage: placeholderImage,
optionsInfo: optionsInfo,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
}
private var lastBackgroundURLKey: Void?
public extension UIButton {
/**
Get the background image URL binded to this button for a specified state.
- parameter state: The state that uses the specified background image.
- returns: Current URL for background image.
*/
public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
}
private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
}
private var kf_backgroundWebURLs: NSMutableDictionary {
var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
if dictionary == nil {
dictionary = NSMutableDictionary()
kf_setBackgroundWebURLs(dictionary!)
}
return dictionary!
}
private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated
public extension UIButton {
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setBackgroundImageWithURL:forState:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setBackgroundImageWithURL(URL: NSURL,
forState state: UIControlState,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setBackgroundImageWithURL(URL, forState: state, placeholderImage: placeholderImage, optionsInfo: [.Options(options)], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit | 6419359a4b979ae46272c71bf47d6ca4 | 52.564189 | 242 | 0.649511 | 6.025081 | false | false | false | false |
ahyattdev/OrangeIRC | OrangeIRC Core/Message.swift | 1 | 7277 | // This file of part of the Swift IRC client framework OrangeIRC Core.
//
// Copyright © 2016 Andrew Hyatt
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
let SPACE = " "
let SLASH = "/"
let COLON = ":"
let EXCLAMATION_MARK = "!"
let AT_SYMBOL = "@"
let CARRIAGE_RETURN = "\r\n"
let EMPTY = ""
internal class Message {
internal typealias Tag = (key: String, value: String?, vendor: String?)
internal struct Prefix {
internal var prefix: String
internal var servername: String?
internal var nickname: String?
internal var user: String?
internal var host: String?
internal init?(_ string: String) {
self.prefix = string
if string.contains(EXCLAMATION_MARK) && string.contains(AT_SYMBOL) {
// One of the msgto formats
let exclamationMark = string.range(of: EXCLAMATION_MARK)!
let atSymbol = string.range(of: AT_SYMBOL)!
self.nickname = String(string[string.startIndex ..< exclamationMark.lowerBound])
self.user = String(string[exclamationMark.upperBound ..< atSymbol.lowerBound])
self.host = String(string[atSymbol.upperBound ..< string.endIndex])
} else {
self.servername = prefix
}
}
internal func toString() -> String {
if let nickname = self.nickname, let user = self.user, let host = self.host {
return nickname + EXCLAMATION_MARK + user + AT_SYMBOL + host
} else {
guard let servername = self.servername else {
return "PREFIX UNKNOWN"
}
return servername
}
}
}
internal var message: String
internal var prefix: Prefix?
internal var command: String
internal var target: [String]
internal var parameters: String?
internal var tags = [Tag]()
internal init?(_ string: String) {
var trimmedString = string.replacingOccurrences(of: CARRIAGE_RETURN, with: EMPTY)
self.message = trimmedString
guard let firstSpaceIndex = trimmedString.range(of: " ")?.lowerBound else {
// The message is invalid if there isn't a single space
return nil
}
var possibleTags = trimmedString[trimmedString.startIndex ..< firstSpaceIndex]
if !possibleTags.isEmpty && possibleTags.hasPrefix("@") {
// There are tags present
// Remove the @ symbol
possibleTags.remove(at: possibleTags.startIndex)
// Seperate by ;
for tag in possibleTags.components(separatedBy: ";") {
/*
<tag> ::= <key> ['=' <escaped value>]
<key> ::= [ <vendor> '/' ] <sequence of letters, digits, hyphens (`-`)>
*/
guard let equalSignIndex = tag.range(of: "=")?.lowerBound else {
print("Invalid tag: \(tag)")
continue
}
var key = tag[tag.startIndex ..< equalSignIndex]
var vendor: String?
if key.contains("/") {
// A vendor is present
let slash = key.range(of: "/")!.lowerBound
vendor = String(key[key.startIndex ..< slash])
key = key[key.index(after: slash) ..< key.endIndex]
}
var value: String? = String(tag[tag.index(after: equalSignIndex) ..< tag.endIndex])
if value!.isEmpty {
value = nil
}
guard !key.isEmpty else {
print("Unexpected empty key: \(tag)")
continue
}
tags.append((key: String(key), value: value, vendor: vendor))
}
// Remove the tags so the old code works
trimmedString.removeSubrange(trimmedString.startIndex ... firstSpaceIndex)
}
if trimmedString[trimmedString.startIndex] == Character(COLON) {
// There is a prefix, and we must handle and trim it
let indexAfterColon = trimmedString.index(after: trimmedString.startIndex)
let indexOfSpace = trimmedString.range(of: SPACE)!.lowerBound
let prefixString = trimmedString[indexAfterColon ..< indexOfSpace]
guard let prefix = Prefix(String(prefixString)) else {
// Present but invalid prefix.
// The whole message may be corrupt, so let's give up 🤡.
return nil
}
self.prefix = prefix
// Trim off the prefix
trimmedString = String(trimmedString[trimmedString.index(after: indexOfSpace) ..< trimmedString.endIndex])
}
if let colonSpaceRange = trimmedString.range(of: " :") {
// There are parameters
let commandAndTargetString = trimmedString[trimmedString.startIndex ..< colonSpaceRange.lowerBound]
// Space seperated array
var commandAndTargetComponents = commandAndTargetString.components(separatedBy: " ")
self.command = commandAndTargetComponents.remove(at: 0)
self.target = commandAndTargetComponents
// If the command is a 3-didgit numeric, the first target must go
if let cmd = Int(command) {
if cmd >= 0 && cmd < 1000 && target.count > 0 {
target.remove(at: 0)
}
}
// If this check if not performed, this code could crash if the last character of trimmedString is a colon
if colonSpaceRange.upperBound != trimmedString.endIndex {
var parametersStart = trimmedString.index(after: colonSpaceRange.upperBound)
// Fixes a bug where the first character of the parameters is cut off
parametersStart = trimmedString.index(before: parametersStart)
self.parameters = String(trimmedString[parametersStart ..< trimmedString.endIndex])
}
} else {
// There are no parameters
var spaceSeperatedArray = trimmedString.components(separatedBy: " ")
self.command = spaceSeperatedArray.remove(at: 0)
self.target = spaceSeperatedArray
}
}
}
| apache-2.0 | fea50701d69cbb9fad9b3b3782becba9 | 40.090395 | 118 | 0.561254 | 5.089573 | false | false | false | false |
bugnitude/SamplePDFViewer | SamplePDFViewer/CGSize+Extension.swift | 1 | 918 | import UIKit
extension CGSize {
enum RoundType {
case none
case down
case up
case off
}
func aspectFitSize(within size: CGSize, roundType: RoundType = .none) -> CGSize {
if self.width == 0.0 || self.height == 0.0 {
return CGSize.zero
}
let widthRatio = size.width / self.width
let heightRatio = size.height / self.height
let aspectFitRatio = min(widthRatio, heightRatio)
var aspectFitSize = CGSize(width: self.width * aspectFitRatio, height: self.height * aspectFitRatio)
switch roundType {
case .down:
aspectFitSize = CGSize(width: floor(aspectFitSize.width), height: floor(aspectFitSize.height))
case .up:
aspectFitSize = CGSize(width: ceil(aspectFitSize.width), height: ceil(aspectFitSize.height))
case .off:
aspectFitSize = CGSize(width: round(aspectFitSize.width), height: round(aspectFitSize.height))
default:
break
}
return aspectFitSize
}
}
| mit | 62a47d0f68e7e61c3ba1061aac5705a8 | 24.5 | 102 | 0.71024 | 3.451128 | false | false | false | false |
radvansky-tomas/SwiftBLEPeripheral | BLEPeriferal/BLEPeriferalServer.swift | 1 | 6069 | //
// BLEPeriferalServer.swift
// BLEPeriferal
//
// Created by Tomas Radvansky on 20/10/2015.
// Copyright © 2015 Radvansky Solutions. All rights reserved.
//
import UIKit
import CoreBluetooth
protocol BLEPeriferalServerDelegate
{
func periferalServer(periferal:BLEPeriferalServer, centralDidSubscribe:CBCentral)
func periferalServer(periferal:BLEPeriferalServer, centralDidUnsubscribe:CBCentral)
}
class BLEPeriferalServer: NSObject,CBPeripheralManagerDelegate {
//MARK:-Public
var serviceName:String?
var serviceUUID:CBUUID?
var characteristicUUID:CBUUID?
var delegate:BLEPeriferalServerDelegate?
//MARK:-Private
var peripheral:CBPeripheralManager?
var characteristic:CBMutableCharacteristic?
var serviceRequiresRegistration:Bool?
var service:CBMutableService?
var pendingData:NSData?
init(withDelegate delegate:BLEPeriferalServerDelegate)
{
super.init()
self.peripheral = CBPeripheralManager(delegate: self, queue: nil)
self.delegate = delegate
}
class func isBluetoothSupported()->Bool
{
if (NSClassFromString("CBPeripheralManager")==nil)
{
return false
}
return true
}
func sendToSubscribers(data:NSData)
{
if (self.peripheral?.state != CBPeripheralManagerState.PoweredOn)
{
print("sendToSubscribers: peripheral not ready for sending state: %d", self.peripheral!.state.rawValue)
return
}
if let success:Bool = (self.peripheral?.updateValue(data, forCharacteristic: self.characteristic!, onSubscribedCentrals: nil))!
{
if !success
{
print("Failed to send data, buffering data for retry once ready.")
self.pendingData = data
return
}
}
}
func applicationDidEnterBackground()
{
}
func applicationWillEnterForeground()
{
print("applicationWillEnterForeground")
}
func startAdvertising()
{
if self.peripheral?.isAdvertising == true
{
self.peripheral?.stopAdvertising()
}
let advertisement:[String:AnyObject]? = [CBAdvertisementDataServiceUUIDsKey:[self.serviceUUID!], CBAdvertisementDataLocalNameKey:self.serviceName!]
self.peripheral?.startAdvertising(advertisement)
}
func stopAdvertising()
{
self.peripheral?.stopAdvertising()
}
func isAdvertising()->Bool?
{
return self.peripheral?.isAdvertising
}
func disableService()
{
self.peripheral?.removeService(self.service!)
self.service = nil
self.stopAdvertising()
}
func enableService()
{
if (self.service != nil)
{
self.peripheral?.removeService(self.service!)
}
self.service = CBMutableService(type: self.serviceUUID!, primary: true)
self.characteristic = CBMutableCharacteristic (type: self.characteristicUUID!, properties: CBCharacteristicProperties.Notify, value: nil, permissions: CBAttributePermissions.Readable)
var characteristics = [CBMutableCharacteristic]()
characteristics.append( self.characteristic!)
self.service?.characteristics = characteristics
self.peripheral?.addService(self.service!)
let runAfter : dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(runAfter, dispatch_get_main_queue()) { () -> Void in
self.startAdvertising()
}
}
//MARK:-CBPeripheralManagerDelegate
func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {
//self.startAdvertising()
}
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
switch (peripheral.state) {
case CBPeripheralManagerState.PoweredOn:
print("peripheralStateChange: Powered On")
// As soon as the peripheral/bluetooth is turned on, start initializing
// the service.
self.enableService()
case CBPeripheralManagerState.PoweredOff:
print("peripheralStateChange: Powered Off")
self.disableService()
self.serviceRequiresRegistration = true
case CBPeripheralManagerState.Resetting:
print("peripheralStateChange: Resetting");
self.serviceRequiresRegistration = true
case CBPeripheralManagerState.Unauthorized:
print("peripheralStateChange: Deauthorized");
self.disableService()
self.serviceRequiresRegistration = true
case CBPeripheralManagerState.Unsupported:
print("peripheralStateChange: Unsupported");
self.serviceRequiresRegistration = true
// TODO: Give user feedback that Bluetooth is not supported.
case CBPeripheralManagerState.Unknown:
print("peripheralStateChange: Unknown")
}
}
func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) {
self.delegate?.periferalServer(self, centralDidSubscribe: central)
}
func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) {
self.delegate?.periferalServer(self, centralDidUnsubscribe: central)
}
func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) {
print(error?.localizedDescription)
}
func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) {
print("isReadyToUpdateSubscribers")
if let data:NSData = self.pendingData
{
self.sendToSubscribers(data)
}
}
}
| mit | af78df2fd79a2b0aaf4714256aa26a17 | 31.978261 | 191 | 0.658537 | 5.451932 | false | false | false | false |
igormatyushkin014/Baggage | Demo/BaggageDemo/BaggageDemo/Flows/Main/MainViewController/MainViewController.swift | 1 | 2290 | //
// MainViewController.swift
// BaggageDemo
//
// Created by Igor Matyushkin on 25.01.16.
// Copyright © 2016 Igor Matyushkin. All rights reserved.
//
import UIKit
class MainViewController: UIViewController, UITextFieldDelegate {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
// MARK: Deinitializer
deinit {
}
// MARK: Outlets
@IBOutlet private weak var sourceTextField: UITextField!
@IBOutlet private weak var resultTextField: UITextField!
@IBOutlet private weak var copyAndPasteButton: UIButton!
// MARK: Variables & properties
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
// MARK: Public methods
override func viewDidLoad() {
super.viewDidLoad()
// Initialize source text field
sourceTextField.delegate = self
// Initialize copy and paste button
copyAndPasteButton.isEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Private methods
// MARK: Actions
@IBAction func copyAndPasteButtonTapped(sender: AnyObject) {
// Copy source text to clipboard
sourceTextField.bg.copy()
// Paste source text to result text field
resultTextField.bg.paste()
}
// MARK: Protocol methods
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == sourceTextField {
let currentText = textField.text ?? ""
let textAfterReplacement = (currentText as NSString).replacingCharacters(in: range, with: string)
let textAfterReplacementIsEmpty = textAfterReplacement.isEmpty
let shouldEnableCopyAndPasteButton = !textAfterReplacementIsEmpty
copyAndPasteButton.isEnabled = shouldEnableCopyAndPasteButton
return true
} else {
return true
}
}
}
| mit | ba7330af84c0a005ca7956b8b900b871 | 24.153846 | 129 | 0.607689 | 5.651852 | false | false | false | false |
Vanlol/MyYDW | SwiftCocoa/Resource/Mine/Controller/XYMainViewController.swift | 1 | 5912 | //
// XYMainViewController.swift
// SwiftCocoa
//
// Created by 祁小峰 on 2017/9/13.
// Copyright © 2017年 admin. All rights reserved.
//
import UIKit
class XYMainViewController: BaseViewController {
@IBOutlet weak var contentScrollView: UIScrollView!
static let dynamicTVTag = 1
static let photoTVTag = 2
let floatViHeight:CGFloat = 38
let headerViHeight:CGFloat = 400
fileprivate lazy var headerView:XYHeaderView = {
let vi = UINib(nibName: "XYHeaderView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! XYHeaderView
vi.frame = CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: 400)
return vi
}()
override func viewDidLoad() {
super.viewDidLoad()
initNav()
addSubViews()
}
/**
* 初始化nav
*/
fileprivate func initNav() {
navigationController?.navigationBar.isTranslucent = false
setUpSystemNav(title: "个人中心", hexColorBg: 0xffffff)
navigationItem.leftBarButtonItem = UIBarButtonItem.backItemWithImage(image: "4_nav_return_icon", target: self, action: #selector(backButtonClick))
}
//MARK: 返回按钮点击事件
func backButtonClick() {
navigationController?.popViewController(animated: true)
}
//MARK: 添加子试图
fileprivate func addSubViews() {
view.addSubview(headerView)
contentScrollView.contentOffset = CGPoint.zero
contentScrollView.contentSize = CGSize(width: 2*C.SCREEN_WIDTH, height: 0)
let dynamicVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "XYDynamicViewControllerID") as! XYDynamicViewController
addChildViewController(dynamicVC)
dynamicVC.tableView.tag = XYMainViewController.dynamicTVTag
dynamicVC.tableView.contentInset = UIEdgeInsets(top: headerViHeight - 64, left: 0, bottom: 64, right: 0)
dynamicVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
let photoVC = UIStoryboard(name: "Mine", bundle: nil).instantiateViewController(withIdentifier: "XYPhotoViewControllerID") as! XYPhotoViewController
addChildViewController(photoVC)
photoVC.tableView.tag = XYMainViewController.photoTVTag
photoVC.tableView.contentInset = UIEdgeInsets(top: headerViHeight - 64, left: 0, bottom: 64, right: 0)
photoVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
contentScrollView.addSubview(dynamicVC.tableView)
contentScrollView.addSubview(photoVC.tableView)
}
//MARK: 重新布局子视图
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
Print.dlog("viewDidLayoutSubviews")
for subVC in childViewControllers {
if subVC.isKind(of: XYDynamicViewController.classForCoder()) {
subVC.view.frame = CGRect(x: 0, y: 0, width: C.SCREEN_WIDTH, height: C.SCREEN_HEIGHT)
}else if subVC.isKind(of: XYPhotoViewController.classForCoder()) {
subVC.view.frame = CGRect(x: C.SCREEN_WIDTH, y: 0, width: C.SCREEN_WIDTH, height: C.SCREEN_HEIGHT)
}
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let tabVi = object as! UITableView
/* 没什么卵用的判断 */
if (contentScrollView.contentOffset.x == 0 && tabVi.tag == XYMainViewController.photoTVTag) || (contentScrollView.contentOffset.x == C.SCREEN_WIDTH && tabVi.tag == XYMainViewController.dynamicTVTag) {
return
}
Print.dlog(tabVi.contentOffset.y)//-336
if tabVi.contentOffset.y >= -floatViHeight {
headerView.frame.origin.y = -headerViHeight + floatViHeight + 64
if tabVi.tag == XYMainViewController.dynamicTVTag {
let anotherTabVi = view.viewWithTag(XYMainViewController.photoTVTag) as! UITableView
if anotherTabVi.contentOffset.y < -floatViHeight {
anotherTabVi.contentOffset = CGPoint(x: 0, y: -floatViHeight)
}
}else{
let anotherTabVi = view.viewWithTag(XYMainViewController.dynamicTVTag) as! UITableView
if anotherTabVi.contentOffset.y < -floatViHeight {
anotherTabVi.contentOffset = CGPoint(x: 0, y: -floatViHeight)
}
}
}else{
headerView.frame.origin.y = -headerViHeight + 64 - tabVi.contentOffset.y
if (tabVi.contentOffset.y < -floatViHeight && tabVi.contentOffset.y >= -headerViHeight) {
let tag = tabVi.tag == XYMainViewController.dynamicTVTag ? XYMainViewController.photoTVTag : XYMainViewController.dynamicTVTag
let anotherTabVi = view.viewWithTag(tag) as! UITableView
anotherTabVi.contentOffset = tabVi.contentOffset
}
}
}
/*
* 注销观察者模式
*/
deinit {
for subVC in childViewControllers {
if subVC.isKind(of: XYDynamicViewController.classForCoder()) {
(subVC as! XYDynamicViewController).tableView.removeObserver(self, forKeyPath: "contentOffset", context: nil)
}else if subVC.isKind(of: XYPhotoViewController.classForCoder()) {
(subVC as! XYPhotoViewController).tableView.removeObserver(self, forKeyPath: "contentOffset", context: nil)
}
}
}
}
extension XYMainViewController:UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isKind(of: UITableView.classForCoder()) {
return
}
}
}
| apache-2.0 | e94da4afcd8a690967909644f98f8471 | 40.564286 | 208 | 0.648393 | 4.629276 | false | false | false | false |
IvanVorobei/RequestPermission | Example/SPPermission/SPPermission/Frameworks/SparrowKit/Animation/SPAnimation.swift | 1 | 2533 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
enum SPAnimation {
static func animate(_ duration: TimeInterval,
animations: (() -> Void)!,
delay: TimeInterval = 0,
options: UIView.AnimationOptions = [],
withComplection completion: (() -> Void)! = {}) {
UIView.animate(
withDuration: duration,
delay: delay,
options: options,
animations: {
animations()
}, completion: { finished in
completion()
})
}
static func animateWithRepeatition(_ duration: TimeInterval,
animations: (() -> Void)!,
delay: TimeInterval = 0,
options: UIView.AnimationOptions = [],
withComplection completion: (() -> Void)! = {}) {
var optionsWithRepeatition = options
optionsWithRepeatition.insert([.autoreverse, .repeat, .allowUserInteraction])
self.animate(
duration,
animations: {
animations()
},
delay: delay,
options: optionsWithRepeatition,
withComplection: {
completion()
})
}
}
| mit | 3d6d706f962f45adfb7db02d4fc25f2e | 37.953846 | 88 | 0.586888 | 5.540481 | false | false | false | false |
siyana/SwiftMaps | PhotoMaps/PhotoMaps/CoreDataManager.swift | 1 | 4087 | //
// CoreDataManager.swift
// PhotoMaps
//
// Created by Siyana Slavova on 3/24/15.
// Copyright (c) 2015 Siyana Slavova. All rights reserved.
//
import Foundation
import CoreData
class CoreDataManager: NSObject {
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "PM.PhotoMaps" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("PhotoMaps", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PhotoMaps.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
} | mit | e45b2738d9e2d2deec0d411ef46d95d9 | 52.789474 | 290 | 0.688769 | 5.732118 | false | false | false | false |
belatrix/iOSAllStars | AllStarsV2/AllStarsV2/iPhone/Classes/Login/ChangePasswordViewController.swift | 1 | 5850 | //
// ChangePasswordViewController.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 25/07/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class ChangePasswordViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var constraintBottomViewLogo : NSLayoutConstraint!
@IBOutlet weak var constraintTopViewLogo : NSLayoutConstraint!
@IBOutlet weak var constraintCenterForm : NSLayoutConstraint!
@IBOutlet weak var viewLogo : UIView!
@IBOutlet weak var viewFormUser : UIView!
@IBOutlet weak var txtCurrentPassword : UITextField!
@IBOutlet weak var txtNewPassword : UITextField!
@IBOutlet weak var txtRepeatNewPassword : UITextField!
@IBOutlet weak var activityPassword : UIActivityIndicatorView!
var initialValueConstraintCenterForm : CGFloat = 0
var objSession : SessionBE!
//MARK: - UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.txtCurrentPassword {
self.txtNewPassword.becomeFirstResponder()
}else if textField == self.txtNewPassword {
self.txtRepeatNewPassword.becomeFirstResponder()
}else if textField == self.txtRepeatNewPassword {
self.clickBtnChangePassword(nil)
}
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
let result = string.replace(" ", withString: "")
return result.count == string.count
}
//MARK: - WebService
func changePassword(){
self.starLoading()
UserBC.resetUserPassword(withSession: self.objSession, currentPassword: self.txtCurrentPassword.text, newPassword: self.txtNewPassword.text, repeatNewPassword: self.txtRepeatNewPassword.text, withSuccessful: { (objSession) in
self.objSession = objSession
self.stopLoading()
if self.objSession.session_base_profile_complete.boolValue == false{
self.performSegue(withIdentifier: "CompleteProfileViewController", sender: nil)
}else{
UserBC.saveSession(self.objSession)
self.performSegue(withIdentifier: "RevealViewController", sender: nil)
}
}) { (title, message) in
self.stopLoading()
CDMUserAlerts.showSimpleAlert(title: title, withMessage: message, withAcceptButton: "ok".localized, withController: self, withCompletion: nil)
}
}
//MARK: -
func starLoading(){
self.view.isUserInteractionEnabled = false
self.activityPassword.startAnimating()
}
func stopLoading(){
self.view.isUserInteractionEnabled = true
self.activityPassword.stopAnimating()
}
//MARK: - IBAction methods
@IBAction func clickBtnChangePassword(_ sender: Any?) {
self.tapToCloseKeyboard(nil)
self.changePassword()
}
@IBAction func tapToCloseKeyboard(_ sender: Any?) {
self.view.endEditing(true)
}
//MARK: - Keyboard Notifications
@objc func keyboardWillShown(notification : NSNotification) -> Void{
let kbSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let finalForm = self.viewFormUser.frame.size.height / 2 + self.initialValueConstraintCenterForm
let sizeScreen = UIScreen.main.bounds.size.height / 2
let availableArea = sizeScreen - (kbSize?.height)!
if finalForm > availableArea {
UIView.animate(withDuration: 0.35, animations: {
self.constraintCenterForm.constant = self.initialValueConstraintCenterForm - (finalForm - availableArea) - 2
self.view.layoutIfNeeded()
})
}
}
@objc func keyboardWillBeHidden(notification : NSNotification) -> Void {
UIView.animate(withDuration: 0.35, animations: {
self.constraintCenterForm.constant = self.initialValueConstraintCenterForm
self.view.layoutIfNeeded()
})
}
//MARK: -
override func viewDidLoad() {
super.viewDidLoad()
self.initialValueConstraintCenterForm = self.constraintCenterForm.constant
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShown(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 63f40b1f1d493af65723b8d89300f688 | 33.204678 | 233 | 0.631732 | 5.425788 | false | false | false | false |
appplemac/ios9-examples | iOS9Sampler/Common/FilterHelper.swift | 6 | 2252 | //
// FilterHelper.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 2015/08/21.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
class FilterHelper: NSObject {
class func filterNamesFor_iOS9(category: String?) -> [String]! {
return FilterHelper.filterNamesFor_iOS9(category, exceptCategories: nil)
}
class func filterNamesFor_iOS9(category: String?, exceptCategories: [String]?) -> [String]! {
var filterNames:[String] = []
let all = CIFilter.filterNamesInCategory(category)
for aFilterName in all {
let attributes = CIFilter(name: aFilterName)!.attributes
if exceptCategories?.count > 0 {
var needExcept = false
let categories = attributes[kCIAttributeFilterCategories] as! [String]
for aCategory in categories {
if (exceptCategories?.contains(aCategory) == true) {
needExcept = true
break
}
}
if needExcept {
continue
}
}
let availability = attributes[kCIAttributeFilterAvailable_iOS]
// print("filtername:\(aFilterName), availability:\(availability)")
if availability != nil &&
availability as! String == "9" {
filterNames.append(aFilterName)
}
}
return filterNames
}
}
extension CIFilter {
func categoriesStringForFilter() -> String {
var categories = self.attributes[kCIAttributeFilterCategories]!.description
categories = categories.stringByReplacingOccurrencesOfString("(", withString: "")
categories = categories.stringByReplacingOccurrencesOfString(")", withString: "")
categories = categories.stringByReplacingOccurrencesOfString("\n", withString: "")
categories = categories.stringByReplacingOccurrencesOfString(" ", withString: "")
categories = categories.stringByReplacingOccurrencesOfString("CICategory", withString: "")
return categories
}
}
| mit | 67abde6a7ff8493b9f2440dde60c851f | 31.623188 | 98 | 0.584629 | 5.641604 | false | false | false | false |
kinetic-fit/sensors-swift-trainers | Sources/SwiftySensorsTrainers/WahooTrainerSerializer.swift | 1 | 5484 | //
// WahooTrainerSerializer.swift
// SwiftySensorsTrainers
//
// https://github.com/kinetic-fit/sensors-swift-trainers
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
import SwiftySensors
/**
Message Serializer / Deserializer for Wahoo Trainers.
Work In Progress!
*/
open class WahooTrainerSerializer {
open class Response {
fileprivate(set) var operationCode: OperationCode!
}
public enum OperationCode: UInt8 {
case unlock = 32
case setResistanceMode = 64
case setStandardMode = 65
case setErgMode = 66
case setSimMode = 67
case setSimCRR = 68
case setSimWindResistance = 69
case setSimGrade = 70
case setSimWindSpeed = 71
case setWheelCircumference = 72
}
public static func unlockCommand() -> [UInt8] {
return [
WahooTrainerSerializer.OperationCode.unlock.rawValue,
0xee, // unlock code
0xfc // unlock code
]
}
public static func setResistanceMode(_ resistance: Float) -> [UInt8] {
let norm = UInt16((1 - resistance) * 16383)
return [
WahooTrainerSerializer.OperationCode.setResistanceMode.rawValue,
UInt8(norm & 0xFF),
UInt8(norm >> 8 & 0xFF)
]
}
public static func setStandardMode(level: UInt8) -> [UInt8] {
return [
WahooTrainerSerializer.OperationCode.setStandardMode.rawValue,
level
]
}
public static func seErgMode(_ watts: UInt16) -> [UInt8] {
return [
WahooTrainerSerializer.OperationCode.setErgMode.rawValue,
UInt8(watts & 0xFF),
UInt8(watts >> 8 & 0xFF)
]
// response: 0x01 0x42 0x01 0x00 watts1 watts2
}
public static func seSimMode(weight: Float, rollingResistanceCoefficient: Float, windResistanceCoefficient: Float) -> [UInt8] {
// Weight units are Kg
// TODO: Throw Error if weight, rrc or wrc are not within "sane" values
let weightN = UInt16(max(0, min(655.35, weight)) * 100)
let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000)
let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000)
return [
WahooTrainerSerializer.OperationCode.setSimMode.rawValue,
UInt8(weightN & 0xFF),
UInt8(weightN >> 8 & 0xFF),
UInt8(rrcN & 0xFF),
UInt8(rrcN >> 8 & 0xFF),
UInt8(wrcN & 0xFF),
UInt8(wrcN >> 8 & 0xFF)
]
}
public static func setSimCRR(_ rollingResistanceCoefficient: Float) -> [UInt8] {
// TODO: Throw Error if rrc is not within "sane" value range
let rrcN = UInt16(max(0, min(65.535, rollingResistanceCoefficient)) * 1000)
return [
WahooTrainerSerializer.OperationCode.setSimCRR.rawValue,
UInt8(rrcN & 0xFF),
UInt8(rrcN >> 8 & 0xFF)
]
}
public static func setSimWindResistance(_ windResistanceCoefficient: Float) -> [UInt8] {
// TODO: Throw Error if wrc is not within "sane" value range
let wrcN = UInt16(max(0, min(65.535, windResistanceCoefficient)) * 1000)
return [
WahooTrainerSerializer.OperationCode.setSimWindResistance.rawValue,
UInt8(wrcN & 0xFF),
UInt8(wrcN >> 8 & 0xFF)
]
}
public static func setSimGrade(_ grade: Float) -> [UInt8] {
// TODO: Throw Error if grade is not between -1 and 1
let norm = UInt16((min(1, max(-1, grade)) + 1.0) * 65535 / 2.0)
return [
WahooTrainerSerializer.OperationCode.setSimGrade.rawValue,
UInt8(norm & 0xFF),
UInt8(norm >> 8 & 0xFF)
]
}
public static func setSimWindSpeed(_ metersPerSecond: Float) -> [UInt8] {
let norm = UInt16((max(-32.767, min(32.767, metersPerSecond)) + 32.767) * 1000)
return [
WahooTrainerSerializer.OperationCode.setSimWindSpeed.rawValue,
UInt8(norm & 0xFF),
UInt8(norm >> 8 & 0xFF)
]
}
public static func setWheelCircumference(_ millimeters: Float) -> [UInt8] {
let norm = UInt16(max(0, millimeters) * 10)
return [
WahooTrainerSerializer.OperationCode.setWheelCircumference.rawValue,
UInt8(norm & 0xFF),
UInt8(norm >> 8 & 0xFF)
]
}
public static func readReponse(_ data: Data) -> Response? {
let bytes = data.map { $0 }
if bytes.count > 1 {
let result = bytes[0] // 01 = success
let opCodeRaw = bytes[1]
if let opCode = WahooTrainerSerializer.OperationCode(rawValue: opCodeRaw) {
let response: Response
switch opCode {
default:
response = Response()
}
response.operationCode = opCode
return response
} else {
SensorManager.logSensorMessage?("Unrecognized Operation Code: \(opCodeRaw)")
}
if result == 1 {
SensorManager.logSensorMessage?("Success for operation: \(opCodeRaw)")
}
}
return nil
}
}
| mit | a5e43bfa3203174e54411ecf364f7994 | 33.923567 | 131 | 0.563378 | 4.094847 | false | false | false | false |
Bunn/firefox-ios | Extensions/Today/TodayViewController.swift | 1 | 10766 | /* 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 NotificationCenter
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
struct TodayStrings {
static let NewPrivateTabButtonLabel = NSLocalizedString("TodayWidget.NewPrivateTabButtonLabel", tableName: "Today", value: "New Private Tab", comment: "New Private Tab button label")
static let NewTabButtonLabel = NSLocalizedString("TodayWidget.NewTabButtonLabel", tableName: "Today", value: "New Tab", comment: "New Tab button label")
static let GoToCopiedLinkLabel = NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard")
}
private struct TodayUX {
static let privateBrowsingColor = UIColor(rgb: 0xcf68ff)
static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0)
static let linkTextSize: CGFloat = 10.0
static let labelTextSize: CGFloat = 14.0
static let imageButtonTextSize: CGFloat = 14.0
static let copyLinkImageWidth: CGFloat = 23
static let margin: CGFloat = 8
static let buttonsHorizontalMarginPercentage: CGFloat = 0.1
}
@objc (TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding {
var copiedURL: URL?
fileprivate lazy var newTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_tab_button_normal")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.setImage(UIImage(named: "new_tab_button_highlight")?.withRenderingMode(.alwaysTemplate), for: .highlighted)
let label = imageButton.label
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewPrivateTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_private_tab_button_normal"), for: .normal)
button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted)
let label = imageButton.label
label.tintColor = TodayUX.privateBrowsingColor
label.textColor = TodayUX.privateBrowsingColor
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = {
let button = ButtonWithSublabel()
button.setTitle(TodayStrings.GoToCopiedLinkLabel, for: .normal)
button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside)
// We need to set the background image/color for .Normal, so the whole button is tappable.
button.setBackgroundColor(UIColor.clear, forState: .normal)
button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted)
button.setImage(UIImage(named: "copy_link_icon")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize)
button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize)
return button
}()
fileprivate lazy var widgetStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = TodayUX.margin / 2
stackView.distribution = UIStackView.Distribution.fill
stackView.layoutMargins = UIEdgeInsets(top: TodayUX.margin, left: TodayUX.margin, bottom: TodayUX.margin, right: TodayUX.margin)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
fileprivate lazy var buttonStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.spacing = 0
stackView.distribution = UIStackView.Distribution.fillEqually
return stackView
}()
fileprivate var scheme: String {
guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else {
// Something went wrong/weird, but we should fallback to the public one.
return "firefox"
}
return string
}
override func viewDidLoad() {
super.viewDidLoad()
let widgetView: UIView!
self.extensionContext?.widgetLargestAvailableDisplayMode = .compact
let effectView = UIVisualEffectView(effect: UIVibrancyEffect.widgetPrimary())
self.view.addSubview(effectView)
effectView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
widgetView = effectView.contentView
buttonStackView.addArrangedSubview(newTabButton)
buttonStackView.addArrangedSubview(newPrivateTabButton)
widgetStackView.addArrangedSubview(buttonStackView)
widgetStackView.addArrangedSubview(openCopiedLinkButton)
widgetView.addSubview(widgetStackView)
widgetStackView.snp.makeConstraints { make in
make.edges.equalTo(widgetView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCopiedLink()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let edge = size.width * TodayUX.buttonsHorizontalMarginPercentage
buttonStackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return .zero
}
func updateCopiedLink() {
UIPasteboard.general.asyncURL().uponQueue(.main) { res in
if let copiedURL: URL? = res.successValue,
let url = copiedURL {
self.openCopiedLinkButton.isHidden = false
self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked()
self.openCopiedLinkButton.subtitleLabel.text = url.absoluteDisplayString
self.copiedURL = url
} else {
self.openCopiedLinkButton.isHidden = true
self.copiedURL = nil
}
}
}
// MARK: Button behaviour
@objc func onPressNewTab(_ view: UIView) {
openContainingApp("?private=false")
}
@objc func onPressNewPrivateTab(_ view: UIView) {
openContainingApp("?private=true")
}
fileprivate func openContainingApp(_ urlSuffix: String = "") {
let urlString = "\(scheme)://open-url\(urlSuffix)"
self.extensionContext?.open(URL(string: urlString)!) { success in
log.info("Extension opened containing app: \(success)")
}
}
@objc func onPressOpenClibpoard(_ view: UIView) {
if let url = copiedURL,
let encodedString = url.absoluteString.escape() {
openContainingApp("?url=\(encodedString)")
}
}
}
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState state: UIControl.State) {
let colorView = UIView(frame: CGRect(width: 1, height: 1))
colorView.backgroundColor = color
UIGraphicsBeginImageContext(colorView.bounds.size)
if let context = UIGraphicsGetCurrentContext() {
colorView.layer.render(in: context)
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: state)
}
}
class ImageButtonWithLabel: UIView {
lazy var button = UIButton()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
func performLayout() {
addSubview(button)
addSubview(label)
button.snp.makeConstraints { make in
make.top.left.centerX.equalTo(self)
}
label.snp.makeConstraints { make in
make.top.equalTo(button.snp.bottom)
make.leading.trailing.bottom.equalTo(self)
}
label.numberOfLines = 1
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
label.textColor = UIColor.white
}
func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControl.Event) {
button.addTarget(target, action: action, for: events)
}
}
class ButtonWithSublabel: UIButton {
lazy var subtitleLabel = UILabel()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
fileprivate func performLayout() {
let titleLabel = self.label
self.titleLabel?.removeFromSuperview()
addSubview(titleLabel)
let imageView = self.imageView!
let subtitleLabel = self.subtitleLabel
subtitleLabel.textColor = UIColor.lightGray
self.addSubview(subtitleLabel)
imageView.snp.makeConstraints { make in
make.centerY.left.equalTo(self)
make.width.equalTo(TodayUX.copyLinkImageWidth)
}
titleLabel.snp.makeConstraints { make in
make.left.equalTo(imageView.snp.right).offset(TodayUX.margin)
make.trailing.top.equalTo(self)
}
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.snp.makeConstraints { make in
make.bottom.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom)
make.leading.trailing.equalTo(titleLabel)
}
}
override func setTitle(_ text: String?, for state: UIControl.State) {
self.label.text = text
super.setTitle(text, for: state)
}
}
| mpl-2.0 | e0f84b03a716b93630e80ef6d0ffc943 | 35.619048 | 186 | 0.680011 | 4.940799 | false | false | false | false |
RevenueCat/purchases-ios | Tests/UnitTests/Mocks/MockUserDefaults.swift | 1 | 2085 | //
// Created by RevenueCat on 2/3/20.
// Copyright (c) 2020 Purchases. All rights reserved.
//
import Foundation
class MockUserDefaults: UserDefaults {
var stringForKeyCalledValue: String?
var setObjectForKeyCalledValue: String?
var setObjectForKeyCallCount: Int = 0
var removeObjectForKeyCalledValues: [String] = []
var dataForKeyCalledValue: String?
var objectForKeyCalledValue: String?
var dictionaryForKeyCalledValue: String?
var setBoolForKeyCalledValue: String?
var setValueForKeyCalledValue: String?
var mockValues: [String: Any] = [:]
override func string(forKey defaultName: String) -> String? {
stringForKeyCalledValue = defaultName
return mockValues[defaultName] as? String
}
override func removeObject(forKey defaultName: String) {
removeObjectForKeyCalledValues.append(defaultName)
mockValues.removeValue(forKey: defaultName)
}
override func set(_ value: Any?, forKey defaultName: String) {
setObjectForKeyCallCount += 1
setObjectForKeyCalledValue = defaultName
mockValues[defaultName] = value
}
override func data(forKey defaultName: String) -> Data? {
dataForKeyCalledValue = defaultName
return mockValues[defaultName] as? Data
}
override func object(forKey defaultName: String) -> Any? {
objectForKeyCalledValue = defaultName
return mockValues[defaultName]
}
override func set(_ value: Bool, forKey defaultName: String) {
setValueForKeyCalledValue = defaultName
mockValues[defaultName] = value
}
override func dictionary(forKey defaultName: String) -> [String: Any]? {
dictionaryForKeyCalledValue = defaultName
return mockValues[defaultName] as? [String: Any]
}
override func dictionaryRepresentation() -> [String: Any] { mockValues }
override func synchronize() -> Bool {
// Nothing to do
return false
}
override func removePersistentDomain(forName domainName: String) {
mockValues = [:]
}
}
| mit | 5e5b04f47c4a99fa58a0eb39517db354 | 29.217391 | 76 | 0.692086 | 4.964286 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Features/Shared/CloudCapability.swift | 2 | 10402 | //
// CloudCapability.swift
// Operations
//
// Created by Daniel Thorpe on 02/10/2015.
// Copyright © 2015 Dan Thorpe. All rights reserved.
//
import CloudKit
/**
# Cloud Status
Value represents the current CloudKit status for the user.
CloudKit has a relatively convoluted status API.
First, we must check the user's accout status, i.e. are
they logged in to iCloud.
Next, we check the status for the application permissions.
Then, we might need to request the application permissions.
*/
public struct CloudStatus: AuthorizationStatusType {
/// - returns: the CKAccountStatus
public let account: CKAccountStatus
/// - returns: the CKApplicationPermissionStatus?
public let permissions: CKApplicationPermissionStatus?
/// - returns: any NSError?
public let error: NSError?
init(account: CKAccountStatus, permissions: CKApplicationPermissionStatus? = .None, error: NSError? = .None) {
self.account = account
self.permissions = permissions
self.error = error
}
/**
Determine whether the application permissions have been met.
This method takes into account, any errors received from CloudKit,
the account status, application permission status, and the required
application permissions.
*/
public func isRequirementMet(requirement: CKApplicationPermissions) -> Bool {
if let _ = error {
return false
}
switch (requirement, account, permissions) {
case ([], .Available, _):
return true
case (_, .Available, .Some(.Granted)) where requirement != []:
return true
default:
return false
}
}
}
/**
A refined CapabilityRegistrarType for Capability.Cloud. This
protocol defines two functions which the registrar uses to get
the current authorization status and request access.
*/
public protocol CloudContainerRegistrarType: CapabilityRegistrarType {
var containerIdentifier: String? { get }
var cloudKitContainer: CKContainer! { get }
/**
Provide an instance of Self with the given identifier. This is
because we need to determined the capability of a specific cloud
kit container.
*/
static func containerWithIdentifier(identifier: String?) -> Self
/**
Get the account status, a CKAccountStatus.
- parameter completionHandler: a completion handler which receives the account status.
*/
func opr_accountStatusWithCompletionHandler(completionHandler: (CKAccountStatus, NSError?) -> Void)
/**
Get the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
func opr_statusForApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock)
/**
Request the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
func opr_requestApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock)
}
/**
The Cloud capability, which generic over CloudContainerRegistrarType.
Framework consumers should not use this directly, but instead
use Capability.Cloud. So that its usage is like this:
```swift
GetAuthorizationStatus(Capability.Cloud()) { status in
// check the status etc.
}
```
- see: Capability.Cloud
*/
public class CloudCapability: NSObject, CapabilityType {
/// - returns: a String, the name of the capability
public let name: String
/// - returns: a CKApplicationPermissions, the required permissions for the container
public let requirement: CKApplicationPermissions
var hasRequirements: Bool {
return requirement != []
}
internal let containerId: String?
internal var storedRegistrar: CloudContainerRegistrarType? = .None
internal var registrar: CloudContainerRegistrarType {
get {
storedRegistrar = storedRegistrar ?? CloudContainerRegistrar.containerWithIdentifier(containerId)
return storedRegistrar!
}
}
public init(permissions: CKApplicationPermissions = [], containerId: String? = .None) {
self.name = "Cloud"
self.requirement = permissions
self.containerId = containerId
super.init()
}
/**
Initialize the capability. By default, it requires no extra application permissions.
Note that framework consumers should not initialized this class directly, but instead
use Capability.Cloud, which is a typealias of CloudCapability, and has a slightly
different initializer to allow supplying the CloudKit container identifier.
- see: Capability.Cloud
- see: CloudCapability
- parameter requirement: the required EKEntityType, defaults to .Event
- parameter registrar: the registrar to use. Defauls to creating a Registrar.
*/
public required init(_ requirement: CKApplicationPermissions = []) {
self.name = "Cloud"
self.requirement = requirement
self.containerId = .None
super.init()
}
/// - returns: true, CloudKit is always available
public func isAvailable() -> Bool {
return true
}
/**
Get the current authorization status of CloudKit from the Registrar.
- parameter completion: a CloudStatus -> Void closure.
*/
public func authorizationStatus(completion: CloudStatus -> Void) {
verifyAccountStatus(completion: completion)
}
/**
Requests authorization to the Cloud Kit container from the Registrar.
- parameter completion: a dispatch_block_t
*/
public func requestAuthorizationWithCompletion(completion: dispatch_block_t) {
verifyAccountStatus(true) { _ in
completion()
}
}
func verifyAccountStatus(shouldRequest: Bool = false, completion: CloudStatus -> Void) {
registrar.opr_accountStatusWithCompletionHandler { status, error in
switch (status, self.hasRequirements) {
case (.Available, true):
self.verifyPermissions(shouldRequest, completion: completion)
default:
completion(CloudStatus(account: status, permissions: .None, error: error))
}
}
}
func verifyPermissions(shouldRequest: Bool = false, completion: CloudStatus -> Void) {
registrar.opr_statusForApplicationPermission(requirement) { status, error in
switch (status, shouldRequest) {
case (.InitialState, true):
self.requestPermissionsWithCompletion(completion)
default:
completion(CloudStatus(account: .Available, permissions: status, error: error))
}
}
}
func requestPermissionsWithCompletion(completion: CloudStatus -> Void) {
dispatch_async(Queue.Main.queue) {
self.registrar.opr_requestApplicationPermission(self.requirement) { status, error in
completion(CloudStatus(account: .Available, permissions: status, error: error))
}
}
}
}
/**
A registrar for CKContainer.
*/
public final class CloudContainerRegistrar: NSObject, CloudContainerRegistrarType {
/// Provide a CloudContainerRegistrar for a CKContainer with the given identifier.
public static func containerWithIdentifier(identifier: String?) -> CloudContainerRegistrar {
let container = CloudContainerRegistrar()
container.containerIdentifier = identifier
if let id = identifier {
container.cloudKitContainer = CKContainer(identifier: id)
}
return container
}
public private(set) var containerIdentifier: String? = .None
public private(set) lazy var cloudKitContainer: CKContainer! = CKContainer.defaultContainer()
/**
Get the account status, a CKAccountStatus.
- parameter completionHandler: a completion handler which receives the account status.
*/
public func opr_accountStatusWithCompletionHandler(completionHandler: (CKAccountStatus, NSError?) -> Void) {
cloudKitContainer.accountStatusWithCompletionHandler(completionHandler)
}
/**
Get the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
public func opr_statusForApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock) {
cloudKitContainer.statusForApplicationPermission(applicationPermission, completionHandler: completionHandler)
}
/**
Request the application permission, a CKApplicationPermissions.
- parameter applicationPermission: the CKApplicationPermissions
- parameter completionHandler: a CKApplicationPermissionBlock closure
*/
public func opr_requestApplicationPermission(applicationPermission: CKApplicationPermissions, completionHandler: CKApplicationPermissionBlock) {
cloudKitContainer.requestApplicationPermission(applicationPermission, completionHandler: completionHandler)
}
}
extension Capability {
/**
# Capability.Cloud
This type represents the app's permission to access a particular CKContainer.
For framework consumers - use with `GetAuthorizationStatus`, `Authorize` and
`AuthorizedFor`.
For example, authorize usage of the default container
```swift
Authorize(Capability.Cloud()) { available, status in
// etc
}
```
For example, authorize usage of another container;
```swift
Authorize(Capability.Cloud(containerId: "iCloud.com.myapp.my-container-id")) { available, status in
// etc
}
```
*/
public typealias Cloud = CloudCapability
}
extension CloudCapability {
/// - returns: the `CKContainer`
public var container: CKContainer {
return registrar.cloudKitContainer
}
}
@available(*, unavailable, renamed="AuthorizedFor(Cloud())")
public typealias CloudContainerCondition = AuthorizedFor<Capability.Cloud>
| gpl-3.0 | 3b819c58aca1f62a043d43b765040d33 | 32.660194 | 150 | 0.705894 | 5.282377 | false | false | false | false |
davidisaaclee/VectorSwift | Example/Tests/CustomVectorSpec.swift | 1 | 3387 | import Quick
import Nimble
import VectorSwift
class CustomVector2TypeSpec: QuickSpec {
typealias VectorType = CustomVector2
override func spec() {
describe("Custom vectors") {
let pt = VectorType(collection: [3, 4])
it("can initialize from collections") {
expect(CustomVector2(x: 0, y: 1)).to(equal(CustomVector2(x: 0, y: 1)))
expect(VectorType(collection: [1, 2])).to(equal(CustomVector2(x: 1, y: 2)))
expect(VectorType(collection: [-1, -2, 3])).to(equal(CustomVector2(x: -1, y: -2)))
}
it("adopts CollectionType") {
expect(pt[0]).to(equal(pt.x))
expect(pt[1]).to(equal(pt.y))
}
it("calculates magnitude") {
expect(pt.magnitude).to(equal(5))
}
it("can add") {
let pt2 = VectorType(collection: [1, -2])
expect(pt + pt2).to(equal(VectorType(collection: [4, 2])))
}
it("can scale") {
expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12])))
expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4])))
}
it("can get unit vector") {
expect(VectorType(collection: [10, 0]).unit).to(equal(VectorType(collection: [1, 0])))
expect(VectorType(collection: [0, 10]).unit).to(equal(VectorType(collection: [0, 1])))
let u = VectorType(collection: [3, 4]).unit
expect(u.x).to(beCloseTo(0.6))
expect(u.y).to(beCloseTo(0.8))
}
it("can negate") {
expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y])))
}
it("can subtract") {
expect(pt - VectorType(collection: [-2, 4])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4])))
}
}
}
}
class CustomVector3TypeSpec: QuickSpec {
typealias VectorType = CustomVector3
override func spec() {
describe("Custom vectors") {
let pt = VectorType(collection: [3, 4, 5])
it("can initialize from collections") {
expect(VectorType(collection: [1, 2, 3])).to(equal(VectorType(x: 1, y: 2, z: 3)))
expect(VectorType(collection: [-1, -2, 3, 4])).to(equal(VectorType(x: -1, y: -2, z: 3)))
}
it("adopts CollectionType") {
expect(pt[0]).to(equal(pt.x))
expect(pt[1]).to(equal(pt.y))
expect(pt[2]).to(equal(pt.z))
}
it("calculates magnitude") {
expect(pt.magnitude).to(beCloseTo(5 * Float(2.0).toThePowerOf(0.5)))
}
it("can add") {
let pt2 = VectorType(collection: [1, -2, 3])
expect(pt + pt2).to(equal(VectorType(collection: [3 + 1, 4 + -2, 5 + 3])))
}
it("can scale") {
expect(pt * Float(3)).to(equal(VectorType(collection: [9, 12, 15])))
expect(pt * Float(-1)).to(equal(VectorType(collection: [-3, -4, -5])))
}
it("can get unit vector") {
expect(VectorType(collection: [10, 0, 0]).unit).to(equal(VectorType(collection: [1, 0, 0])))
expect(VectorType(collection: [0, 10, 0]).unit).to(equal(VectorType(collection: [0, 1, 0])))
expect(VectorType(collection: [0, 0, 10]).unit).to(equal(VectorType(collection: [0, 0, 1])))
let u = VectorType(collection: [3, 4, 5]).unit
expect(u.x).to(beCloseTo(3.0 / (5.0 * pow(2.0, 0.5))))
expect(u.y).to(beCloseTo(2.0 * pow(2.0, 0.5) / 5.0))
expect(u.z).to(beCloseTo(1.0 / pow(2.0, 0.5)))
}
it("can negate") {
expect(pt.negative).to(equal(VectorType(collection: [-pt.x, -pt.y, -pt.z])))
}
it("can subtract") {
expect(pt - VectorType(collection: [-2, 4, 1])).to(equal(VectorType(collection: [pt.x + 2, pt.y - 4, pt.z - 1])))
}
}
}
}
| mit | 8eac2e2053cf7d43ac3599c931047851 | 30.073394 | 117 | 0.607322 | 2.769419 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/Future+Functional.swift | 111 | 7931 | //===--- Future+Functional.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Result
import Boilerplate
import ExecutionContext
public extension Future {
public func onComplete(callback: Result<Value, AnyError> -> Void) -> Self {
return self.onCompleteInternal(callback)
}
}
public extension FutureType {
public func onSuccess(f: Value -> Void) -> Self {
return self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
f(value)
}, ifFailure: {_ in})
}
}
public func onFailure<E : ErrorProtocol>(f: E -> Void) -> Self{
return self.onComplete { (result:Result<Value, E>) in
result.analysis(ifSuccess: {_ in}, ifFailure: {error in
f(error)
})
}
}
public func onFailure(f: ErrorProtocol -> Void) -> Self {
return self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: {_ in}, ifFailure: {error in
f(error.error)
})
}
}
}
public extension FutureType {
public func map<B>(f:(Value) throws -> B) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result = result.flatMap { value in
materializeAny {
try f(value)
}
}
try! future.complete(result)
}
return future
}
public func flatMap<B, F : FutureType where F.Value == B>(f:(Value) -> F) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
let b = f(value)
b.onComplete { (result:Result<B, AnyError>) in
try! future.complete(result)
}
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func flatMap<B, E : ErrorProtocol>(f:(Value) -> Result<B, E>) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
let b = f(value)
try! future.complete(b)
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func flatMap<B>(f:(Value) -> B?) -> Future<B> {
let future = MutableFuture<B>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result:Result<B, AnyError> = result.flatMap { value in
guard let b = f(value) else {
return Result(error: AnyError(Error.MappedNil))
}
return Result(value: b)
}
try! future.complete(result)
}
return future
}
public func filter(f: (Value)->Bool) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
result.analysis(ifSuccess: { value in
if f(value) {
try! future.success(value)
} else {
try! future.fail(Error.FilteredOut)
}
}, ifFailure: { error in
try! future.fail(error)
})
}
return future
}
public func filterNot(f: (Value)->Bool) -> Future<Value> {
return self.filter { value in
return !f(value)
}
}
public func recover<E : ErrorProtocol>(f:(E) throws ->Value) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, E>) in
let result = result.flatMapError { error in
return materializeAny {
try f(error)
}
}
future.tryComplete(result)
}
// if first one didn't match this one will be called next
future.completeWith(self)
return future
}
public func recover(f:(ErrorProtocol) throws ->Value) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let result = result.flatMapError { error in
return materializeAny {
try f(error.error)
}
}
future.tryComplete(result)
}
// if first one didn't match this one will be called next
future.completeWith(self)
return future
}
public func recoverWith<E : ErrorProtocol>(f:(E) -> Future<Value>) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
guard let mapped:Result<Value, E> = result.tryAsError() else {
try! future.complete(result)
return
}
mapped.analysis(ifSuccess: { _ in
try! future.complete(result)
}, ifFailure: { e in
future.completeWith(f(e))
})
}
return future
}
public func recoverWith(f:(ErrorProtocol) -> Future<Value>) -> Future<Value> {
let future = MutableFuture<Value>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
guard let mapped:Result<Value, AnyError> = result.tryAsError() else {
try! future.complete(result)
return
}
mapped.analysis(ifSuccess: { _ in
try! future.complete(result)
}, ifFailure: { e in
future.completeWith(f(e.error))
})
}
return future
}
public func zip<B, F : FutureType where F.Value == B>(f:F) -> Future<(Value, B)> {
let future = MutableFuture<(Value, B)>(context: self.context)
self.onComplete { (result:Result<Value, AnyError>) in
let context = ExecutionContext.current
result.analysis(ifSuccess: { first -> Void in
f.onComplete { (result:Result<B, AnyError>) in
context.execute {
result.analysis(ifSuccess: { second in
try! future.success((first, second))
}, ifFailure: { e in
try! future.fail(e.error)
})
}
}
}, ifFailure: { e in
try! future.fail(e.error)
})
}
return future
}
} | mit | ce0e8554091fb309de72bf1189d1011d | 31.912863 | 92 | 0.510276 | 4.809582 | false | false | false | false |
seraphjiang/JHUIKit | Example/JHUIKit/JHProfileViewController.swift | 1 | 2198 | //
// JHProfileViewController.swift
// JHUIKit
//
// Created by Huan Jiang on 5/6/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import JHUIKit
class JHProfileViewController: UIViewController, JHSwipeViewDelegate {
let runtimeConstants = RuntimeConstants()
var personView: JHProfileCardView?
override func viewDidLoad() {
super.viewDidLoad()
addPersonCard()
handleNotification()
}
func addPersonCard()
{
let superView = UIView(frame: CGRectMake(runtimeConstants.CardMarginWidth, self.runtimeConstants.CardTop, self.runtimeConstants.CardWidth, runtimeConstants.AdaptiveCardHeight))
personView = JHProfileCardView(frame: superView.bounds, image: UIImage(named: "mask")!, radius: 200)
personView!.swipeViewDelegate = self
superView.addSubview(personView!)
self.view.addSubview(superView);
}
func handleNotification()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JHProfileViewController.cardSwiped(_:)), name: "CardSwipedNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JHProfileViewController.cardLikeOrDislike(_:)), name: "CardLikeOrDislikeNotification", object: nil)
}
func cardSwiped(notification: NSNotification)
{
if let _: NSDictionary = notification.userInfo
{
// let swipe_action:String = info["swipe_action"] as! String
// var isLike: Int = swipe_action == "like" ? 1 : 0
}
self.personView!.removeFromSuperview()
NSLog("PersonCard.Notification:jobCardSwiped ")
self.addPersonCard()
}
func cardLikeOrDislike(notification: NSNotification)
{
if let _: NSDictionary = notification.userInfo
{
// let action:String = info["action"] as! String
// var isLike: Int = action == "like" ? 1 : 0
}
self.addPersonCard()
}
func cardUsedUp() {
}
func cardSwiped(liked: Bool, viewSwiped:UIView) {
}
func addNextCard() {
}
} | mit | e018b2f43e1fe5861ee8cbc9e2494819 | 29.957746 | 184 | 0.646336 | 4.577083 | false | false | false | false |
xiaotaijun/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleMediaCell.swift | 2 | 15010 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class AABubbleMediaCell : AABubbleBaseFileCell, NYTPhotosViewControllerDelegate {
// Views
let preview = UIImageView()
let progressBg = UIImageView()
let circullarNode = CircullarNode()
let fileStatusIcon = UIImageView()
let timeBg = UIImageView()
let timeLabel = UILabel()
let statusView = UIImageView()
// Layout
var contentWidth = 0
var contentHeight = 0
var contentViewSize: CGSize? = nil
// Binded data
var thumb : ACFastThumb? = nil
var thumbLoaded = false
var contentLoaded = false
// MARK: -
// MARK: Constructors
init(frame: CGRect) {
super.init(frame: frame, isFullSize: false)
timeBg.image = Imaging.imageWithColor(MainAppTheme.bubbles.mediaDateBg, size: CGSize(width: 1, height: 1))
timeLabel.font = UIFont(name: "HelveticaNeue-Italic", size: 11)
timeLabel.textColor = MainAppTheme.bubbles.mediaDate
statusView.contentMode = UIViewContentMode.Center
fileStatusIcon.contentMode = UIViewContentMode.Center
progressBg.image = Imaging.roundedImage(UIColor(red: 0, green: 0, blue: 0, alpha: 0x64/255.0), size: CGSizeMake(CGFloat(64.0),CGFloat(64.0)), radius: CGFloat(32.0))
mainView.addSubview(preview)
mainView.addSubview(progressBg)
mainView.addSubview(fileStatusIcon)
mainView.addSubview(circullarNode.view)
mainView.addSubview(timeBg)
mainView.addSubview(timeLabel)
mainView.addSubview(statusView)
preview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "mediaDidTap"))
preview.userInteractionEnabled = true
contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func bind(message: ACMessage, reuse: Bool, cellLayout: CellLayout, setting: CellSetting) {
bubbleInsets = UIEdgeInsets(
top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop,
left: 10 + (isIPad ? 16 : 0),
bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom,
right: 10 + (isIPad ? 16 : 0))
if (!reuse) {
// Bind bubble
if (self.isOut) {
bindBubbleType(BubbleType.MediaOut, isCompact: false)
} else {
bindBubbleType(BubbleType.MediaIn, isCompact: false)
}
// Build bubble size
if (message.getContent() is ACPhotoContent) {
var photo = message.getContent() as! ACPhotoContent;
thumb = photo.getFastThumb()
contentWidth = Int(photo.getW())
contentHeight = Int(photo.getH())
} else if (message.getContent() is ACVideoContent) {
var video = message.getContent() as! ACVideoContent;
thumb = video.getFastThumb()
contentWidth = Int(video.getW())
contentHeight = Int(video.getH())
} else {
fatalError("Unsupported content")
}
contentViewSize = AABubbleMediaCell.measureMedia(contentWidth, h: contentHeight)
// Reset loaded thumbs and contents
preview.image = nil
thumbLoaded = false
contentLoaded = false
// Reset progress
circullarNode.hidden = true
circullarNode.setProgress(0, animated: false)
UIView.animateWithDuration(0, animations: { () -> Void in
self.circullarNode.alpha = 0
self.preview.alpha = 0
self.progressBg.alpha = 0
})
// Bind file
fileBind(message, autoDownload: message.getContent() is ACPhotoContent)
}
// Update time
timeLabel.text = cellLayout.date
// Update status
if (isOut) {
statusView.hidden = false
switch(UInt(message.getMessageState().ordinal())) {
case ACMessageState.PENDING.rawValue:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSending
break;
case ACMessageState.SENT.rawValue:
self.statusView.image = Resources.iconCheck1;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSent
break;
case ACMessageState.RECEIVED.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaReceived
break;
case ACMessageState.READ.rawValue:
self.statusView.image = Resources.iconCheck2;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaRead
break;
case ACMessageState.ERROR.rawValue:
self.statusView.image = Resources.iconError;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaError
break
default:
self.statusView.image = Resources.iconClock;
self.statusView.tintColor = MainAppTheme.bubbles.statusMediaSending
break;
}
} else {
statusView.hidden = true
}
}
func mediaDidTap() {
var content = bindedMessage!.getContent() as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
Actor.requestStateWithFileId(fileSource.getFileReference().getFileId(), withCallback: CocoaDownloadCallback(
notDownloaded: { () -> () in
Actor.startDownloadingWithReference(fileSource.getFileReference())
}, onDownloading: { (progress) -> () in
Actor.cancelDownloadingWithFileId(fileSource.getFileReference().getFileId())
}, onDownloaded: { (reference) -> () in
var photoInfo = AAPhoto(image: UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference))!)
var controller = NYTPhotosViewController(photos: [photoInfo])
controller.delegate = self
self.controller.presentViewController(controller, animated: true, completion: nil)
}))
} else if let fileSource = content.getSource() as? ACFileLocalSource {
var rid = bindedMessage!.getRid()
Actor.requestUploadStateWithRid(rid, withCallback: CocoaUploadCallback(
notUploaded: { () -> () in
Actor.resumeUploadWithRid(rid)
}, onUploading: { (progress) -> () in
Actor.pauseUploadWithRid(rid)
}, onUploadedClosure: { () -> () in
var photoInfo = AAPhoto(image: UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor()))!)
var controller = NYTPhotosViewController(photos: [photoInfo])
controller.delegate = self
self.controller.presentViewController(controller, animated: true, completion: nil)
}))
}
}
override func fileUploadPaused(reference: String, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgShowState(selfGeneration)
bgShowIcon("ic_upload", selfGeneration: selfGeneration)
bgHideProgress(selfGeneration)
}
override func fileUploading(reference: String, progress: Double, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgShowState(selfGeneration)
bgHideIcon(selfGeneration)
bgShowProgress(progress, selfGeneration: selfGeneration)
}
override func fileDownloadPaused(selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgShowState(selfGeneration)
bgShowIcon("ic_download", selfGeneration: selfGeneration)
bgHideProgress(selfGeneration)
}
override func fileDownloading(progress: Double, selfGeneration: Int) {
bgLoadThumb(selfGeneration)
bgShowState(selfGeneration)
bgHideIcon(selfGeneration)
bgShowProgress(progress, selfGeneration: selfGeneration)
}
override func fileReady(reference: String, selfGeneration: Int) {
bgLoadReference(reference, selfGeneration: selfGeneration)
bgHideState(selfGeneration)
bgHideIcon(selfGeneration)
bgHideProgress(selfGeneration)
}
func bgLoadThumb(selfGeneration: Int) {
if (thumbLoaded) {
return
}
thumbLoaded = true
if (thumb != nil) {
var loadedThumb = UIImage(data: self.thumb!.getImage().toNSData()!)?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
runOnUiThread(selfGeneration,closure: { ()->() in
self.setPreviewImage(loadedThumb!, fast: true)
});
}
}
func bgLoadReference(reference: String, selfGeneration: Int) {
if (contentLoaded) {
return
}
contentLoaded = true
var loadedContent = UIImage(contentsOfFile: CocoaFiles.pathFromDescriptor(reference))?.roundCorners(contentViewSize!.width - 2, h: contentViewSize!.height - 2, roundSize: 14)
if (loadedContent == nil) {
return
}
runOnUiThread(selfGeneration, closure: { () -> () in
self.setPreviewImage(loadedContent!, fast: false)
})
}
// Progress show/hide
func bgHideProgress(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.circullarNode.alpha = 0
}, completion: { (val) -> Void in
if (val) {
self.circullarNode.hidden = true
}
})
})
}
func bgShowProgress(value: Double, selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
if (self.circullarNode.hidden) {
self.circullarNode.hidden = false
self.circullarNode.alpha = 0
}
self.circullarNode.postProgress(value, animated: true)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.circullarNode.alpha = 1
})
})
}
// State show/hide
func bgHideState(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.progressBg.hideView()
})
}
func bgShowState(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.progressBg.showView()
})
}
// Icon show/hide
func bgShowIcon(name: String, selfGeneration: Int) {
var img = UIImage(named: name)?.tintImage(UIColor.whiteColor())
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.fileStatusIcon.image = img
self.fileStatusIcon.showView()
})
}
func bgHideIcon(selfGeneration: Int) {
self.runOnUiThread(selfGeneration, closure: { () -> () in
self.fileStatusIcon.hideView()
})
}
func setPreviewImage(img: UIImage, fast: Bool){
if ((fast && self.preview.image == nil) || !fast) {
self.preview.image = img;
self.preview.showView()
}
}
// MARK: -
// MARK: Getters
private class func measureMedia(w: Int, h: Int) -> CGSize {
var screenScale = UIScreen.mainScreen().scale;
var scaleW = 240 / CGFloat(w)
var scaleH = 340 / CGFloat(h)
var scale = min(scaleW, scaleH)
return CGSize(width: scale * CGFloat(w), height: scale * CGFloat(h))
}
class func measureMediaHeight(message: ACMessage) -> CGFloat {
if (message.getContent() is ACPhotoContent) {
var photo = message.getContent() as! ACPhotoContent;
return measureMedia(Int(photo.getW()), h: Int(photo.getH())).height + 2;
} else if (message.getContent() is ACVideoContent) {
var video = message.getContent() as! ACVideoContent;
return measureMedia(Int(video.getW()), h: Int(video.getH())).height + 2;
} else {
fatalError("Unknown content type")
}
}
// MARK: -
// MARK: Layout
override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) {
var insets = fullContentInsets
var contentWidth = self.contentView.frame.width
var contentHeight = self.contentView.frame.height
var bubbleHeight = contentHeight - insets.top - insets.bottom
var bubbleWidth = bubbleHeight * CGFloat(self.contentWidth) / CGFloat(self.contentHeight)
layoutBubble(bubbleWidth, contentHeight: bubbleHeight)
if (isOut) {
preview.frame = CGRectMake(contentWidth - insets.left - bubbleWidth, insets.top, bubbleWidth, bubbleHeight)
} else {
preview.frame = CGRectMake(insets.left, insets.top, bubbleWidth, bubbleHeight)
}
circullarNode.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 32, preview.frame.origin.y + preview.frame.height/2 - 32, 64, 64)
progressBg.frame = circullarNode.frame
fileStatusIcon.frame = CGRectMake(preview.frame.origin.x + preview.frame.width/2 - 24, preview.frame.origin.y + preview.frame.height/2 - 24, 48, 48)
timeLabel.frame = CGRectMake(0, 0, 1000, 1000)
timeLabel.sizeToFit()
var timeWidth = (isOut ? 23 : 0) + timeLabel.bounds.width
var timeHeight: CGFloat = 20
timeLabel.frame = CGRectMake(preview.frame.maxX - timeWidth - 18, preview.frame.maxY - timeHeight - 6, timeLabel.frame.width, timeHeight)
if (isOut) {
statusView.frame = CGRectMake(timeLabel.frame.maxX, timeLabel.frame.minY, 23, timeHeight)
}
timeBg.frame = CGRectMake(timeLabel.frame.minX - 3, timeLabel.frame.minY - 1, timeWidth + 6, timeHeight + 2)
}
func photosViewController(photosViewController: NYTPhotosViewController!, referenceViewForPhoto photo: NYTPhoto!) -> UIView! {
return self.preview
}
}
| mit | 58a0fa9c5da64e401b2e0418dce44558 | 38.293194 | 182 | 0.596602 | 4.783301 | false | false | false | false |
mauriciosantos/Buckets-Swift | Source/BitArray.swift | 3 | 9259 | //
// BitArray.swift
// Buckets
//
// Created by Mauricio Santos on 2/23/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// An array of boolean values stored
/// using individual bits, thus providing a
/// very small memory footprint. It has most of the features of a
/// standard array such as constant time random access and
/// amortized constant time insertion at the end of the array.
///
/// Conforms to `MutableCollection`, `ExpressibleByArrayLiteral`
/// , `Equatable`, `Hashable`, `CustomStringConvertible`
public struct BitArray {
// MARK: Creating a BitArray
/// Constructs an empty bit array.
public init() {}
/// Constructs a bit array from a `Bool` sequence, such as an array.
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == Bool {
for value in elements {
append(value)
}
}
/// Constructs a new bit array from an `Int` array representation.
/// All values different from 0 are considered `true`.
public init(intRepresentation : [Int]) {
bits.reserveCapacity((intRepresentation.count/Constants.IntSize) + 1)
for value in intRepresentation {
append(value != 0)
}
}
/// Constructs a new bit array with `count` bits set to the specified value.
public init(repeating repeatedValue: Bool, count: Int) {
precondition(count >= 0, "Can't construct BitArray with count < 0")
let numberOfInts = (count/Constants.IntSize) + 1
let intValue = repeatedValue ? ~0 : 0
bits = [Int](repeating: intValue, count: numberOfInts)
self.count = count
if repeatedValue {
bits[bits.count - 1] = 0
let missingBits = count % Constants.IntSize
self.count = count - missingBits
for _ in 0..<missingBits {
append(repeatedValue)
}
cardinality = count
}
}
// MARK: Querying a BitArray
/// Number of bits stored in the bit array.
public fileprivate(set) var count = 0
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return count == 0
}
/// The first bit, or nil if the bit array is empty.
public var first: Bool? {
return isEmpty ? nil : valueAtIndex(0)
}
/// The last bit, or nil if the bit array is empty.
public var last: Bool? {
return isEmpty ? nil : valueAtIndex(count-1)
}
/// The number of bits set to `true` in the bit array.
public fileprivate(set) var cardinality = 0
// MARK: Adding and Removing Bits
/// Adds a new `Bool` as the last bit.
public mutating func append(_ bit: Bool) {
if realIndexPath(count).arrayIndex >= bits.count {
bits.append(0)
}
setValue(bit, atIndex: count)
count += 1
}
/// Inserts a bit into the array at a given index.
/// Use this method to insert a new bit anywhere within the range
/// of existing bits, or as the last bit. The index must be less
/// than or equal to the number of bits in the bit array. If you
/// attempt to remove a bit at a greater index, you’ll trigger an error.
public mutating func insert(_ bit: Bool, at index: Int) {
checkIndex(index, lessThan: count + 1)
append(bit)
for i in stride(from: (count - 2), through: index, by: -1) {
let iBit = valueAtIndex(i)
setValue(iBit, atIndex: i+1)
}
setValue(bit, atIndex: index)
}
/// Removes the last bit from the bit array and returns it.
///
/// - returns: The last bit, or nil if the bit array is empty.
@discardableResult
public mutating func removeLast() -> Bool {
if let value = last {
setValue(false, atIndex: count-1)
count -= 1
return value
}
preconditionFailure("Array is empty")
}
/// Removes the bit at the given index and returns it.
/// The index must be less than the number of bits in the
/// bit array. If you attempt to remove a bit at a
/// greater index, you’ll trigger an error.
@discardableResult
public mutating func remove(at index: Int) -> Bool {
checkIndex(index)
let bit = valueAtIndex(index)
for i in (index + 1)..<count {
let iBit = valueAtIndex(i)
setValue(iBit, atIndex: i-1)
}
removeLast()
return bit
}
/// Removes all the bits from the array, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepingCapacity keep: Bool = false) {
if !keep {
bits.removeAll(keepingCapacity: false)
} else {
bits[0 ..< bits.count] = [0]
}
count = 0
cardinality = 0
}
// MARK: Private Properties and Helper Methods
/// Structure holding the bits.
fileprivate var bits = [Int]()
fileprivate func valueAtIndex(_ logicalIndex: Int) -> Bool {
let indexPath = realIndexPath(logicalIndex)
var mask = 1 << indexPath.bitIndex
mask = mask & bits[indexPath.arrayIndex]
return mask != 0
}
fileprivate mutating func setValue(_ newValue: Bool, atIndex logicalIndex: Int) {
let indexPath = realIndexPath(logicalIndex)
let mask = 1 << indexPath.bitIndex
let oldValue = mask & bits[indexPath.arrayIndex] != 0
switch (oldValue, newValue) {
case (false, true):
cardinality += 1
case (true, false):
cardinality -= 1
default:
break
}
if newValue {
bits[indexPath.arrayIndex] |= mask
} else {
bits[indexPath.arrayIndex] &= ~mask
}
}
fileprivate func realIndexPath(_ logicalIndex: Int) -> (arrayIndex: Int, bitIndex: Int) {
return (logicalIndex / Constants.IntSize, logicalIndex % Constants.IntSize)
}
fileprivate func checkIndex(_ index: Int, lessThan: Int? = nil) {
let bound = lessThan == nil ? count : lessThan
precondition(count >= 0 && index < bound!, "Index out of range (\(index))")
}
// MARK: Constants
fileprivate struct Constants {
// Int size in bits
static let IntSize = MemoryLayout<Int>.size * 8
}
}
extension BitArray: MutableCollection {
// MARK: MutableCollection Protocol Conformance
/// Always zero, which is the index of the first bit when non-empty.
public var startIndex : Int {
return 0
}
/// Always `count`, which the successor of the last valid
/// subscript argument.
public var endIndex : Int {
return count
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Int) -> Int {
return i + 1
}
/// Provides random access to individual bits using square bracket noation.
/// The index must be less than the number of items in the bit array.
/// If you attempt to get or set a bit at a greater
/// index, you’ll trigger an error.
public subscript(index: Int) -> Bool {
get {
checkIndex(index)
return valueAtIndex(index)
}
set {
checkIndex(index)
setValue(newValue, atIndex: index)
}
}
}
extension BitArray: ExpressibleByArrayLiteral {
// MARK: ExpressibleByArrayLiteral Protocol Conformance
/// Constructs a bit array using a `Bool` array literal.
/// `let example: BitArray = [true, false, true]`
public init(arrayLiteral elements: Bool...) {
bits.reserveCapacity((elements.count/Constants.IntSize) + 1)
for element in elements {
append(element)
}
}
}
extension BitArray: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the bit array.
public var description: String {
return "[" + self.map {"\($0)"}.joined(separator: ", ") + "]"
}
}
extension BitArray: Equatable {
}
// MARK: BitArray Equatable Protocol Conformance
/// Returns `true` if and only if the bit arrays contain the same bits in the same order.
public func ==(lhs: BitArray, rhs: BitArray) -> Bool {
if lhs.count != rhs.count || lhs.cardinality != rhs.cardinality {
return false
}
return lhs.elementsEqual(rhs)
}
extension BitArray: Hashable {
// MARK: Hashable Protocol Conformance
/// The hash value.
/// `x == y` implies `x.hashValue == y.hashValue`
public var hashValue: Int {
var result = 43
result = (31 ^ result) ^ count
for element in self {
result = (31 ^ result) ^ element.hashValue
}
return result
}
}
| mit | c25695c49aaeb21688c611d6ccf59fa7 | 30.260135 | 93 | 0.591484 | 4.558128 | false | false | false | false |
antoninbiret/ABSteppedProgressBar | Exemple-ABSteppedProgressBar/Pods/ABSteppedProgressBar/Sources/ABSteppedProgessBar.swift | 1 | 13992 | //
// ABSteppedProgressBar.swift
// ABSteppedProgressBar
//
// Created by Antonin Biret on 17/02/15.
// Copyright (c) 2015 Antonin Biret. All rights reserved.
//
import UIKit
import Foundation
import CoreGraphics
@objc public protocol ABSteppedProgressBarDelegate {
optional func progressBar(progressBar: ABSteppedProgressBar,
willSelectItemAtIndex index: Int)
optional func progressBar(progressBar: ABSteppedProgressBar,
didSelectItemAtIndex index: Int)
optional func progressBar(progressBar: ABSteppedProgressBar,
canSelectItemAtIndex index: Int) -> Bool
optional func progressBar(progressBar: ABSteppedProgressBar,
textAtIndex index: Int) -> String
}
@IBDesignable public class ABSteppedProgressBar: UIView {
@IBInspectable public var numberOfPoints: Int = 3 {
didSet {
self.setNeedsDisplay()
}
}
public var currentIndex: Int = 0 {
willSet(newValue){
if let delegate = self.delegate {
delegate.progressBar?(self, willSelectItemAtIndex: newValue)
}
}
didSet {
animationRendering = true
self.setNeedsDisplay()
}
}
private var previousIndex: Int = 0
@IBInspectable public var lineHeight: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _lineHeight: CGFloat {
get {
if(lineHeight == 0.0 || lineHeight > self.bounds.height) {
return self.bounds.height * 0.4
}
return lineHeight
}
}
@IBInspectable public var radius: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _radius: CGFloat {
get{
if(radius == 0.0 || radius > self.bounds.height / 2.0) {
return self.bounds.height / 2.0
}
return radius
}
}
@IBInspectable public var progressRadius: CGFloat = 0.0 {
didSet {
maskLayer.cornerRadius = progressRadius
self.setNeedsDisplay()
}
}
private var _progressRadius: CGFloat {
get {
if(progressRadius == 0.0 || progressRadius > self.bounds.height / 2.0) {
return self.bounds.height / 2.0
}
return progressRadius
}
}
@IBInspectable public var progressLineHeight: CGFloat = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
private var _progressLineHeight: CGFloat {
get {
if(progressLineHeight == 0.0 || progressLineHeight > _lineHeight) {
return _lineHeight
}
return progressLineHeight
}
}
@IBInspectable public var stepAnimationDuration: CFTimeInterval = 0.4
@IBInspectable public var displayNumbers: Bool = true {
didSet {
self.setNeedsDisplay()
}
}
public var numbersFont: UIFont? {
didSet {
self.setNeedsDisplay()
}
}
public var numbersColor: UIColor? {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable public var backgroundShapeColor: UIColor = UIColor(red: 166.0/255.0, green: 160.0/255.0, blue: 151.0/255.0, alpha: 0.8) {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable public var selectedBackgoundColor: UIColor = UIColor(red: 150.0/255.0, green: 24.0/255.0, blue: 33.0/255.0, alpha: 1.0) {
didSet {
self.setNeedsDisplay()
}
}
public var delegate: ABSteppedProgressBarDelegate?
private var backgroundLayer: CAShapeLayer = CAShapeLayer()
private var progressLayer: CAShapeLayer = CAShapeLayer()
private var maskLayer: CAShapeLayer = CAShapeLayer()
private var centerPoints = Array<CGPoint>()
private var animationRendering = false
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
convenience init() {
self.init(frame:CGRectZero)
}
func commonInit() {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "gestureAction:")
let swipeGestureRecognizer = UIPanGestureRecognizer(target: self, action: "gestureAction:")
self.addGestureRecognizer(tapGestureRecognizer)
self.addGestureRecognizer(swipeGestureRecognizer)
self.backgroundColor = UIColor.clearColor()
self.layer.addSublayer(backgroundLayer)
self.layer.addSublayer(progressLayer)
progressLayer.mask = maskLayer
self.contentMode = UIViewContentMode.Redraw
}
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
let largerRadius = fmax(_radius, _progressRadius)
let distanceBetweenCircles = (self.bounds.width - (CGFloat(numberOfPoints) * 2 * largerRadius)) / CGFloat(numberOfPoints - 1)
var xCursor: CGFloat = largerRadius
for _ in 0...(numberOfPoints - 1) {
centerPoints.append(CGPointMake(xCursor, bounds.height / 2))
xCursor += 2 * largerRadius + distanceBetweenCircles
}
let progressCenterPoints = Array<CGPoint>(centerPoints[0..<(currentIndex+1)])
if(!animationRendering) {
if let bgPath = shapePath(centerPoints, aRadius: _radius, aLineHeight: _lineHeight) {
backgroundLayer.path = bgPath.CGPath
backgroundLayer.fillColor = backgroundShapeColor.CGColor
}
if let progressPath = shapePath(centerPoints, aRadius: _progressRadius, aLineHeight: _progressLineHeight) {
progressLayer.path = progressPath.CGPath
progressLayer.fillColor = selectedBackgoundColor.CGColor
}
if(displayNumbers) {
for i in 0...(numberOfPoints - 1) {
let centerPoint = centerPoints[i]
let textLayer = CATextLayer()
var textLayerFont = UIFont.boldSystemFontOfSize(_progressRadius)
textLayer.contentsScale = UIScreen.mainScreen().scale
if let nFont = self.numbersFont {
textLayerFont = nFont
}
textLayer.font = CTFontCreateWithName(textLayerFont.fontName as CFStringRef, textLayerFont.pointSize, nil)
textLayer.fontSize = textLayerFont.pointSize
if let nColor = self.numbersColor {
textLayer.foregroundColor = nColor.CGColor
}
if let text = self.delegate?.progressBar?(self, textAtIndex: i) {
textLayer.string = text
} else {
textLayer.string = "\(i)"
}
textLayer.sizeWidthToFit()
textLayer.frame = CGRectMake(centerPoint.x - textLayer.bounds.width/2, centerPoint.y - textLayer.bounds.height/2, textLayer.bounds.width, textLayer.bounds.height)
self.layer.addSublayer(textLayer)
}
}
}
if let currentProgressCenterPoint = progressCenterPoints.last {
let maskPath = self.maskPath(currentProgressCenterPoint)
maskLayer.path = maskPath.CGPath
CATransaction.begin()
let progressAnimation = CABasicAnimation(keyPath: "path")
progressAnimation.duration = stepAnimationDuration * CFTimeInterval(abs(currentIndex - previousIndex))
progressAnimation.toValue = maskPath
progressAnimation.removedOnCompletion = false
progressAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
CATransaction.setCompletionBlock { () -> Void in
if(self.animationRendering) {
if let delegate = self.delegate {
delegate.progressBar?(self, didSelectItemAtIndex: self.currentIndex)
}
self.animationRendering = false
}
}
maskLayer.addAnimation(progressAnimation, forKey: "progressAnimation")
CATransaction.commit()
}
previousIndex = currentIndex
}
func shapePath(centerPoints: Array<CGPoint>, aRadius: CGFloat, aLineHeight: CGFloat) -> UIBezierPath? {
let nbPoint = centerPoints.count
let path = UIBezierPath()
var distanceBetweenCircles: CGFloat = 0
if let first = centerPoints.first where nbPoint > 2 {
let second = centerPoints[1]
distanceBetweenCircles = second.x - first.x - 2 * aRadius
}
let angle = aLineHeight / 2.0 / aRadius;
var xCursor: CGFloat = 0
for i in 0...(2 * nbPoint - 1) {
var index = i
if(index >= nbPoint) {
index = (nbPoint - 1) - (i - nbPoint)
}
let centerPoint = centerPoints[index]
var startAngle: CGFloat = 0
var endAngle: CGFloat = 0
if(i == 0) {
xCursor = centerPoint.x
startAngle = CGFloat(M_PI)
endAngle = -angle
} else if(i < nbPoint - 1) {
startAngle = CGFloat(M_PI) + angle
endAngle = -angle
} else if(i == (nbPoint - 1)){
startAngle = CGFloat(M_PI) + angle
endAngle = 0
} else if(i == nbPoint) {
startAngle = 0
endAngle = CGFloat(M_PI) - angle
} else if (i < (2 * nbPoint - 1)) {
startAngle = angle
endAngle = CGFloat(M_PI) - angle
} else {
startAngle = angle
endAngle = CGFloat(M_PI)
}
path.addArcWithCenter(CGPointMake(centerPoint.x, centerPoint.y), radius: aRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
if(i < nbPoint - 1) {
xCursor += aRadius + distanceBetweenCircles
path.addLineToPoint(CGPointMake(xCursor, centerPoint.y - aLineHeight / 2.0))
xCursor += aRadius
} else if (i < (2 * nbPoint - 1) && i >= nbPoint) {
xCursor -= aRadius + distanceBetweenCircles
path.addLineToPoint(CGPointMake(xCursor, centerPoint.y + aLineHeight / 2.0))
xCursor -= aRadius
}
}
return path
}
func progressMaskPath(currentProgressCenterPoint: CGPoint) -> UIBezierPath {
let maskPath = UIBezierPath(rect: CGRectMake(0.0, 0.0, currentProgressCenterPoint.x + _progressRadius, self.bounds.height))
return maskPath
}
func maskPath(currentProgressCenterPoint: CGPoint) -> UIBezierPath {
let angle = _progressLineHeight / 2.0 / _progressRadius;
let xOffset = cos(angle) * _progressRadius
let maskPath = UIBezierPath()
maskPath.moveToPoint(CGPointMake(0.0, 0.0))
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, 0.0))
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, currentProgressCenterPoint.y - _progressLineHeight))
maskPath.addArcWithCenter(currentProgressCenterPoint, radius: _progressRadius, startAngle: -angle, endAngle: angle, clockwise: true)
maskPath.addLineToPoint(CGPointMake(currentProgressCenterPoint.x + xOffset, self.bounds.height))
maskPath.addLineToPoint(CGPointMake(0.0, self.bounds.height))
maskPath.closePath()
return maskPath
}
func gestureAction(gestureRecognizer:UIGestureRecognizer) {
if(gestureRecognizer.state == UIGestureRecognizerState.Ended ||
gestureRecognizer.state == UIGestureRecognizerState.Changed ) {
let touchPoint = gestureRecognizer.locationInView(self)
var smallestDistance = CGFloat(Float.infinity)
var selectedIndex = 0
for (index, point) in centerPoints.enumerate() {
let distance = touchPoint.distanceWith(point)
if(distance < smallestDistance) {
smallestDistance = distance
selectedIndex = index
}
}
if(currentIndex != selectedIndex) {
if let canSelect = self.delegate?.progressBar?(self, canSelectItemAtIndex: selectedIndex) {
if (canSelect) {
currentIndex = selectedIndex
}
} else {
currentIndex = selectedIndex
}
}
}
}
}
| mit | e908dd80483693a2a92ea224bbe6cb0e | 32.961165 | 182 | 0.542882 | 5.592326 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/Examples/2 - Primitives/InputExamples.swift | 1 | 3487 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
#if canImport(UIKit)
import UIKit
struct InputExamples: View {
@State var firstResponder: Field? = .email
@State var text: String = ""
@State var password: String = ""
@State var hidePassword: Bool = true
@State var number: String = ""
enum Field {
case email
case password
case number
}
var showPasswordError: Bool {
!password.isEmpty && password.count < 5
}
var body: some View {
VStack {
// Text
Input(
text: $text,
isFirstResponder: firstResponderBinding(for: .email),
subTextStyle: .default,
placeholder: "Email Address",
prefix: nil,
state: .default,
configuration: { textField in
textField.keyboardType = .emailAddress
textField.textContentType = .emailAddress
textField.returnKeyType = .next
},
onReturnTapped: {
firstResponder = .password
}
)
// Password
Input(
text: $password,
isFirstResponder: firstResponderBinding(for: .password),
subText: showPasswordError ? "Password too short" : nil,
subTextStyle: showPasswordError ? .error : .default,
placeholder: "Password",
state: showPasswordError ? .error : .default,
configuration: { textField in
textField.isSecureTextEntry = hidePassword
textField.textContentType = .password
textField.returnKeyType = .next
},
trailing: {
if hidePassword {
IconButton(icon: .visibilityOn) {
hidePassword = false
}
} else {
IconButton(icon: .visibilityOff) {
hidePassword = true
}
}
},
onReturnTapped: {
firstResponder = .number
}
)
// Number
Input(
text: $number,
isFirstResponder: firstResponderBinding(for: .number),
label: "Purchase amount",
placeholder: "0",
prefix: "USD",
configuration: { textField in
textField.keyboardType = .decimalPad
textField.returnKeyType = .done
}
)
Spacer()
}
.padding()
}
func firstResponderBinding(for field: Field) -> Binding<Bool> {
Binding(
get: { firstResponder == field },
set: { newValue in
if newValue {
firstResponder = field
} else if firstResponder == field {
firstResponder = nil
}
}
)
}
}
struct InputExamples_Previews: PreviewProvider {
static var previews: some View {
InputExamples()
}
}
#else
struct InputExamples: View {
var body: some View {
Text("Not supported on macOS")
}
}
#endif
| lgpl-3.0 | 5227744dd98d99737599bc78e288c956 | 27.112903 | 72 | 0.472174 | 5.928571 | false | false | false | false |
harlanhaskins/csh.link | Sources/csh.link/Models/Link.swift | 1 | 2335 | import Vapor
import Fluent
import Foundation
enum LinkError: Error {
case noID
case invalidShortCode
}
struct Link: Model {
var id: Node?
var url: URL
var code: String
var created: Date
var exists: Bool = false
var active: Bool = true
var creator: String? = nil
init(url: URL, code: String? = nil, creator: String? = nil, created: Date? = nil) throws {
self.url = url
self.code = code ?? IDGenerator.encodeID(url.hashValue ^ Date().hashValue)
self.creator = creator
self.created = created ?? Date()
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
let urlString: String = try node.extract("url")
url = URL(string: urlString)!
code = try node.extract("code")
creator = try node.extract("creator")
active = try node.extract("active")
created = try node.extract("created_at") { (timestamp: TimeInterval) -> Date in
return Date(timeIntervalSince1970: timestamp)
}
}
func makeNode(context: Context) -> Node {
var data: Node = [
"url": .string(url.absoluteString),
"active": .bool(active),
"code": .string(code),
"id": id ?? .null,
"created_at": .number(Node.Number(created.timeIntervalSince1970))
]
if let creator = creator {
data["creator"] = .string(creator)
}
return data
}
func makeJSON() -> JSON {
return JSON(makeNode(context: EmptyNode))
}
static func forCode(_ code: String) throws -> Link? {
return try Link.query()
.filter("code", code)
.filter("active", true)
.first()
}
static func prepare(_ database: Database) throws {
try database.create("links") { link in
link.id()
link.string("url")
link.string("code")
link.string("creator", length: 36, optional: false)
link.bool("active")
link.double("created_at")
}
}
static func revert(_ database: Database) throws {
try database.delete("links")
}
func visits() -> Children<Visit> {
return children()
}
}
| mit | cebe9e1f292b284956f20d73b8021340 | 27.82716 | 94 | 0.541328 | 4.316081 | false | false | false | false |
T-Pro/CircularRevealKit | Example/CircularRevealKit/UIImageViewExtension.swift | 1 | 1993 | //
// Copyright (c) 2019 T-Pro
//
// 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 UIImageView {
func roundCornersForAspectFit(radius: CGFloat) {
if let image = self.image {
//calculate drawingRect
let boundsScale = self.bounds.size.width / self.bounds.size.height
let imageScale = image.size.width / image.size.height
var drawingRect: CGRect = self.bounds
if boundsScale > imageScale {
drawingRect.size.width = drawingRect.size.height * imageScale
drawingRect.origin.x = (self.bounds.size.width - drawingRect.size.width) / 2
} else {
drawingRect.size.height = drawingRect.size.width / imageScale
drawingRect.origin.y = (self.bounds.size.height - drawingRect.size.height) / 2
}
let path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
| mit | ecd02829548782fc11913322245b7c41 | 41.404255 | 90 | 0.722529 | 4.295259 | false | false | false | false |
lamb/Tile | Tile/view/ScoreView.swift | 1 | 1191 | //
// ScoreView.swift
// Tile
//
// Created by Lamb on 14-6-22.
// Copyright (c) 2014年 mynah. All rights reserved.
//
import UIKit
protocol ScoreViewProtocol{
func changeScore(value s:Int)
}
class ScoreView:UIView, ScoreViewProtocol{
var label:UILabel
let defaultFrame = CGRectMake(0, 0, 100, 30)
var score:Int = 0{
didSet{
label.text = "分数\(score)"
}
}
override init(){
label = UILabel(frame:defaultFrame)
label.textAlignment = NSTextAlignment.Center
super.init(frame:defaultFrame)
backgroundColor = UIColor.orangeColor()
label.font = UIFont(name:"微软雅黑", size:16)
label.textColor = UIColor.whiteColor()
self.addSubview(label)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func changeScore(value s:Int){
score = s
}
}
class BestScoreView:ScoreView, ScoreViewProtocol{
var bestScore:Int = 0{
didSet{
label.text = "最高分\(bestScore)"
}
}
override func changeScore(value s:Int){
bestScore = s
}
}
| mit | 9d0c157db79f8c11acd74369947a8428 | 18.196721 | 59 | 0.599488 | 3.839344 | false | false | false | false |
mechinn/our-alliance-ios | ouralliance/MasterViewController.swift | 2 | 9498 | //
// MasterViewController.swift
// ouralliance
//
// Created by Michael Chinn on 9/13/15.
// Copyright (c) 2015 frc869. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
cell.textLabel!.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| gpl-2.0 | b64aebf6248c7e6dda14cb8a251b7953 | 45.788177 | 360 | 0.690356 | 6.220039 | false | false | false | false |
johnno1962d/swift | test/IRGen/struct_resilience.swift | 3 | 9234 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience %s | FileCheck %s
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %Si = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @_TMfV17struct_resilience26StructWithResilientStorage = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
public func functionWithResilientTypes(_ s: Size, f: Size -> Size) -> Size {
// CHECK: [[RESULT:%.*]] = alloca [[BUFFER_TYPE:\[.* x i8\]]]
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 5
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeBufferWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[BUFFER:%.*]] = call %swift.opaque* [[initializeBufferWithCopy]]([[BUFFER_TYPE]]* [[RESULT]], %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: call void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[BUFFER]], %swift.refcounted* %3)
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 3
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[deallocateBuffer:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: call void [[deallocateBuffer]]([[BUFFER_TYPE]]* [[RESULT]], %swift.type* [[METADATA]])
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: ret void
return f(s)
}
// CHECK-LABEL: declare %swift.type* @_TMaV16resilient_struct4Size()
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFV16resilient_struct9RectangleT_(%V16resilient_struct9Rectangle* noalias nocapture)
public func functionWithResilientTypes(_ r: Rectangle) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct9Rectangle()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V16resilient_struct9Rectangle* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_(%V17struct_resilience6MySize* {{.*}}, %V17struct_resilience6MySize* {{.*}}, i8*, %swift.refcounted*)
public func functionWithMyResilientTypes(_ s: MySize, f: MySize -> MySize) -> MySize {
// CHECK: [[TEMP:%.*]] = alloca %V17struct_resilience6MySize
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: [[COPY:%.*]] = bitcast %V17struct_resilience6MySize* %4 to i8*
// CHECK: [[ARG:%.*]] = bitcast %V17struct_resilience6MySize* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* [[COPY]], i8* [[ARG]], {{i32 8|i64 16}}, i32 {{.*}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call void [[FN]](%V17struct_resilience6MySize* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* %3)
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience26StructWithResilientStorageg1nSi(%V17struct_resilience26StructWithResilientStorage* {{.*}})
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV17struct_resilience26StructWithResilientStorage()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V17struct_resilience26StructWithResilientStorage* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience31StructWithIndirectResilientEnumg1nSi(%V17struct_resilience31StructWithIndirectResilientEnum* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %V17struct_resilience31StructWithIndirectResilientEnum, %V17struct_resilience31StructWithIndirectResilientEnum* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaV17struct_resilience6MySize()
// CHECK: ret %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @_TMfV17struct_resilience6MySize, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, [[INT]] -1)
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_TWVBi{{32|64}}_, i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
// CHECK: store atomic %swift.type* {{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, %swift.type** @_TMLV17struct_resilience26StructWithResilientStorage release,
// CHECK: ret void
| apache-2.0 | ff95faa219bdf1e34162f0255b3f7b20 | 50.876404 | 233 | 0.661468 | 3.569385 | false | false | false | false |
ryanbaldwin/RealmSwiftFHIR | firekit/fhir-parser-resources/fhir-1.6.0/swift-3.1/template-resource-initializers.swift | 1 | 1097 | {% if klass.has_nonoptional %}
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(
{%- for nonop in klass.properties|rejectattr("nonoptional", "equalto", false) %}
{%- if loop.index is greaterthan 1 %}, {% endif -%}
{%- if "value" == nonop.name %}val{% else %}{{ nonop.name }}{% endif %}: {% if nonop.is_array %}[{% endif %}{{ nonop.class_name }}{% if nonop.is_array %}]{% endif %}
{%- endfor -%}
) {
self.init(json: nil)
{%- for nonop in klass.properties %}{% if nonop.nonoptional %}
{%- if nonop.is_array and nonop.is_native %}
self.{{ nonop.name }}.append(objectsIn: {{ nonop.name }}.map{ Realm{{ nonop.class_name }}(value: [$0]) })
{%- elif nonop.is_array %}
self.{{ nonop.name }}.append(objectsIn: {{ nonop.name }})
{%- else %}
self.{{ nonop.name }}{% if nonop|requires_realm_optional %}.value{% endif %} = {% if "value" == nonop.name %}val{% else %}{{ nonop.name }}{% endif %}
{%- endif %}
{%- endif %}{% endfor %}
}
{% endif -%} | apache-2.0 | 9183a23cf8bff63430a055195aad61e9 | 53.9 | 173 | 0.550593 | 3.406832 | false | false | false | false |
LearningSwift2/LearningApps | SimpleBallFun/SimpleBallFun/ViewController.swift | 1 | 2779 | //
// ViewController.swift
// SimpleBallFun
//
// Created by Phil Wright on 4/9/16.
// Copyright © 2016 Touchopia, LLC. All rights reserved.
//
import UIKit
import QuartzCore
class ViewController: UIViewController, UICollisionBehaviorDelegate {
let leftIdentifier = "leftSide"
let rightIdentifier = "rightSide"
let velocity: CGFloat = 1.0
var ball = UIView(frame: CGRect(x: 100, y: 100, width: 40, height: 40))
var animator = UIDynamicAnimator()
override func viewDidLoad() {
super.viewDidLoad()
self.ball.backgroundColor = UIColor.redColor()
self.ball.layer.cornerRadius = 20
self.view.addSubview(self.ball)
self.animator = UIDynamicAnimator(referenceView: self.view)
addCollision()
pushLeft()
}
func pushLeft() {
let push = UIPushBehavior(items: [self.ball], mode: .Instantaneous)
push.pushDirection = CGVector(dx: -1 * velocity, dy: 0)
self.animator.addBehavior(push)
}
func pushRight() {
let push = UIPushBehavior(items: [self.ball], mode: .Instantaneous)
push.pushDirection = CGVector(dx: 1 * velocity, dy: 0)
self.animator.addBehavior(push)
}
func addCollision() {
let collisionBehavior = UICollisionBehavior(items: [self.ball])
collisionBehavior.collisionDelegate = self
let frame = self.view.frame
let leftFromPoint = CGPoint(x: 0, y: 0)
let leftToPoint = CGPoint(x: 0, y: frame.size.height)
collisionBehavior.addBoundaryWithIdentifier(leftIdentifier,
fromPoint:leftFromPoint,
toPoint: leftToPoint)
let rightFromPoint = CGPoint(x: frame.size.width, y: 0)
let rightToPoint = CGPoint(x: frame.size.width, y: frame.size.height)
collisionBehavior.addBoundaryWithIdentifier(rightIdentifier,
fromPoint: rightFromPoint,
toPoint: rightToPoint)
self.animator.addBehavior(collisionBehavior)
}
func collisionBehavior(behavior: UICollisionBehavior, endedContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?) {
if let identifier = identifier as? String {
print(identifier)
if identifier == leftIdentifier {
pushRight()
}
if identifier == rightIdentifier {
pushLeft()
}
}
}
}
| apache-2.0 | d68ac42961b0bb915a16f55f03d119cf | 28.553191 | 147 | 0.561195 | 5.221805 | false | false | false | false |
Obisoft2017/BeautyTeamiOS | BeautyTeam/BeautyTeam/ViewController.swift | 1 | 4103 | //
// ViewController.swift
// BeautyTeam
//
// Created by 李昂 on 3/29/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Alamofire.request(.GET, "https://www.obisoft.com.cn/api/").responseJSON(completionHandler: {
// resp in
//
// print(resp.request)
// print(resp.response)
// print(resp.data)
// print(resp.result)
//
// guard let JSON = resp.result.value else {
// return
// }
// print(JSON)
// })
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Register", parameters: [
// "Email": "[email protected]",
// "Password": "FbK7xr.fE9H/fh",
// "ConfirmPassword": "FbK7xr.fE9H/fh"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Login", parameters: [
// "Email": "[email protected]",
// "Password": "Kn^GGs6R6hcbm#",
// "RememberMe": true.description
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
//
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/Log", parameters: [
// "HappenTime": "2016/4/12 15:00:00",
// "Description": "Blame the user",
// "HappenPlatform": "ios",
// "version": "v1.0.0"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// Alamofire.request(.POST, "https://www.obisoft.com.cn/api/ForgotPassword", parameters: [
// "Email": "[email protected]",
// "ByEmailNotBySms": true.description
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// fatalError()
// }
// print(json)
// }
Alamofire.request(.POST, "https://www.obisoft.com.cn/api/ChangePassword/", parameters: [
"OldPassword": "Kn^GGs6", // Kn^GGs6R6hcbm#
"NewPassword": "123456",
"ConfirmPassword": "123456"
]).responseJSON {
resp in
guard let json = resp.result.value else {
fatalError()
}
print(json)
}
Alamofire.request(.POST, "https://www.obisoft.com.cn/api/SetSchoolAccount", parameters: [
"Account": "20155134",
"Password": "1q2w3e4r"
]).responseJSON {
resp in
guard let json = resp.result.value else {
fatalError()
}
print(json)
}
// Alamofire.request(.GET, "https://www.obisoft.com.cn/api/latestversion", parameters: [
// "Platform": "ios",
// "CurrentVersion": "v0.0.1"
// ]).responseJSON {
// resp in
//
// guard let json = resp.result.value else {
// return
// }
// print(json)
// }
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | a51b1ff12fbfce86101fac62bf9ad479 | 31.015625 | 102 | 0.449244 | 4.029499 | false | false | false | false |
Onix-Systems/RainyRefreshControl | Example/RainyRefreshControl Demo/ViewController.swift | 1 | 1536 | //
// ViewController.swift
// RainyRefreshControl Demo
//
// Created by Anton Dolzhenko on 04.01.17.
// Copyright © 2017 Onix-Systems. All rights reserved.
//
import UIKit
import RainyRefreshControl
class ViewController: UIViewController {
fileprivate var items = Array(1...10).map{ "\($0)"}
@IBOutlet weak var tableView: UITableView!
fileprivate let refresh = RainyRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.barTintColor = UIColor.white
refresh.addTarget(self, action: #selector(ViewController.doRefresh), for: .valueChanged)
tableView.addSubview(refresh)
}
func doRefresh(){
let popTime = DispatchTime.now() + Double(Int64(3.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC);
DispatchQueue.main.asyncAfter(deadline: popTime) { () -> Void in
self.refresh.endRefreshing()
}
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
cell.config()
return cell
}
}
| mit | ac473da291054de5e5d89c65348fbf66 | 26.909091 | 108 | 0.663844 | 4.723077 | false | false | false | false |
BBBInc/AlzPrevent-ios | researchline/IdentificationViewController.swift | 1 | 1878 | //
// EnterPasswordViewController.swift
// researchline
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
class IdentificationViewController: UIViewController {
var passcode = ""
@IBOutlet weak var password: UITextField!
@IBOutlet weak var nextButton: UIBarButtonItem!
@IBAction func passwordChange(sender: AnyObject) {
var sizeOfCode = password.text!.characters.count
let passwordText: String = password.text!
let toNumber = Int(passwordText)
if(passwordText == ""){
return
}else if((toNumber == nil)){
password.text = self.passcode
}
if(sizeOfCode > 4){
password.text = self.passcode
sizeOfCode = password.text!.characters.count
}else{
self.passcode = password.text!
}
if(sizeOfCode == 4){
nextButton.enabled = true
Constants.userDefaults.setObject(self.passcode, forKey: "passcode")
}else{
nextButton.enabled = false
Constants.userDefaults.removeObjectForKey("passcode")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| bsd-3-clause | 6ae6aa49c37d08aa48a1f3ab8ad33b21 | 26.573529 | 106 | 0.617067 | 5.095109 | false | false | false | false |
alessandrostone/RIABrowser | RIABrowser/object/ObjectExtractor.swift | 1 | 6014 | //
// ObjectExtractor.swift
// RIABrowser
//
// Created by Yoshiyuki Tanaka on 2015/05/10.
// Copyright (c) 2015 Yoshiyuki Tanaka. All rights reserved.
//
import UIKit
import RealmSwift
class ObjectExtractor {
typealias Extractor = ()-> [RIAObject]
typealias ArrayPropertyExtractor = (object:Object, name:String) -> [Object]?
var realmPath = Realm.defaultPath
private var classes = [String:Extractor]()
private var arrayPropertyExtractors = [String:ArrayPropertyExtractor]()
class var sharedInstance : ObjectExtractor {
struct Static {
static let instance : ObjectExtractor = ObjectExtractor()
}
return Static.instance
}
func registerClass<T:Object>(type:T.Type) {
var name = "\(type)".componentsSeparatedByString(".")[1]
let extractor:Extractor = {
var riaObjects = [RIAObject]()
let realmSwiftObjects = self.realm.objects(type)
for i in 0..<realmSwiftObjects.count {
riaObjects.append(self.convertToRIAObject(realmSwiftObjects[i]))
}
return riaObjects
}
classes["\(name)"] = extractor
let arrayPropertyExtractor:ArrayPropertyExtractor = {(object:Object, name:String) -> [Object]? in
var riaObjects = [Object]()
if let value = object.valueForKey(name) as? List<T> {
var objectList = [Object]()
for i in 0..<value.count {
objectList.append(value[i])
}
return objectList
}
return nil
}
arrayPropertyExtractors["\(name)"] = arrayPropertyExtractor
}
func unregisterClass<T:Object>(type:T.Type) {
var name = "\(type)".componentsSeparatedByString(".")[1]
classes.removeValueForKey("\(name)")
arrayPropertyExtractors.removeValueForKey("\(name)")
}
var classNames:[String] {
get {
var names = [String]()
for (className, extractor) in classes {
names.append(className)
}
return names;
}
}
func objects (className: String) -> [RIAObject] {
if let objects = classes[className]?() {
return objects
}
return [RIAObject]()
}
private var realm:Realm {
get {
return Realm(path: realmPath)
}
}
private func convertToRIAObject(object: Object) -> RIAObject {
let riaObject = RIAObject(name: object.objectSchema.className)
let primaryKeyProperty:Property? = object.objectSchema.primaryKeyProperty
for property in object.objectSchema.properties {
var isPrimaryKey = false
if property == primaryKeyProperty {
isPrimaryKey = true
}
let riaProperty = convertToRIAProperty(object, name: property.name, type: property.type)
riaObject.addProperty(riaProperty, primaryKey: isPrimaryKey)
}
return riaObject
}
private func convertToRIAProperty(object: Object, name: String,type :PropertyType) -> RIAProperty {
switch type {
case .String:
return stringToString(object, name: name)
case .Int:
return intToString(object, name: name)
case .Float:
return floatToString(object, name: name)
case .Double:
return doubleToString(object, name: name)
case .Bool:
return boolToString(object, name: name)
case .Date:
return dateToString(object, name: name)
case .Data:
return dataToString(object, name: name)
case .Object:
return objectToString(object, name: name)
case .Array:
return arrayToString(object, name: name)
case .Any:
return anyToString(object, name: name)
}
}
private func stringToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! String
return RIAStringProperty(type: "String", name: name, stringValue: value)
}
private func intToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Int
return RIAStringProperty(type: "Int", name: name, stringValue: String(value))
}
private func floatToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Float
return RIAStringProperty(type: "Float", name: name, stringValue: "\(value)")
}
private func doubleToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Double
return RIAStringProperty(type: "Double", name: name, stringValue: "\(value)")
}
private func boolToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! Bool
return RIAStringProperty(type: "Double", name: name, stringValue: "\(value)")
}
private func dateToString(object: Object, name: String) -> RIAStringProperty {
let value = object.valueForKey(name) as! NSDate
return RIAStringProperty(type: "Date", name: name, stringValue: "\(value)")
}
private func dataToString(object: Object, name: String) -> RIAProperty {
let value = object.valueForKey(name) as! NSData
return RIADataProperty(type: "Data", name: name, dataValue: value)
}
private func objectToString(object: Object, name: String) -> RIAObjectProperty {
let value = object.valueForKey(name) as! Object
return RIAObjectProperty(type: "Object", name: name, objectValue:convertToRIAObject(value))
}
private func arrayToString(object: Object, name: String) -> RIAArrayProperty {
var objects:[Object]?
for (className, extractor) in arrayPropertyExtractors {
objects = extractor(object: object, name: name)
if objects != nil {
break
}
}
var riaObjects = objects?.map({ (o) -> RIAObject in
return self.convertToRIAObject(o)
})
if riaObjects == nil {
riaObjects = [RIAObject]()
}
return RIAArrayProperty(type: "Object", name: name, arrayValue:riaObjects!)
}
private func anyToString (object: Object, name: String) -> RIAStringProperty {
return RIAStringProperty(type: "Any", name: name, stringValue: "Any type is not supported")
}
}
| mit | 3e39ac30995a7a56ba6230290aab99f2 | 31.508108 | 101 | 0.671267 | 4.093941 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Views/ZSVoiceCategoryHeaderView.swift | 1 | 1460 | //
// QSCatalogPresenter.swift
// zhuishushenqi
//
// Created yung on 2017/4/21.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
class ZSVoiceCategoryHeaderView: UITableViewHeaderFooterView {
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
imageView = UIImageView(frame: CGRect.zero)
contentView.addSubview(imageView)
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = UIColor.black
titleLabel.textAlignment = .left
titleLabel.font = UIFont.systemFont(ofSize: 17)
contentView.addSubview(titleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
guard let image = imageView.image else {
titleLabel.frame = CGRect(x: 20, y: 0, width: bounds.width, height: bounds.height)
return
}
imageView.frame = CGRect(x: 20, y: bounds.height/2 - image.size.height/2, width: image.size.width, height: image.size.height)
titleLabel.frame = CGRect(x: imageView.frame.maxX + 10, y: 0, width: bounds.width, height: bounds.height)
}
var imageView:UIImageView!
var titleLabel:UILabel!
}
| mit | cc1ca6ad340143dd181db2613ecbd0f8 | 30.652174 | 133 | 0.652473 | 4.359281 | false | false | false | false |
mpclarkson/StravaSwift | Sources/StravaSwift/GeneralExtensions.swift | 1 | 718 | //
// GeneralExtensions.swift
// StravaSwift
//
// Created by Matthew on 19/11/2015.
// Copyright © 2015 Matthew Clarkson. All rights reserved.
//
import Foundation
extension RawRepresentable {
init?(optionalRawValue rawValue: RawValue?) {
guard let rawValue = rawValue, let value = Self(rawValue: rawValue) else { return nil }
self = value
}
}
extension DateFormatter {
func dateFromString(optional string: String?) -> Date? {
guard let string = string else { return nil }
return date(from: string)
}
}
extension URL {
init?(optionalString string: String?) {
guard let string = string else { return nil }
self.init(string: string)
}
}
| mit | b020db7f5fd4eff4b5d9bc6380d31e06 | 22.9 | 95 | 0.651325 | 4.144509 | false | false | false | false |
jjluebke/pigeon | Pigeon/FlightController.swift | 1 | 7894 | //
// FlightController.swift
// Pigeon
//
// Created by Jason Luebke on 5/22/15.
// Copyright (c) 2015 Jason Luebke. All rights reserved.
//
import Foundation
import CoreMotion
class FlightController : HardwareInterfaceDelegate {
var hardwareInterface:HardwareInterface!
var motion = CMMotionManager()
var delegate: Pigeon!
var attitude: Attitude!
var motors: Outputs = Array(count: 4, repeatedValue: 0)
var rotationRate: RotationRate!
var vitalsTimer: NSTimer!
var pids: PIDs!
var inputs:Inputs!
var yawTarget: Double = 0
var gyroStable: Bool = false
var pidRateVals: PIDValues!
var pidStabVals: PIDValues!
init () {
motion.showsDeviceMovementDisplay = true
motion.deviceMotionUpdateInterval = 1/60
hardwareInterface = PWMAudio()
hardwareInterface.delegate = self
}
func setupPIDs () {
pids = PIDs()
pidRateVals = PIDValues(
name: "ratePID",
delegate: delegate,
pitch : ["p": 0.5, "i": 1, "imax": 50],
roll : ["p": 0.5, "i": 1, "imax": 50],
yaw : ["p": 0.5, "i": 1, "imax": 50]
)
pidStabVals = PIDValues(
name: "stabPID",
delegate: delegate,
pitch : ["p": 4.5, "i": 1],
roll : ["p": 4.5, "i": 1],
yaw : ["p": 4.5, "i": 1]
)
self.updatePIDvalues()
}
func updatePIDvalues () {
pids.pitchRate = PID(pids: pidRateVals.pitch)
pids.rollRate = PID(pids: pidRateVals.roll)
pids.yawRate = PID(pids: pidRateVals.yaw)
pids.pitchStab = PID(pids: pidStabVals.pitch)
pids.rollStab = PID(pids: pidStabVals.roll)
pids.yawStab = PID(pids: pidStabVals.yaw)
}
func arm (data: Array<AnyObject>, ack: SocketAckEmitter?) {
motion.startDeviceMotionUpdatesUsingReferenceFrame(CMAttitudeReferenceFrame.XArbitraryCorrectedZVertical, toQueue: NSOperationQueue.mainQueue(), withHandler: self.didReceiveMotionUpdate)
vitalsTimer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "sendVitals:", userInfo: nil, repeats: true)
}
func disarm (data: Array<AnyObject>, ack: SocketAckEmitter?) {
motion.stopDeviceMotionUpdates()
gyroStable = false
delegate.armed(self.gyroStable)
if hardwareInterface.available {
hardwareInterface.stop()
}
}
@objc func sendVitals (timer: NSTimer) {
if attitude != nil {
delegate.sendPayload(attitude, motors: self.motors)
}
}
func didReceiveMotionUpdate (data: CMDeviceMotion?, error: NSError?) {
if let motion = data {
attitude = Attitude(data: motion.attitude)
rotationRate = RotationRate(data: motion.rotationRate)
}
if gyroStable {
self.processFrameData()
} else {
self.initGyro()
}
}
func initGyro () {
let threshhold: Double = 5
let diff: Double = abs(toDeg(attitude.roll) - toDeg(attitude.pitch))
if diff <= threshhold {
self.gyroStable = true
delegate.armed(self.gyroStable)
hardwareInterface.start()
} else {
delegate.armed(self.gyroStable)
}
}
func processInput(data: Array<AnyObject>, ack: SocketAckEmitter?) {
self.inputs = scaleInputs(data[0] as! Inputs)
}
func processFrameData () {
self.updatePIDvalues()
// from CM.rotationRate
var rollRate: Double!
var pitchRate: Double!
var yawRate: Double!
// from CM.attitude
var roll: Double!
var pitch: Double!
var yaw: Double!
// from the tx
var rcThro: Double = 0
var rcRoll: Double = 0
var rcPitch: Double = 0
var rcYaw: Double = 0
// outputs
var rollStabOutput: Double!
var pitchStabOutput: Double!
var yawStabOutput: Double!
var rollOutput: Double!
var pitchOutput: Double!
var yawOutput: Double!
if self.inputs != nil {
pitchRate = toDeg(rotationRate.x)
rollRate = toDeg(rotationRate.y)
yawRate = toDeg(rotationRate.z)
roll = toDeg(attitude.roll)
pitch = toDeg(attitude.pitch)
yaw = toDeg(attitude.yaw)
rcThro = inputs["thro"]!
rcRoll = inputs["roll"]!
rcPitch = inputs["pitch"]!
rcYaw = inputs["yaw"]!
rollStabOutput = constrain(pids.rollStab.calculate(rcRoll - roll, scaler: 1), low: -250, high: 250)
pitchStabOutput = constrain(pids.pitchStab.calculate(rcPitch - pitch, scaler: 1), low: -250, high: 250)
yawStabOutput = constrain(pids.yawStab.calculate(self.wrap180(yawTarget - yaw), scaler: 1), low: -360, high: 360)
// is pilot asking for yaw change
// if so feed directly to rate pid (overwriting yaw stab output)
if(abs(rcYaw ) > 5) {
yawStabOutput = rcYaw
yawTarget = yaw // remember this yaw for when pilot stops
}
rollOutput = constrain(pids.rollRate.calculate(rollStabOutput - rollRate, scaler: 1), low: -500, high: 500)
pitchOutput = constrain(pids.pitchRate.calculate(pitchStabOutput - pitchRate, scaler: 1), low: -500, high: 500)
yawOutput = constrain(pids.yawRate.calculate(yawStabOutput - yawRate, scaler: 1), low: -500, high: 500)
if rcThro >= 50 {
motors[0] = mapValue(rcThro + rollOutput + pitchOutput - yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[1] = mapValue(rcThro + rollOutput - pitchOutput + yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[2] = mapValue(rcThro - rollOutput + pitchOutput + yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
motors[3] = mapValue(rcThro - rollOutput - pitchOutput - yawOutput, inMin: -500, inMax: 1250, outMin: EscRange.Low.rawValue, outMax: EscRange.High.rawValue)
}
if hardwareInterface.available {
hardwareInterface.write(motors)
}
}
}
func wrap180 (yaw: Double) -> Double {
return yaw < -180 ? yaw + 360 : (yaw > 180 ? yaw - 360: yaw)
}
func toDeg(rad: Double) -> Double {
return (rad * 180) / M_PI
}
func constrain (n: Double, low: Double, high: Double) -> Double {
return min(max(n, low), high)
}
func scaleInputs(inputs: Inputs) -> Inputs {
var result: Inputs = Inputs()
var high: Double
var low: Double
for(channel, value) in inputs {
switch channel {
case "pitch":
fallthrough
case "roll":
high = RollRange.High.rawValue
low = RollRange.Low.rawValue
case "yaw":
high = YawRange.High.rawValue
low = YawRange.Low.rawValue
default:
high = ThroRange.High.rawValue
low = ThroRange.Low.rawValue
}
result[channel] = mapValue(value, inMin: InputRange.Low.rawValue, inMax: InputRange.High.rawValue, outMin: low, outMax: high)
}
return result
}
} | apache-2.0 | 40a37eb7a537d656891556c85fe229d8 | 32.312236 | 194 | 0.558779 | 4.035787 | false | false | false | false |
kriscarle/dev4outdoors-parkbook | Parkbook/FirstViewController.swift | 1 | 3748 | //
// FirstViewController.swift
// Parkbook
//
// Created by Kristofor Carle on 4/12/15.
// Copyright (c) 2015 Kristofor Carle. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, BeaconManagerDelegate, UIAlertViewDelegate {
var mapView: MGLMapView!
var beaconManager: BeaconManager?
var beaconList = Dictionary<String, Bool>() // major+minor -> yes or no
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initializeMap()
self.beaconManager = sharedBeaconManager
self.beaconManager?.delegate = self
self.beaconManager?.start()
}
func initializeMap() {
//set your MapBox account token - see: https://www.mapbox.com/account/apps/
let mapBoxAccountToken = "INSERT TOKEN HERE"
//frame for the map view
let mapFrame = CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height)
//instantiate a MapBoxGL map
mapView = MGLMapView(frame: mapFrame, accessToken: mapBoxAccountToken)
mapView.tintColor = UIColor(red: 30, green: 30, blue: 30, alpha: 1)
//set the default style
mapView.useBundledStyleNamed("outdoors")
//zoom map to area of interest
let lat = 38.889487
let lng = -77.0347045
let centerCoordinate = CLLocationCoordinate2DMake(lat, lng)
mapView.setCenterCoordinate(centerCoordinate, zoomLevel: 14, animated: true)
//add the map to the parent view
view.addSubview(mapView)
}
func insideRegion(regionIdentifier: String) {
// println("VC insideRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = true
//self.setUI()
sendLocalNotificationWithMessage(regionIdentifier, playSound: false) // Only send notification when we enter
}
func didEnterRegion(regionIdentifier: String) {
println("VC didEnterRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = true
//self.setUI()
sendLocalNotificationWithMessage(regionIdentifier, playSound: false) // Only send notification when we enter
}
func didExitRegion(regionIdentifier: String) {
println("VC didExitRegion \(regionIdentifier)")
//self.beaconList[regionIdentifier] = nil
//self.setUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sendLocalNotificationWithMessage(message: String!, playSound: Bool) {
let notification:UILocalNotification = UILocalNotification()
let alertMessage = "Checked into park: " + message;
notification.alertBody = alertMessage
if(playSound) {
// classic star trek communicator beep
// http://www.trekcore.com/audio/
//
// note: convert mp3 and wav formats into caf using:
// "afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf"
// http://stackoverflow.com/a/10388263
notification.soundName = "tos_beep.caf";
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
let alertView = UIAlertController(title: "Checked In", message: alertMessage, preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertView, animated: true, completion: nil)
}
}
| mit | d1dad334d039ef665002a117340bc2f1 | 32.168142 | 116 | 0.633138 | 4.964238 | false | false | false | false |
brave/browser-ios | Shared/Logger.swift | 17 | 3652 | /* 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 XCGLogger
public struct Logger {}
// MARK: - Singleton Logger Instances
public extension Logger {
static let logPII = false
/// Logger used for recording happenings with Sync, Accounts, Providers, Storage, and Profiles
static let syncLogger = RollingFileLogger(filenameRoot: "sync", logDirectoryPath: Logger.logFileDirectoryPath())
/// Logger used for recording frontend/browser happenings
static let browserLogger = RollingFileLogger(filenameRoot: "browser", logDirectoryPath: Logger.logFileDirectoryPath())
/// Logger used for recording interactions with the keychain
static let keychainLogger: XCGLogger = Logger.fileLoggerWithName("keychain")
/// Logger used for logging database errors such as corruption
static let corruptLogger: RollingFileLogger = {
let logger = RollingFileLogger(filenameRoot: "corruptLogger", logDirectoryPath: Logger.logFileDirectoryPath())
logger.newLogWithDate(Date())
return logger
}()
/**
Return the log file directory path. If the directory doesn't exist, make sure it exist first before returning the path.
:returns: Directory path where log files are stored
*/
static func logFileDirectoryPath() -> String? {
if let cacheDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first {
let logDir = "\(cacheDir)/Logs"
if !FileManager.default.fileExists(atPath: logDir) {
do {
try FileManager.default.createDirectory(atPath: logDir, withIntermediateDirectories: false, attributes: nil)
return logDir
} catch _ as NSError {
return nil
}
} else {
return logDir
}
}
return nil
}
static private func fileLoggerWithName(_ name: String) -> XCGLogger {
let log = XCGLogger()
if let logFileURL = urlForLogNamed(name) {
let fileDestination = FileDestination(
owner: log,
writeToFile: logFileURL.absoluteString,
identifier: "com.mozilla.firefox.filelogger.\(name)"
)
log.add(destination: fileDestination)
}
return log
}
static private func urlForLogNamed(_ name: String) -> URL? {
guard let logDir = Logger.logFileDirectoryPath() else {
return nil
}
return URL(string: "\(logDir)/\(name).log")
}
/**
Grabs all of the configured logs that write to disk and returns them in NSData format along with their
associated filename.
- returns: Tuples of filenames to each file's contexts in a NSData object
*/
static func diskLogFilenamesAndData() throws -> [(String, Data?)] {
var filenamesAndURLs = [(String, URL)]()
filenamesAndURLs.append(("browser", urlForLogNamed("browser")!))
filenamesAndURLs.append(("keychain", urlForLogNamed("keychain")!))
// Grab all sync log files
do {
filenamesAndURLs += try syncLogger.logFilenamesAndURLs()
filenamesAndURLs += try corruptLogger.logFilenamesAndURLs()
filenamesAndURLs += try browserLogger.logFilenamesAndURLs()
} catch _ {
}
return filenamesAndURLs.map { ($0, try? Data(contentsOf: URL(fileURLWithPath: $1.absoluteString))) }
}
}
| mpl-2.0 | 6030a25689ab510086f495bfac15d32b | 37.041667 | 128 | 0.647317 | 5.009602 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/Triangle/AKTriangleOscillator.swift | 1 | 6956 | //
// AKTriangleOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Bandlimited triangleoscillator This is a bandlimited triangle oscillator
/// ported from the "triangle" function from the Faust programming language.
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public class AKTriangleOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKTriangleOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var detuningOffsetParameter: AUParameter?
private var detuningMultiplierParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz.
public var frequency: Double = 440 {
willSet(newValue) {
if frequency != newValue {
if internalAU!.isSetUp() {
frequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.frequency = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet(newValue) {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Frequency offset in Hz.
public var detuningOffset: Double = 0 {
willSet(newValue) {
if detuningOffset != newValue {
if internalAU!.isSetUp() {
detuningOffsetParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningOffset = Float(newValue)
}
}
}
}
/// Frequency detuning multiplier
public var detuningMultiplier: Double = 1 {
willSet(newValue) {
if detuningMultiplier != newValue {
if internalAU!.isSetUp() {
detuningMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.detuningMultiplier = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(frequency: 440)
}
/// Initialize this oscillator node
///
/// - parameter frequency: In cycles per second, or Hz.
/// - parameter amplitude: Output Amplitude.
/// - parameter detuningOffset: Frequency offset in Hz.
/// - parameter detuningMultiplier: Frequency detuning multiplier
///
public init(
frequency: Double,
amplitude: Double = 0.5,
detuningOffset: Double = 0,
detuningMultiplier: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.detuningOffset = detuningOffset
self.detuningMultiplier = detuningMultiplier
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x7472696f /*'trio'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKTriangleOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKTriangleOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKTriangleOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter
detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
} else if address == self.detuningOffsetParameter!.address {
self.detuningOffset = Double(value)
} else if address == self.detuningMultiplierParameter!.address {
self.detuningMultiplier = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
internalAU?.detuningOffset = Float(detuningOffset)
internalAU?.detuningMultiplier = Float(detuningMultiplier)
}
/// Function create an identical new node for use in creating polyphonic instruments
public override func duplicate() -> AKVoice {
let copy = AKTriangleOscillator(frequency: self.frequency, amplitude: self.amplitude, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
public override func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public override func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 | d1989e51d0fb2d89f2080cbb60deaf40 | 35.041451 | 175 | 0.616302 | 5.830679 | false | false | false | false |
eneko/JSONRequest | Sources/JSONRequestVerbs.swift | 1 | 7199 | //
// JSONRequestVerbs.swift
// JSONRequest
//
// Created by Eneko Alonso on 1/11/16.
// Copyright © 2016 Hathway. All rights reserved.
//
public enum JSONRequestHttpVerb: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
}
// MARK: Instance basic sync/async
public extension JSONRequest {
public func send(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil) -> JSONResult {
return submitSyncRequest(method, url: url, queryParams: queryParams,
payload: payload, headers: headers)
}
public func send(method: JSONRequestHttpVerb, url: String, queryParams: JSONObject? = nil,
payload: AnyObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
submitAsyncRequest(method, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
}
// MARK: Instance HTTP Sync methods
public extension JSONRequest {
public func get(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.GET, url: url, queryParams: queryParams, headers: headers)
}
public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.POST, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.PUT, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.PATCH, url: url, queryParams: queryParams, payload: payload,
headers: headers)
}
public func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return send(.DELETE, url: url, queryParams: queryParams, headers: headers)
}
}
// MARK: Instance HTTP Async methods
public extension JSONRequest {
public func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
send(.GET, url: url, queryParams: queryParams, headers: headers,
complete: complete)
}
public func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.POST, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.PUT, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.PATCH, url: url, queryParams: queryParams, payload: payload,
headers: headers, complete: complete)
}
public func delete(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
send(.DELETE, url: url, queryParams: queryParams, headers: headers,
complete: complete)
}
}
// MARK: Class HTTP Sync methods
public extension JSONRequest {
public class func get(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().get(url, queryParams: queryParams, headers: headers)
}
public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().post(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().put(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().patch(url, queryParams: queryParams, payload: payload,
headers: headers)
}
public class func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil) -> JSONResult {
return JSONRequest().delete(url, queryParams: queryParams, headers: headers)
}
}
// MARK: Class HTTP Async methods
public extension JSONRequest {
public class func get(url: String, queryParams: JSONObject? = nil, headers: JSONObject? = nil,
complete: (result: JSONResult) -> Void) {
JSONRequest().get(url, queryParams: queryParams, headers: headers, complete: complete)
}
public class func post(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().post(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func put(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().put(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func patch(url: String, queryParams: JSONObject? = nil, payload: AnyObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().patch(url, queryParams: queryParams, payload: payload, headers: headers,
complete: complete)
}
public class func delete(url: String, queryParams: JSONObject? = nil,
headers: JSONObject? = nil, complete: (result: JSONResult) -> Void) {
JSONRequest().delete(url, queryParams: queryParams, headers: headers, complete: complete)
}
}
| mit | eccfc4fa999504d9018b1ac94adfce30 | 39.438202 | 99 | 0.603918 | 4.661917 | false | false | false | false |
samodom/TestableCoreLocation | TestableCoreLocation/CLLocationManager/CLLocationManagerStopMonitoringForRegionSpy.swift | 1 | 3016 | //
// CLLocationManagerStopMonitoringForRegionSpy.swift
// TestableCoreLocation
//
// Created by Sam Odom on 3/6/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import CoreLocation
import FoundationSwagger
import TestSwagger
public extension CLLocationManager {
private static let stopMonitoringForRegionCalledKeyString = UUIDKeyString()
private static let stopMonitoringForRegionCalledKey =
ObjectAssociationKey(stopMonitoringForRegionCalledKeyString)
private static let stopMonitoringForRegionCalledReference =
SpyEvidenceReference(key: stopMonitoringForRegionCalledKey)
private static let stopMonitoringForRegionRegionKeyString = UUIDKeyString()
private static let stopMonitoringForRegionRegionKey =
ObjectAssociationKey(stopMonitoringForRegionRegionKeyString)
private static let stopMonitoringForRegionRegionReference =
SpyEvidenceReference(key: stopMonitoringForRegionRegionKey)
/// Spy controller for ensuring that a location manager has had `stopMonitoring(for:)`
/// called on it.
public enum StopMonitoringForRegionSpyController: SpyController {
public static let rootSpyableClass: AnyClass = CLLocationManager.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(CLLocationManager.stopMonitoring(for:)),
spy: #selector(CLLocationManager.spy_stopMonitoring(for:))
)
] as Set
public static let evidence = [
stopMonitoringForRegionCalledReference,
stopMonitoringForRegionRegionReference
] as Set
public static let forwardsInvocations = false
}
/// Spy method that replaces the true implementation of `stopMonitoring(for:)`
dynamic public func spy_stopMonitoring(for region: CLRegion) {
stopMonitoringForRegionCalled = true
stopMonitoringForRegionRegion = region
}
/// Indicates whether the `stopMonitoring(for:)` method has been called on this object.
public final var stopMonitoringForRegionCalled: Bool {
get {
return loadEvidence(with: CLLocationManager.stopMonitoringForRegionCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: CLLocationManager.stopMonitoringForRegionCalledReference)
}
}
/// Provides the region passed to `stopMonitoring(for:)` if called.
public final var stopMonitoringForRegionRegion: CLRegion? {
get {
return loadEvidence(with: CLLocationManager.stopMonitoringForRegionRegionReference) as? CLRegion
}
set {
let reference = CLLocationManager.stopMonitoringForRegionRegionReference
guard let region = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(region, with: reference)
}
}
}
| mit | 2f9caa322aa9b399b256290fd708a639 | 35.768293 | 113 | 0.709453 | 6.115619 | false | false | false | false |
lanffy/phpmanual | swift/Demo.playground/Contents.swift | 1 | 1493 | import UIKit
let colors = [
"Air Force Blue":(red:93,green:138,blue:168),
"Bittersweet":(red:254,green:111,blue:94),
"Canary Yellow":(red:255,green:239,blue:0),
"Dark Orange":(red:255,green:140,blue:0),
"Electric Violet":(red:143,green:0,blue:255),
"Fern":(red:113,green:188,blue:120),
"Gamboge":(red:228,green:155,blue:15),
"Hollywood Cerise":(red:252,green:0,blue:161),
"Icterine":(red:252,green:247,blue:94),
"Jazzberry Jam":(red:165,green:11,blue:94)
]
print(colors)
var backView = UIView(frame: CGRect.init(x: 0.0, y: 0.0, width: 320.0, height: CGFloat(colors.count * 50)))
backView.backgroundColor = UIColor.black
backView
var index = 0
for (colorName,rgbTuple) in colors {
let colorStripe = UILabel.init(frame: CGRect.init(x: 0.0, y: CGFloat(index * 50 + 5), width: 320.0, height: 40.0))
colorStripe.backgroundColor = UIColor.init(
red: CGFloat(rgbTuple.red) / 255.0,
green: CGFloat(rgbTuple.green) / 255.0,
blue: CGFloat(rgbTuple.blue) / 255.0,
alpha: 1.0
)
let colorNameLable = UILabel.init(frame: CGRect.init(x: 0.0, y: 0.0, width: 300.0, height: 40.0))
colorNameLable.font = UIFont.init(name: "Arial", size: 24.0)
colorNameLable.textColor = UIColor.black
colorNameLable.textAlignment = NSTextAlignment.right
colorNameLable.text = colorName
colorStripe.addSubview(colorNameLable)
backView.addSubview(colorStripe)
index += 1
}
backView
| apache-2.0 | a2dfc8c7d0468b3cdc03b1a11aafaedc | 30.104167 | 118 | 0.659745 | 3.004024 | false | false | false | false |
zwaldowski/ParksAndRecreation | Latest/HTMLDocument.playground/Sources/HTMLDocument.swift | 1 | 11065 | import Darwin
private struct XML2 {
typealias CBufferCreate = @convention(c) () -> UnsafeMutableRawPointer?
typealias CBufferFree = @convention(c) (UnsafeMutableRawPointer?) -> Void
typealias CBufferGetContent = @convention(c) (UnsafeRawPointer?) -> UnsafePointer<CChar>
typealias CDocFree = @convention(c) (UnsafeMutableRawPointer) -> Void
typealias CDocAddFragment = @convention(c) (UnsafeMutableRawPointer) -> UnsafeMutableRawPointer?
typealias CDocGetRootElement = @convention(c) (UnsafeRawPointer) -> UnsafeMutableRawPointer?
typealias CNodeAddChild = @convention(c) (_ parent: UnsafeMutableRawPointer, _ cur: UnsafeRawPointer) -> UnsafeMutableRawPointer?
typealias CNodeUnlink = @convention(c) (UnsafeRawPointer) -> Void
typealias CNodeCopyProperty = @convention(c) (UnsafeRawPointer, UnsafePointer<CChar>) -> UnsafeMutablePointer<CChar>?
typealias CNodeCopyContent = @convention(c) (UnsafeRawPointer) -> UnsafeMutablePointer<CChar>?
typealias CHTMLNodeDump = @convention(c) (UnsafeMutableRawPointer?, UnsafeRawPointer, UnsafeRawPointer) -> Int32
typealias CHTMLReadMemory = @convention(c) (UnsafePointer<CChar>?, Int32, UnsafePointer<CChar>?, UnsafePointer<CChar>?, Int32) -> UnsafeMutableRawPointer?
// libxml/tree.h
let bufferCreate: CBufferCreate
let bufferFree: CBufferFree
let bufferGetContent: CBufferGetContent
let docFree: CDocFree
let docAddFragment: CDocAddFragment
let docGetRootElement: CDocGetRootElement
let nodeAddChild: CNodeAddChild
let nodeUnlink: CNodeUnlink
let nodeCopyProperty: CNodeCopyProperty
let nodeCopyContent: CNodeCopyContent
// libxml/HTMLtree.h
let htmlNodeDump: CHTMLNodeDump
// libxml/HTMLparser.h
let htmlReadMemory: CHTMLReadMemory
static let shared: XML2 = {
let handle = dlopen("/usr/lib/libxml2.dylib", RTLD_LAZY)
return XML2(
bufferCreate: unsafeBitCast(dlsym(handle, "xmlBufferCreate"), to: CBufferCreate.self),
bufferFree: unsafeBitCast(dlsym(handle, "xmlBufferFree"), to: CBufferFree.self),
bufferGetContent: unsafeBitCast(dlsym(handle, "xmlBufferContent"), to: CBufferGetContent.self),
docFree: unsafeBitCast(dlsym(handle, "xmlFreeDoc"), to: CDocFree.self),
docAddFragment: unsafeBitCast(dlsym(handle, "xmlNewDocFragment"), to: CDocAddFragment.self),
docGetRootElement: unsafeBitCast(dlsym(handle, "xmlDocGetRootElement"), to: CDocGetRootElement.self),
nodeAddChild: unsafeBitCast(dlsym(handle, "xmlAddChild"), to: CNodeAddChild.self),
nodeUnlink: unsafeBitCast(dlsym(handle, "xmlUnlinkNode"), to: CNodeUnlink.self),
nodeCopyProperty: unsafeBitCast(dlsym(handle, "xmlGetProp"), to: CNodeCopyProperty.self),
nodeCopyContent: unsafeBitCast(dlsym(handle, "xmlNodeGetContent"), to: CNodeCopyContent.self),
htmlNodeDump: unsafeBitCast(dlsym(handle, "htmlNodeDump"), to: CHTMLNodeDump.self),
htmlReadMemory: unsafeBitCast(dlsym(handle, "htmlReadMemory"), to: CHTMLReadMemory.self))
}()
}
/// A fragment of HTML parsed into a logical tree structure. A tree can have
/// many child nodes but only one element, the root element.
public final class HTMLDocument {
/// Element nodes in an tree structure. An element may have child nodes,
/// specifically element nodes, text nodes, comment nodes, or
/// processing-instruction nodes. It may also have subscript attributes.
public struct Node {
public struct Index {
fileprivate let variant: IndexVariant
}
/// A strong back-reference to the containing document.
public let document: HTMLDocument
fileprivate let handle: UnsafeRawPointer
}
/// Options you can use to control the parser's treatment of HTML.
private struct ParseOptions: OptionSet {
let rawValue: Int32
init(rawValue: Int32) { self.rawValue = rawValue }
// libxml/HTMLparser.h
/// Relaxed parsing
static let relaxedParsing = ParseOptions(rawValue: 1 << 0)
/// suppress error reports
static let noErrors = ParseOptions(rawValue: 1 << 5)
/// suppress warning reports
static let noWarnings = ParseOptions(rawValue: 1 << 6)
/// remove blank nodes
static let noBlankNodes = ParseOptions(rawValue: 1 << 8)
/// Forbid network access
static let noNetworkAccess = ParseOptions(rawValue: 1 << 11)
/// Do not add implied html/body... elements
static let noImpliedElements = ParseOptions(rawValue: 1 << 13)
}
fileprivate let handle: UnsafeMutableRawPointer
fileprivate init?<Input>(parsing input: Input) where Input: StringProtocol {
let options = [
.relaxedParsing, .noErrors, .noWarnings, .noBlankNodes,
.noNetworkAccess, .noImpliedElements
] as ParseOptions
guard let handle = input.withCString({ (cString) in
XML2.shared.htmlReadMemory(cString, Int32(strlen(cString)), nil, "UTF-8", options.rawValue)
}) else { return nil }
self.handle = handle
}
deinit {
XML2.shared.docFree(handle)
}
}
extension HTMLDocument {
/// Parses the HTML contents of a string source, such as "<p>Hello.</p>"
public static func parse<Input>(_ input: Input) -> Node? where Input: StringProtocol {
return HTMLDocument(parsing: input)?.root
}
/// Parses the HTML contents of an escaped string source, such as "<p>Hello.</p>".
public static func parseFragment<Input>(_ input: Input) -> Node? where Input: StringProtocol {
guard let document = HTMLDocument(parsing: "<html><body>\(input)"),
let textNode = document.root?.first?.first, textNode.kind == .text,
let rootNode = parse("<root>\(textNode.content)") else { return nil }
if let onlyChild = rootNode.first, rootNode.dropFirst().isEmpty {
return onlyChild
} else if let fragment = XML2.shared.docAddFragment(rootNode.document.handle) {
for child in rootNode {
XML2.shared.nodeUnlink(child.handle)
XML2.shared.nodeAddChild(fragment, child.handle)
}
return Node(document: rootNode.document, handle: fragment)
} else {
return nil
}
}
/// The root node of the receiver.
public var root: Node? {
guard let rootHandle = XML2.shared.docGetRootElement(handle) else { return nil }
return Node(document: self, handle: rootHandle)
}
}
// MARK: - Node
extension HTMLDocument.Node {
/// The different element types carried by an XML tree.
/// See http://www.w3.org/TR/REC-DOM-Level-1/
// libxml/tree.h
public enum Kind: Int32 {
case element = 1
case attribute = 2
case text = 3
case characterDataSection = 4
case entityReference = 5
case entity = 6
case processingInstruction = 7
case comment = 8
case document = 9
case documentType = 10
case documentFragment = 11
case notation = 12
case htmlDocument = 13
case documentTypeDefinition = 14
case elementDeclaration = 15
case attributeDeclaration = 16
case entityDeclaration = 17
case namespaceDeclaration = 18
case includeStart = 19
case includeEnd = 20
}
/// The natural type of this element.
/// See also [the W3C](http://www.w3.org/TR/REC-DOM-Level-1/).
public var kind: Kind {
// xmlNodePtr->type
return Kind(rawValue: handle.load(fromByteOffset: MemoryLayout<Int>.stride, as: Int32.self))!
}
/// The element tag. (ex: for `<foo />`, `"foo"`)
public var name: String {
// xmlNodePtr->name
guard let pointer = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 2, as: UnsafePointer<CChar>?.self) else { return "" }
return String(cString: pointer)
}
/// If the node is a text node, the text carried directly by the node.
/// Otherwise, the aggregrate string of the values carried by this node.
public var content: String {
guard let buffer = XML2.shared.nodeCopyContent(handle) else { return "" }
defer { buffer.deallocate() }
return String(cString: buffer)
}
/// Request the content of the attribute `key`.
public subscript(key: String) -> String? {
guard let buffer = XML2.shared.nodeCopyProperty(handle, key) else { return nil }
defer { buffer.deallocate() }
return String(cString: buffer)
}
}
extension HTMLDocument.Node: Collection {
fileprivate enum IndexVariant: Equatable {
case valid(UnsafeRawPointer, offset: Int)
case invalid
}
public var startIndex: Index {
// xmlNodePtr->children
guard let firstHandle = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 3, as: UnsafeRawPointer?.self) else { return Index(variant: .invalid) }
return Index(variant: .valid(firstHandle, offset: 0))
}
public var endIndex: Index {
return Index(variant: .invalid)
}
public subscript(position: Index) -> HTMLDocument.Node {
guard case .valid(let handle, _) = position.variant else { preconditionFailure("Index out of bounds") }
return HTMLDocument.Node(document: document, handle: handle)
}
public func index(after position: Index) -> Index {
// xmlNodePtr->next
guard case .valid(let handle, let offset) = position.variant,
let nextHandle = handle.load(fromByteOffset: MemoryLayout<Int>.stride * 6, as: UnsafeRawPointer?.self) else { return Index(variant: .invalid) }
let nextOffset = offset + 1
return Index(variant: .valid(nextHandle, offset: nextOffset))
}
}
extension HTMLDocument.Node: CustomDebugStringConvertible {
public var debugDescription: String {
let buffer = XML2.shared.bufferCreate()
defer { XML2.shared.bufferFree(buffer) }
_ = XML2.shared.htmlNodeDump(buffer, document.handle, handle)
return String(cString: XML2.shared.bufferGetContent(buffer))
}
}
extension HTMLDocument.Node: CustomReflectable {
public var customMirror: Mirror {
// Always use the debugDescription for `po`, none of this "▿" stuff.
return Mirror(self, unlabeledChildren: self, displayStyle: .struct)
}
}
// MARK: - Node Index
extension HTMLDocument.Node.Index: Comparable {
public static func == (lhs: HTMLDocument.Node.Index, rhs: HTMLDocument.Node.Index) -> Bool {
return lhs.variant == rhs.variant
}
public static func < (lhs: HTMLDocument.Node.Index, rhs: HTMLDocument.Node.Index) -> Bool {
switch (lhs.variant, rhs.variant) {
case (.valid(_, let lhs), .valid(_, let rhs)):
return lhs < rhs
case (.valid, .invalid):
return true
default:
return false
}
}
}
| mit | 1487f4800f487468bad242d31a0d69dc | 38.366548 | 158 | 0.664618 | 4.36543 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Settings/HomePageSettingViewController.swift | 1 | 6678 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class HomePageSettingViewController: SettingsTableViewController {
/* variables for checkmark settings */
let prefs: Prefs
var currentChoice: NewTabPage!
var hasHomePage = false
init(prefs: Prefs) {
self.prefs = prefs
super.init(style: .grouped)
self.title = Strings.AppMenuOpenHomePageTitleString
hasSectionSeparatorLine = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func generateSettings() -> [SettingSection] {
// The Home button and the New Tab page can be set independently
self.currentChoice = NewTabAccessors.getHomePage(self.prefs)
self.hasHomePage = HomeButtonHomePageAccessors.getHomePage(self.prefs) != nil
let onFinished = {
self.prefs.removeObjectForKey(PrefsKeys.HomeButtonHomePageURL)
self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
}
let showTopSites = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabTopSites), subtitle: nil, accessibilityIdentifier: "HomeAsFirefoxHome", isEnabled: {return self.currentChoice == NewTabPage.topSites}, onChanged: {
self.currentChoice = NewTabPage.topSites
onFinished()
})
let showBookmarks = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabBookmarks), subtitle: nil, accessibilityIdentifier: "HomeAsBookmarks", isEnabled: {return self.currentChoice == NewTabPage.bookmarks}, onChanged: {
self.currentChoice = NewTabPage.bookmarks
onFinished()
})
let showHistory = CheckmarkSetting(title: NSAttributedString(string: Strings.SettingsNewTabHistory), subtitle: nil, accessibilityIdentifier: "HomeAsHistory", isEnabled: {return self.currentChoice == NewTabPage.history}, onChanged: {
self.currentChoice = NewTabPage.history
onFinished()
})
let showWebPage = WebPageSetting(prefs: prefs, prefKey: PrefsKeys.HomeButtonHomePageURL, defaultValue: nil, placeholder: Strings.CustomNewPageURL, accessibilityIdentifier: "HomeAsCustomURL", settingDidChange: { (string) in
self.currentChoice = NewTabPage.homePage
self.prefs.setString(self.currentChoice.rawValue, forKey: NewTabAccessors.HomePrefKey)
self.tableView.reloadData()
})
showWebPage.textField.textAlignment = .natural
let section = SettingSection(title: NSAttributedString(string: Strings.NewTabSectionName), footerTitle: NSAttributedString(string: Strings.NewTabSectionNameFooter), children: [showTopSites, showBookmarks, showHistory, showWebPage])
let topsitesSection = SettingSection(title: NSAttributedString(string: Strings.SettingsTopSitesCustomizeTitle), footerTitle: NSAttributedString(string: Strings.SettingsTopSitesCustomizeFooter), children: [TopSitesSettings(settings: self)])
let isPocketEnabledDefault = Pocket.IslocaleSupported(Locale.current.identifier)
let pocketSetting = BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.ASPocketStoriesVisible, defaultValue: isPocketEnabledDefault, attributedTitleText: NSAttributedString(string: Strings.SettingsNewTabPocket))
let pocketSection = SettingSection(title: NSAttributedString(string: Strings.SettingsNewTabASTitle), footerTitle: NSAttributedString(string: Strings.SettingsNewTabPocketFooter), children: [pocketSetting])
return [section, topsitesSection, pocketSection]
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.post(name: .HomePanelPrefsChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.keyboardDismissMode = .onDrag
}
class TopSitesSettings: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator }
override var status: NSAttributedString {
let num = self.profile.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows
return NSAttributedString(string: String(format: Strings.TopSitesRowCount, num))
}
override var accessibilityIdentifier: String? { return "TopSitesRows" }
override var style: UITableViewCellStyle { return .value1 }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: Strings.ASTopSitesTitle, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]))
}
override func onClick(_ navigationController: UINavigationController?) {
let viewController = TopSitesRowCountSettingsController(prefs: profile.prefs)
viewController.profile = profile
navigationController?.pushViewController(viewController, animated: true)
}
}
}
class TopSitesRowCountSettingsController: SettingsTableViewController {
let prefs: Prefs
var numberOfRows: Int32
static let defaultNumberOfRows: Int32 = 2
init(prefs: Prefs) {
self.prefs = prefs
numberOfRows = self.prefs.intForKey(PrefsKeys.NumberOfTopSiteRows) ?? TopSitesRowCountSettingsController.defaultNumberOfRows
super.init(style: .grouped)
self.title = Strings.AppMenuTopSitesTitleString
hasSectionSeparatorLine = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func generateSettings() -> [SettingSection] {
let createSetting: (Int32) -> CheckmarkSetting = { num in
return CheckmarkSetting(title: NSAttributedString(string: "\(num)"), subtitle: nil, isEnabled: { return num == self.numberOfRows }, onChanged: {
self.numberOfRows = num
self.prefs.setInt(Int32(num), forKey: PrefsKeys.NumberOfTopSiteRows)
self.tableView.reloadData()
})
}
let rows = [1, 2, 3, 4].map(createSetting)
let section = SettingSection(title: NSAttributedString(string: Strings.TopSitesRowSettingFooter), footerTitle: nil, children: rows)
return [section]
}
}
| mpl-2.0 | 47bbfe7e70042d65f3b72272f0cd0930 | 49.210526 | 248 | 0.719377 | 5.241758 | false | false | false | false |
zyhndesign/SDX_DG | sdxdg/sdxdg/ConsumeListViewController.swift | 1 | 4456 | //
// ConsumeListViewController.swift
// sdxdg
//
// Created by lotusprize on 16/12/26.
// Copyright © 2016年 geekTeam. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
class ConsumeListViewController: UITableViewController {
var storyBoard:UIStoryboard?
var naviController:UINavigationController?
let refresh = UIRefreshControl.init()
let pageLimit:Int = 10
var pageNum:Int = 0
var matchList:[Match] = []
let userId = LocalDataStorageUtil.getUserIdFromUserDefaults()
var vipName:String = ""
init(storyBoard:UIStoryboard, naviController:UINavigationController, vipName:String){
super.init(nibName: nil, bundle: nil)
self.storyBoard = storyBoard
self.naviController = naviController
self.vipName = vipName
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(FeedbackListCell.self, forCellReuseIdentifier: "feedbackCell")
//self.tableView.dataSource = self
refresh.backgroundColor = UIColor.white
refresh.tintColor = UIColor.lightGray
refresh.attributedTitle = NSAttributedString(string:"下拉刷新")
refresh.addTarget(self, action: #selector(refreshLoadingData), for: UIControlEvents.valueChanged)
self.tableView.addSubview(refresh)
loadCostumeData(limit: pageLimit,offset: 0)
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matchList.count;
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identify:String = "feedbackCell"
let cell:FeedbackListCell = tableView.dequeueReusableCell(withIdentifier: identify, for: indexPath) as! FeedbackListCell;
let match:Match = matchList[indexPath.row]
let matchLists:[Matchlist] = match.matchlists!
cell.initDataForCell(name:match.seriesname! , fbIcon1: matchLists[0].modelurl!, fbIcon2: matchLists[1].modelurl!,
fbIcon3: matchLists[2].modelurl!, fbIcon4: matchLists[3].modelurl!,time:match.createtime! ,storyBoard: storyBoard!, navigationController:naviController!)
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshLoadingData(){
loadCostumeData(limit: pageLimit,offset: pageLimit * pageNum)
}
func loadCostumeData(limit:Int, offset:Int){
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "正在加载中..."
let parameters:Parameters = ["userId":userId, "vipName":vipName, "limit":limit,"offset":offset]
Alamofire.request(ConstantsUtil.APP_SHARE_HISTORY_URL,method:.post, parameters:parameters).responseObject { (response: DataResponse<MatchServerModel>) in
let matchServerModel = response.result.value
if (matchServerModel?.resultCode == 200){
if let matchServerModelList = matchServerModel?.object {
for matchModel in matchServerModelList{
self.matchList.insert(matchModel, at: 0)
self.pageNum = self.pageNum + 1
}
self.tableView.reloadData()
self.refresh.endRefreshing()
hud.label.text = "加载成功"
hud.hide(animated: true, afterDelay: 0.5)
}
else{
hud.label.text = "无推送历史数据"
hud.hide(animated: true, afterDelay: 0.5)
}
}
else{
hud.label.text = "加载失败"
hud.hide(animated: true, afterDelay: 0.5)
}
}
}
}
| apache-2.0 | e49de1ed11130bd6eb817bfaf5223dae | 34.524194 | 182 | 0.612259 | 4.916295 | false | false | false | false |
bmichotte/HSTracker | HSTracker/UIs/Trackers/OpponentDrawChance.swift | 3 | 1052 | //
// CountTextCellView.swift
// HSTracker
//
// Created by Benjamin Michotte on 6/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Cocoa
class OpponentDrawChance: TextFrame {
private let frameRect = NSRect(x: 0, y: 0, width: CGFloat(kFrameWidth), height: 71)
private let draw1Frame = NSRect(x: 70, y: 32, width: 68, height: 25)
private let draw2Frame = NSRect(x: 148, y: 32, width: 68, height: 25)
private let hand1Frame = NSRect(x: 70, y: 1, width: 68, height: 25)
private let hand2Frame = NSRect(x: 148, y: 1, width: 68, height: 25)
var drawChance1 = 0.0
var drawChance2 = 0.0
var handChance1 = 0.0
var handChance2 = 0.0
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
add(image: "opponent-chance-frame.png", rect: frameRect)
add(double: drawChance1, rect: draw1Frame)
add(double: drawChance2, rect: draw2Frame)
add(double: handChance1, rect: hand1Frame)
add(double: handChance2, rect: hand2Frame)
}
}
| mit | 7cee1fa60949f67660646c6e5061faf4 | 30.848485 | 87 | 0.658421 | 3.294671 | false | false | false | false |
pietrocaselani/Trakt-Swift | Trakt/Models/Sync/HistoryParameters.swift | 1 | 838 | import Foundation
public final class HistoryParameters: Hashable {
public let type: HistoryType?
public let id: Int?
public let startAt, endAt: Date?
public init(type: HistoryType? = nil, id: Int? = nil, startAt: Date? = nil, endAt: Date? = nil) {
self.type = type
self.id = id
self.startAt = startAt
self.endAt = endAt
}
public var hashValue: Int {
var hash = 11
if let typeHash = type?.hashValue {
hash ^= typeHash
}
if let idHash = id?.hashValue {
hash ^= idHash
}
if let startAtHash = startAt?.hashValue {
hash ^= startAtHash
}
if let endAtHash = endAt?.hashValue {
hash ^= endAtHash
}
return hash
}
public static func == (lhs: HistoryParameters, rhs: HistoryParameters) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| unlicense | 83a9b7682725f715bb705cea5c5c8de7 | 19.95 | 99 | 0.622912 | 3.791855 | false | false | false | false |
lambdaacademy/2015.01_swift | Lectures/1/LA_2015.01_1-Introduction_completed.playground/section-1.swift | 1 | 4108 | //
// Lambda Academy 2015.01 Lecture 1
//
import Foundation
// Define three variables – a string, an integer and a double with implicit data type
var strVar = "string"
var intVar = 1
var floVar = 2.0
// Define three constants with explicit data type
let str: String = "string"
let int: Int = 1
let flo: Double = 2.0
// Define string constants which is a concatenation of the string defined in previous example, a space, and the float defined in ex. 1.
let s = str + " " + "\(flo)"
// Create one array and one dictionary.
let arr = [1, 2, 3, 4]
let dic = ["a": 1, "b": 2, "c": 3]
// Append one element to the simple array and to the simple dictionary declared in previous example
let arr2 = arr + [5]
// Define a string variable that may or may not have a value, set it up to have a string equal to a string from previous example and then in the next line remove this value from a newly created variable (note that a variable that does not have a value is not the same as a variable with an empty string). Then assign this value back to string from previous example, what happens?
var maybeStr: String? = str
strVar = maybeStr!
maybeStr = nil
//strVar = maybeStr! // this will cause BAD_ACCESS,
// Use "if let" syntax to deal with the optional values being not set and rewrite a previous example setting strVar within if let
if let aStr = maybeStr {
strVar = aStr // we don't have to explicitly unwrap an optional now
}
// Define an empty dictionary containing characters as keys and integers as values.
var dic2: [Character: Int] = [:]
var dic3 = [Character: Int]()
// Write a for loop which populates the array with 10 entries of the following form:
for a in 1...10 {
let char = Character(UnicodeScalar(a+64))
dic2[char] = a
}
dic2
// Create switch statement on the following "myVeg" variable, print it within switch. If it is tomato print it twice, if its cocumber, print it in a form "My favourite tomato is cocumber" where cocumber is taken from myVeg
let vegetables = ["red pepper", "green pepper", "cocumber", "tomato"]
let myVeg = vegetables[Int(arc4random()%3)]
switch myVeg {
case "red pepper":
println(myVeg)
case "tomato":
println(myVeg)
println(myVeg)
case "cocumber":
println("My favourite veg is \(myVeg)")
default:
println(myVeg)
}
// Change the above example by adding one more case that uses pattern matching ("where" keyword) to match all "peppers"
switch myVeg {
case let x where x.hasSuffix("pepper"):
println("This is pepper called '\(x)'")
default:
println(myVeg)
}
// Write a function which takes two parameters
// 1. An integer (index)
// 2. A Function that returns a String
// This function should return a tuple consising of:
// 1. Vegetable name that is under specified index (if exists) or a default value taken from a function passed as a second argument
// 2. an index
// Call this function, passing different indexes
func testFunc(x: Int, def: ()->String) -> (String, Int) {
let res = (x >= 0 && x < vegetables.count) ? vegetables[x] : def()
return (res, x)
}
testFunc(4, { return "default" });
// Enums in Objective-C are just numbers, one of it's side effects possibility of performing calculations. for example the following if statement is true but it doesn't make sense:
if NSASCIIStringEncoding + NSNEXTSTEPStringEncoding == NSJapaneseEUCStringEncoding {
print("NSASCIIStringEncoding + NSNEXTSTEPStringEncoding == NSJapaneseEUCStringEncoding !!!")
}
// Swifts' enums doesn't have such issue.
// Define swift enum that represents few encoding types
enum Encoding {
case UTF8Encoding
case ASCIIEncoding
}
// Add an "extension" to the previous enumeration type that will adopt it to "Printable" protocol
extension Encoding: Printable {
var description: String {
get {
switch self {
case .UTF8Encoding:
return "UTF8Enconding"
case .ASCIIEncoding:
return "ASCIIEncoding"
}
}
}
}
Encoding.UTF8Encoding.description
| apache-2.0 | f61cb0da6d6e6ed68a1fc14cc4c2f7a4 | 31.330709 | 379 | 0.693619 | 3.840973 | false | false | false | false |
thierrybucco/Eureka | Source/Core/Cell.swift | 5 | 4884 | // Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Base class for the Eureka cells
open class BaseCell: UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (() -> CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder: AnyObject? = self
while responder != nil {
if let formVC = responder as? FormViewController {
return formVC
}
responder = responder?.next
}
return nil
}
open func setup() {}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T: Equatable> : BaseCell, TypedCellType {
public typealias Value = T
/// The row associated to this cell
public weak var row: RowOf<T>!
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row) {
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
height = { UITableViewAutomaticDimension }
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup() {
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update() {
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? .gray : .black
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
return false
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
/// The untyped row associated to this cell.
public override var baseRow: BaseRow! { return row }
}
| mit | 4c210a4d7797eb53d104631ba4567e73 | 30.307692 | 126 | 0.664619 | 5.050672 | false | false | false | false |
ppoh71/motoRoutes | motoRoutes/motoRouteOptions.swift | 1 | 2409 | //
// motoRoutesOptions.swift
// motoRoutes
//
// Created by Peter Pohlmann on 10.05.16.
// Copyright © 2016 Peter Pohlmann. All rights reserved.
//
import UIKit
class motoRouteOptions: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
//Picker 1 Data Stuff
let pickerData = [
["1","2","3","4","5","8","10","25","50","80","100","150","250","500","750","1000","1250","1500","1800","2000","2500","3000","3500","4000","4500"],
["0.0001", "0.0003", "0.0005", "0.0007", "0.0009", "0.001","0.003", "0.005", "0.007", "0.009", "0.01", "0.03", "0.05", "0.07", "0.1", "0.3", "0.5", "0.7", "0.9","1.0","1.1","1.2","1.3","1.5","2","3","4","5"],
["1","2","3","4","5","8","10","25","50","80"]
]
//vars to set from root controller
var sliceAmount = 1
var timeIntervalMarker = 0.001
//picker outlet
@IBOutlet var amountPicker: UIPickerView!
//
// override func super init
//
override func viewDidLoad() {
super.viewDidLoad()
self.amountPicker.dataSource = self;
self.amountPicker.delegate = self;
}
//picker funcs
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return pickerData.count
}
//picker funcs
func pickerView(
_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int
) -> Int {
return pickerData[component].count
}
//picker funcs
func pickerView(
_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int
) -> String? {
return pickerData[component][row]
}
//picker funcs
func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if let sliceAmountPicker = Int(pickerData[0][amountPicker.selectedRow(inComponent: 0)]) {
sliceAmount = Int(sliceAmountPicker)
}
if let timeIntervalPicker = Double(pickerData[1][amountPicker.selectedRow(inComponent: 1)]) {
timeIntervalMarker = timeIntervalPicker
}
if let arrayStepPicker = Double(pickerData[2][amountPicker.selectedRow(inComponent: 2)]){
globalArrayStep.gArrayStep = Int(arrayStepPicker)
}
}
}
| apache-2.0 | 6e3967b67be0d79062337f044b45a34d | 29.1 | 222 | 0.562292 | 4.026756 | false | false | false | false |
Mindera/Alicerce | Sources/PerformanceMetrics/Trackers/PerformanceMetrics+MultiTracker.swift | 1 | 6431 | import Foundation
#if canImport(AlicerceCore)
import AlicerceCore
#endif
public extension PerformanceMetrics {
/// A performance metrics tracker that forwards performance measuring events to multiple trackers, while not doing
/// any tracking on its own.
class MultiTracker: PerformanceMetricsTracker {
/// The configured sub trackers.
public let trackers: [PerformanceMetricsTracker]
/// The tracker's tokenizer.
private let tokenizer = Tokenizer<Tag>()
/// The tracker's token dictionary, containing the mapping between internal and sub trackers' tokens.
private let tokens = Atomic<[Token<Tag> : [Token<Tag>]]>([:])
/// Creates a new performance metrics multi trcker instance, with the specified sub trackers.
///
/// - Parameters:
/// -trackers: The sub trackers to forward performance measuring events to.
public init(trackers: [PerformanceMetricsTracker]) {
assert(trackers.isEmpty == false, "🙅♂️ Trackers shouldn't be empty, since it renders this tracker useless!")
self.trackers = trackers
}
// MARK: - PerformanceMetricsTracker
/// Starts measuring the execution time of a specific code block identified by a particular identifier, by
/// propagating it to all registered sub tracker.
///
/// - Parameters:
/// - identifier: The metric's identifier, to group multiple metrics on the provider.
/// - Returns: A token identifying this particular metric instance.
public func start(with identifier: Identifier) -> Token<Tag> {
let token = tokenizer.next
let subTokens = startTrackers(with: identifier)
tokens.modify { $0[token] = subTokens }
return token
}
/// Stops measuring the execution of a specific code block while attaching any additional metric metadata, by
/// propagating it to all registered sub trackers.
///
/// - Parameters:
/// - token: The metric's identifying token, returned by `start(with:)`.
/// - metadata: The metric's metadata dictionary.
public func stop(with token: Token<Tag>, metadata: Metadata? = nil) {
guard let subTokens = tokens.modify({ $0.removeValue(forKey: token) }) else {
assertionFailure("🔥 Missing sub tokens for token \(token)!")
return
}
stopTrackers(with: subTokens, metadata: metadata)
}
/// Measures a given closure's execution time once it returns or throws (i.e. *synchronously*). An optional
/// metadata dictionary can be provided to be associated with the recorded metric. The metric is calculated on
/// all sub trackers.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - metadata: The metric's metadata dictionary. The default is `nil`.
/// - execute: The closure to measure the execution time of.
/// - Returns: The closure's return value, if any.
/// - Throws: The closure's thrown error, if any.
@discardableResult
public func measure<T>(with identifier: Identifier,
metadata: Metadata? = nil,
execute: () throws -> T) rethrows -> T {
let subTokens = startTrackers(with: identifier)
defer { stopTrackers(with: subTokens, metadata: metadata) }
let measureResult = try execute()
return measureResult
}
/// Measures a given closure's execution time *until* an inner `stop` closure is invoked by it with an optional
/// metadata dictionary to be associated with the recorded metric. The metric is calculated on all sub trackers.
///
/// Should be used for asynchronous code, or when the metric metadata is only available during execution.
///
/// - Important: The `stop` closure should be called *before* the `execute` either returns or throws.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - execute: The closure to measure the execution time of.
/// - stop: The closure to be invoked by `execute` to stop measuring the execution time, along with any
/// additional metric metadata.
/// - metadata: The metric's metadata dictionary.
/// - Returns: The closure's return value, if any.
/// - Throws: The closure's thrown error, if any.
@discardableResult
public func measure<T>(with identifier: Identifier,
execute: (_ stop: @escaping (_ metadata: Metadata?) -> Void) throws -> T) rethrows -> T {
let subTokens = startTrackers(with: identifier)
return try execute { [weak self] metadata in
self?.stopTrackers(with: subTokens, metadata: metadata)
}
}
// MARK: - Private
/// Starts measuring the execution time of a specific code block identified by a particular identifier on all
/// sub trackers.
///
/// - Parameters:
/// - identifier: The metric's identifier.
/// - Returns: The metric's identifying tokens for each sub tracker, returned by each tracker's `start(with:)`
/// in the same order as `trackers`.
private func startTrackers(with identifier: Identifier) -> [Token<Tag>] {
return trackers.map { $0.start(with: identifier) }
}
/// Stops measuring the execution of a specific code block while attaching any additional metric metadata on
/// all sub trackers.
///
/// - Important: The provided tokens order *must* match the `trackers` order.
///
/// - Parameters:
/// - subTokens: The metric's identifying tokens for each sub tracker, returned by each tracker's
/// `start(with:)`.
/// - metadata: The metric's metadata dictionary.
private func stopTrackers(with subTokens: [Token<Tag>], metadata: Metadata?) {
assert(subTokens.count == trackers.count, "😱 Number of sub tokens and sub trackers must match!")
zip(trackers, subTokens).forEach { tracker, token in tracker.stop(with: token, metadata: metadata) }
}
}
}
| mit | 8936847b35fbd657e19201eef01a3621 | 42.945205 | 121 | 0.614246 | 5.079968 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome | Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Defer.swift | 2 | 1695 | //
// Defer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Defer_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = Defer<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let disposable = parent.eval().flatMap { result in
return success(result.subscribe(self))
}.recoverWith { e in
trySendError(observer, e)
self.dispose()
return success(DefaultDisposable())
}
return disposable.get()
}
func on(event: Event<Element>) {
trySend(observer, event)
switch event {
case .Next:
break
case .Error:
dispose()
case .Completed:
dispose()
}
}
}
class Defer<Element> : Producer<Element> {
typealias Factory = () -> RxResult<Observable<Element>>
let observableFactory : Factory
init(observableFactory: Factory) {
self.observableFactory = observableFactory
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Defer_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
func eval() -> RxResult<Observable<Element>> {
return observableFactory()
}
} | mit | 14dcefebc31863082507ac72f3789581 | 24.69697 | 145 | 0.585841 | 4.581081 | false | false | false | false |
hivinau/LivingElectro | iOS/LivingElectro/LivingElectro/TitleCell.swift | 1 | 1155 | //
// TitleCell.swift
// LivingElectro
//
// Created by Aude Sautier on 14/05/2017.
// Copyright © 2017 Hivinau GRAFFE. All rights reserved.
//
import UIKit
@objc(TitleCell)
public class TitleCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: PaddingLabel!
public override var isSelected: Bool {
didSet {
titleLabel.textColor = isSelected ? .white : .gray
}
}
public var titleValue: String? {
didSet {
titleLabel.text = titleValue
titleLabel.sizeToFit()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.textAlignment = .center
titleLabel.textColor = isSelected ? .white : .gray
if let font = UIFont(name: "Helvetica", size: 14.0) {
titleLabel.font = font
}
}
public override func prepareForReuse() {
super.prepareForReuse()
titleLabel.text?.removeAll()
}
}
| mit | beb0ba14367095c260de4b3e1b20419c | 22.08 | 62 | 0.571924 | 5.039301 | false | false | false | false |
readium/r2-streamer-swift | r2-streamer-swift/Parser/EPUB/Extensions/Presentation+EPUB.swift | 1 | 2237 | //
// Presentation+EPUB.swift
// r2-streamer-swift
//
// Created by Mickaël on 24/02/2020.
//
// Copyright 2020 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import R2Shared
extension Presentation.Orientation {
/// Creates from an EPUB rendition:orientation property.
public init(epub: String, fallback: Presentation.Orientation? = nil) {
switch epub {
case "landscape":
self = .landscape
case "portrait":
self = .portrait
case "auto":
self = .auto
default:
self = fallback ?? .auto
}
}
}
extension Presentation.Overflow {
/// Creates from an EPUB rendition:flow property.
public init(epub: String, fallback: Presentation.Overflow? = nil) {
switch epub {
case "auto":
self = .auto
case "paginated":
self = .paginated
case "scrolled-doc", "scrolled-continuous":
self = .scrolled
default:
self = fallback ?? .auto
}
}
}
extension Presentation.Spread {
/// Creates from an EPUB rendition:spread property.
public init(epub: String, fallback: Presentation.Spread? = nil) {
switch epub {
case "none":
self = .none
case "auto":
self = .auto
case "landscape":
self = .landscape
// `portrait` is deprecated and should fallback to `both`.
// See. https://readium.org/architecture/streamer/parser/metadata#epub-3x-11
case "both", "portrait":
self = .both
default:
self = fallback ?? .auto
}
}
}
extension EPUBLayout {
/// Creates from an EPUB rendition:layout property.
public init(epub: String, fallback: EPUBLayout? = nil) {
switch epub {
case "reflowable":
self = .reflowable
case "pre-paginated":
self = .fixed
default:
self = fallback ?? .reflowable
}
}
}
| bsd-3-clause | 7e0fdd9622ba458bdb2dc30b93cccb66 | 24.701149 | 95 | 0.568426 | 4.401575 | false | false | false | false |
olaf-olaf/finalProject | drumPad/DistortionParameterViewController.swift | 1 | 2083 | //
// distortionParametersViewController.swift
// drumPad
//
// Created by Olaf Kroon on 25/01/17.
// Student number: 10787321
// Course: Programmeerproject
//
// DistortionParametersViewController consists of rotary knobs that are used to determine the parameters
// of the reverb object in AudioContoller.
//
// Copyright © 2017 Olaf Kroon. All rights reserved.
//
import UIKit
class distortionParametersViewController: UIViewController {
// MARK: - Variables.
let enabledColor = UIColor(red: (246/255.0), green: (124/255.0), blue: (113/255.0), alpha: 1.0)
var decimationKnob: Knob!
var roundingKnob: Knob!
// MARK: - Outlets.
@IBOutlet weak var setDistortion: UIButton!
@IBOutlet weak var roundingKnobPlaceholder: UIView!
@IBOutlet weak var decimationKnobPlaceholder: UIView!
// MARK: - UIViewController lifecycle.
override func viewDidLoad() {
super.viewDidLoad()
setDistortion.layer.cornerRadius = 5
decimationKnob = Knob(frame: decimationKnobPlaceholder.bounds)
decimationKnobPlaceholder.addSubview(decimationKnob)
decimationKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 1)
decimationKnob.value = Float(AudioController.sharedInstance.distortion.decimation)
roundingKnob = Knob(frame: roundingKnobPlaceholder.bounds)
roundingKnobPlaceholder.addSubview(roundingKnob)
roundingKnob.setKnobDisplay(largeButton: true, minimum: 0, maximum: 1)
roundingKnob.value = Float(AudioController.sharedInstance.distortion.rounding)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Actions.
@IBAction func setDistortionParameters(_ sender: UIButton) {
setDistortion.backgroundColor = enabledColor
let decimation = Double(decimationKnob.value)
let rounding = Double(roundingKnob.value)
AudioController.sharedInstance.setDistortionParameters(distortionDecimation: decimation, distortionRouding: rounding)
}
}
| mit | b3d3ce70411775169db7d92a96d35815 | 36.178571 | 125 | 0.717579 | 4.506494 | false | false | false | false |
Sufi-Al-Hussaini/Swift-CircleMenu | CircleMenuDemo/CircleMenuDemo/DefaultRotatingViewController.swift | 1 | 1668 | //
// DefaultRotatingViewController.swift
// CircleMenuDemo
//
// Created by Shoaib Ahmed on 11/25/16.
// Copyright © 2016 Shoaib Ahmed / Sufi-Al-Hussaini. All rights reserved.
//
import UIKit
class DefaultRotatingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
prepareView()
prepareDefaultCircleMenu()
}
func prepareView() {
view.backgroundColor = UIColor.lightGray
}
func prepareDefaultCircleMenu() {
// Create circle
let circle = Circle(with: CGRect(x: 10, y: 90, width: 300, height: 300), numberOfSegments: 10, ringWidth: 80.0)
// Set dataSource and delegate
circle.dataSource = self
circle.delegate = self
// Position and customize
circle.center = view.center
// Create overlay with circle
let overlay = CircleOverlayView(with: circle)
// Add to view
self.view.addSubview(circle)
self.view.addSubview(overlay!)
}
}
extension DefaultRotatingViewController: CircleDelegate, CircleDataSource {
func circle(_ circle: Circle, didMoveTo segment: Int, thumb: CircleThumb) {
let alert = UIAlertController(title: "Selected", message: "Item with tag: \(segment)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func circle(_ circle: Circle, iconForThumbAt row: Int) -> UIImage {
return UIImage(named: "icon_arrow_up")!
}
}
| mit | 3b77c97e87afb1e4776e713a7768ee0e | 28.767857 | 140 | 0.646071 | 4.554645 | false | false | false | false |
noppoMan/aws-sdk-swift | scripts/create-modules.swift | 1 | 4753 | #!/usr/bin/env swift sh
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import ArgumentParser // apple/swift-argument-parser ~> 0.0.1
import Files // JohnSundell/Files
import Stencil // soto-project/Stencil
class GenerateProcess {
let parameters: GenerateProjects
let environment: Environment
let fsLoader: FileSystemLoader
var targetFolder: Folder!
var servicesFolder: Folder!
var extensionsFolder: Folder!
var zlibSourceFolder: Folder!
init(_ parameters: GenerateProjects) {
self.parameters = parameters
self.fsLoader = FileSystemLoader(paths: ["./scripts/templates/create-modules"])
self.environment = Environment(loader: self.fsLoader)
}
func createProject(_ serviceName: String) throws {
let serviceSourceFolder = try servicesFolder.subfolder(at: serviceName)
let extensionSourceFolder = try? self.extensionsFolder.subfolder(at: serviceName)
let includeZlib = (serviceName == "S3")
// create folders
let serviceTargetFolder = try targetFolder.createSubfolder(at: serviceName)
let workflowsTargetFolder = try serviceTargetFolder.createSubfolder(at: ".github/workflows")
let sourceTargetFolder = try serviceTargetFolder.createSubfolder(at: "Sources")
// delete folder if it already exists
if let folder = try? sourceTargetFolder.subfolder(at: serviceName) {
try folder.delete()
}
// copy source files across
try serviceSourceFolder.copy(to: sourceTargetFolder)
// if there is an extensions folder copy files across to target source folder
if let extensionSourceFolder = extensionSourceFolder {
let serviceSourceTargetFolder = try sourceTargetFolder.subfolder(at: serviceName)
try extensionSourceFolder.files.forEach { try $0.copy(to: serviceSourceTargetFolder) }
}
// if zlib is required copy CAWSZlib folder
if includeZlib {
try self.zlibSourceFolder.copy(to: sourceTargetFolder)
}
// Package.swift
let context = [
"name": serviceName,
"version": parameters.version,
]
let packageTemplate = includeZlib ? "Package_with_Zlib.stencil" : "Package.stencil"
let package = try environment.renderTemplate(name: packageTemplate, context: context)
let packageFile = try serviceTargetFolder.createFile(named: "Package.swift")
try packageFile.write(package)
// readme
let readme = try environment.renderTemplate(name: "README.md", context: context)
let readmeFile = try serviceTargetFolder.createFile(named: "README.md")
try readmeFile.write(readme)
// copy license
let templatesFolder = try Folder(path: "./scripts/templates/create-modules")
let licenseFile = try templatesFolder.file(named: "LICENSE")
try licenseFile.copy(to: serviceTargetFolder)
// gitIgnore
let gitIgnore = try templatesFolder.file(named: ".gitignore")
try gitIgnore.copy(to: serviceTargetFolder)
// copy ci.yml
let ciYml = try templatesFolder.file(named: "ci.yml")
try ciYml.copy(to: workflowsTargetFolder)
}
func run() throws {
self.servicesFolder = try Folder(path: "./Sources/Soto/Services")
self.extensionsFolder = try Folder(path: "./Sources/Soto/Extensions")
self.zlibSourceFolder = try Folder(path: "./Sources/CAWSZlib")
self.targetFolder = try Folder(path: ".").createSubfolder(at: self.parameters.targetPath)
// try Folder(path: "targetFolder").
try self.parameters.services.forEach { service in
try createProject(service)
}
}
}
struct GenerateProjects: ParsableCommand {
@Argument(help: "The folder to create projects inside.")
var targetPath: String
@Option(name: .shortAndLong, help: "SotoCore version to use.")
var version: String
let services = [
/* "APIGateway",
"CloudFront",
"CloudWatch",
"DynamoDB",
"EC2",
"ECR",
"ECS",
"IAM",
"Kinesis",
"Lambda",*/
"S3",
"SES",
]
func run() throws {
try GenerateProcess(self).run()
}
}
GenerateProjects.main()
| apache-2.0 | 68eec03e329216e21792d6e24e0a5615 | 37.024 | 100 | 0.637913 | 4.492439 | false | false | false | false |
boland25/ResearchKit | samples/ORKSample/ORKSample/AppDelegate.swift | 5 | 4440 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let healthStore = HKHealthStore()
var window: UIWindow?
var containerViewController: ResearchContainerViewController? {
return window?.rootViewController as? ResearchContainerViewController
}
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let standardDefaults = NSUserDefaults.standardUserDefaults()
if standardDefaults.objectForKey("ORKSampleFirstRun") == nil {
ORKPasscodeViewController.removePasscodeFromKeychain()
standardDefaults.setValue("ORKSampleFirstRun", forKey: "ORKSampleFirstRun")
}
// Appearance customization
let pageControlAppearance = UIPageControl.appearance()
pageControlAppearance.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControlAppearance.currentPageIndicatorTintColor = UIColor.blackColor()
// Dependency injection.
containerViewController?.injectHealthStore(healthStore)
return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
lockApp()
return true
}
func applicationDidEnterBackground(application: UIApplication) {
if ORKPasscodeViewController.isPasscodeStoredInKeychain() {
// Hide content so it doesn't appear in the app switcher.
containerViewController?.contentHidden = true
}
}
func applicationWillEnterForeground(application: UIApplication) {
lockApp()
}
func lockApp() {
/*
Only lock the app if there is a stored passcode and a passcode
controller isn't already being shown.
*/
guard ORKPasscodeViewController.isPasscodeStoredInKeychain() && !(containerViewController?.presentedViewController is ORKPasscodeViewController) else { return }
window?.makeKeyAndVisible()
let passcodeViewController = ORKPasscodeViewController.passcodeAuthenticationViewControllerWithText("Welcome back to ResearchKit Sample App", delegate: self) as! ORKPasscodeViewController
containerViewController?.presentViewController(passcodeViewController, animated: false, completion: nil)
}
}
extension AppDelegate: ORKPasscodeDelegate {
func passcodeViewControllerDidFinishWithSuccess(viewController: UIViewController) {
containerViewController?.contentHidden = false
viewController.dismissViewControllerAnimated(true, completion: nil)
}
func passcodeViewControllerDidFailAuthentication(viewController: UIViewController) {
}
}
| bsd-3-clause | bf698766d99d912ba269c6e32154b102 | 42.960396 | 195 | 0.753153 | 5.959732 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS | iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/BsonUtil.swift | 1 | 4457 | //
// BsonUtil.swift
// iOSDeepLearningKitApp
//
// Created by Neil on 15/11/2016.
// Copyright © 2016 DeepLearningKit. All rights reserved.
//
import Foundation
func readArr(stream: inout InputStream) -> Any {
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(byteBuf, maxLength: 1)
stream.read(intBuf, maxLength: 4)
let byte = byteBuf[0]
let cnt = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
if byte == 0 { // value
let arrBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: cnt * 4)
stream.read(arrBuf, maxLength: cnt * 4)
let floatArrBuf = arrBuf.deinitialize().assumingMemoryBound(to: Float.self)
var arr = Array(repeating: 0.0, count: cnt) as! [Float]
for i in 0...(cnt-1) {
arr[i] = floatArrBuf[i]
}
arrBuf.deinitialize().deallocate(bytes: cnt * 4, alignedTo: 1)
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 1 { // dictionary
var arr = [Any].init()
for _ in 0...(cnt-1) {
arr.append(readDic(stream: &stream))
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 3 { // string
var arr = [String].init()
for _ in 0...(cnt-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
let data = Data(bytes: strBuf, count: strLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
arr.append(valStr!)
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else { // never get here
assert(false)
}
assert(false)
return [Any].init()
}
func readDic(stream: inout InputStream) -> Dictionary<String, Any> {
var dic = Dictionary<String, Any>.init()
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(intBuf, maxLength: 4)
let num = intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0]
for _ in 0...(num-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
var data = Data(bytes: strBuf, count: strLen)
let str = String(data: data, encoding: String.Encoding.ascii)
stream.read(byteBuf, maxLength: 1)
let byte = byteBuf[0]
if byte == 0 { // value
stream.read(intBuf, maxLength: 4)
let f = intBuf.deinitialize().assumingMemoryBound(to: Float.self)[0]
dic[str!] = f
} else if byte == 1 { // dictionary
dic[str!] = readDic(stream: &stream)
} else if byte == 2 { // array
dic[str!] = readArr(stream: &stream)
} else if byte == 3 { // string
// read string length
stream.read(intBuf, maxLength: 4)
let innerStrLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: innerStrLen)
stream.read(buf, maxLength: innerStrLen)
data = Data(bytes: buf, count: innerStrLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
dic[str!] = valStr
buf.deallocate(capacity: innerStrLen)
} else {
assert(false) // cannot get in
}
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return dic
}
func readBson(file: String) -> Dictionary<String, Any> {
var stream = InputStream(fileAtPath: file)
stream?.open()
let dic = readDic(stream: &stream!)
stream?.close()
return dic
}
| apache-2.0 | 288cca0aa8fa70f46b9b33f7c2ceaad7 | 35.826446 | 96 | 0.598743 | 3.946856 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Defines.swift | 1 | 1556 | //
// Defines.swift
// Inbbbox
//
// Created by Peter Bruz on 04/01/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import SwiftyUserDefaults
/// Keys related to reminders and notifications.
enum NotificationKey: String {
case ReminderOn = "ReminderOn"
case ReminderDate = "ReminderDate"
case UserNotificationSettingsRegistered = "UserNotificationSettingsRegistered"
case LocalNotificationSettingsProvided = "LocalNotificationSettingsProvided"
}
/// Keys related to streams sources.
enum StreamSourceKey: String {
case streamSourceIsSet = "StreamSourceIsSet"
case followingStreamSourceOn = "FollowingStreamSourceOn"
case newTodayStreamSourceOn = "NewTodayStreamSourceOn"
case popularTodayStreamSourceOn = "PopularTodayStreamSourceOn"
case debutsStreamSourceOn = "DebutsStreamSourceOn"
case mySetStreamSourceOn = "MySetStreamSourceOn"
}
/// Keys related to customization settings.
enum CustomizationKey: String {
case showAuthorOnHomeScreen = "ShowAuthorOnHomeScreen"
case language = "CustomAppLanguage"
case nightMode = "NightModeStatus"
case autoNightMode = "AutoNightMode"
case colorMode = "CurrentColorMode"
case selectedStreamSource = "SelectedStreamSource"
}
extension DefaultsKeys {
static let onboardingPassed = DefaultsKey<Bool>("onboardingPassed")
}
/// Keys for NSNotifications about changing settings.
enum InbbboxNotificationKey: String {
case UserDidChangeStreamSourceSettings
case UserDidChangeNotificationsSettings
}
| gpl-3.0 | 608e63ee100beb36c0bc5a9b721755c8 | 31.395833 | 82 | 0.777492 | 4.49422 | false | false | false | false |
SakuragiYoshimasa/PhotoCallender | PhotoCallender/AppDelegate.swift | 1 | 6115 | //
// AppDelegate.swift
// PhotoCallender
//
// Created by 櫻木善将 on 2015/06/22.
// Copyright © 2015年 YoshimasaSakuragi. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "kyoto.PhotoCallender" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("PhotoCallender", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 89b596e07db53dd0914b03f1c6f6bdf2 | 53.990991 | 290 | 0.720511 | 5.841148 | false | false | false | false |
congnt24/AwesomeMVVM | AwesomeMVVM/Classes/Base/AwesomeToggleViewByHeight.swift | 1 | 939 | //
// AwesomeToggleViewByHeight.swift
// Pods
//
// Created by Cong Nguyen on 8/19/17.
//
//
import UIKit
open class AwesomeToggleViewByHeight: BaseCustomView {
@IBInspectable var isHide: Bool = false
var heightConstraint: NSLayoutConstraint?
var height: CGFloat!
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
heightConstraint = (self.constraints.filter { $0.firstAttribute == .height }.first)
height = heightConstraint?.constant
}
override open func awakeFromNib() {
if isHide {
heightConstraint?.constant = 0
self.alpha = 0
}
}
open func toggleHeight() {
if heightConstraint?.constant == 0 {
heightConstraint?.constant = height
self.alpha = 1
} else {
heightConstraint?.constant = 0
self.alpha = 0
}
}
}
| mit | 5319a958181dfa96f733db9d787733f7 | 22.475 | 91 | 0.588924 | 4.718593 | false | false | false | false |
yangyu2010/DouYuZhiBo | DouYuZhiBo/DouYuZhiBo/Class/Home/View/RecycleHeaderView.swift | 1 | 3966 | //
// RecycleHeaderView.swift
// DouYuZhiBo
//
// Created by Young on 2017/2/21.
// Copyright © 2017年 YuYang. All rights reserved.
//
import UIKit
fileprivate let kRecycleCellID = "kRecycleCellID"
class RecycleHeaderView: UIView {
// MARK: -xib控件
@IBOutlet weak var recycleCollecView: UICollectionView!
@IBOutlet weak var pageController: UIPageControl!
// MARK: -系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
// 设置该控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
recycleCollecView.register(UINib(nibName: "RecycleHeaderCell", bundle: nil), forCellWithReuseIdentifier: kRecycleCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
//设置layout 不能在xib里设置 因为xib里的大小还没固定下来
let layout = recycleCollecView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = recycleCollecView.bounds.size
}
// MARK: -自定义属性
var recycleModelArr : [RecycleModel]? {
didSet {
guard recycleModelArr != nil else { return }
// 1.刷新数据
recycleCollecView.reloadData()
// 2.设置pageController的总个数
pageController.numberOfPages = recycleModelArr!.count
// 3.设置collectionView滚动到中间某个位置
let path = IndexPath(item: recycleModelArr!.count * 50, section: 0)
recycleCollecView.scrollToItem(at: path, at: .left, animated: false)
// 4.添加定时器
addTimer()
}
}
/// 定时器
fileprivate var timer : Timer?
}
// MARK: -数据源
extension RecycleHeaderView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (recycleModelArr?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kRecycleCellID, for: indexPath) as! RecycleHeaderCell
cell.model = recycleModelArr?[indexPath.item % recycleModelArr!.count]
return cell
}
}
// MARK: -代理
extension RecycleHeaderView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
let count = Int(offsetX / scrollView.bounds.width)
pageController.currentPage = count % recycleModelArr!.count
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
stopTimer()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTimer()
}
}
// MARK: -提供个类方法创建view
extension RecycleHeaderView {
class func creatView() -> RecycleHeaderView {
return Bundle.main.loadNibNamed("RecycleHeaderView", owner: nil, options: nil)?.first as! RecycleHeaderView
}
}
// MARK: -处理timer
extension RecycleHeaderView {
fileprivate func addTimer() {
timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
fileprivate func stopTimer() {
timer?.invalidate()
timer = nil
}
@objc fileprivate func scrollToNext() {
let currentOffsetX = recycleCollecView.contentOffset.x
let offset = currentOffsetX + recycleCollecView.bounds.width
recycleCollecView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
}
}
| mit | 1b7b774efcb7bc8415f5c6fc672ad6b4 | 27.816794 | 139 | 0.651126 | 4.870968 | false | false | false | false |
kirayamato1989/KYPhotoBrowser | KYPhotoBrowser/KYPhotoItem.swift | 1 | 1900 | //
// KYPhotoItem.swift
// KYPhotoBrowser
//
// Created by 郭帅 on 2016/11/8.
// Copyright © 2016年 郭帅. All rights reserved.
//
import UIKit
import Kingfisher
/// 照片模型类
public class KYPhotoItem: KYPhotoSource {
public var url: URL?
public var placeholder: UIImage?
public var image: UIImage?
public var des: String?
public init(url: URL?, placeholder: UIImage?, image: UIImage?, des: String?) {
self.image = image
self.url = url
self.placeholder = placeholder
self.des = des
}
public func loadIfNeed(progress: ((KYPhotoSource, Int64, Int64) -> ())?, complete: ((KYPhotoSource, UIImage?, Error?) -> ())?) {
if image == nil, let _ = url {
if url!.isFileURL {
let localImage = UIImage(contentsOfFile: url!.path)
var error: Error?
if localImage == nil {
error = NSError()
}
image = localImage
complete?(self, localImage, error)
}
else {
// 抓取image
KingfisherManager.shared.retrieveImage(with: url!, options: [.preloadAllAnimationData], progressBlock: { [weak self](current, total) in
if let _ = self {
progress?(self!, current, total)
}
}, completionHandler: {[weak self](image, error, cacheType, url) in
if let _ = self {
self!.image = image
complete?(self!, image, error)
}
})
}
}
else {
let error: Error? = image == nil ? NSError() : nil
complete?(self, image, error)
}
}
public func releaseImage() {
self.image = nil
}
}
| mit | b7dbecbd814ef377acf94b23b624edf5 | 30.25 | 151 | 0.490667 | 4.722922 | false | false | false | false |
february29/Learning | swift/ARDemo/ARDemo/ViewController.swift | 1 | 8396 | //
// ViewController.swift
// ARDemo
//
// Created by bai on 2019/5/28.
// Copyright © 2019 北京仙指信息技术有限公司. All rights reserved.
//
import UIKit
import ARKit
import SceneKit
class ViewController: UIViewController ,ARSCNViewDelegate,ARSessionDelegate{
//场景
lazy var sceneView: ARSCNView = {
let sceneView = ARSCNView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height));
sceneView.showsStatistics = true;
sceneView.autoenablesDefaultLighting = true
return sceneView;
}()
// 会话
lazy var sesson: ARSession = {
let temp = ARSession();
temp.delegate = self;
return temp;
}()
lazy var scene: SCNScene = {
// 存放所有 3D 几何体的容器
let scene = SCNScene()
return scene;
}()
//小树人
lazy var treeNode: SCNNode = {
let temp = SCNNode();
guard let url = Bundle.main.url(forResource: "linglang", withExtension: "max") else {
fatalError("baby_groot.dae not exit.")
}
guard let customNode = SCNReferenceNode(url: url) else {
fatalError("load baby_groot error.")
}
customNode.load();
temp.addChildNode(customNode)
temp.position = SCNVector3Make(0, 0, -0.5);
return temp;
}()
//红色立方体
lazy var redNode: SCNNode = {
// 想要绘制的 3D 立方体
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.0)
boxGeometry.firstMaterial?.diffuse.contents = UIColor.red;
// 将几何体包装为 node 以便添加到 scene
let boxNode = SCNNode(geometry: boxGeometry)
boxNode.position = SCNVector3Make(0, 0, -0.5);
return boxNode;
}()
//相机节点 代表第一视角的位置。 空节点
lazy var selfNode: SCNNode = {
let temp = SCNNode()
return temp;
}()
//
lazy var boxNode: SCNNode = {
// 想要绘制的 3D 立方体
let boxGeometry = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.0)
// 将几何体包装为 node 以便添加到 scene
let boxNode = SCNNode(geometry: boxGeometry)
return boxNode;
}()
lazy var configuration:ARWorldTrackingConfiguration = {
let temp = ARWorldTrackingConfiguration();
temp.isLightEstimationEnabled = true;
temp.planeDetection = .horizontal;
return temp
}()
override func viewDidLoad() {
super.viewDidLoad()
self.sceneView.session = self.sesson;
self.sceneView.delegate = self;
self.view.addSubview(sceneView);
// rootNode 是一个特殊的 node,它是所有 node 的起始点
self.scene.rootNode.addChildNode(self.redNode)
self.sceneView.scene = self.scene
self.scene.rootNode.addChildNode(self.treeNode)
//ARSCNView 的scene 为 SCNScene ,SCNScene的rootNode 添加子node
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.sceneView.session.run(self.configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
self.sceneView.session.pause()
}
//MARK:ARSCNViewDelegate 继承自 ARSessionObserver
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print("添加锚点")
}
func session(_ session: ARSession, didUpdate frame: ARFrame) {
// print("相机移动: (x: \(frame.camera.transform.columns.3.x) y:\(frame.camera.transform.columns.3.y) z:\(frame.camera.transform.columns.3.z))")
// if self.node != nil {
// self.node.position = SCNVector3Make(frame.camera.transform.columns.3.x,frame.camera.transform.columns.3.y,frame.camera.transform.columns.3.z);
// }
selfNode.position = SCNVector3Make(frame.camera.transform.columns.3.x,frame.camera.transform.columns.3.y,frame.camera.transform.columns.3.z);
}
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
print("更新锚点")
}
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
//MARK:ARSCNViewDelegate
////添加节点时候调用(当开启平地捕捉模式之后,如果捕捉到平地,ARKit会自动添加一个平地节点)
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
print("添加节点");
// if anchor.isMember(of: ARPlaneAnchor.self) {
// print("捕捉到平地");
//
//
// let planeAnchor = anchor as! ARPlaneAnchor;
// self.boxNode.position = SCNVector3Make(planeAnchor.center.x, 0, planeAnchor.center.z)
// node.addChildNode(self.boxNode)
// }
//
}
//点击屏幕。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super .touchesBegan(touches, with: event);
self.nodeAroundAnimation();
self.treeRotation();
}
func treeRotation() {
//旋转核心动画
let moonRotationAnimation = CABasicAnimation(keyPath: "rotation");
//旋转周期
moonRotationAnimation.duration = 5;
//围绕Y轴旋转360度
moonRotationAnimation.toValue = NSValue(scnVector4: SCNVector4Make(0, 1, 0, Float(M_PI*2)));
//无限旋转 重复次数为无穷大
moonRotationAnimation.repeatCount = Float.greatestFiniteMagnitude;
//开始旋转 !!!:切记这里是让空节点旋转,而不是台灯节点。 理由同上
treeNode.addAnimation(moonRotationAnimation, forKey: "tree rotation around self");
}
func nodeAroundAnimation() {
//3.绕相机旋转
//绕相机旋转的关键点在于:在相机的位置创建一个空节点,然后将台灯添加到这个空节点,最后让这个空节点自身旋转,就可以实现台灯围绕相机旋转
//1.为什么要在相机的位置创建一个空节点呢?因为你不可能让相机也旋转
//2.为什么不直接让台灯旋转呢? 这样的话只能实现台灯的自转,而不能实现公转
//空节点位置与相机节点位置一致
selfNode.position = self.sceneView.scene.rootNode.position;
//将空节点添加到相机的根节点
self.sceneView.scene.rootNode.addChildNode(selfNode)
// !!!将移动节点作为自己节点的子节点,如果不这样,那么你将看到的是台灯自己在转,而不是围着你转
selfNode.addChildNode(self.redNode)
//旋转核心动画
let moonRotationAnimation = CABasicAnimation(keyPath: "rotation");
//旋转周期
moonRotationAnimation.duration = 5;
//围绕Y轴旋转360度
moonRotationAnimation.toValue = NSValue(scnVector4: SCNVector4Make(0, 1, 0, Float(M_PI*2)));
//无限旋转 重复次数为无穷大
moonRotationAnimation.repeatCount = Float.greatestFiniteMagnitude;
//开始旋转 !!!:切记这里是让空节点旋转,而不是台灯节点。 理由同上
selfNode.addAnimation(moonRotationAnimation, forKey: "moon rotation around earth");
}
}
| mit | 7a391bb295dba7b8ca4435161ddcbbc4 | 26.621723 | 157 | 0.585763 | 4.032258 | false | false | false | false |
milseman/swift | test/Constraints/array_literal.swift | 5 | 9535 | // RUN: %target-typecheck-verify-swift
struct IntList : ExpressibleByArrayLiteral {
typealias Element = Int
init(arrayLiteral elements: Int...) {}
}
struct DoubleList : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {}
}
struct IntDict : ExpressibleByArrayLiteral {
typealias Element = (String, Int)
init(arrayLiteral elements: Element...) {}
}
final class DoubleDict : ExpressibleByArrayLiteral {
typealias Element = (String, Double)
init(arrayLiteral elements: Element...) {}
}
final class List<T> : ExpressibleByArrayLiteral {
typealias Element = T
init(arrayLiteral elements: T...) {}
}
final class Dict<K,V> : ExpressibleByArrayLiteral {
typealias Element = (K,V)
init(arrayLiteral elements: (K,V)...) {}
}
infix operator =>
func => <K, V>(k: K, v: V) -> (K,V) { return (k,v) }
func useIntList(_ l: IntList) {}
func useDoubleList(_ l: DoubleList) {}
func useIntDict(_ l: IntDict) {}
func useDoubleDict(_ l: DoubleDict) {}
func useList<T>(_ l: List<T>) {}
func useDict<K,V>(_ d: Dict<K,V>) {}
useIntList([1,2,3])
useIntList([1.0,2,3]) // expected-error{{cannot convert value of type 'Double' to expected element type 'Int'}}
useIntList([nil]) // expected-error {{nil is not compatible with expected element type 'Int'}}
useDoubleList([1.0,2,3])
useDoubleList([1.0,2.0,3.0])
useIntDict(["Niners" => 31, "Ravens" => 34])
useIntDict(["Niners" => 31, "Ravens" => 34.0]) // expected-error{{cannot convert value of type '(String, Double)' to expected element type '(String, Int)'}}
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
useDoubleDict(["Niners" => 31, "Ravens" => 34.0])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34])
useDoubleDict(["Niners" => 31.0, "Ravens" => 34.0])
// Generic slices
useList([1,2,3])
useList([1.0,2,3])
useList([1.0,2.0,3.0])
useDict(["Niners" => 31, "Ravens" => 34])
useDict(["Niners" => 31, "Ravens" => 34.0])
useDict(["Niners" => 31.0, "Ravens" => 34.0])
// Fall back to [T] if no context is otherwise available.
var a = [1,2,3]
var a2 : [Int] = a
var b = [1,2,3.0]
var b2 : [Double] = b
var arrayOfStreams = [1..<2, 3..<4]
struct MyArray : ExpressibleByArrayLiteral {
typealias Element = Double
init(arrayLiteral elements: Double...) {
}
}
var myArray : MyArray = [2.5, 2.5]
// Inference for tuple elements.
var x1 = [1]
x1[0] = 0
var x2 = [(1, 2)]
x2[0] = (3, 4)
var x3 = [1, 2, 3]
x3[0] = 4
func trailingComma() {
_ = [1, ]
_ = [1, 2, ]
_ = ["a": 1, ]
_ = ["a": 1, "b": 2, ]
}
func longArray() {
var _=["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
}
[1,2].map // expected-error {{expression type '((Int) throws -> _) throws -> [_]' is ambiguous without more context}}
// <rdar://problem/25563498> Type checker crash assigning array literal to type conforming to _ArrayProtocol
func rdar25563498<T : ExpressibleByArrayLiteral>(t: T) {
var x: T = [1] // expected-error {{cannot convert value of type '[Int]' to specified type 'T'}}
// expected-warning@-1{{variable 'x' was never used; consider replacing with '_' or removing it}}
}
func rdar25563498_ok<T : ExpressibleByArrayLiteral>(t: T) -> T
where T.ArrayLiteralElement : ExpressibleByIntegerLiteral {
let x: T = [1]
return x
}
class A { }
class B : A { }
class C : A { }
/// Check for defaulting the element type to 'Any' / 'Any?'.
func defaultToAny(i: Int, s: String) {
let a1 = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a1 // expected-error{{value of type '[Any]'}}
let a2: Array = [1, "a", 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional}}
let _: Int = a2 // expected-error{{value of type 'Array<Any>'}}
let a3 = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a3 // expected-error{{value of type '[Any?]'}}
let a4: Array = [1, "a", nil, 3.5]
// expected-error@-1{{heterogeneous collection literal could only be inferred to '[Any?]'; add explicit type annotation if this is intentional}}
let _: Int = a4 // expected-error{{value of type 'Array<Any?>'}}
let a5 = []
// expected-error@-1{{empty collection literal requires an explicit type}}
let _: Int = a5 // expected-error{{value of type '[Any]'}}
let _: [Any] = [1, "a", 3.5]
let _: [Any] = [1, "a", [3.5, 3.7, 3.9]]
let _: [Any] = [1, "a", [3.5, "b", 3]]
let _: [Any?] = [1, "a", nil, 3.5]
let _: [Any?] = [1, "a", nil, [3.5, 3.7, 3.9]]
let _: [Any?] = [1, "a", nil, [3.5, "b", nil]]
let a6 = [B(), C()]
let _: Int = a6 // expected-error{{value of type '[A]'}}
}
func noInferAny(iob: inout B, ioc: inout C) {
var b = B()
var c = C()
let _ = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
let _: [A] = [b, c, iob, ioc] // do not infer [Any] when elements are lvalues or inout
b = B()
c = C()
}
/// Check handling of 'nil'.
protocol Proto1 {}
protocol Proto2 {}
struct Nilable: ExpressibleByNilLiteral {
init(nilLiteral: ()) {}
}
func joinWithNil<T>(s: String, a: Any, t: T, m: T.Type, p: Proto1 & Proto2, arr: [Int], opt: Int?, iou: Int!, n: Nilable) {
let a1 = [s, nil]
let _: Int = a1 // expected-error{{value of type '[String?]'}}
let a2 = [nil, s]
let _: Int = a2 // expected-error{{value of type '[String?]'}}
let a3 = ["hello", nil]
let _: Int = a3 // expected-error{{value of type '[String?]'}}
let a4 = [nil, "hello"]
let _: Int = a4 // expected-error{{value of type '[String?]'}}
let a5 = [(s, s), nil]
let _: Int = a5 // expected-error{{value of type '[(String, String)?]'}}
let a6 = [nil, (s, s)]
let _: Int = a6 // expected-error{{value of type '[(String, String)?]'}}
let a7 = [("hello", "world"), nil]
let _: Int = a7 // expected-error{{value of type '[(String, String)?]'}}
let a8 = [nil, ("hello", "world")]
let _: Int = a8 // expected-error{{value of type '[(String, String)?]'}}
let a9 = [{ $0 * 2 }, nil]
let _: Int = a9 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a10 = [nil, { $0 * 2 }]
let _: Int = a10 // expected-error{{value of type '[((Int) -> Int)?]'}}
let a11 = [a, nil]
let _: Int = a11 // expected-error{{value of type '[Any?]'}}
let a12 = [nil, a]
let _: Int = a12 // expected-error{{value of type '[Any?]'}}
let a13 = [t, nil]
let _: Int = a13 // expected-error{{value of type '[T?]'}}
let a14 = [nil, t]
let _: Int = a14 // expected-error{{value of type '[T?]'}}
let a15 = [m, nil]
let _: Int = a15 // expected-error{{value of type '[T.Type?]'}}
let a16 = [nil, m]
let _: Int = a16 // expected-error{{value of type '[T.Type?]'}}
let a17 = [p, nil]
let _: Int = a17 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a18 = [nil, p]
let _: Int = a18 // expected-error{{value of type '[(Proto1 & Proto2)?]'}}
let a19 = [arr, nil]
let _: Int = a19 // expected-error{{value of type '[[Int]?]'}}
let a20 = [nil, arr]
let _: Int = a20 // expected-error{{value of type '[[Int]?]'}}
let a21 = [opt, nil]
let _: Int = a21 // expected-error{{value of type '[Int?]'}}
let a22 = [nil, opt]
let _: Int = a22 // expected-error{{value of type '[Int?]'}}
let a23 = [iou, nil]
let _: Int = a23 // expected-error{{value of type '[Int?]'}}
let a24 = [nil, iou]
let _: Int = a24 // expected-error{{value of type '[Int?]'}}
let a25 = [n, nil]
let _: Int = a25 // expected-error{{value of type '[Nilable]'}}
let a26 = [nil, n]
let _: Int = a26 // expected-error{{value of type '[Nilable]'}}
}
struct OptionSetLike : ExpressibleByArrayLiteral {
typealias Element = OptionSetLike
init() { }
init(arrayLiteral elements: OptionSetLike...) { }
static let option: OptionSetLike = OptionSetLike()
}
func testOptionSetLike(b: Bool) {
let _: OptionSetLike = [ b ? [] : OptionSetLike.option, OptionSetLike.option]
let _: OptionSetLike = [ b ? [] : .option, .option]
}
// Join of class metatypes - <rdar://problem/30233451>
class Company<T> {
init(routes: [() -> T]) { }
}
class Person { }
class Employee: Person { }
class Manager: Person { }
let router = Company(
routes: [
{ () -> Employee.Type in
_ = ()
return Employee.self
},
{ () -> Manager.Type in
_ = ()
return Manager.self
}
]
)
// Same as above but with existentials
protocol Fruit {}
protocol Tomato : Fruit {}
struct Chicken : Tomato {}
protocol Pear : Fruit {}
struct Beef : Pear {}
let router = Company(
routes: [
// FIXME: implement join() for existentials
// expected-error@+1 {{cannot convert value of type '() -> Tomato.Type' to expected element type '() -> _'}}
{ () -> Tomato.Type in
_ = ()
return Chicken.self
},
{ () -> Pear.Type in
_ = ()
return Beef.self
}
]
)
// Infer [[Int]] for SR3786aa.
// FIXME: As noted in SR-3786, this was the behavior in Swift 3, but
// it seems like the wrong choice and is less by design than by
// accident.
let SR3786a: [Int] = [1, 2, 3]
let SR3786aa = [SR3786a.reversed(), SR3786a]
| apache-2.0 | fda3d5e8200085420e214288dc4d84a2 | 28.248466 | 178 | 0.592764 | 3.0512 | false | false | false | false |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatisticsTests/RankTests.swift | 1 | 1729 | //
// RanksTest.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import XCTest
import SigmaSwiftStatistics
class RankTests: XCTestCase {
func testRank() {
let result = Sigma.rank([2, 3, 6, 5, 3])
XCTAssertEqual([1, 2.5, 5, 4, 2.5], result)
}
func testRank_decimals() {
let data = [0.98, 1.11, 1.27, 1.32, 1.44, 1.56, 1.56, 1.76, 2.56, 3.07,
0.37, 0.38, 0.61, 0.78, 0.83, 0.86, 0.9, 0.95, 1.63, 1.97]
let result = Sigma.rank(data)
let expected: [Double] = [9, 10, 11, 12, 13, 14.5, 14.5, 17, 19, 20,
1, 2, 3, 4, 5, 6, 7, 8, 16, 18]
XCTAssertEqual(expected, result)
}
func testRank_singleValue() {
let result = Sigma.rank([50])
XCTAssertEqual([1.0], result)
}
func testRank_empty() {
let result = Sigma.rank([])
XCTAssertEqual([], result)
}
// MARK: ties
func testRank_tiesMean() {
let result = Sigma.rank([100, 100, 100, 100], ties: .average)
XCTAssertEqual([2.5, 2.5, 2.5, 2.5], result)
}
func testRanksTiesMin() {
let result = Sigma.rank([100, 100, 100, 100], ties: .min)
XCTAssertEqual([1, 1, 1, 1], result)
}
func testRanksTiesMax() {
let result = Sigma.rank([100, 100, 100, 100], ties: .max)
XCTAssertEqual([4, 4, 4, 4], result)
}
func testRank_tiesFirst() {
let result = Sigma.rank([100, 100, 100, 100], ties: .first)
XCTAssertEqual([1, 2, 3, 4], result)
}
func testRank_tiesLast() {
let result = Sigma.rank([100, 100, 100, 100], ties: .last)
XCTAssertEqual([4, 3, 2, 1], result)
}
}
| mit | 286bc8952670b4a9fa020ae4c4f72978 | 23.338028 | 75 | 0.564236 | 2.984456 | false | true | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro | Parse Dashboard for iOS/Views/ConsoleView.swift | 1 | 3731 | //
// ConsoleView.swift
// Parse Dashboard for iOS
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 12/20/17.
//
import UIKit
class ConsoleView: UIView {
enum LogKind {
case error, success, info
}
// MARK: - Properties
static var shared = ConsoleView()
private var textView: UITextView = {
let textView = UITextView()
textView.textContainerInset = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 6)
textView.textColor = .white
textView.font = UIFont(name: "Menlo", size: 11.0)!
textView.backgroundColor = .clear
textView.isEditable = false
textView.isSelectable = false
return textView
}()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Setup View
func setupView() {
backgroundColor = .black
layer.shadowRadius = 3
layer.shadowOffset = CGSize(width: 0, height: -1)
layer.shadowOpacity = 0.3
layer.shadowColor = UIColor.darkGray.cgColor
addSubview(textView)
textView.fillSuperview()
}
// MARK: - Methods
public func scrollToBottom() {
if textView.bounds.height < textView.contentSize.height {
textView.layoutManager.ensureLayout(for: textView.textContainer)
let offset = CGPoint(x: 0, y: (textView.contentSize.height - textView.frame.size.height))
textView.setContentOffset(offset, animated: true)
}
}
func log(message: String, kind: LogKind = .info) {
DispatchQueue.main.async {
let dateString = Date().string(dateStyle: .none, timeStyle: .medium)
let newText = NSMutableAttributedString(attributedString: self.textView.attributedText)
newText.normal("\(dateString) > ", font: UIFont(name: "Menlo", size: 11.0)!, color: .white)
switch kind {
case .info: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .white)
case .error: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .red)
case .success: newText.normal(message + "\n", font: UIFont(name: "Menlo", size: 11.0)!, color: .green)
}
self.textView.attributedText = newText
self.scrollToBottom()
}
}
}
| mit | 5cc2a70d69c109bd8e8e68fc775dc03e | 34.865385 | 114 | 0.633512 | 4.488568 | false | false | false | false |
voyages-sncf-technologies/Collor | Example/Collor/PantoneSample/cell/PantoneColorAdapter.swift | 1 | 1117 | //
// PantoneColorAdapter.swift
// Collor
//
// Created by Guihal Gwenn on 08/08/2017.
// Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved.
//
import Foundation
import Collor
struct PantoneColorAdapter: CollectionAdapter {
let hexaColor:Int
let color:UIColor
init(hexaColor:Int) {
self.hexaColor = hexaColor
color = UIColor(rgb: hexaColor)
}
}
// from https://stackoverflow.com/questions/24263007/how-to-use-hex-colour-values-in-swift-ios
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
}
| bsd-3-clause | c075c8ef721e3a5ffe2db8705a4de863 | 25.595238 | 116 | 0.598926 | 3.458204 | false | false | false | false |
thoughtbot/Perform | Sources/Perform/Perform.swift | 1 | 3166 | import UIKit
extension UIViewController {
/// Perform the storyboard segue identified by `segue`, invoking `prepare`
/// with the destination view controller when `prepareForSegue(_:sender:)`
/// is received.
///
/// **Example**
///
/// // prepare for segue inside the closure
/// perform(.showTaskDetails) { taskVC in
/// taskVC.task = self.selectedTask
/// }
///
/// // just perform a segue
/// perform(.signOut)
///
/// If the destination view controller itself doesn't match the destination
/// type specified by `segue`, its view controller hierarchy is searched
/// until the matching view controller is found. For example, if the desired
/// view controller is embedded inside a `UINavigationController`, it will
/// still be found and passed along to `prepare`.
///
/// - parameter segue:
/// An instance of `Segue<Destination>` which specifies the identifier
/// and destination view controller type.
///
/// - parameter prepare:
/// A function that will be invoked with the matching destination view
/// view controller when `prepareForSegue(_:sender:)` is received. The
/// default value for this parameter does nothing.
///
/// - note:
/// If no matching view controller is found in the destination
/// view controller hierarchy, this method will raise a fatal error
/// and crash. This usually means that the view controller hasn't
/// been configured with the correct type in the storyboard.
public func perform<Destination>(_ segue: Segue<Destination>, prepare: @escaping (Destination) -> Void = { _ in }) {
performSegue(withIdentifier: segue.identifier) { [segueDescription = { String(reflecting: segue) }] segue, _ in
guard let destination = segue.destinationViewController(ofType: Destination.self) else {
#if DEBUG
let printHierarchy = "_printHierarchy"
let hierarchy = segue.destination.perform(Selector(printHierarchy)).takeUnretainedValue()
fatalError("\(segueDescription()): expected destination view controller hierarchy to include \(Destination.self), got:\n\(hierarchy)")
#else
fatalError("\(segueDescription()): expected destination view controller hierarchy to include \(Destination.self)")
#endif
}
prepare(destination)
}
}
internal func performSegue(withIdentifier identifier: String, sender: Any? = nil, prepare: @escaping (UIStoryboardSegue, Any?) -> Void) {
_ = try! aspect_hook(
#selector(UIViewController.prepare(for:sender:)),
options: .optionAutomaticRemoval,
body: { info in
let arguments = info.arguments()!
prepare(arguments.first as! UIStoryboardSegue, arguments.second)
}
)
performSegue(withIdentifier: identifier, sender: sender)
}
}
// MARK: - Type checker ambiguity hack
extension UIViewController {
@available(*, unavailable)
public func perform() {
fatalError(
"This method will never be called, and exists only to remove an " +
"apparent ambiguity resolving the generic method 'perform(_:prepare:)'"
)
}
}
| mit | e66edfa17c831e7df22ffc1e435a5a9e | 39.589744 | 144 | 0.673089 | 4.848392 | false | false | false | false |
mklbtz/finch | Sources/TaskManagement/Storage.swift | 1 | 1644 | import Foundation
public struct Storage<Stored> {
public let path: String
public let defaultValue: Stored?
let transcoder: Transcoder<Stored, Data>
public init(atPath path: String, default: Stored? = nil, transcoder: Transcoder<Stored, Data>) {
self.path = path
self.transcoder = transcoder
self.defaultValue = `default`
}
}
extension Storage {
public func load() throws -> Stored {
return try withNiceErrors {
do {
let input = try file.load()
return try transcoder.decode(input)
}
catch File.Error.couldNotRead(let file) {
if let defaultValue = defaultValue {
return defaultValue
} else {
throw File.Error.couldNotRead(file)
}
}
}
}
public func save(_ stored: Stored) throws {
return try withNiceErrors {
let output = try transcoder.encode(stored)
try file.save(output)
}
}
var file: File {
return File(atPath: path)
}
private func withNiceErrors<A>(_ run: () throws -> A) rethrows -> A {
do {
return try run()
}
catch let error as NSError {
print("caught NSError")
throw error.localizedDescription
}
}
}
extension Storage where Stored == [Task] {
public static var defaultPath: String {
return ".todo"
}
}
public func TaskStorage(atPath path: String = Storage<[Task]>.defaultPath) -> Storage<[Task]> {
return .init(atPath: path, default: [], transcoder: JSONTranscoder())
}
public func StringStorage(atPath path: String = Storage<[Task]>.defaultPath) -> Storage<String> {
return .init(atPath: path, transcoder: StringTranscoder())
}
| mit | 16788a2b8c72b13123ade3844dfa67ec | 23.909091 | 98 | 0.645377 | 4.069307 | false | false | false | false |
wikimedia/wikipedia-ios | Widgets/Widgets/TopReadWidget.swift | 1 | 15581 | import SwiftUI
import WidgetKit
import WMF
// MARK: - Widget
struct TopReadWidget: Widget {
private let kind: String = WidgetController.SupportedWidget.topRead.identifier
public var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: TopReadProvider(), content: { entry in
TopReadView(entry: entry)
})
.configurationDisplayName(LocalizedStrings.widgetTitle)
.description(LocalizedStrings.widgetDescription)
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}
// MARK: - Data
final class TopReadData {
// MARK: Properties
static let shared = TopReadData()
let maximumRankedArticles = 4
var placeholder: TopReadEntry {
return TopReadEntry(date: Date())
}
func fetchLatestAvailableTopRead(usingCache: Bool = false, completion userCompletion: @escaping (TopReadEntry) -> Void) {
let widgetController = WidgetController.shared
widgetController.startWidgetUpdateTask(userCompletion) { (dataStore, widgetUpdateTaskCompletion) in
widgetController.fetchNewestWidgetContentGroup(with: .topRead, in: dataStore, isNetworkFetchAllowed: !usingCache) { (contentGroup) in
guard let contentGroup = contentGroup else {
widgetUpdateTaskCompletion(self.placeholder)
return
}
self.assembleTopReadFromContentGroup(contentGroup, with: dataStore, usingImageCache: usingCache, completion: widgetUpdateTaskCompletion)
}
}
}
// MARK: Private
private func assembleTopReadFromContentGroup(_ topRead: WMFContentGroup, with dataStore: MWKDataStore, usingImageCache: Bool = false, completion: @escaping (TopReadEntry) -> Void) {
guard let articlePreviews = topRead.contentPreview as? [WMFFeedTopReadArticlePreview] else {
completion(placeholder)
return
}
// The WMFContentGroup can only be accessed synchronously
// re-accessing it from the main queue or another queue might lead to unexpected behavior
let layoutDirection: LayoutDirection = topRead.isRTL ? .rightToLeft : .leftToRight
let groupURL = topRead.url
let isCurrent = topRead.isForToday // even though the top read data is from yesterday, the content group is for today
var rankedElements: [TopReadEntry.RankedElement] = []
for articlePreview in articlePreviews {
if let fetchedArticle = dataStore.fetchArticle(with: articlePreview.articleURL), let viewCounts = fetchedArticle.pageViewsSortedByDate {
let title = fetchedArticle.displayTitle ?? articlePreview.displayTitle
let description = fetchedArticle.wikidataDescription ?? articlePreview.wikidataDescription ?? fetchedArticle.snippet ?? articlePreview.snippet ?? ""
let rankedElement = TopReadEntry.RankedElement(title: title, description: description, articleURL: articlePreview.articleURL, thumbnailURL: articlePreview.thumbnailURL, viewCounts: viewCounts)
rankedElements.append(rankedElement)
}
}
rankedElements = Array(rankedElements.prefix(maximumRankedArticles))
let group = DispatchGroup()
for (index, element) in rankedElements.enumerated() {
group.enter()
guard let thumbnailURL = element.thumbnailURL else {
group.leave()
continue
}
let fetcher = dataStore.cacheController.imageCache
if usingImageCache {
if let cachedImage = fetcher.cachedImage(withURL: thumbnailURL) {
rankedElements[index].image = cachedImage.staticImage
}
group.leave()
continue
}
fetcher.fetchImage(withURL: thumbnailURL, failure: { _ in
group.leave()
}, success: { fetchedImage in
rankedElements[index].image = fetchedImage.image.staticImage
group.leave()
})
}
group.notify(queue: .main) {
completion(TopReadEntry(date: Date(), rankedElements: rankedElements, groupURL: groupURL, isCurrent: isCurrent, contentLayoutDirection: layoutDirection))
}
}
}
// MARK: - Model
struct TopReadEntry: TimelineEntry {
struct RankedElement: Identifiable {
var id: String = UUID().uuidString
let title: String
let description: String
var articleURL: URL? = nil
var image: UIImage? = nil
var thumbnailURL: URL? = nil
let viewCounts: [NSNumber]
}
let date: Date // for Timeline Entry
var rankedElements: [RankedElement] = Array(repeating: RankedElement.init(title: "–", description: "–", image: nil, viewCounts: [.init(floatLiteral: 0)]), count: 4)
var groupURL: URL? = nil
var isCurrent: Bool = false
var contentLayoutDirection: LayoutDirection = .leftToRight
}
// MARK: - TimelineProvider
struct TopReadProvider: TimelineProvider {
// MARK: Nested Types
public typealias Entry = TopReadEntry
// MARK: Properties
private let dataStore = TopReadData.shared
// MARK: TimelineProvider
func placeholder(in: Context) -> TopReadEntry {
return dataStore.placeholder
}
func getTimeline(in context: Context, completion: @escaping (Timeline<TopReadEntry>) -> Void) {
dataStore.fetchLatestAvailableTopRead { entry in
let isError = entry.groupURL == nil || !entry.isCurrent
let nextUpdate: Date
let currentDate = Date()
if !isError {
nextUpdate = currentDate.randomDateShortlyAfterMidnight() ?? currentDate
} else {
let components = DateComponents(hour: 2)
nextUpdate = Calendar.current.date(byAdding: components, to: currentDate) ?? currentDate
}
completion(Timeline(entries: [entry], policy: .after(nextUpdate)))
}
}
func getSnapshot(in context: Context, completion: @escaping (TopReadEntry) -> Void) {
dataStore.fetchLatestAvailableTopRead(usingCache: context.isPreview) { (entry) in
completion(entry)
}
}
}
// MARK: - Views
struct TopReadView: View {
@Environment(\.widgetFamily) private var family
@Environment(\.colorScheme) private var colorScheme
var entry: TopReadProvider.Entry?
var readersTextColor: Color {
colorScheme == .light
? Theme.light.colors.rankGradientEnd.asColor
: Theme.dark.colors.rankGradientEnd.asColor
}
@ViewBuilder
var body: some View {
GeometryReader { proxy in
switch family {
case .systemMedium:
rowBasedWidget(.systemMedium)
.widgetURL(entry?.groupURL)
case .systemLarge:
rowBasedWidget(.systemLarge)
.widgetURL(entry?.groupURL)
default:
smallWidget
.frame(width: proxy.size.width, height: proxy.size.height, alignment: .center)
.overlay(TopReadOverlayView(rankedElement: entry?.rankedElements.first))
.widgetURL(entry?.rankedElements.first?.articleURL)
}
}
.environment(\.layoutDirection, entry?.contentLayoutDirection ?? .leftToRight)
.flipsForRightToLeftLayoutDirection(true)
}
// MARK: View Components
@ViewBuilder
var smallWidget: some View {
if let image = entry?.rankedElements.first?.image {
Image(uiImage: image).resizable().scaledToFill()
} else {
Rectangle()
.foregroundColor(colorScheme == .dark ? Color.black : Color.white)
}
}
@ViewBuilder
func rowBasedWidget(_ family: WidgetFamily) -> some View {
let showSparkline = family == .systemLarge ? true : false
let rowCount = family == .systemLarge ? 4 : 2
VStack(alignment: .leading, spacing: 8) {
Text(TopReadWidget.LocalizedStrings.widgetTitle)
.font(.subheadline)
.fontWeight(.bold)
ForEach(entry?.rankedElements.indices.prefix(rowCount) ?? 0..<0, id: \.self) { elementIndex in
if let articleURL = entry?.rankedElements[elementIndex].articleURL {
Link(destination: articleURL, label: {
elementRow(elementIndex, rowCount: rowCount, showSparkline: showSparkline)
})
} else {
elementRow(elementIndex, rowCount: rowCount, showSparkline: showSparkline)
}
}
}
.padding(16)
}
@ViewBuilder
func elementRow(_ index: Int, rowCount: Int, showSparkline: Bool = false) -> some View {
let rankColor = colorScheme == .light ? Theme.light.colors.rankGradient.color(at: CGFloat(index)/CGFloat(rowCount)).asColor : Theme.dark.colors.rankGradient.color(at: CGFloat(index)/CGFloat(rowCount)).asColor
GeometryReader { proxy in
HStack(alignment: .center) {
Circle()
.strokeBorder(rankColor, lineWidth: 1)
.frame(width: 22, height: 22, alignment: .leading)
.overlay(
Text("\(NumberFormatter.localizedThousandsStringFromNumber(NSNumber(value: index + 1)))")
.font(.footnote)
.fontWeight(.light)
.foregroundColor(rankColor)
)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 7))
VStack(alignment: .leading, spacing: 5) {
Text("\(entry?.rankedElements[index].title ?? "–")")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(Color(.label))
if showSparkline {
Text("\(entry?.rankedElements[index].description ?? "–")")
.lineLimit(2)
.font(.caption)
.foregroundColor(Color(.secondaryLabel))
Sparkline(style: .compactWithViewCount, timeSeries: entry?.rankedElements[index].viewCounts)
.cornerRadius(4)
.frame(height: proxy.size.height / 3.0, alignment: .leading)
} else {
Text("\(numberOfReadersTextOrEmptyForViewCount(entry?.rankedElements[index].viewCounts.last))")
.font(.caption)
.fontWeight(.medium)
.lineLimit(2)
.foregroundColor(readersTextColor)
}
}
Spacer()
elementImageOrEmptyView(index)
.frame(width: proxy.size.height / 1.1, height: proxy.size.height / 1.1, alignment: .trailing)
.mask(
RoundedRectangle(cornerRadius: 5, style: .continuous)
)
}
}
}
@ViewBuilder
func elementImageOrEmptyView(_ elementIndex: Int) -> some View {
if let image = entry?.rankedElements[elementIndex].image {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fill)
} else {
EmptyView()
}
}
// MARK: Private
private func numberOfReadersTextOrEmptyForViewCount(_ viewCount: NSNumber?) -> String {
guard let viewCount = viewCount else {
return "–"
}
let formattedCount = NumberFormatter.localizedThousandsStringFromNumber(viewCount)
return String.localizedStringWithFormat(TopReadWidget.LocalizedStrings.readersCountFormat, formattedCount)
}
}
struct TopReadOverlayView: View {
@Environment(\.colorScheme) var colorScheme
var rankedElement: TopReadEntry.RankedElement?
var isExpandedStyle: Bool {
return rankedElement?.image == nil
}
var readersForegroundColor: Color {
colorScheme == .light
? Theme.light.colors.rankGradientEnd.asColor
: Theme.dark.colors.rankGradientEnd.asColor
}
var primaryTextColor: Color {
isExpandedStyle
? colorScheme == .dark ? Color.white : Color.black
: .white
}
private var currentNumberOfReadersTextOrEmpty: String {
guard let currentViewCount = rankedElement?.viewCounts.last else {
return "–"
}
let formattedCount = NumberFormatter.localizedThousandsStringFromNumber(currentViewCount)
return String.localizedStringWithFormat(TopReadWidget.LocalizedStrings.readersCountFormat, formattedCount)
}
var body: some View {
if isExpandedStyle {
content
} else {
content
.background(
Rectangle()
.foregroundColor(.black)
.mask(LinearGradient(gradient: Gradient(colors: [.clear, .black]), startPoint: .center, endPoint: .bottom))
.opacity(0.35)
)
}
}
// MARK: View Components
var content: some View {
VStack(alignment: .leading) {
if isExpandedStyle {
Text(currentNumberOfReadersTextOrEmpty)
.fontWeight(.medium)
.lineLimit(nil)
.font(.subheadline)
.foregroundColor(readersForegroundColor)
.padding(EdgeInsets(top: 16, leading: 16, bottom: 0, trailing: 0))
}
sparkline(expanded: isExpandedStyle)
Spacer()
description()
}
.foregroundColor(.white)
}
func sparkline(expanded: Bool) -> some View {
HStack(alignment: .top) {
Spacer()
if expanded {
Sparkline(style: .expanded, timeSeries: rankedElement?.viewCounts)
.padding(EdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 16))
} else {
Sparkline(style: .compact, timeSeries: rankedElement?.viewCounts)
.cornerRadius(4)
.frame(height: 20, alignment: .trailing)
.padding(EdgeInsets(top: 16, leading: 0, bottom: 0, trailing: 16))
// TODO: Apply shadow just to final content – not children views as well
// .clipped()
// .readableShadow(intensity: 0.60)
}
}
}
func description() -> some View {
VStack(alignment: .leading, spacing: 5) {
Text(TopReadWidget.LocalizedStrings.widgetTitle)
.font(.caption2)
.fontWeight(.bold)
.aspectRatio(contentMode: .fit)
.foregroundColor(primaryTextColor)
.readableShadow(intensity: isExpandedStyle ? 0 : 0.8)
Text("\(rankedElement?.title ?? "–")")
.lineLimit(nil)
.font(.headline)
.foregroundColor(primaryTextColor)
.readableShadow(intensity: isExpandedStyle ? 0 : 0.8)
}
.padding(EdgeInsets(top: 0, leading: 16, bottom: 16, trailing: 16))
}
}
| mit | 7e28ec883759da6a739230d28ced74ba | 37.527228 | 216 | 0.5885 | 5.093259 | false | false | false | false |
TheTekton/Malibu | MalibuTests/Specs/Validation/StatusCodeVadatorSpec.swift | 1 | 1300 | @testable import Malibu
import Quick
import Nimble
class StatusCodeValidatorSpec: QuickSpec {
override func spec() {
describe("StatusCodeValidator") {
let URL = NSURL(string: "http://hyper.no")!
let request = NSURLRequest(URL: URL)
let data = NSData()
var validator: StatusCodeValidator<[Int]>!
describe("#validate") {
beforeEach {
validator = StatusCodeValidator(statusCodes: [200])
}
context("when response has expected status code") {
it("does not throw an error") {
let HTTPResponse = NSHTTPURLResponse(URL: URL, statusCode: 200,
HTTPVersion: "HTTP/2.0", headerFields: nil)!
let result = Wave(data: data, request: request, response: HTTPResponse)
expect{ try validator.validate(result) }.toNot(throwError())
}
}
context("when response has not expected status code") {
it("throws an error") {
let HTTPResponse = NSHTTPURLResponse(URL: URL, statusCode: 404,
HTTPVersion: "HTTP/2.0", headerFields: nil)!
let result = Wave(data: data, request: request, response: HTTPResponse)
expect{ try validator.validate(result) }.to(throwError())
}
}
}
}
}
}
| mit | 7b60f6cf26ae3d9a6e96bec938bdeaba | 30.707317 | 83 | 0.6 | 4.727273 | false | false | false | false |
huangboju/Eyepetizer | Eyepetizer/Eyepetizer/Main/MainNavigation.swift | 1 | 2614 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
class MainNavigation: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if respondsToSelector(Selector("interactivePopGestureRecognizer")) {
interactivePopGestureRecognizer?.delegate = self
navigationBar.titleTextAttributes = ["Font" : UIFont.customFont_Lobster(fontSize: LABEL_FONT_SIZE)]
delegate = self
}
navigationBar.tintColor = UIColor.blackColor()
navigationBar.barStyle = .Default
navigationBar.backIndicatorImage = R.image.ic_action_back()
navigationBar.backIndicatorTransitionMaskImage = R.image.ic_action_back()
}
override func pushViewController(viewController: UIViewController, animated: Bool) {
if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated {
interactivePopGestureRecognizer?.enabled = false
}
super.pushViewController(viewController, animated: animated)
}
override func popToRootViewControllerAnimated(animated: Bool) -> [UIViewController]? {
if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated {
interactivePopGestureRecognizer?.enabled = false
}
return super.popToRootViewControllerAnimated(animated)
}
override func popToViewController(viewController: UIViewController, animated: Bool) -> [UIViewController]? {
if respondsToSelector(Selector("interactivePopGestureRecognizer")) && animated {
interactivePopGestureRecognizer?.enabled = false
}
return super.popToViewController(viewController, animated: false)
}
// MARK: - UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
if respondsToSelector(Selector("interactivePopGestureRecognizer")) {
interactivePopGestureRecognizer?.enabled = true
}
}
//MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == interactivePopGestureRecognizer {
if viewControllers.count < 2 || visibleViewController == viewControllers[0] {
return false
}
}
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | c4de63d22a5edd219baa6a13304d39c0 | 41.112903 | 149 | 0.700881 | 6.781818 | false | false | false | false |
cubixlabs/SocialGIST | Pods/GISTFramework/GISTFramework/Classes/Extentions/UIView+Utility.swift | 1 | 4775 | //
// UIView+Utility.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
// MARK: - UIView Utility Extension
public extension UIView {
/// Rotate a view by specified degrees in CGFloat
public var rotation:CGFloat {
get {
let radians:CGFloat = atan2(self.transform.b, self.transform.a)
let degrees:CGFloat = radians * (180.0 / CGFloat(M_PI))
return degrees;
}
set {
let radians = newValue / 180.0 * CGFloat(M_PI)
let rotation = self.transform.rotated(by: radians);
self.transform = rotation
}
} //P.E.
/// Loads nib from Bundle
///
/// - Parameters:
/// - nibName: Nib Name
/// - viewIndex: View Index
/// - owner: Nib Owner AnyObject
/// - Returns: UIView
public class func loadWithNib(_ nibName:String, viewIndex:Int, owner: AnyObject) -> Any {
return Bundle.main.loadNibNamed(nibName, owner: owner, options: nil)![viewIndex];
} //F.E.
/// Loads dynamic nib from Bundle
///
/// - Parameters:
/// - nibName: Nib Name
/// - viewIndex: View Index
/// - owner: Nib Owner AnyObject
/// - Returns: UIView
public class func loadDynamicViewWithNib(_ nibName:String, viewIndex:Int, owner: AnyObject) -> Any {
let bundle = Bundle(for: type(of: owner));
let nib = UINib(nibName: nibName, bundle: bundle);
let rView: Any = nib.instantiate(withOwner: owner, options: nil)[viewIndex];
return rView;
} //F.E.
/// Adds Boarder for the View
///
/// - Parameters:
/// - color: Border Color
/// - width: Border Width
public func addBorder(_ color:UIColor?, width:Int){
let layer:CALayer = self.layer;
layer.borderColor = color?.cgColor
layer.borderWidth = (CGFloat(width)/CGFloat(2)) as CGFloat
} //F.E.
/// Makes Rounded corners of View. it trims the view in circle
public func addRoundedCorners() {
self.addRoundedCorners(self.frame.size.width/2.0);
} //F.E.
/// Adds rounded corner with defined radius
///
/// - Parameter radius: Radius Value
public func addRoundedCorners(_ radius:CGFloat) {
let layer:CALayer = self.layer;
layer.cornerRadius = radius
layer.masksToBounds = true
} //F.E.
/// Adds Drop shadow on the view
public func addDropShadow() {
let shadowPath:UIBezierPath=UIBezierPath(rect: self.bounds)
let layer:CALayer = self.layer;
layer.shadowColor = UIColor.black.cgColor;
layer.shadowOffset = CGSize(width: 1, height: 1);
layer.shadowOpacity = 0.21
layer.shadowRadius = 2.0
layer.shadowPath = shadowPath.cgPath
layer.masksToBounds = false;
} //F.E.
/// Shows view with fadeIn animation
///
/// - Parameters:
/// - duration: Fade duration - Default Value is 0.25
/// - completion: Completion block
public func fadeIn(withDuration duration:Double = 0.25, _ completion:((_ finished:Bool)->())? = nil) {
self.alpha = 0.0;
self.isHidden = false;
UIView.animate(withDuration: duration, animations: { () -> Void in
self.alpha = 1.0;
}, completion: { (finish:Bool) -> Void in
completion?(finish)
})
} //F.E.
// Hides view with fadeOut animation
///
/// - Parameters:
/// - duration: Fade duration - Default Value is 0.25
/// - completion: Completion block
public func fadeOut(withDuration duration:Double = 0.25, _ completion:((_ finished:Bool)->())? = nil) {
self.alpha = 1.0
UIView.animate(withDuration: duration, animations: { () -> Void in
self.alpha=0.0;
}, completion: { (finish:Bool) -> Void in
self.isHidden = true;
completion?(finish)
})
} //F.E.
/// Shakes view in a static animation
public func shake() {
let shake:CABasicAnimation = CABasicAnimation(keyPath: "position");
shake.duration = 0.1;
shake.repeatCount = 2;
shake.autoreverses = true;
shake.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 5, y: self.center.y));
shake.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 5, y: self.center.y));
self.layer.add(shake, forKey: "position");
} //F.E.
/// Rempves all views from the view
public func removeAllSubviews() {
for view in self.subviews {
view.removeFromSuperview();
}
} //F.E.
} //E.E.
| gpl-3.0 | bcac4842b4d4cdc890e8ba814eff058b | 32.152778 | 107 | 0.577294 | 4.224779 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/Homework 12/Homework 12/ThreeWeather.swift | 1 | 2275 | //
// ThreeWeather.swift
// Homework 12
//
// Created by Ivan Krylov on 18.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import Foundation
class ThreeWeather {
var weatherCondition: String = ""
var temp: Int = 0
var date: String = ""
init?(weatherJson: NSDictionary) {
if let listJson = weatherJson["list"] as? NSArray {
for item in listJson {
if let main = item as? NSDictionary {
if let date = main["dt_txt"] as? String {
self.date = date
print(date)
}
if let temp = main["main"] as? NSDictionary {
if let temperature = temp["temp"] as? Double {
self.temp = Int(round(temperature - 273.15))
print(temp)
}
}
if let nestedJson = main["weather"] as? NSArray {
if let desc = nestedJson[0] as? NSDictionary {
if let weathCond = desc["description"] as? String {
self.weatherCondition = weathCond
print(weatherCondition)
}
}
}
}
}
}
// guard let listJson = weatherJson["list"] as? NSArray else { return nil }
// guard let zeroMain = listJson[0] as? NSDictionary else { return nil }
// guard let date = zeroMain["dt_txt"] as? String else { return nil }
// self.date = date
// guard let temp = zeroMain["main"] as? NSDictionary else { return nil }
// guard let temperature = temp["temp"] as? Double else { return nil }
// self.temp = Int(round(temperature - 273.15))
// guard let weather = zeroMain["weather"] as? NSArray else { return nil }
// guard let desc = weather[0] as? NSDictionary else { return nil }
// guard let weatherCondition = desc["description"] as? String else { return nil }
// self.weatherCondition = weatherCondition.capitalized
}
}
| apache-2.0 | f5289d096b83a75ee69800bc83643a00 | 41.90566 | 97 | 0.480651 | 4.911447 | false | false | false | false |
KennethTsang/GrowingTextView | Example/GrowingTextView/Example2.swift | 1 | 2172 | //
// Example2.swift
// GrowingTextView
//
// Created by Tsang Kenneth on 16/3/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GrowingTextView
class Example2: UIViewController {
@IBOutlet weak var inputToolbar: UIView!
@IBOutlet weak var textView: GrowingTextView!
@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// *** Customize GrowingTextView ***
textView.layer.cornerRadius = 4.0
// *** Listen to keyboard show / hide ***
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
// *** Hide keyboard when tapping outside ***
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
view.addGestureRecognizer(tapGesture)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y
if #available(iOS 11, *) {
if keyboardHeight > 0 {
keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom
}
}
textViewBottomConstraint.constant = keyboardHeight + 8
view.layoutIfNeeded()
}
}
@objc func tapGestureHandler() {
view.endEditing(true)
}
}
extension Example2: GrowingTextViewDelegate {
// *** Call layoutIfNeeded on superview for animation when changing height ***
func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| mit | be3974f3429217154b0baa03459eceff | 33.460317 | 166 | 0.663749 | 5.321078 | false | false | false | false |
kortnee1021/Kortnee | 03-Single View App/Swift 1/BMI-Step7/BMI/ViewController.swift | 4 | 1707 | //
// ViewController.swift
// BMI
//
// Created by Nicholas Outram on 30/12/2014.
// Copyright (c) 2014 Plymouth University. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var weight : Double?
var height : Double?
var bmi : Double? {
get {
if (weight != nil) && (height != nil) {
return weight! / (height! * height!)
} else {
return nil
}
}
}
@IBOutlet weak var bmiLabel: UILabel!
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
updateUI()
return true
}
func updateUI() {
if let b = self.bmi {
self.bmiLabel.text = String(format: "%4.1f", b)
}
}
func textFieldDidEndEditing(textField: UITextField) {
let conv = { NSNumberFormatter().numberFromString($0)?.doubleValue }
switch (textField) {
case self.weightTextField:
self.weight = conv(textField.text)
case self.heightTextField:
self.height = conv(textField.text)
default:
println("Something has gone very wrong!")
}
updateUI()
}
}
| mit | 7c7cc30acdfdcbdee870ff2d46229521 | 24.477612 | 80 | 0.581722 | 4.891117 | false | false | false | false |
exponent/exponent | packages/expo-dev-menu/ios/UITests/DevMenuUIMatchers.swift | 2 | 2760 | import XCTest
import UIKit
class DevMenuViews {
static let mainScreen = "DevMenuMainScreen"
static let footer = "DevMenuFooter"
static let settingsScreen = "DevMenuSettingsScreen"
static let profileScreen = "DevMenuProfileScreen"
}
class DevMenuUIMatchers {
static func currentRootView() -> UIView? {
return UIApplication.shared.keyWindow?.rootViewController?.view
}
static func findView(rootView: UIView, _ matcher: (UIView) -> Bool) -> UIView? {
if matcher(rootView) {
return rootView
}
for subView in rootView.subviews {
let found = findView(rootView: subView, matcher)
if found != nil {
return found
}
}
return nil
}
static func findView(_ matcher: (UIView) -> Bool) -> UIView? {
guard let view = DevMenuUIMatchers.currentRootView() else {
return nil
}
return findView(rootView: view, matcher)
}
static func findView(rootView: UIView, tag: String) -> UIView? {
return DevMenuUIMatchers.findView(rootView: rootView) {
return $0.accessibilityIdentifier == tag && $0.isVisible()
}
}
static func findView(tag: String) -> UIView? {
guard let view = DevMenuUIMatchers.currentRootView() else {
return nil
}
return findView(rootView: view, tag: tag)
}
static func waitForView(_ matcher: (UIView) -> Bool) -> UIView {
let timer = Date(timeIntervalSinceNow: DevMenuTestOptions.defaultTimeout)
while timer.timeIntervalSinceNow > 0 {
DevMenuLooper.runMainLoop(for: DevMenuTestOptions.loopTime)
guard let view = DevMenuUIMatchers.currentRootView() else {
continue
}
let found = findView(rootView: view, matcher)
if found != nil {
return found!
}
}
XCTFail("Can not find view.")
return UIView() // just for compiler
}
static func waitForView(tag: String) -> UIView {
return waitForView {
return $0.accessibilityIdentifier == tag && $0.isVisible()
}
}
static func waitForView(text: String) -> UIView {
return waitForView {
if type(of: $0) == NSClassFromString("RCTTextView")! {
return $0.isVisible() && ($0.value(forKey: "_textStorage") as! NSTextStorage).string == text
}
return false
}
}
static func findView(rootView: UIView, text: String) -> UIView? {
findView(rootView: rootView) {
if type(of: $0) == NSClassFromString("RCTTextView")! {
return $0.isVisible() && ($0.value(forKey: "_textStorage") as! NSTextStorage).string == text
}
return false
}
}
static func findView(text: String) -> UIView? {
guard let view = DevMenuUIMatchers.currentRootView() else {
return nil
}
return findView(rootView: view, text: text)
}
}
| bsd-3-clause | 86897a19e6424be5c52e23b3fcc7bb88 | 25.037736 | 100 | 0.65 | 4.207317 | false | false | false | false |
suominentoni/nearest-departures | HSL Nearest Departures WatchKit Extension/NearestStopsInterfaceController.swift | 1 | 5044 | import WatchKit
import Foundation
import NearestDeparturesDigitransit
open class NearestStopsInterfaceController: WKInterfaceController, CLLocationManagerDelegate {
@IBOutlet var nearestStopsTable: WKInterfaceTable!
@IBOutlet var loadingIndicatorLabel: WKInterfaceLabel!
var nearestStops: [Stop] = []
var locationManager: CLLocationManager!
var lat: Double = 0
var lon: Double = 0
override open func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
nearestStopsTable.performSegue(forRow: rowIndex)
}
open override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
if let row = table.rowController(at: rowIndex) as? NearestStopsRow {
return ["stopCode": row.code]
}
return nil
}
override open func awake(withContext context: Any?) {
super.awake(withContext: context)
self.setTitle(NSLocalizedString("NEAREST", comment: ""))
self.initTimer()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 5
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) {
locationManager.requestWhenInUseAuthorization()
} else {
requestLocation()
}
}
open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
requestLocation()
}
func requestLocation() {
showLoadingIndicator()
if(CLLocationManager.authorizationStatus() != CLAuthorizationStatus.restricted || CLLocationManager.authorizationStatus() != CLAuthorizationStatus.denied) {
NSLog("Requesting location")
locationManager.requestLocation()
}
}
open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
NSLog("Location Manager error: " + error.localizedDescription)
if(error._code == CLError.Code.denied.rawValue) {
self.presentAlert(
NSLocalizedString("LOCATION_REQUEST_FAILED_TITLE", comment: ""),
message: NSLocalizedString("LOCATION_REQUEST_FAILED_MSG", comment: ""),
action: requestLocation)
} else {
requestLocation()
}
}
open func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NSLog("New location data received")
let lat = locations.last!.coordinate.latitude
let lon = locations.last!.coordinate.longitude
TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: updateInterface)
}
fileprivate func updateInterface(_ nearestStops: [Stop]) -> Void {
NSLog("Updating Nearest Stops interface")
let nearestStopsWithDepartures = nearestStops.filter({ $0.departures.count > 0 })
loadingIndicatorLabel.setHidden(true)
hideLoadingIndicator()
self.nearestStops = nearestStopsWithDepartures
nearestStopsTable.setNumberOfRows(nearestStopsWithDepartures.count, withRowType: "nearestStopsRow")
if(nearestStopsWithDepartures.count == 0) {
self.presentAlert(NSLocalizedString("NO_STOPS_TITLE", comment: ""), message: NSLocalizedString("NO_STOPS_MSG", comment: ""))
} else {
var i: Int = 0
for stop in nearestStopsWithDepartures {
let nearestStopRow = nearestStopsTable.rowController(at: i) as! NearestStopsRow
nearestStopRow.code = stop.codeLong
nearestStopRow.stopName.setText(stop.name)
nearestStopRow.stopCode.setText(stop.codeShort)
nearestStopRow.distance.setText(String(stop.distance) + " m")
i += 1
}
}
}
override open func willDisappear() {
invalidateTimer()
}
override open func willActivate() {
requestLocation()
}
fileprivate func showLoadingIndicator() {
initTimer()
self.loadingIndicatorLabel.setHidden(false)
}
fileprivate func hideLoadingIndicator() {
self.loadingIndicatorLabel.setHidden(true)
}
@IBAction func refreshClick() {
requestLocation()
}
var counter = 1
var timer: Timer = Timer()
func initTimer() {
invalidateTimer()
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(NearestStopsInterfaceController.updateLoadingIndicatorText), userInfo: nil, repeats: true)
self.timer.fire()
}
func invalidateTimer() {
self.timer.invalidate()
}
@objc fileprivate func updateLoadingIndicatorText() {
self.counter == 4 ? (self.counter = 1) : (self.counter = self.counter + 1)
let dots = (1...counter).map({_ in "."}).joined()
self.loadingIndicatorLabel.setText(dots)
}
}
| mit | 03c7720da5c7a9602d0c724f05b386c7 | 35.550725 | 185 | 0.665147 | 5.309474 | false | false | false | false |
LonelyHusky/SCWeibo | SCWeibo/Classes/Tools/SCNetworkTools.swift | 1 | 1582 | //
// SCNetworkTools.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/23.
//
//
import UIKit
import AFNetworking
enum SCRequestMethod:String {
case Post = "post"
case Get = "get"
}
class SCNetworkTools: AFHTTPSessionManager {
// 单例:全局访问点
static let sharedTools: SCNetworkTools = {
let tools = SCNetworkTools()
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
return tools
}()
// 定义请求
typealias SCRequestCallBack = (responseObject:AnyObject?,error:NSError?)->()
func request(method:SCRequestMethod = .Get,urlString:String ,parameters:AnyObject?,finished:SCRequestCallBack) {
// 定义一个请求成功之后要执行的闭包
let success = {(dataTasks:NSURLSessionTask,responseObject:AnyObject?)-> Void in
// 请求成功的回调
finished(responseObject:responseObject,error: nil)
}
// 定义一个请求失败之后要执行的闭包
let failure = { (dataTasks:NSURLSessionDataTask?,error:NSError) ->Void in
finished(responseObject:nil,error: error)
}
if method == .Get {
GET(urlString,parameters: parameters,progress: nil,success: success,failure: failure)
}else{
POST(urlString, parameters: parameters, progress: nil,success: success, failure: failure)
}
}
}
| mit | d3a14ac217ff4281e7660fa5472d964c | 18.090909 | 117 | 0.619728 | 4.509202 | false | false | false | false |
DeKoServidoni/Hackaton2016 | Ágora/SearchProductsViewController.swift | 1 | 3585 | //
// SearchProductsViewController.swift
// Ágora
//
// Created by Clerton Leal on 20/08/16.
// Copyright © 2016 Avenue Code. All rights reserved.
//
import UIKit
protocol SearchDelegate {
func itemsSelected(products: [Product])
}
class SearchProductViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var myTableView: UITableView!
var initialList = ProductStore.getAllProducts()
var list = ProductStore.getAllProducts()
var delegate: SearchDelegate?
override func prefersStatusBarHidden() -> Bool {
return true
}
@IBAction func cancelAction(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func addAction(sender: UIBarButtonItem) {
if delegate != nil {
let coisas = initialList.filter({ (p) -> Bool in
return p.checked
})
delegate?.itemsSelected(coisas)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
myTableView.allowsMultipleSelection = true
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell")! as UITableViewCell
let product = list[indexPath.row]
if (product.checked) {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
cell.selectionStyle = .None
cell.textLabel?.text = product.name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
var product = list[indexPath.row]
product.checked = true
initialList = initialList.map { (Product) -> Product in
if (product.name == Product.name) {
return product;
}
return Product
}
searchBar.resignFirstResponder()
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None
var product = list[indexPath.row]
product.checked = false
initialList = initialList.map { (Product) -> Product in
if (product.name == Product.name) {
return product;
}
return Product
}
searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let searchText = self.searchBar.text! + text
if (searchText.isEmpty || (text.isEmpty) && searchText.characters.count == 1) {
list = initialList
} else {
list = initialList.filter { (Product) -> Bool in
return Product.name.containsString(searchText)
}
}
self.myTableView.reloadData()
return true
}
}
| apache-2.0 | 1bb454555a0f89db3a1ab550769b6dde | 31.279279 | 122 | 0.63271 | 5.512308 | false | false | false | false |
bravelocation/yeltzland-ios | yeltzland/MainSplitViewController.swift | 1 | 5320 | //
// MainSplitViewController.swift
// Yeltzland
//
// Created by John Pollard on 01/11/2020.
// Copyright © 2020 John Pollard. All rights reserved.
//
import UIKit
#if canImport(SwiftUI)
import Combine
#endif
class MainSplitViewController: UISplitViewController {
private lazy var navigationCommandSubscriber: Any? = nil
private lazy var reloadCommandSubscriber: Any? = nil
private lazy var historyCommandSubscriber: Any? = nil
var sidebarViewController: UIViewController!
init?(tabController: MainTabBarController) {
if #available(iOS 14.0, *) {
super.init(style: .doubleColumn)
self.sidebarViewController = SidebarViewController()
self.primaryBackgroundStyle = .sidebar
self.preferredDisplayMode = .oneOverSecondary
self.setViewController(self.sidebarViewController, for: .primary)
let initalView = self.initialSecondaryView()
self.setViewController(initalView, for: .secondary)
self.setViewController(tabController, for: .compact)
// Set color of expand button and expanders
self.view.tintColor = UIColor.white
self.setupMenuCommandHandler()
} else {
super.init(coder: NSCoder())
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initialSecondaryView() -> UIViewController {
let webViewController = WebPageViewController()
webViewController.navigationElement = NavigationManager.shared.mainSection.elements.first
return UINavigationController(rootViewController: webViewController)
}
}
// MARK: - Menu options
extension MainSplitViewController {
func setupMenuCommandHandler() {
if #available(iOS 14.0, *) {
self.navigationCommandSubscriber = NotificationCenter.default.publisher(for: .navigationCommand)
.receive(on: RunLoop.main)
.sink(receiveValue: { notification in
if let sender = notification.object as? UIKeyCommand {
if let keyInput = sender.input, let sidebarVC = self.sidebarViewController as? SidebarViewController {
if let inputValue = Int(keyInput) {
sidebarVC.handleMainKeyboardCommand(inputValue)
} else {
sidebarVC.handleOtherKeyboardCommand(keyInput)
}
}
}
})
self.reloadCommandSubscriber = NotificationCenter.default.publisher(for: .reloadCommand)
.receive(on: RunLoop.main)
.sink(receiveValue: { _ in
print("Handle reload command ...")
if let sidebarVC = self.sidebarViewController as? SidebarViewController {
sidebarVC.handleReloadKeyboardCommand()
}
})
self.historyCommandSubscriber = NotificationCenter.default.publisher(for: .historyCommand)
.receive(on: RunLoop.main)
.sink(receiveValue: { notification in
if let command = notification.object as? UIKeyCommand, let sidebarVC = self.sidebarViewController as? SidebarViewController {
sidebarVC.handleHistoryKeyboardCommand(sender: command)
}
})
}
}
func isBackMenuEnabled() -> Bool {
if #available(iOS 14.0, *) {
if let sidebarVC = self.sidebarViewController as? SidebarViewController, let webViewController = sidebarVC.currentWebController() {
return webViewController.webView?.canGoBack ?? false
}
}
return false
}
func isForwardMenuEnabled() -> Bool {
if #available(iOS 14.0, *) {
if let sidebarVC = self.sidebarViewController as? SidebarViewController, let webViewController = sidebarVC.currentWebController() {
return webViewController.webView?.canGoForward ?? false
}
}
return false
}
func isHomeMenuEnabled() -> Bool {
if #available(iOS 14.0, *) {
if let sidebarVC = self.sidebarViewController as? SidebarViewController {
return sidebarVC.currentWebController() != nil
}
}
return false
}
}
// MARK: - UIResponder function
extension MainSplitViewController {
/// Description Restores the tab state based on the juser activity
/// - Parameter activity: Activity state to restore
override func restoreUserActivityState(_ activity: NSUserActivity) {
print("Restoring user activity in split controller [\(activity.activityType)] ...")
// Pass through directly to sidebar controller
if #available(iOS 14.0, *) {
if let sidebarVC = self.sidebarViewController as? SidebarViewController {
sidebarVC.restoreUserActivity(activity)
}
}
}
}
| mit | 88e5f300a90b9463f916f3fb76e55481 | 35.682759 | 145 | 0.592969 | 5.628571 | false | false | false | false |
VBVMI/VerseByVerse-iOS | Pods/VimeoNetworking/VimeoNetworking/Sources/Scope.swift | 1 | 2388 | //
// Scope.swift
// VimeoNetworkingExample-iOS
//
// Created by Huebner, Rob on 3/23/16.
// Copyright © 2016 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Scope` describes a permission that your application requests from the API
public enum Scope: String
{
/// View public videos
case Public = "public"
/// View private videos
case Private = "private"
/// View Vimeo On Demand purchase history
case Purchased = "purchased"
/// Create new videos, groups, albums, etc.
case Create = "create"
/// Edit videos, groups, albums, etc.
case Edit = "edit"
/// Delete videos, groups, albums, etc.
case Delete = "delete"
/// Interact with a video on behalf of a user, such as liking a video or adding it to your watch later queue
case Interact = "interact"
/// Upload a video
case Upload = "upload"
/**
Combines an array of scopes into a scope string as expected by the api
- parameter scopes: an array of `Scope` values
- returns: a string of space-separated scope strings
*/
public static func combine(_ scopes: [Scope]) -> String
{
return scopes.map({ $0.rawValue }).joined(separator: " ")
}
}
| mit | bc38f344c446d1d3fd8053dff64ddb4a | 34.626866 | 116 | 0.674906 | 4.436803 | false | false | false | false |