repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/UI/CropValidator.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// Responsible for validating and clamping trial crop ranges.
class CropValidator {
// MARK: - Properties
private static let minimumCropDuration: Int64 = 1000 // 1 second.
private let trialRecordingRange: ChartAxis<Int64>
/// True if the recording range is the minimum length for cropping, otherwise false.
var isRecordingRangeValidForCropping: Bool {
return isRangeAtLeastMinimumForCrop(trialRecordingRange)
}
// MARK: - Public
/// Designated initializer.
///
/// - Parameter trialRecordingRange: The trial recording range.
init(trialRecordingRange: ChartAxis<Int64>) {
self.trialRecordingRange = trialRecordingRange
}
/// True if the timestamp is within the recording range, otherwise false.
///
/// - Parameter timestamp: A timestamp.
/// - Returns: A Boolean indicating whether the timestamp is within the recording range.
func isTimestampWithinRecordingRange(_ timestamp: Int64) -> Bool {
return trialRecordingRange.contains(timestamp)
}
/// True if the crop range is valid, otherwise false.
///
/// - Parameter cropRange: The crop range to test.
/// - Returns: A Boolean indicating whether the crop range is valid.
func isCropRangeValid(_ cropRange: ChartAxis<Int64>) -> Bool {
guard trialRecordingRange.contains(cropRange.min) else {
// Crop start is outside recording range.
return false
}
guard trialRecordingRange.contains(cropRange.max) else {
// Crop end is outside recording range.
return false
}
// Crop must be at least the minimum crop duration.
return isRangeAtLeastMinimumForCrop(cropRange)
}
/// Returns the input timestamp if it is within acceptable bounds for a crop start timetamp,
/// otherwise clamps to the nearest boundary.
///
/// - Parameters:
/// - timestamp: A crop start timestamp.
/// - cropRange: The current crop range.
/// - Returns: A valid crop start timestamp.
func startCropTimestampClampedToValidRange(_ timestamp: Int64,
cropRange: ChartAxis<Int64>) -> Int64? {
let maxTimestamp = cropRange.max - CropValidator.minimumCropDuration
guard maxTimestamp >= trialRecordingRange.min else {
// An invalid range will crash, so guard against it.
return nil
}
return (trialRecordingRange.min...maxTimestamp).clamp(timestamp)
}
/// Returns the input timestamp if it is within acceptable bounds for a crop end timetamp,
/// otherwise clamps to the nearest boundary.
///
/// - Parameters:
/// - timestamp: A crop end timestamp.
/// - cropRange: The current crop range.
/// - Returns: A valid crop end timestamp.
func endCropTimestampClampedToValidRange(_ timestamp: Int64,
cropRange: ChartAxis<Int64>) -> Int64? {
let minTimestamp = cropRange.min + CropValidator.minimumCropDuration
guard trialRecordingRange.max >= minTimestamp else {
// An invalid range will crash, so guard against it.
return nil
}
return (minTimestamp...trialRecordingRange.max).clamp(timestamp)
}
/// True if the range meets the minimum duration to perform a crop, otherwise false.
///
/// - Parameter range: A time range.
/// - Returns: A Boolean indicating whether the range is equal to or greater than the minimum
/// needed to crop.
func isRangeAtLeastMinimumForCrop(_ range: ChartAxis<Int64>) -> Bool {
return range.length >= CropValidator.minimumCropDuration
}
}
| 2fb2d221340dcc709f6be3850f821612 | 35.165217 | 95 | 0.697764 | false | false | false | false |
qutheory/vapor | refs/heads/master | Sources/Vapor/Validation/Validations.swift | mit | 1 | public struct Validations {
var storage: [Validation]
public init() {
self.storage = []
}
public mutating func add<T>(
_ key: ValidationKey,
as type: T.Type = T.self,
is validator: Validator<T> = .valid,
required: Bool = true
) {
let validation = Validation(key: key, required: required, validator: validator)
self.storage.append(validation)
}
public mutating func add(
_ key: ValidationKey,
result: ValidatorResult
) {
let validation = Validation(key: key, result: result)
self.storage.append(validation)
}
public mutating func add(
_ key: ValidationKey,
required: Bool = true,
_ nested: (inout Validations) -> ()
) {
var validations = Validations()
nested(&validations)
let validation = Validation(key: key, required: required, nested: validations)
self.storage.append(validation)
}
public func validate(request: Request) throws -> ValidationsResult {
guard let contentType = request.headers.contentType else {
throw Abort(.unprocessableEntity)
}
guard let body = request.body.data else {
throw Abort(.unprocessableEntity)
}
let contentDecoder = try ContentConfiguration.global.requireDecoder(for: contentType)
let decoder = try contentDecoder.decode(DecoderUnwrapper.self, from: body, headers: request.headers)
return try self.validate(decoder.decoder)
}
public func validate(query: URI) throws -> ValidationsResult {
let urlDecoder = try ContentConfiguration.global.requireURLDecoder()
let decoder = try urlDecoder.decode(DecoderUnwrapper.self, from: query)
return try self.validate(decoder.decoder)
}
public func validate(json: String) throws -> ValidationsResult {
let decoder = try JSONDecoder().decode(DecoderUnwrapper.self, from: Data(json.utf8))
return try self.validate(decoder.decoder)
}
public func validate(_ decoder: Decoder) throws -> ValidationsResult {
try self.validate(decoder.container(keyedBy: ValidationKey.self))
}
internal func validate(_ decoder: KeyedDecodingContainer<ValidationKey>) -> ValidationsResult {
.init(results: self.storage.map {
$0.run(decoder)
})
}
}
| 4ec1836374b8dcc6ba7d8fa377113f8e | 33.6 | 108 | 0.637077 | false | false | false | false |
DivineDominion/mac-appdev-code | refs/heads/master | CoreDataOnly/Box.swift | mit | 1 | import Foundation
import CoreData
private var boxContext = 0
public protocol BoxType: class {
var boxId: BoxId { get }
var title: String { get }
var items: [ItemType] { get }
func addItemWithId(_ itemId: ItemId, title: String)
func item(itemId: ItemId) -> ItemType?
func removeItem(itemId: ItemId)
func changeTitle(_ title: String)
func changeItemTitle(itemId: ItemId, title: String)
}
public protocol BoxRepository {
func nextId() -> BoxId
func nextItemId() -> ItemId
func addBoxWithId(_ boxId: BoxId, title: String)
func removeBox(boxId: BoxId)
func boxes() -> [BoxType]
func boxWithId(_ boxId: BoxId) -> BoxType?
func count() -> Int
}
@objc(Box)
open class Box: NSManagedObject {
@NSManaged open var creationDate: Date
@NSManaged open var modificationDate: Date
@NSManaged open var title: String
@NSManaged open var uniqueId: NSNumber
@NSManaged open var managedItems: NSSet
open class func insertBoxWithId(_ boxId: BoxId, title: String, inManagedObjectContext managedObjectContext:NSManagedObjectContext) {
let box = NSEntityDescription.insertNewObject(forEntityName: entityName, into: managedObjectContext)as! Box
box.uniqueId = uniqueIdFromBoxId(boxId)
box.title = title
}
class func uniqueIdFromBoxId(_ boxId: BoxId) -> NSNumber {
return NSNumber(value: boxId.identifier as Int64)
}
}
extension Box: Entity {
public class var entityName: String {
return "ManagedBox"
}
public class func entityDescriptionInManagedObjectContext(_ managedObjectContext: NSManagedObjectContext) -> NSEntityDescription? {
return NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext)
}
}
extension Box: BoxType {
public var boxId: BoxId {
return BoxId(uniqueId.int64Value)
}
public var items: [ItemType] {
return managedItems.allObjects.map { $0 as! ItemType }
}
public func addItemWithId(_ itemId: ItemId, title: String) {
Item.insertItemWithId(itemId, title: title, intoBox: self, inManagedObjectContext: managedObjectContext!)
}
public func item(itemId: ItemId) -> ItemType? {
return items.filter { $0.itemId == itemId }.first
}
public func removeItem(itemId: ItemId) {
guard let item = self.item(itemId: itemId) else {
return
}
let existingItems = mutableSetValue(forKey: "managedItems")
existingItems.remove(item)
}
public func changeTitle(_ title: String) {
self.title = title
}
public func changeItemTitle(itemId: ItemId, title: String) {
guard let item = item(itemId: itemId) else {
return
}
item.changeTitle(title)
}
}
| cc652daa1550002e340b793a30beea70 | 27.633663 | 136 | 0.653181 | false | false | false | false |
SwiftORM/SQLite-StORM | refs/heads/master | Sources/SQLiteStORM/Delete.swift | apache-2.0 | 1 | //
// Delete.swift
// SQLiteStORM
//
// Created by Jonathan Guthrie on 2016-10-07.
//
//
import PerfectLib
import StORM
import PerfectLogger
/// Performs delete-specific functions as an extension
extension SQLiteStORM {
func deleteSQL(_ table: String, idName: String = "id") -> String {
return "DELETE FROM \(table) WHERE \(idName) = :1"
}
/// Deletes one row, with an id as an integer
@discardableResult
public func delete(_ id: Int, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [String(id)])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
/// Deletes one row, with an id as a String
@discardableResult
public func delete(_ id: String, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [id])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
/// Deletes one row, with an id as a UUID
@discardableResult
public func delete(_ id: UUID, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [id.string])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
}
| c47bb900a7b852e46be125cf46e73e22 | 24.186441 | 74 | 0.65074 | false | false | false | false |
Den-Ree/InstagramAPI | refs/heads/master | src/InstagramAPI/InstagramAPI/Example/ViewControllers/Comment/CommentTableViewController.swift | mit | 2 | //
// CommentTableViewController.swift
// InstagramAPI
//
// Created by Admin on 04.06.17.
// Copyright © 2017 ConceptOffice. All rights reserved.
//
import UIKit
class CommentTableViewController: UITableViewController {
var mediaId: String?
fileprivate var dataSource: [InstagramComment] = []
override func viewDidLoad() {
super.viewDidLoad()
let commentRouter = InstagramCommentRouter.getComments(mediaId: mediaId!)
InstagramClient().send(commentRouter, completion: {( comments: InstagramArrayResponse<InstagramComment>?, error: Error?) in
if error == nil {
if let data = comments?.data {
self.dataSource = data
self.tableView.reloadData()
}
}
})
}
}
extension CommentTableViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentCell
let comment = dataSource[indexPath.row]
cell.commentLabel.text = comment.text
cell.usernameLabel.text = comment.from.username
cell.dateLabel.text = comment.createdDate.description
return cell
}
}
| e09aef2a276efc0250c8b0d918d30fa4 | 29.647059 | 131 | 0.668586 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/compiler_crashers_fixed/00085-swift-typechecker-typecheckpattern.swift | apache-2.0 | 65 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func fe<on>() -> (on, on -> on) -> on {
cb w cb.gf = {
}
{
on) {
> ji) -> ji in
dc ih(on, s)
}
}
func w(ed: (((ji, ji) -> ji) -> ji)) -> ji {
dc ed({
(x: ji, h:ji) -> ji in
dc x
})
}
w(fe(hg, fe(kj, lk)))
t l {
ml b
}
y ih<cb> {
nm <l: l q l.b == cb>(x: l.b) {
}
}
func fe<po : n>(w: po) {
}
fe(r qp n)
x o = u rq: Int -> Int = {
dc $sr
}
let k: Int = { (on: Int, fe: Int in
dc fe(on)
}(o, rq)
let w: Int = { on, fe in
dc fe(on)
}(o, rq)
func c(fe: v) -> <po>(() -> po) -> gf
| 01d88d7b8ca68c9c45c62649fc4c2a14 | 20.477273 | 79 | 0.532275 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/UserSectionController.swift | apache-2.0 | 2 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class UserSectionController: ListSectionController {
private var user: User?
private let isReorderable: Bool
required init(isReorderable: Bool = false) {
self.isReorderable = isReorderable
super.init()
}
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: DetailLabelCell.self, for: self, at: index) as? DetailLabelCell else {
fatalError()
}
cell.title = user?.name
cell.detail = "@" + (user?.handle ?? "")
return cell
}
override func didUpdate(to object: Any) {
self.user = object as? User
}
override func canMoveItem(at index: Int) -> Bool {
return isReorderable
}
}
| 82e6aa23f10d96cee32f55e38e1c91dc | 32.5 | 138 | 0.702736 | false | false | false | false |
1000copy/fin | refs/heads/master | View/V2ActivityViewController.swift | mit | 1 | //
// V2ActivityViewController.swift
// V2ex-Swift
//
// Created by huangfeng on 3/7/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
@objc protocol V2ActivityViewDataSource {
/**
获取有几个 ,当前不考虑复用,最多仅支持4个,之后会考虑复用并可以返回Int.max多个。
*/
func V2ActivityView(_ activityView:V2ActivityViewController ,numberOfCellsInSection section: Int) -> Int
/**
返回Activity ,主要是标题和图片
*/
func V2ActivityView(_ activityView:V2ActivityViewController ,ActivityAtIndexPath indexPath:IndexPath) -> V2Activity
/**
有多少组 ,和UITableView 一样。
*/
@objc optional func numberOfSectionsInV2ActivityView(_ activityView:V2ActivityViewController) ->Int
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,heightForHeaderInSection section: Int) -> CGFloat
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,heightForFooterInSection section: Int) -> CGFloat
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,viewForHeaderInSection section: Int) ->UIView?
@objc optional func V2ActivityView(_ activityView:V2ActivityViewController ,viewForFooterInSection section: Int) ->UIView?
@objc optional func V2ActivityView(_ activityView: V2ActivityViewController, didSelectRowAtIndexPath indexPath: IndexPath)
}
class V2Activity:NSObject {
var title:String
var image:UIImage
init(title aTitle:String , image aImage:UIImage){
title = aTitle
image = aImage
}
}
class V2ActivityButton: UIButton {
var indexPath:IndexPath?
}
/// 一个和UIActivityViewController 一样的弹出框
class V2ActivityViewController: UIViewController ,UIViewControllerTransitioningDelegate {
weak var dataSource:V2ActivityViewDataSource?
var section:Int{
get{
if let _section = dataSource?.numberOfSectionsInV2ActivityView?(self) {
return _section
}
else {
return 1
}
}
}
var panel:UIToolbar = UIToolbar()
/**
当前不考虑复用,每一行最多支持4个cell
*/
func numberOfCellsInSection(_ section:Int) -> Int{
if var cells = dataSource?.V2ActivityView(self, numberOfCellsInSection: section) {
if cells > 4 {
cells = 4
}
return cells
}
else{
return 0
}
}
//MARK: - 页面生命周期事件
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0, alpha: 0)
self.transitioningDelegate = self
self.panel.barStyle = V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault ? .default : .black
self.view.addSubview(self.panel)
self.panel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(self.view).offset(-90)
make.left.equalTo(self.view).offset(10)
make.right.equalTo(self.view).offset(-10)
}
self.panel.layer.cornerRadius = 6
self.panel.layer.masksToBounds = true
self.setupView()
if let lastView = self.panel.subviews.last {
self.panel.snp.makeConstraints{ (make) -> Void in
make.bottom.equalTo(lastView)
}
}
let cancelPanel = UIToolbar()
cancelPanel.barStyle = self.panel.barStyle
cancelPanel.layer.cornerRadius = self.panel.layer.cornerRadius
cancelPanel.layer.masksToBounds = true
self.view.addSubview(cancelPanel)
cancelPanel.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self.panel.snp.bottom).offset(10)
make.left.right.equalTo(self.panel);
make.height.equalTo(45)
}
let cancelButton = UIButton()
cancelButton.setTitle(NSLocalizedString("cancel2"), for: UIControlState())
cancelButton.titleLabel?.font = v2Font(18)
cancelButton.setTitleColor(V2EXColor.colors.v2_TopicListTitleColor, for: UIControlState())
cancelPanel.addSubview(cancelButton)
cancelButton.snp.makeConstraints{ (make) -> Void in
make.left.top.right.bottom.equalTo(cancelPanel)
}
cancelButton.addTarget(self, action: #selector(dismiss as (Void) -> Void), for: .touchUpInside)
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss as (Void) -> Void)))
}
func dismiss(){
self.dismiss(animated: true, completion: nil)
}
//#MARK: - 配置视图
fileprivate func setupView(){
for i in 0..<section {
//setupHeaderView
//...
//setupSectionView
let sectionView = self.setupSectionView(i)
self.panel.addSubview(sectionView)
sectionView.snp.makeConstraints{ (make) -> Void in
make.left.right.equalTo(self.panel)
make.height.equalTo(110)
if self.panel.subviews.count > 1 {
make.top.equalTo(self.panel.subviews[self.panel.subviews.count - 1 - 1].snp.bottom)
}
else {
make.top.equalTo(self.panel)
}
}
//setupFoterView
self.setupFooterView(i)
}
}
//配置每组的cell
fileprivate func setupSectionView(_ _section:Int) -> UIView {
let sectionView = UIView()
let margin = (SCREEN_WIDTH-20 - 60 * 4 )/5.0
for i in 0..<self.numberOfCellsInSection(_section) {
let cellView = self.setupCellView(i, currentSection: _section);
sectionView.addSubview(cellView)
cellView.snp.makeConstraints{ (make) -> Void in
make.width.equalTo(60)
make.height.equalTo(80)
make.centerY.equalTo(sectionView)
make.left.equalTo(sectionView).offset( CGFloat((i+1)) * margin + CGFloat(i * 60) )
}
}
return sectionView
}
//配置每组的 footerView
fileprivate func setupFooterView(_ _section:Int) {
if let view = dataSource?.V2ActivityView?(self, viewForFooterInSection: _section) {
var height = dataSource?.V2ActivityView?(self, heightForFooterInSection: _section)
if height == nil {
height = 40
}
self.panel.addSubview(view)
view.snp.makeConstraints{ (make) -> Void in
make.left.right.equalTo(self.panel)
make.height.equalTo(height!)
if self.panel.subviews.count > 1 {
make.top.equalTo(self.panel.subviews[self.panel.subviews.count - 1 - 1].snp.bottom)
}
else {
make.top.equalTo(self.panel)
}
}
}
}
//配置每个cell
fileprivate func setupCellView(_ index:Int , currentSection:Int) -> UIView {
let cellView = UIView()
let buttonBackgoundView = UIImageView()
//用颜色生成图片 切成圆角 并拉伸显示
buttonBackgoundView.image = createImageWithColor(V2EXColor.colors.v2_CellWhiteBackgroundColor, size: CGSize(width: 15, height: 15)).roundedCornerImageWithCornerRadius(5).stretchableImage(withLeftCapWidth: 7, topCapHeight: 7)
cellView.addSubview(buttonBackgoundView)
buttonBackgoundView.snp.makeConstraints{ (make) -> Void in
make.width.height.equalTo(60)
make.top.left.equalTo(cellView)
}
let activity = dataSource?.V2ActivityView(self, ActivityAtIndexPath: IndexPath(row: index, section: currentSection))
let button = V2ActivityButton()
button.setImage(activity?.image.withRenderingMode(.alwaysTemplate), for: UIControlState())
cellView.addSubview(button)
button.tintColor = V2EXColor.colors.v2_TopicListUserNameColor
button.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(buttonBackgoundView)
}
button.indexPath = IndexPath(row: index, section: currentSection)
button.addTarget(self, action: #selector(V2ActivityViewController.cellDidSelected(_:)), for: .touchUpInside)
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 2
titleLabel.text = activity?.title
titleLabel.font = v2Font(12)
titleLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor
cellView.addSubview(titleLabel)
titleLabel.snp.makeConstraints{ (make) -> Void in
make.centerX.equalTo(cellView)
make.left.equalTo(cellView)
make.right.equalTo(cellView)
make.top.equalTo(buttonBackgoundView.snp.bottom).offset(5)
}
return cellView
}
func cellDidSelected(_ sender:V2ActivityButton){
dataSource?.V2ActivityView?(self, didSelectRowAtIndexPath: sender.indexPath!)
}
//MARK: - 转场动画
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return V2ActivityTransionPresent()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return V2ActivityTransionDismiss()
}
}
/// 显示转场动画
class V2ActivityTransionPresent:NSObject,UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
fromVC?.view.isHidden = true
let screenshotImage = fromVC?.view.screenshot()
let tempView = UIImageView(image: screenshotImage)
tempView.tag = 9988
container.addSubview(tempView)
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
container.addSubview(toVC!.view)
toVC?.view.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 7, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
toVC?.view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
tempView.transform = CGAffineTransform(scaleX: 0.98, y: 0.98);
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
/// 隐藏转场动画
class V2ActivityTransionDismiss:NSObject,UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
container.addSubview(toVC!.view)
let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
container.addSubview(fromVC!.view)
let tempView = container.viewWithTag(9988)
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
fromVC?.view.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
tempView!.transform = CGAffineTransform(scaleX: 1, y: 1);
}, completion: { (finished) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
toVC?.view.isHidden = false
})
}
}
| b095005e888d215418da86f7421446a8 | 38.416667 | 232 | 0.642218 | false | false | false | false |
blstream/StudyBox_iOS | refs/heads/master | Pods/Swifternalization/Swifternalization/InequalityExpressionParser.swift | apache-2.0 | 1 | //
// InequalityExpressionParser.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Parses inequality expression patterns. e.g. `ie:x=5`.
*/
class InequalityExpressionParser: ExpressionParser {
/**
A pattern of expression.
*/
let pattern: ExpressionPattern
/**
Initializes parser.
:param: pattern A pattern that will be parsed.
*/
required init(_ pattern: ExpressionPattern) {
self.pattern = pattern
}
/**
Parses `pattern` passed during initialization.
:returns: `ExpressionMatcher` object or nil if pattern cannot be parsed.
*/
func parse() -> ExpressionMatcher? {
if let sign = sign(), let value = value() {
return InequalityExpressionMatcher(sign: sign, value: value)
}
return nil
}
/**
Get mathematical inequality sign.
:returns: `InequalitySign` or nil if sign cannot be found.
*/
private func sign() -> InequalitySign? {
return getSign(ExpressionPatternType.Inequality.rawValue+":x(<=|<|=|>=|>)", failureMessage: "Cannot find any sign", capturingGroupIdx: 1)
}
/**
Get value - Double.
:returns: value or nil if value cannot be found
*/
private func value() -> Double? {
return getValue(ExpressionPatternType.Inequality.rawValue+":x[^-\\d]{1,2}(-?\\d+[.]{0,1}[\\d]{0,})", failureMessage: "Cannot find any value", capturingGroupIdx: 1)
}
// MARK: Helpers
/**
Get value with regex and prints failure message if not found.
:param: regex A regular expression.
:param: failureMessage A message that is printed out in console on failure.
:returns: A value or nil if value cannot be found.
*/
func getValue(regex: String, failureMessage: String, capturingGroupIdx: Int? = nil) -> Double? {
if let value = Regex.matchInString(pattern, pattern: regex, capturingGroupIdx: capturingGroupIdx) {
return NSString(string: value).doubleValue
} else {
print("\(failureMessage), pattern: \(pattern), regex: \(regex)")
return nil
}
}
/**
Get sign with regex and prints failure message if not found.
:param: regex A regular expression.
:param: failureMessage A message that is printed out in console on failure.
:returns: A sign or nil if value cannot be found.
*/
func getSign(regex: String, failureMessage: String, capturingGroupIdx: Int? = nil) -> InequalitySign? {
if let rawValue = Regex.matchInString(pattern, pattern: regex, capturingGroupIdx: capturingGroupIdx),
let sign = InequalitySign(rawValue: rawValue) {
return sign
} else {
print("\(failureMessage), pattern: \(pattern), regex: \(regex)")
return nil
}
}
}
| c42fd1fc9921df9cfd0508d40ea8caa1 | 29.947917 | 171 | 0.622013 | false | false | false | false |
WaterReporter/WaterReporter-iOS | refs/heads/master | WaterReporter/WaterReporter/AppDelegate.swift | agpl-3.0 | 1 | //
// AppDelegate.swift
// WaterReporter
//
// Created by Viable Industries on 7/24/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//
// Before doing anything else make sure that the user is logged
// in to the WaterReporter.org platform.
//
if let _account = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") {
_ = _account
print("AppDelegate::didFinishLaunchingWithOptions::AccountFound")
}
else {
print("AppDelegate::didFinishLaunchingWithOptions::NotFound")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("LoginTableViewController") as! LoginTableViewController
self.window?.makeKeyAndVisible()
self.window?.rootViewController = nextViewController
}
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:.
}
}
| 17ce1682cbfb5e949f0eff60a86409c0 | 43.382353 | 285 | 0.719019 | false | false | false | false |
mfk-ableton/MusicKit | refs/heads/master | MusicKit/ChordQuality.swift | mit | 2 | // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
public enum ChordQuality: String {
//: Dyads
case PowerChord = "5"
//> Triads
case Major = "M"
case Minor = "m"
case Augmented = "+"
case Diminished = "°"
case Sus2 = "sus2"
case Sus4 = "sus4"
//> UnalteredTetrads
case DominantSeventh = "7"
case MajorSeventh = "Δ7"
case MinorMajorSeventh = "mΔ7"
case MinorSeventh = "m7"
case AugmentedMajorSeventh = "+Δ7"
case AugmentedSeventh = "+7"
case HalfDiminishedSeventh = "ø7"
case DiminishedSeventh = "°7"
//> AlteredTetrads
case DominantSeventhFlatFive = "7♭5"
case MajorSeventhFlatFive = "Δ7♭5"
case DominantSeventhSusFour = "7sus4"
case MajorSeventhSusFour = "Δ7sus4"
case MajorSixth = "6"
case MinorSixth = "m6"
case AddNine = "add9"
case MinorAddNine = "madd9"
case AddEleven = "add11"
case MinorAddEleven = "madd11"
case AugmentedAddEleven = "+add11"
case DiminishedAddEleven = "°add11"
case AddSharpEleven = "add♯11"
case MinorAddSharpEleven = "madd♯11"
case AugmentedAddSharpEleven = "+add♯11"
//> UnalteredPentads
case DominantNinth = "9"
case MajorNinth = "Δ9"
case MinorMajorNinth = "mΔ9"
case MinorNinth = "m9"
case AugmentedMajorNinth = "+Δ9"
case AugmentedNinth = "+9"
case HalfDiminishedNinth = "ø9"
case DiminishedNinth = "°9"
//> AlteredPentads
// flat nine pentads
case DominantSeventhFlatNine = "7♭9"
case MajorSeventhFlatNine = "Δ7♭9"
case MinorMajorSeventhFlatNine = "mΔ7♭9"
case MinorSeventhFlatNine = "m7♭9"
case AugmentedMajorSeventhFlatNine = "+Δ7♭9"
case AugmentedSeventhFlatNine = "+7♭9"
case HalfDiminishedSeventhFlatNine = "ø7♭9"
case DiminishedSeventhFlatNine = "°7♭9"
// sharp eleven pentads
case DominantSeventhSharpEleven = "7♯11"
case MajorSeventhSharpEleven = "Δ7♯11"
case MinorMajorSeventhSharpEleven = "mΔ7♯11"
case MinorSeventhSharpEleven = "m7♯11"
case AugmentedMajorSeventhSharpEleven = "+Δ7♯11"
case AugmentedSeventhSharpEleven = "+7♯11"
// flat thirteen pentads
case DominantSeventhFlatThirteen = "7♭13"
case MajorSeventhFlatThirteen = "Δ7♭13"
case MinorMajorSeventhFlatThirteen = "mΔ7♭13"
case MinorSeventhFlatThirteen = "m7♭13"
case HalfDiminishedSeventhFlatThirteen = "ø7♭13"
case DiminishedSeventhFlatThirteen = "°7♭13"
// other pentads
case Dominant9Sus4 = "9sus4"
case SixNine = "6/9"
//> UnalteredHexads
case DominantEleventh = "11"
case MajorEleventh = "Δ11"
case MinorMajorEleventh = "mΔ11"
case MinorEleventh = "m11"
case AugmentedMajorEleventh = "+Δ11"
case AugmentedEleventh = "+11"
case HalfDiminishedEleventh = "ø11"
case DiminishedEleventh = "°11"
//> AlteredHexads
// flat nine hexads
case DominantEleventhFlatNine = "11♭9"
case MajorEleventhFlatNine = "Δ11♭9"
case MinorMajorEleventhFlatNine = "mΔ11♭9"
case MinorEleventhFlatNine = "m11♭9"
case AugmentedMajorEleventhFlatNine = "+Δ11♭9"
case AugmentedEleventhFlatNine = "+11♭9"
case HalfDiminishedEleventhFlatNine = "ø11♭9"
case DiminishedEleventhFlatNine = "°11♭9"
// sharp eleven hexads
case DominantNinthSharpEleven = "9♯11"
case MajorNinthSharpEleven = "Δ9♯11"
case MinorMajorNinthSharpEleven = "mΔ9♯11"
case MinorNinthSharpEleven = "m9♯11"
case AugmentedMajorNinthSharpEleven = "+Δ9♯11"
case AugmentedNinthSharpEleven = "+9♯11"
// flat thirteen hexads
case DominantNinthFlatThirteen = "9♭13"
case MajorNinthFlatThirteen = "Δ9♭13"
case MinorMajorNinthFlatThirteen = "mΔ9♭13"
case MinorNinthFlatThirteen = "m9♭13"
case HalfDiminishedNinthFlatThirteen = "ø9♭13"
case DiminishedNinthFlatThirteen = "°9♭13"
// flat nine sharp eleven hexads
case DominantSeventhFlatNineSharpEleven = "7♭9♯11"
case MajorSeventhFlatNineSharpEleven = "Δ7♭9♯11"
case MinorMajorSeventhFlatNineSharpEleven = "mΔ7♭9♯11"
case MinorSeventhFlatNineSharpEleven = "m7♭9♯11"
case AugmentedMajorSeventhFlatNineSharpEleven = "+Δ7♭9♯11"
case AugmentedSeventhFlatNineSharpEleven = "+7♭9♯11"
// flat nine flat thirteen hexads
case DominantSeventhFlatNineFlatThirteen = "7♭9♭13"
case MajorSeventhFlatNineFlatThirteen = "Δ7♭9♭13"
case MinorMajorSeventhFlatNineFlatThirteen = "mΔ7♭9♭13"
case MinorSeventhFlatNineFlatThirteen = "m7♭9♭13"
case HalfDiminishedSeventhFlatNineFlatThirteen = "ø7♭9♭13"
case DiminishedSeventhFlatNineFlatThirteen = "°7♭9♭13"
// sharp eleven flat thirteen hexads
case DominantSeventhSharpElevenFlatThirteen = "7♯11♭13"
case MajorSeventhSharpElevenFlatThirteen = "Δ7♯11♭13"
case MinorMajorSeventhSharpElevenFlatThirteen = "mΔ7♯11♭13"
case MinorSeventhSharpElevenFlatThirteen = "m7♯11♭13"
//> UnalteredHeptads
case DominantThirteenth = "13"
case MajorThirteenth = "Δ13"
case MinorMajorThirteenth = "mΔ13"
case MinorThirteenth = "m13"
case AugmentedMajorThirteenth = "+Δ13"
case AugmentedThirteenth = "+13"
case HalfDiminishedThirteenth = "ø13"
case DiminishedThirteenth = "°13"
//> AlteredHeptads
// flat nine heptads
case DominantThirteenthFlatNine = "13♭9"
case MajorThirteenthFlatNine = "Δ13♭9"
case MinorMajorThirteenthFlatNine = "mΔ13♭9"
case MinorThirteenthFlatNine = "m13♭9"
case AugmentedMajorThirteenthFlatNine = "+Δ13♭9"
case AugmentedThirteenthFlatNine = "+13♭9"
case HalfDiminishedThirteenthFlatNine = "ø13♭9"
case DiminishedThirteenthFlatNine = "°13♭9"
// sharp eleven heptads
case DominantThirteenthSharpEleven = "13♯11"
case MajorThirteenthSharpEleven = "Δ13♯11"
case MinorMajorThirteenthSharpEleven = "mΔ13♯11"
case MinorThirteenthSharpEleven = "m13♯11"
case AugmentedMajorThirteenthSharpEleven = "+Δ13♯11"
case AugmentedThirteenthSharpEleven = "+13♯11"
// flat thirteen heptads
case DominantEleventhFlatThirteen = "11♭13"
case MajorEleventhFlatThirteen = "Δ11♭13"
case MinorMajorEleventhFlatThirteen = "mΔ11♭13"
case MinorEleventhFlatThirteen = "m11♭13"
case HalfDiminishedEleventhFlatThirteen = "ø11♭13"
case DiminishedEleventhFlatThirteen = "°11♭13"
// flat nine sharp eleven heptads
case DominantThirteenthFlatNineSharpEleven = "13♭9♯11"
case MajorThirteenthFlatNineSharpEleven = "Δ13♭9♯11"
case MinorMajorThirteenthFlatNineSharpEleven = "mΔ13♭9♯11"
case MinorThirteenthFlatNineSharpEleven = "m13♭9♯11"
case AugmentedMajorThirteenthFlatNineSharpEleven = "+Δ13♭9♯11"
case AugmentedThirteenthFlatNineSharpEleven = "+13♭9♯11"
// flat nine flat thirteen heptads
case DominantEleventhFlatNineFlatThirteen = "11♭9♭13"
case MajorEleventhFlatNineFlatThirteen = "Δ11♭9♭13"
case MinorMajorEleventhFlatNineFlatThirteen = "mΔ11♭9♭13"
case MinorEleventhFlatNineFlatThirteen = "m11♭9♭13"
case HalfDiminishedEleventhFlatNineFlatThirteen = "ø11♭9♭13"
case DiminishedEleventhFlatNineFlatThirteen = "°11♭9♭13"
// sharp eleven flat thirteen heptads
case DominantNinthSharpElevenFlatThirteen = "9♯11♭13"
case MajorNinthSharpElevenFlatThirteen = "Δ9♯11♭13"
case MinorMajorNinthSharpElevenFlatThirteen = "mΔ9♯11♭13"
case MinorNinthSharpElevenFlatThirteen = "m9♯11♭13"
// flat nine sharp eleven flat thirteen heptads
case DominantSeventhFlatNineSharpElevenFlatThirteen = "7♭9♯11♭13"
case MajorSeventhFlatNineSharpElevenFlatThirteen = "Δ7♭9♯11♭13"
case MinorMajorSeventhFlatNineSharpElevenFlatThirteen = "mΔ7♭9♯11♭13"
case MinorSeventhFlatNineSharpElevenFlatThirteen = "m7♭9♯11♭13"
//.
public var intervals: [Float] {
switch self {
// dyads
case PowerChord: return [7]
// triads
case Major: return [4, 3]
case Minor: return [3, 4]
case Augmented: return [4, 4]
case Diminished: return [3, 3]
case Sus2: return [2, 5]
case Sus4: return [5, 2]
// tetrads
case DominantSeventh: return [4, 3, 3]
case MajorSeventh: return [4, 3, 4]
case MinorMajorSeventh: return [3, 4, 4]
case MinorSeventh: return [3, 4, 3]
case AugmentedMajorSeventh: return [4, 4, 3]
case AugmentedSeventh: return [4, 4, 2]
case HalfDiminishedSeventh: return [3, 3, 4]
case DiminishedSeventh: return [3, 3, 3]
case DominantSeventhFlatFive: return [4, 2, 4]
case MajorSeventhFlatFive: return [4, 2, 5]
case DominantSeventhSusFour: return [5, 2, 3]
case MajorSeventhSusFour: return [5, 2, 4]
case MajorSixth: return [4, 3, 2]
case MinorSixth: return [3, 4, 2]
case AddNine: return [2, 2, 3]
case MinorAddNine: return [2, 1, 4]
case AddEleven: return [4, 1, 2]
case MinorAddEleven: return [3, 2, 2]
case AugmentedAddEleven: return [4, 1, 3]
case DiminishedAddEleven: return [3, 2, 1]
case AddSharpEleven: return [4, 2, 1]
case MinorAddSharpEleven: return [3, 3, 1]
case AugmentedAddSharpEleven: return [4, 2, 2]
// pentads
// unaltered pentads
case DominantNinth: return [4, 3, 3, 4]
case MajorNinth: return [4, 3, 4, 3]
case MinorMajorNinth: return [3, 4, 4, 3]
case MinorNinth: return [3, 4, 3, 4]
case AugmentedMajorNinth: return [4, 4, 3, 3]
case AugmentedNinth: return [4, 4, 2, 4]
case HalfDiminishedNinth: return [3, 3, 4, 4]
case DiminishedNinth: return [3, 3, 3, 5]
// flat nine pentads
case DominantSeventhFlatNine: return [4, 3, 3, 3]
case MajorSeventhFlatNine: return [4, 3, 4, 2]
case MinorMajorSeventhFlatNine: return [3, 4, 4, 2]
case MinorSeventhFlatNine: return [3, 4, 3, 3]
case AugmentedMajorSeventhFlatNine: return [4, 4, 3, 2]
case AugmentedSeventhFlatNine: return [4, 4, 2, 3]
case HalfDiminishedSeventhFlatNine: return [3, 3, 4, 3]
case DiminishedSeventhFlatNine: return [3, 3, 3, 4]
// sharp eleven pentads
case DominantSeventhSharpEleven: return [4, 3, 3, 8]
case MajorSeventhSharpEleven: return [4, 3, 4, 7]
case MinorMajorSeventhSharpEleven: return [3, 4, 4, 7]
case MinorSeventhSharpEleven: return [3, 4, 3, 8]
case AugmentedMajorSeventhSharpEleven: return [4, 4, 3, 7]
case AugmentedSeventhSharpEleven: return [4, 4, 2, 8]
// flat thirteen pentads
case DominantSeventhFlatThirteen: return [4, 3, 3, 10]
case MajorSeventhFlatThirteen: return [4, 3, 4, 9]
case MinorMajorSeventhFlatThirteen: return [3, 4, 4, 9]
case MinorSeventhFlatThirteen: return [3, 4, 3, 10]
case HalfDiminishedSeventhFlatThirteen: return [3, 3, 4, 10]
case DiminishedSeventhFlatThirteen: return [3, 3, 3, 11]
// other pentads
case SixNine: return [4, 3, 1, 5]
case Dominant9Sus4: return [5, 2, 3, 4]
// hexads
// unaltered hexads
case DominantEleventh: return [4, 3, 3, 4, 3]
case MajorEleventh: return [4, 3, 4, 3, 3]
case MinorMajorEleventh: return [3, 4, 4, 3, 3]
case MinorEleventh: return [3, 4, 3, 4, 3]
case AugmentedMajorEleventh: return [4, 4, 3, 3, 3]
case AugmentedEleventh: return [4, 4, 2, 4, 3]
case HalfDiminishedEleventh: return [3, 3, 4, 4, 3]
case DiminishedEleventh: return [3, 3, 3, 5, 3]
// flat nine hexads
case DominantEleventhFlatNine: return [4, 3, 3, 3, 4]
case MajorEleventhFlatNine: return [4, 3, 4, 2, 4]
case MinorMajorEleventhFlatNine: return [3, 4, 4, 2, 4]
case MinorEleventhFlatNine: return [3, 4, 3, 3, 4]
case AugmentedMajorEleventhFlatNine: return [4, 4, 3, 2, 4]
case AugmentedEleventhFlatNine: return [4, 4, 2, 3, 4]
case HalfDiminishedEleventhFlatNine: return [3, 3, 4, 3, 4]
case DiminishedEleventhFlatNine: return [3, 3, 3, 4, 4]
// sharp eleven hexads
case DominantNinthSharpEleven: return [4, 3, 3, 4, 4]
case MajorNinthSharpEleven: return [4, 3, 4, 3, 4]
case MinorMajorNinthSharpEleven: return [3, 4, 4, 3, 4]
case MinorNinthSharpEleven: return [3, 4, 3, 4, 4]
case AugmentedMajorNinthSharpEleven: return [4, 4, 3, 3, 4]
case AugmentedNinthSharpEleven: return [4, 4, 2, 4, 4]
// flat thirteen hexads
case DominantNinthFlatThirteen: return [4, 3, 3, 4, 6]
case MajorNinthFlatThirteen: return [4, 3, 4, 3, 6]
case MinorMajorNinthFlatThirteen: return [3, 4, 4, 3, 6]
case MinorNinthFlatThirteen: return [3, 4, 3, 4, 6]
case HalfDiminishedNinthFlatThirteen: return [3, 3, 4, 4, 6]
case DiminishedNinthFlatThirteen: return [3, 3, 3, 5, 6]
// flat nine sharp eleven hexads
case DominantSeventhFlatNineSharpEleven: return [4, 3, 3, 3, 5]
case MajorSeventhFlatNineSharpEleven: return [4, 3, 4, 2, 5]
case MinorMajorSeventhFlatNineSharpEleven: return [3, 4, 4, 2, 5]
case MinorSeventhFlatNineSharpEleven: return [3, 4, 3, 3, 5]
case AugmentedMajorSeventhFlatNineSharpEleven: return [4, 4, 3, 2, 5]
case AugmentedSeventhFlatNineSharpEleven: return [4, 4, 2, 3, 5]
// flat nine flat thirteen hexads
case DominantSeventhFlatNineFlatThirteen: return [4, 3, 3, 3, 7]
case MajorSeventhFlatNineFlatThirteen: return [4, 3, 4, 2, 7]
case MinorMajorSeventhFlatNineFlatThirteen: return [3, 4, 4, 2, 7]
case MinorSeventhFlatNineFlatThirteen: return [3, 4, 3, 3, 7]
case HalfDiminishedSeventhFlatNineFlatThirteen: return [3, 3, 4, 3, 7]
case DiminishedSeventhFlatNineFlatThirteen: return [3, 3, 3, 4, 7]
// sharp eleven flat thirteen hexads
case DominantSeventhSharpElevenFlatThirteen: return [4, 3, 3, 8, 2]
case MajorSeventhSharpElevenFlatThirteen: return [4, 3, 4, 7, 2]
case MinorMajorSeventhSharpElevenFlatThirteen: return [3, 4, 4, 7, 2]
case MinorSeventhSharpElevenFlatThirteen: return [3, 4, 3, 8, 2]
// heptads
// unaltered heptads
case DominantThirteenth: return [4, 3, 3, 4, 3, 4]
case MajorThirteenth: return [4, 3, 4, 3, 3, 4]
case MinorMajorThirteenth: return [3, 4, 4, 3, 3, 4]
case MinorThirteenth: return [3, 4, 3, 4, 3, 4]
case AugmentedMajorThirteenth: return [4, 4, 3, 3, 3, 4]
case AugmentedThirteenth: return [4, 4, 2, 4, 3, 4]
case HalfDiminishedThirteenth: return [3, 3, 4, 4, 3, 4]
case DiminishedThirteenth: return [3, 3, 3, 5, 3, 4]
// flat nine heptads
case DominantThirteenthFlatNine: return [4, 3, 3, 3, 4, 4]
case MajorThirteenthFlatNine: return [4, 3, 4, 2, 4, 4]
case MinorMajorThirteenthFlatNine: return [3, 4, 4, 2, 4, 4]
case MinorThirteenthFlatNine: return [3, 4, 3, 3, 4, 4]
case AugmentedMajorThirteenthFlatNine: return [4, 4, 3, 2, 4, 4]
case AugmentedThirteenthFlatNine: return [4, 4, 2, 3, 4, 4]
case HalfDiminishedThirteenthFlatNine: return [3, 3, 4, 3, 4, 4]
case DiminishedThirteenthFlatNine: return [3, 3, 3, 4, 4, 4]
// sharp eleven heptads
case DominantThirteenthSharpEleven: return [4, 3, 3, 4, 4, 3]
case MajorThirteenthSharpEleven: return [4, 3, 4, 3, 4, 3]
case MinorMajorThirteenthSharpEleven: return [3, 4, 4, 3, 4, 3]
case MinorThirteenthSharpEleven: return [3, 4, 3, 4, 4, 3]
case AugmentedMajorThirteenthSharpEleven: return [4, 4, 3, 3, 4, 3]
case AugmentedThirteenthSharpEleven: return [4, 4, 2, 4, 4, 3]
// flat thirteen heptads
case DominantEleventhFlatThirteen: return [4, 3, 3, 4, 3, 3]
case MajorEleventhFlatThirteen: return [4, 3, 4, 3, 3, 3]
case MinorMajorEleventhFlatThirteen: return [3, 4, 4, 3, 3, 3]
case MinorEleventhFlatThirteen: return [3, 4, 3, 4, 3, 3]
case HalfDiminishedEleventhFlatThirteen: return [3, 3, 4, 4, 3, 3]
case DiminishedEleventhFlatThirteen: return [3, 3, 3, 5, 3, 3]
// flat nine sharp eleven heptads
case DominantThirteenthFlatNineSharpEleven: return [4, 3, 3, 3, 5, 3]
case MajorThirteenthFlatNineSharpEleven: return [4, 3, 4, 2, 5, 3]
case MinorMajorThirteenthFlatNineSharpEleven: return [3, 4, 4, 2, 5, 3]
case MinorThirteenthFlatNineSharpEleven: return [3, 4, 3, 3, 5, 3]
case AugmentedMajorThirteenthFlatNineSharpEleven: return [4, 4, 3, 2, 5, 3]
case AugmentedThirteenthFlatNineSharpEleven: return [4, 4, 2, 3, 5, 3]
// flat nine flat thirteen heptads
case DominantEleventhFlatNineFlatThirteen: return [4, 3, 3, 3, 4, 3]
case MajorEleventhFlatNineFlatThirteen: return [4, 3, 4, 2, 4, 3]
case MinorMajorEleventhFlatNineFlatThirteen: return [3, 4, 4, 2, 4, 3]
case MinorEleventhFlatNineFlatThirteen: return [3, 4, 3, 3, 4, 3]
case HalfDiminishedEleventhFlatNineFlatThirteen: return [3, 3, 4, 3, 4, 3]
case DiminishedEleventhFlatNineFlatThirteen: return [3, 3, 3, 4, 4, 3]
// sharp eleven flat thirteen heptads
case DominantNinthSharpElevenFlatThirteen: return [4, 3, 3, 4, 4, 2]
case MajorNinthSharpElevenFlatThirteen: return [4, 3, 4, 3, 4, 2]
case MinorMajorNinthSharpElevenFlatThirteen: return [3, 4, 4, 3, 4, 2]
case MinorNinthSharpElevenFlatThirteen: return [3, 4, 3, 4, 4, 2]
// flat nine sharp eleven flat thirteen heptads
case DominantSeventhFlatNineSharpElevenFlatThirteen: return [4, 3, 3, 3, 5, 2]
case MajorSeventhFlatNineSharpElevenFlatThirteen: return [4, 3, 4, 2, 5, 2]
case MinorMajorSeventhFlatNineSharpElevenFlatThirteen: return [3, 4, 4, 2, 5, 2]
case MinorSeventhFlatNineSharpElevenFlatThirteen: return [3, 4, 3, 3, 5, 2]
}
}
}
extension ChordQuality: CustomStringConvertible {
public var description: String {
return rawValue
}
}
| 6221a150d3851a4ece9e86c1d31622dd | 47.336 | 88 | 0.668708 | false | false | false | false |
navrit/dosenet-apps | refs/heads/master | iOS/DoseNet/DoseNet/DosimeterGraphsViewController.swift | mit | 1 | //
// DosimeterGraphsViewController.swift
// DoseNet
//
// Created by Navrit Bal on 06/01/2016.
// Copyright © 2016 navrit. All rights reserved.
//
import UIKit
import Alamofire
import CSwiftV
import Charts
let CPMtoUSV:Double = 0.036
class DosimeterGraphsViewController: UIViewController {
@IBOutlet weak var labelLeadingMarginConstraint: NSLayoutConstraint!
@IBOutlet weak var lineChartView: LineChartView!
@IBOutlet weak var segmentedControl_Unit: UISegmentedControl!
@IBAction func unitChanged(sender : UISegmentedControl) {
switch segmentedControl_Unit.selectedSegmentIndex {
case 0:
print("Selected µSv/hr")
dose_unit = "µSv/hr"
chartData.removeDataSet(chartDataSet)
self.updatePlot( self.reducedDataUSV )
case 1:
print("Selected mRem/hr")
dose_unit = "mRem/hr"
chartData.removeDataSet(chartDataSet)
self.updatePlot( self.reducedDataREM )
default:
break;
}
}
private var labelLeadingMarginInitialConstant: CGFloat!
var reducedDataUSV: csvStruct!
var reducedDataREM: csvStruct!
var dose_unit: String!
var shortDoseUnit:String! = "USV"
var time_unit: String! = "Day"
var chartDataSet:LineChartDataSet!
var chartData:LineChartData!
struct csvStruct {
var times: [NSDate]
var doses: [Double]
func length() -> Int {
return doses.count
}
/*subscript(start: Int, end: Int) -> csvStruct {
get {
return csvStruct(times: Array(times[start...end]), doses: Array(doses[start...end]))
}
}*/
subscript(range : Range<Int>) -> csvStruct {
get {
return csvStruct(times: Array(times[range.startIndex..<range.endIndex]), doses: Array(doses[range.startIndex..<range.endIndex]))
}
}
subscript(index: Int) -> csvStruct {
get {
return csvStruct(times: [times[index]], doses: [doses[index]])
}
}
init(times: [NSDate], doses: [Double]) {
self.times = times
self.doses = doses
}
}
func main() {
getData()
}
func getShortName( longName:String ) -> String {
if longName == "Campolindo High School" {
return "campolindo"
} else if longName == "Pinewood High School" {
return "pinewood"
} else if longName == "Etcheverry Hall" {
return "etchhall"
} else if longName == "Etcheverry Hall Roof" {
return "etchhall_roof"
} else if longName == "LBL" {
return "lbl"
} else {
return ""
}
}
func getData() {
var url = "https://radwatch.berkeley.edu/sites/default/files/dosenet/"
url += "campolindo.csv"
//url += (self.getShortName() + ".csv")
//print((self.getShortName() + ".csv"))
Alamofire.request(.GET, url).responseString { response in
switch response.result {
case .Success:
print("SUCCESS")
if let value = response.result.value {
let allData = self.csvParse( CSwiftV(String: value) )
self.reducedDataUSV = self.reduceData( allData.csvStruct, sampleSize: allData.sampleSize, scaleFactor: allData.scaleFactor )
self.reducedDataREM = self.reducedDataUSV
for i in 0..<self.reducedDataREM.length() {
self.reducedDataREM.doses[Int(i)] /= 10
}
self.initPlot()
self.updatePlot( self.reducedDataUSV )
}
case .Failure(let error):
print(error)
}
}
}
/*
Process CSV (data, dose_unit, time_unit)
#entries = lines.length
newest_data = lines[lines.length-2].split(",")
oldest_data = lines[1].split(",")
end_date = new Date(parseDate(newest_data[0]))
start_date = new Date(parseDate(oldest_data[0]))
switch time_unit -> case time_options
get end date
#entries
get sample size
Parse date
Get sample size (time)
# of intervals
Avg. data
Plot data (location, dose, time, div)
Get Title text
data label
y text
*/
func csvParse(csv: CSwiftV) -> (csvStruct: csvStruct!, sampleSize: Int, scaleFactor: Double) {
let rows = csv.rows
var times:[NSDate]! = []
var doses:[Double]! = []
var sampleSize:Int = 1
var scaleFactor:Double = 1
switch(shortDoseUnit) { // Scale dose relative to CPM
case "CPM":
scaleFactor = 1
dose_unit = "CPM"
case "USV":
scaleFactor = CPMtoUSV
dose_unit = "µSv/hr"
case "REM":
scaleFactor = CPMtoUSV/10
dose_unit = "mRem/hr"
case "cigarette":
scaleFactor = CPMtoUSV*0.00833333335
dose_unit = "Cigarettes/hr"
case "medical":
scaleFactor = CPMtoUSV*0.2
dose_unit = "X-rays/hr"
case "plane":
scaleFactor = CPMtoUSV*0.420168067
dose_unit = "Air travel/hr"
default:
scaleFactor = CPMtoUSV
print("Defaulting on µSv/hr, unit: \(shortDoseUnit)")
}
for row in rows {
times.append(stringToDate(row[0]))
doses.append(Double(row[1])!*scaleFactor)
}
let output = csvStruct(times:times, doses:doses)
var numEntries:Int = output.length()
let newestData:(csvStruct) = output[output.length()-2]
let oldestData:(csvStruct) = output[0]
var endDate:NSDate! = newestData.times[0]
let startDate:NSDate! = oldestData.times[0]
switch(time_unit) { // Time clipping
case "Hour":
endDate = endDate.dateByAddingTimeInterval(-1*3600)
numEntries = min(numEntries, 13) // 12 5 minute intervals in last hour
case "Day":
endDate = endDate.dateByAddingTimeInterval(-24*3600)
numEntries = min(numEntries, 289) // 288 5 minute intervals in last day
sampleSize = 6
case "Week":
endDate = endDate.addNoOfDays(-7*24*3600)
numEntries = min(numEntries, 2017) // 2016 in last week
sampleSize = 12
case "Month":
endDate = endDate.addNoOfDays(-30*24*3600)
numEntries = min(numEntries, 8641) // 8640 in last month (30 days)
sampleSize = 48
case "Year":
endDate = endDate.addNoOfDays(-365*24*3600)
numEntries = min(numEntries, 105121) // 105120 in last year
sampleSize = 288 // compress to once a day
case "All":
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
endDate = NSDate(timeIntervalSinceReferenceDate: endDate.timeIntervalSince1970 - startDate.timeIntervalSince1970)
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
default: // "Hour"
endDate = endDate.dateByAddingTimeInterval(-1*3600)
numEntries = min(numEntries, 13) // 12 5 minute intervals in last hour
print("Defaulting on Hour")
}
print("Time selected: \(time_unit)")
var reducedOutput:csvStruct
var reducedDoses:[Double] = []
var reducedTimes:[NSDate] = []
for i in (output.length() - numEntries)..<(output.length()) {
if (output.times[i] < endDate) { break }
reducedDoses.append(output.doses[i])
reducedTimes.append(output.times[i])
}
reducedOutput = csvStruct(times: reducedTimes, doses: reducedDoses)
//print(reducedOutput.doses[0...2])
return (reducedOutput, sampleSize, scaleFactor)
}
func reduceData( data : csvStruct, sampleSize : Int, scaleFactor: Double) -> csvStruct {
var times:[NSDate]! = []
var doses:[Double]! = []
var doseErrors:[Double]! = []
let groups = Int(floor(Double(data.length()/sampleSize)))
var n:Int = 0
print(data.doses[0...2])
print("Original length: \(data.length())")
print("Upper index: \(groups)")
print("Sample size: \(sampleSize)")
//print(data[0])
//print(data[data.length()-1])
while n < groups-1 {
n += 1
let subData:(csvStruct) = data[(n*sampleSize)...((n+1)*sampleSize)] // Sub-sample with manually implemented struct
var average:Double = 0
for i in 0..<subData.length() {
// this_data = sub_data[i]
average += subData.doses[i]*5 // total counts was already averaged over 5 minute interval
}
let t = Double(subData.length())/5
let error:Double = sqrt(average)/t
average = average/t
let d = Int(round(Double(subData.length()/2)))
let midDate = subData.times[d] //subDates[d]
times.append(midDate)
doses.append(average*scaleFactor)
doseErrors.append(error*scaleFactor)
}
let out = csvStruct(times:times, doses:doses)
/*print("Reduced length: \(out.length())")
print(out[0...2].doses)*/
return out
}
func initPlot() {
lineChartView.noDataText = "Error: No data received"
lineChartView.descriptionText = ""
lineChartView.animate(xAxisDuration: 2, easingOption: ChartEasingOption.EaseInOutSine)
lineChartView.rightAxis.enabled = false
}
func updatePlot( data : csvStruct ) {
//print(data.times[0...5])
//print(data.doses[0...2])
var dataEntries: [ChartDataEntry] = []
for i in 0..<data.times.count {
let dataEntry = ChartDataEntry(value: data.doses[i], xIndex: i)
dataEntries.append(dataEntry)
}
self.chartDataSet = LineChartDataSet(yVals:dataEntries, label:"Radiation levels over time in \(self.dose_unit)")
self.chartDataSet.colors = ChartColorTemplates.liberty()
self.chartDataSet.drawFilledEnabled = true
self.chartDataSet.drawHorizontalHighlightIndicatorEnabled = false
self.chartDataSet.drawCirclesEnabled = false
self.chartDataSet.lineWidth = 0.2
self.chartData = LineChartData(xVals: data.times, dataSet: chartDataSet)
self.chartData.setDrawValues(false)
let ll = ChartLimitLine(limit: self.chartData.average, label: "Average: \(NSString(format: "%.3f", self.chartData.average)) \(self.dose_unit)")
lineChartView.leftAxis.addLimitLine(ll)
lineChartView.data = self.chartData
lineChartView.notifyDataSetChanged()
}
override func viewDidLoad() {
super.viewDidLoad()
main()
}
override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
/* https://stackoverflow.com/questions/26198526/nsdate-comparison-using-swift */
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
extension NSDate: Comparable { }
public func stringToDate( str: String ) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.dateFromString(str)!
}
extension NSDate {
func addNoOfDays(noOfDays:Int) -> NSDate! {
let cal:NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(abbreviation: "UTC")!
let comps:NSDateComponents = NSDateComponents()
comps.day = noOfDays
return cal.dateByAddingComponents(comps, toDate: self, options: NSCalendarOptions(rawValue: 0))
}
}
| ad5ff5f3618d4a5ddfa59bda8c2e0217 | 33.685083 | 151 | 0.568891 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | refs/heads/master | Classes/Chat/ChatMessageCounterService.swift | apache-2.0 | 1 | //
// ChatMessageCounterService.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 14.07.2021.
//
import Foundation
class ChatMessageCounterService: MobileMessagingService {
weak var chatService: MMInAppChatService?
init(mmContext: MobileMessaging) {
super.init(mmContext: mmContext, uniqueIdentifier: "ChatMessageCounterService")
}
override func handleNewMessage(_ message: MM_MTMessage, completion: @escaping (MessageHandlingResult) -> Void) {
guard message.isChatMessage else {
completion(MessageHandlingResult.noData)
return
}
let internalData = mmContext.internalData()
let newValue = internalData.chatMessageCounter + 1
internalData.chatMessageCounter = newValue
internalData.archiveCurrent()
logDebug("counter set \(newValue)")
completion(MessageHandlingResult.noData)
callCounterHandler(newValue: newValue)
}
private func callCounterHandler(newValue: Int) {
DispatchQueue.main.async {
UserEventsManager.postInAppChatUnreadMessagesCounterUpdatedEvent(newValue)
self.chatService?.delegate?.didUpdateUnreadMessagesCounter?(newValue)
}
}
override func depersonalizeService(_ mmContext: MobileMessaging, completion: @escaping () -> Void) {
resetCounter()
completion()
}
func resetCounter() {
let newValue = 0
let internalData = mmContext.internalData()
internalData.chatMessageCounter = newValue
internalData.archiveCurrent()
logDebug("counter reset")
callCounterHandler(newValue: newValue)
}
func getCounter() -> Int {
return mmContext.internalData().chatMessageCounter
}
}
| 8e1d9a6f10b8958d5ce2339f5e8df148 | 31.618182 | 116 | 0.679487 | false | false | false | false |
satyammedidi/TimeApp | refs/heads/master | TimeApp /TimeApp/LoginWindow.swift | mit | 1 | //
// LoginWindow.swift
// TimeTime
//
// Created by medidi vv satyanarayana murty on 02/02/16.
// Copyright © 2016 Medidi vv satyanarayana murty. All rights reserved.
//
import Cocoa
import SecurityFoundation
let Keychain_keyName = "password"
class LoginWindow: NSWindowController
{
@IBOutlet var userName: NSTextField!
@IBOutlet var password: NSSecureTextField!
@IBOutlet var loginButton: NSButton!
let keyChain = KeychainSwift()
let createLoginButtonTag = 0
let loginButtonTag = 1
var timeSheetLayout:TimeSheetWindow? = nil
var forgotPassword:ForgotPasswordWindow? = nil
override func windowDidLoad()
{
super.windowDidLoad()
if let _ = NSUserDefaults.standardUserDefaults().valueForKey("username")
{
loginButton.title = "LogIn"
loginButton.tag = loginButtonTag
}
else
{
print(" No user Found ")
loginButton.title = "Create"
loginButton.tag = createLoginButtonTag
}
}
override var windowNibName:String
{
return "LoginWindow"
}
@IBAction func resetFields(sender: NSButton)
{
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("username")
defaults.removeObjectForKey("pasword")
password.stringValue = ""
userName.stringValue = ""
loginButton.title = "Create"
loginButton.tag = createLoginButtonTag
}
@IBAction func forgotPassword(sender: NSButton)
{
self.window?.close()
let forgot = ForgotPasswordWindow(windowNibName: "ForgotPasswordWindow")
forgot.showWindow(self)
forgotPassword = forgot
}
@IBAction func login(sender: NSButton)
{
if sender.tag == loginButtonTag
{
if (userName.stringValue == "" || password.stringValue == "")
{
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Password Should Notbe Empty"
alert.runModal()
return
}
if checkLogin(userName.stringValue, password: password.stringValue)
{
let alert = NSAlert()
alert.messageText = "Success"
alert.informativeText = "Successfully Login"
alert.runModal()
password.stringValue = ""
self.window?.close()
let time = TimeSheetWindow(windowNibName: "TimeSheetWindow")
time.showWindow(self)
timeSheetLayout = time
}
else
{
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Entered Wrong Password "
password.stringValue = ""
alert.runModal()
}
}
else
{
if (userName.stringValue == "" || password.stringValue == "")
{
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = " Creation Failed "
alert.runModal()
return
}
else
{
let hasKey = NSUserDefaults.standardUserDefaults().boolForKey("hasLoginKey")
if hasKey == false
{
NSUserDefaults.standardUserDefaults().setObject(userName.stringValue, forKey: "userName")
}
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasPassword")
NSUserDefaults.standardUserDefaults().synchronize()
keyChain.set(password.stringValue, forKey: Keychain_keyName)
let alert = NSAlert()
alert.messageText = "Success"
alert.informativeText = "Successfully Created"
alert.runModal()
password.stringValue = ""
loginButton.title = "LogIn"
loginButton.tag = loginButtonTag
}
}
}
func checkLogin(username: String, password: String ) -> Bool
{
if (password == keyChain.get (Keychain_keyName)) && username == (NSUserDefaults.standardUserDefaults().valueForKey("userName") as? String)!
{
return true
}
else
{
return false
}
}
}
///////create login/create button by code
// let pstyle = NSMutableParagraphStyle()
// pstyle.alignment = .CenterTextAlignment
// loginButton.attributedTitle = NSAttributedString(string: "Create", attributes: [ NSForegroundColorAttributeName : NSColor.blackColor(), NSParagraphStyleAttributeName : pstyle ])
//
| 630107d1cc7ef3c973e32cd7101247c9 | 27.698864 | 191 | 0.542863 | false | false | false | false |
qualaroo/QualarooSDKiOS | refs/heads/master | QualarooTests/Interactors/AnswerDropdownInteractorSpec.swift | mit | 1 | //
// AnswerDropdownInteractorSpec.swift
// QualarooTests
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class AnswerDropdownInteractorSpec: QuickSpec {
override func spec() {
super.spec()
describe("AnswerDropdownInteractor") {
var builder: SingleSelectionAnswerResponseBuilder!
var buttonHandler: SurveyPresenterMock!
var answerHandler: SurveyInteractorMock!
var interactor: AnswerDropdownInteractor!
var questionDict: [String: Any]!
beforeEach {
let answerList = [JsonLibrary.answer(id: 111),
JsonLibrary.answer(id: 222)]
questionDict = JsonLibrary.question(type: "dropdown",
answerList: answerList)
let question = try! QuestionFactory(with: questionDict).build()
builder = SingleSelectionAnswerResponseBuilder(question: question)
buttonHandler = SurveyPresenterMock()
answerHandler = SurveyInteractorMock()
interactor = AnswerDropdownInteractor(responseBuilder: builder,
buttonHandler: buttonHandler,
answerHandler: answerHandler,
question: question)
}
it("always have button enabled") {
expect(buttonHandler.enableButtonFlag).to(beTrue())
}
it("passes answer to handler") {
expect(answerHandler.answerChangedValue).to(beNil())
interactor.setAnswer(0)
let answer = AnswerResponse(id: 111,
alias: nil,
text: nil)
let model = QuestionResponse(id: 1,
alias: nil,
answerList: [answer])
let response = NodeResponse.question(model)
expect(answerHandler.answerChangedValue).to(equal(response))
}
it("is not passing non-existing answer") {
expect(answerHandler.answerChangedValue).to(beNil())
interactor.setAnswer(3)
expect(answerHandler.answerChangedValue).to(beNil())
}
it("doesn't try to show next node if there is 'Next' button") {
expect(answerHandler.goToNextNodeFlag).to(beFalse())
interactor.setAnswer(0)
expect(answerHandler.goToNextNodeFlag).to(beFalse())
}
it("tries to show next node if there is no 'Next' button") {
questionDict["always_show_send"] = false
let question = try! QuestionFactory(with: questionDict).build()
builder = SingleSelectionAnswerResponseBuilder(question: question)
interactor = AnswerDropdownInteractor(responseBuilder: builder,
buttonHandler: buttonHandler,
answerHandler: answerHandler,
question: question)
expect(answerHandler.goToNextNodeFlag).to(beFalse())
interactor.setAnswer(0)
expect(answerHandler.goToNextNodeFlag).to(beTrue())
}
}
}
}
| f17f255a84c2723af70e6d7cf0dd8e7b | 40.469136 | 75 | 0.599881 | false | false | false | false |
zrtalent/SwiftPictureViewer | refs/heads/master | SwiftPictureViewer/SwiftPictureViewer/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// SwiftPictureViewer
//
// Created by Zr on 15/3/11.
// Copyright (c) 2015年 Tarol. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20;
}
/// 准备表格的cell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 提取cell信息
let info = cellInfo(indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier(info.cellId, forIndexPath: indexPath) as! StatusCell
// 判断表格的闭包是否被设置
if cell.photoDidSelected == nil {
// 设置闭包
weak var weakSelf = self
cell.photoDidSelected = { (status: Status, photoIndex: Int)->() in
println("\(status.text) \(photoIndex)")
// 将数据传递给照片浏览器视图控制器
// 使用类方法调用,不需要知道视图控制器太多的内部细节
let vc = PhotoBrowserViewController.photoBrowserViewController()
vc.urls = status.largeUrls
vc.selectedIndex = photoIndex
weakSelf?.presentViewController(vc, animated: true, completion: nil)
}
}
cell.status = info.status
return cell
}
}
| 6a44f35da304cb90a98c2f254d9813f0 | 27.296296 | 118 | 0.583115 | false | false | false | false |
jjessel/JHTAlertController | refs/heads/master | Example/JHTAlertController/ViewController.swift | mit | 1 | //
// ViewController.swift
// JHTAlertController
//
// Created by placeholder for master on 11/17/2016.
// Copyright (c) 2016 placeholder for master. All rights reserved.
//
import UIKit
import JHTAlertController
class ViewController: UIViewController {
let defaultBgColor = UIColor(red:0.82, green:0.93, blue:0.99, alpha:1.0)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = defaultBgColor
}
@IBAction func darkAlert(_ sender: Any) {
let alertController = JHTAlertController(title: "", message: "This is an alert. It is only an alert.", preferredStyle: .alert)
alertController.titleImage = #imageLiteral(resourceName: "Turtle")
alertController.titleViewBackgroundColor = .black
alertController.alertBackgroundColor = .black
alertController.setAllButtonBackgroundColors(to: .black)
alertController.hasRoundedCorners = true
// Create the action.
let cancelAction = JHTAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = JHTAlertAction(title: "Yes", style: .default) { _ in
print("Do something here!")
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// Show alert
present(alertController, animated: true, completion: nil)
}
@IBAction func lightAlert(_ sender: Any) {
let alertController = JHTAlertController(title: "", message: "This message is a placeholder so you can see what the alert looks like with a message.", preferredStyle: .alert)
alertController.titleImage = #imageLiteral(resourceName: "Turtle")
alertController.titleViewBackgroundColor = .black
alertController.alertBackgroundColor = .lightGray
alertController.setAllButtonBackgroundColors(to: .lightGray)
alertController.hasRoundedCorners = true
let cancelAction = JHTAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = JHTAlertAction(title: "Yes", style: .default) { _ in
print("Do something here!")
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
@IBAction func threeButtonAlert(_ sender: Any) {
let alertController = JHTAlertController(title: "Turtle", message: "In this alert we use a String for the title instead of an image.", preferredStyle: .alert)
alertController.titleViewBackgroundColor = UIColor.white
alertController.titleTextColor = .black
alertController.alertBackgroundColor = .black
alertController.setAllButtonBackgroundColors(to: .black)
alertController.hasRoundedCorners = true
// You can add plural action.
let cancelAction = JHTAlertAction(title: "Cancel", style: .cancel, handler: nil)
let defaultAction = JHTAlertAction(title: "Default", style: .default, handler: { [weak self] _ in
self?.view.backgroundColor = self?.defaultBgColor
})
let blueAction = JHTAlertAction(title: "Red", style: .default) { [weak self] _ in
self?.view.backgroundColor = .red
}
alertController.addActions([defaultAction,blueAction, cancelAction])
// Show alert
present(alertController, animated: true, completion: nil)
}
@IBAction func iconAlert(_ sender: Any) {
let alertController = JHTAlertController(title: "Creating a long title message to test what happens when it is really long.!", message: "You can even set an icon for the alert.", preferredStyle: .alert, iconImage: #imageLiteral(resourceName: "TurtleDark") )
alertController.titleViewBackgroundColor = .white
alertController.titleTextColor = .black
alertController.alertBackgroundColor = .white
alertController.messageFont = .systemFont(ofSize: 18)
alertController.messageTextColor = .black
alertController.setAllButtonBackgroundColors(to: .white)
alertController.setButtonTextColorFor(.default, to: .black)
alertController.setButtonTextColorFor(.cancel, to: .black)
alertController.dividerColor = .black
alertController.hasRoundedCorners = true
// Create the action.
let cancelAction = JHTAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = JHTAlertAction(title: "Yes", style: .default) { _ in
guard let textField = alertController.textFields?.first else { return }
print(textField.text!)
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Some Info Here"
textField.backgroundColor = .black
textField.textColor = .white
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Password"
textField.backgroundColor = .black
textField.isSecureTextEntry = true
textField.textColor = .white
}
// Show alert
present(alertController, animated: true, completion: nil)
}
}
| 83bd1828a5f9c0f5a8e533c6d85da358 | 42.94958 | 263 | 0.694073 | false | false | false | false |
Ramesh-P/virtual-tourist | refs/heads/master | Virtual Tourist/Constants.swift | mit | 1 | //
// Constants.swift
// Virtual Tourist
//
// Created by Ramesh Parthasarathy on 2/23/17.
// Copyright © 2017 Ramesh Parthasarathy. All rights reserved.
//
import Foundation
import UIKit
import MapKit
// MARK: Constants
struct Constants {
// MARK: Screen Height
struct ScreenHeight {
static let phoneSE: CGFloat = 568.0
static let phone: CGFloat = 667.0
static let phonePlus: CGFloat = 736.0
}
// MARK: Font Size
struct FontSize {
struct BarButton {
static let phoneSE: CGFloat = 10.2
static let phone: CGFloat = 12.0
static let phonePlus: CGFloat = 13.2
}
struct Label {
static let phoneSE: CGFloat = 11.1
static let phone: CGFloat = 13.0
static let phonePlus: CGFloat = 14.4
}
}
// MARK: Left Margin
struct LeftMargin {
static let phoneSE: CGFloat = -16.0
static let phone: CGFloat = -10.0
static let phonePlus: CGFloat = -10.0
}
// MARK: Map Overlay
struct MapOverlay {
static let openStreetMapCarto = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
static let openStreetMapGrayscale = "https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png"
static let cartoLightAll = "http://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"
static let cartoLightNolabels = "http://a.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png"
static let stamenToner = "http://a.tile.stamen.com/toner/{z}/{x}/{y}.png"
}
// MARK: Default Span
struct DefaultSpan {
struct LatitudeDelta {
static let phoneSE: CLLocationDegrees = 59.0989451658838
static let phone: CLLocationDegrees = 62.8194090540796
static let phonePlus: CLLocationDegrees = 65.3578156691795
}
struct LongitudeDelta {
static let phoneSE: CLLocationDegrees = 61.2760150000001
static let phone: CLLocationDegrees = 61.276015
static let phonePlus: CLLocationDegrees = 61.276015
}
}
}
| 85b78aaa9c65a803174ebbc7179a4000 | 29.956522 | 103 | 0.602528 | false | false | false | false |
Reggian/IOS-Pods-DFU-Library | refs/heads/master | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/Streams/DFUStreamHex.swift | bsd-3-clause | 3 | /*
* Copyright (c) 2016, Nordic Semiconductor
* 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 nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
internal class DFUStreamHex : DFUStream {
fileprivate(set) var currentPart = 1
fileprivate(set) var parts = 1
fileprivate(set) var currentPartType:UInt8 = 0
/// Firmware binaries
fileprivate var binaries:Data
/// The init packet content
fileprivate var initPacketBinaries:Data?
fileprivate var firmwareSize:UInt32 = 0
var size:DFUFirmwareSize {
switch currentPartType {
case FIRMWARE_TYPE_SOFTDEVICE:
return DFUFirmwareSize(softdevice: firmwareSize, bootloader: 0, application: 0)
case FIRMWARE_TYPE_BOOTLOADER:
return DFUFirmwareSize(softdevice: 0, bootloader: firmwareSize, application: 0)
// case FIRMWARE_TYPE_APPLICATION:
default:
return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: firmwareSize)
}
}
var currentPartSize:DFUFirmwareSize {
return size
}
init(urlToHexFile:URL, urlToDatFile:URL?, type:DFUFirmwareType) {
let hexData = try? Data.init(contentsOf: urlToHexFile)
binaries = IntelHex2BinConverter.convert(hexData)
firmwareSize = UInt32(binaries.count)
if let dat = urlToDatFile {
initPacketBinaries = try? Data.init(contentsOf: dat)
}
self.currentPartType = type.rawValue
}
var data:Data {
return binaries
}
var initPacket:Data? {
return initPacketBinaries
}
func hasNextPart() -> Bool {
return false
}
func switchToNextPart() {
// do nothing
}
}
| 28dfab3ddc05ac8de6746600b6ed9f9e | 39.333333 | 144 | 0.70979 | false | false | false | false |
silence0201/Swift-Study | refs/heads/master | GuidedTour/GuidedTour.playground/Pages/Objects and Classes.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Objects and Classes
//:
//: Use `class` followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it is in the context of a class. Likewise, method and function declarations are written the same way.
//:
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
//: - Experiment:
//: Add a constant property with `let`, and add another method that takes an argument.
//:
//: Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance.
//:
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
//: This version of the `Shape` class is missing something important: an initializer to set up the class when an instance is created. Use `init` to create one.
//:
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
//: Notice how `self` is used to distinguish the `name` property from the `name` argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as with `numberOfSides`) or in the initializer (as with `name`).
//:
//: Use `deinit` to create a deinitializer if you need to perform some cleanup before the object is deallocated.
//:
//: Subclasses include their superclass name after their class name, separated by a colon. There is no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed.
//:
//: Methods on a subclass that override the superclass’s implementation are marked with `override`—overriding a method by accident, without `override`, is detected by the compiler as an error. The compiler also detects methods with `override` that don’t actually override any method in the superclass.
//:
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
//: - Experiment:
//: Make another subclass of `NamedShape` called `Circle` that takes a radius and a name as arguments to its initializer. Implement an `area()` and a `simpleDescription()` method on the `Circle` class.
//:
//: In addition to simple properties that are stored, properties can have a getter and a setter.
//:
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
//: In the setter for `perimeter`, the new value has the implicit name `newValue`. You can provide an explicit name in parentheses after `set`.
//:
//: Notice that the initializer for the `EquilateralTriangle` class has three different steps:
//:
//: 1. Setting the value of properties that the subclass declares.
//:
//: 1. Calling the superclass’s initializer.
//:
//: 1. Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point.
//:
//: If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use `willSet` and `didSet`. The code you provide is run any time the value changes outside of an initializer. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square.
//:
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
//: When working with optional values, you can write `?` before operations like methods, properties, and subscripting. If the value before the `?` is `nil`, everything after the `?` is ignored and the value of the whole expression is `nil`. Otherwise, the optional value is unwrapped, and everything after the `?` acts on the unwrapped value. In both cases, the value of the whole expression is an optional value.
//:
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
//: [Previous](@previous) | [Next](@next) | 1d119062dffeef0d8ec69906fc8f9c21 | 41.695652 | 413 | 0.709727 | false | false | false | false |
nnianhou-/M-Vapor | refs/heads/master | Sources/App/Controllers/ChannelController.swift | mit | 1 | //
// ChannelController.swift
// App
//
// Created by N年後 on 2017/10/22.
//
import Vapor
import HTTP
import Random
final class ChannelController: ResourceRepresentable {
func index(_ req: Request) throws -> ResponseRepresentable {
let data = try Channel.all().makeJSON()
return try JSON(node: [
"code" : "0",
"msg": "查询成功",
"data" : data,
])
}
func create(_ req: Request) throws -> ResponseRepresentable {
let channel = try req.channel()
try channel.save()
return try JSON(node: [
"code" : "0",
"msg": "发布成功",
"data" : channel.makeJSON(),
])
}
func show(_ req: Request, festival: Channel) throws -> ResponseRepresentable {
let data = try festival.makeJSON()
return try JSON(node: [
"code" : "0",
"msg": "查询成功",
"data" : data,
])
}
func delete(_ req: Request, festival: Channel) throws -> ResponseRepresentable {
try festival.delete()
return Response(status: .ok)
}
func clear(_ req: Request) throws -> ResponseRepresentable {
try Channel.makeQuery().delete()
return Response(status: .ok)
}
func update(_ req: Request, festival: Channel) throws -> ResponseRepresentable {
try festival.update(for: req)
try festival.save()
return festival
}
func replace(_ req: Request, festival: Channel) throws -> ResponseRepresentable {
let new = try req.channel()
try festival.save()
return festival
}
func channellist(_ req: Request) throws -> ResponseRepresentable {
guard let dockingNumber = req.data["type"]?.string else {
throw Abort.badRequest
}
let videos = try Channel.makeQuery().filter("type",.equals,dockingNumber).all()
return try JSON(node: [
"code" : "0",
"data" : JSON(json: videos.makeJSON())
])
}
func makeResource() -> Resource<Channel> {
return Resource(
index: index,
store: create,
show: show,
update: update,
replace: replace,
destroy: delete,
clear: clear
)
}
}
extension Request {
func channel() throws -> Channel {
guard let json = json else { throw Abort.badRequest }
return try Channel(json: json)
}
}
extension ChannelController: EmptyInitializable { }
| a4445c4d1541d3f06f6c80029f88e109 | 22.963636 | 87 | 0.533384 | false | false | false | false |
shitoudev/marathon | refs/heads/master | marathon/RunCell.swift | mit | 1 | //
// RunCell.swift
// marathon
//
// Created by zhenwen on 9/10/15.
// Copyright © 2015 zhenwen. All rights reserved.
//
import UIKit
import marathonKit
import FontAwesome_swift
class RunCell: UITableViewCell {
@IBOutlet weak var kmLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var paceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
timeLabel.font = UIFont.fontAwesomeOfSize(13)
paceLabel.font = UIFont.systemFontOfSize(14)
}
func updateCell(run: RunModel) {
let totalString = stringDistance(run.distance)
let attributedStr = NSMutableAttributedString(string: totalString, attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(22)])
attributedStr.appendAttributedString(NSAttributedString(string: " km", attributes: [NSForegroundColorAttributeName: UIColor.grayColor(), NSFontAttributeName: UIFont.systemFontOfSize(11)]))
kmLabel.attributedText = attributedStr
let timeString = stringSecondCount(run.total_time)
timeLabel.text = String.fontAwesomeIconWithName(.ClockO) + " \(timeString)"
dateLabel.text = run.time.toString(format: DateFormat.Custom("yy/MM/dd HH:mm"))
paceLabel.text = stringAvgPace(run.distance, seconds: run.total_time) + "/km"
}
}
| 15ee190111f69683b8e61fec59c0981d | 35.894737 | 196 | 0.703281 | false | false | false | false |
ibrdrahim/TopBarMenu | refs/heads/master | TopBarMenu/View3.swift | mit | 1 | //
// View3.swift
// TopBarMenu
//
// Created by ibrahim on 11/22/16.
// Copyright © 2016 Indosytem. All rights reserved.
//
import Foundation
import UIKit
class View3: UIView {
var contentView : UIView?
@IBOutlet weak var imageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
// additional option
}
func xibSetup() {
contentView = loadViewFromNib()
// use bounds not frame or it'll be offset
contentView!.frame = bounds
// Make the view stretch with containing view
contentView!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(contentView!)
}
func loadViewFromNib() -> UIView! {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
| d2547f4f20b205b99af503a1bfe27c9f | 23.333333 | 109 | 0.596651 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Prototypes/CollectionTransformers.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// FIXME: This test runs very slowly on watchOS.
// UNSUPPORTED: OS=watchos
import SwiftPrivate
public enum ApproximateCount {
case Unknown
case Precise(Int64)
case Underestimate(Int64)
case Overestimate(Int64)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<
C : RandomAccessCollection
>(
_ elements: C,
_ range: Range<C.Index>
) -> [Range<C.Index>] {
let startIndex = range.lowerBound
let endIndex = range.upperBound
let length = elements.distance(from: startIndex, to: endIndex)
if length < 2 {
return [range]
}
let middle = elements.index(startIndex, offsetBy: length / 2)
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
associatedtype Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(self, range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == T {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.joined())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: OS=linux-gnu, OS=windows-msvc, OS=openbsd, OS=linux-android
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize(count: 1)
_mutex.deallocate()
}
func withLock<Result>(_ body: () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize(count: 1)
_cond.deallocate()
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: @escaping () -> T,
isEquivalent: @escaping (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: DispatchQueue?
if #available(OSX 10.10, iOS 8.0, *) {
queue = DispatchQueue.global(qos: .background)
} else {
queue = DispatchQueue.global(priority: .background)
}
queue!.async {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_ = _pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool?
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result?
public init(_task: @escaping () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.firstIndex { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_ = _totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_ = _totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = _workDeques.indices.randomElement()!
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
>(_ tasks: C)
where C.Iterator.Element == ForkJoinTaskBase {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
_submissionQueues.randomElement()!.append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
_submissionQueues.randomElement()!.append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: @escaping (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ isIncluded: @escaping (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
isIncluded($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var i = range.lowerBound
while i != range.upperBound {
let e = c[i]
collector.append(e)
c.formIndex(after: &i)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerStep<PipelineInputElement, OutputElement>
where InputStep.PipelineInputElement == PipelineInputElement {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {
(input: InputElement) -> OutputElement? in
if let e = localTransform(input) {
return isIncluded(e) ? e : nil
}
return nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var collectorWrapper =
_ElementCollectorOneToMaybeOne(collector, _transform)
_input.transform(c, range, &collectorWrapper)
collector = collectorWrapper._baseCollector
}
}
struct _ElementCollectorOneToMaybeOne<
BaseCollector : _ElementCollector,
Element_
> : _ElementCollector {
typealias Element = Element_
var _baseCollector: BaseCollector
var _transform: (Element) -> BaseCollector.Element?
init(
_ baseCollector: BaseCollector,
_ transform: @escaping (Element) -> BaseCollector.Element?
) {
self._baseCollector = baseCollector
self._transform = transform
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
if let e = _transform(element) {
_baseCollector.append(e)
}
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
}
protocol _ElementCollector {
associatedtype Element
mutating func sizeHint(_ approximateSize: Int)
mutating func append(_ element: Element)
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
}
class _CollectionTransformerFinalizer<PipelineInputElement, Result> {
func transform<
InputCollection : Collection
>(_ c: InputCollection) -> Result
where InputCollection.Iterator.Element == PipelineInputElement {
fatalError("implement")
}
}
final class _CollectionTransformerFinalizerReduce<
PipelineInputElement,
U,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement {
var _input: InputStep
var _initial: U
var _combine: (U, InputElementTy) -> U
init(_ input: InputStep, _ initial: U, _ combine: @escaping (U, InputElementTy) -> U) {
self._input = input
self._initial = initial
self._combine = combine
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorReduce(_initial, _combine)
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorReduce<Element_, Result> : _ElementCollector {
typealias Element = Element_
var _current: Result
var _combine: (Result, Element) -> Result
init(_ initial: Result, _ combine: @escaping (Result, Element) -> Result) {
self._current = initial
self._combine = combine
}
mutating func sizeHint(_ approximateSize: Int) {}
mutating func append(_ element: Element) {
_current = _combine(_current, element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
for e in elements {
append(e)
}
}
mutating func takeResult() -> Result {
return _current
}
}
final class _CollectionTransformerFinalizerCollectTo<
PipelineInputElement,
U : BuildableCollectionProtocol,
InputElementTy,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerFinalizer<PipelineInputElement, U>
where
InputStep.OutputElement == InputElementTy,
InputStep.PipelineInputElement == PipelineInputElement,
U.Builder.Destination == U,
U.Builder.Element == U.Iterator.Element,
U.Iterator.Element == InputStep.OutputElement {
var _input: InputStep
init(_ input: InputStep, _: U.Type) {
self._input = input
}
override func transform<
InputCollection : Collection
>(_ c: InputCollection) -> U
where InputCollection.Iterator.Element == PipelineInputElement {
var collector = _ElementCollectorCollectTo<U>()
_input.transform(c, c.startIndex..<c.endIndex, &collector)
return collector.takeResult()
}
}
struct _ElementCollectorCollectTo<
BuildableCollection : BuildableCollectionProtocol
> : _ElementCollector
where
BuildableCollection.Builder.Destination == BuildableCollection,
BuildableCollection.Builder.Element == BuildableCollection.Iterator.Element {
typealias Element = BuildableCollection.Iterator.Element
var _builder: BuildableCollection.Builder
init() {
self._builder = BuildableCollection.Builder()
}
mutating func sizeHint(_ approximateSize: Int) {
_builder.sizeHint(approximateSize)
}
mutating func append(_ element: Element) {
_builder.append(element)
}
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element {
_builder.append(contentsOf: elements)
}
mutating func takeResult() -> BuildableCollection {
return _builder.takeResult()
}
}
internal func _optimizeCollectionTransformer<PipelineInputElement, Result>(
_ transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result>
) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> {
return transformer
}
internal func _runCollectionTransformer<
InputCollection : Collection, Result
>(
_ c: InputCollection,
_ transformer: _CollectionTransformerFinalizer<InputCollection.Iterator.Element, Result>
) -> Result {
dump(transformer)
let optimized = _optimizeCollectionTransformer(transformer)
dump(optimized)
return transformer.transform(c)
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: public interface
//===----------------------------------------------------------------------===//
public struct CollectionTransformerPipeline<
InputCollection : Collection, T
> {
internal var _input: InputCollection
internal var _step: _CollectionTransformerStep<InputCollection.Iterator.Element, T>
public func map<U>(_ transform: @escaping (T) -> U)
-> CollectionTransformerPipeline<InputCollection, U> {
return CollectionTransformerPipeline<InputCollection, U>(
_input: _input,
_step: _step.map(transform)
)
}
public func filter(_ isIncluded: @escaping (T) -> Bool)
-> CollectionTransformerPipeline<InputCollection, T> {
return CollectionTransformerPipeline<InputCollection, T>(
_input: _input,
_step: _step.filter(isIncluded)
)
}
public func reduce<U>(
_ initial: U, _ combine: @escaping (U, T) -> U
) -> U {
return _runCollectionTransformer(_input, _step.reduce(initial, combine))
}
public func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> C
where
C.Builder.Destination == C,
C.Iterator.Element == T,
C.Builder.Element == T {
return _runCollectionTransformer(_input, _step.collectTo(c))
}
public func toArray() -> [T] {
return collectTo(Array<T>.self)
}
}
public func transform<C : Collection>(_ c: C)
-> CollectionTransformerPipeline<C, C.Iterator.Element> {
return CollectionTransformerPipeline<C, C.Iterator.Element>(
_input: c,
_step: _CollectionTransformerStepCollectionSource<C.Iterator.Element>())
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: tests
//===----------------------------------------------------------------------===//
import StdlibUnittest
var t = TestSuite("t")
t.test("fusion/map+reduce") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+filter+reduce") {
let xs = [ 1, 2, 3 ]
let result = transform(xs)
.map { $0 * 2 }
.filter { $0 != 0 }
.reduce(0, { $0 + $1 })
expectEqual(12, result)
}
t.test("fusion/map+collectTo") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.collectTo(Array<Int>.self)
expectEqual([ 2, 4, 6 ], result)
}
t.test("fusion/map+toArray") {
let xs = [ 1, 2, 3 ]
let result =
transform(xs)
.map { $0 * 2 }
.toArray()
expectEqual([ 2, 4, 6 ], result)
}
t.test("ForkJoinPool.forkTask") {
var tasks: [ForkJoinTask<()>] = []
for i in 0..<100 {
tasks.append(ForkJoinPool.commonPool.forkTask {
() -> () in
var result = 1
for i in 0..<10000 {
result = result &* i
_blackHole(result)
}
return ()
})
}
for t in tasks {
t.wait()
}
}
func fib(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if n == 38 {
print("\(pthread_self()) fib(\(n))")
}
if n < 39 {
let r = fib(n - 1) + fib(n - 2)
_blackHole(r)
return r
}
print("fib(\(n))")
let t1 = ForkJoinTask() { fib(n - 1) }
let t2 = ForkJoinTask() { fib(n - 2) }
ForkJoinPool.invokeAll(t1, t2)
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
t.test("ForkJoinPool.forkTask/Fibonacci") {
let t = ForkJoinPool.commonPool.forkTask { fib(40) }
expectEqual(102334155, t.waitAndGetResult())
}
func _parallelMap(_ input: [Int], transform: @escaping (Int) -> Int, range: Range<Int>)
-> Array<Int>.Builder {
var builder = Array<Int>.Builder()
if range.count < 1_000 {
builder.append(contentsOf: input[range].map(transform))
} else {
let tasks = input.split(range).map {
(subRange) in
ForkJoinTask<Array<Int>.Builder> {
_parallelMap(input, transform: transform, range: subRange)
}
}
ForkJoinPool.invokeAll(tasks)
for t in tasks {
var otherBuilder = t.waitAndGetResult()
builder.moveContentsOf(&otherBuilder)
}
}
return builder
}
func parallelMap(_ input: [Int], transform: @escaping (Int) -> Int) -> [Int] {
let t = ForkJoinPool.commonPool.forkTask {
_parallelMap(
input,
transform: transform,
range: input.startIndex..<input.endIndex)
}
var builder = t.waitAndGetResult()
return builder.takeResult()
}
t.test("ForkJoinPool.forkTask/MapArray") {
expectEqual(
Array(2..<1_001),
parallelMap(Array(1..<1_000)) { $0 + 1 }
)
}
/*
* FIXME: reduce compiler crasher
t.test("ForkJoinPool.forkTask") {
func fib(_ n: Int) -> Int {
if n == 0 || n == 1 {
return 1
}
let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) }
let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) }
return t2.waitAndGetResult() + t1.waitAndGetResult()
}
expectEqual(0, fib(10))
}
*/
/*
Useful links:
http://habrahabr.ru/post/255659/
*/
runAllTests()
| 7445d85e6d1835f6465c7934f626b32d | 26.137052 | 108 | 0.653757 | false | false | false | false |
li-wenxue/Weibo | refs/heads/master | 新浪微博/新浪微博/Class/Tools/Extension/UIImageView+WebImage.swift | mit | 1 | //
// UIImageView+WebImage.swift
// 新浪微博
//
// Created by win_学 on 16/9/13.
// Copyright © 2016年 win_学. All rights reserved.
//
import SDWebImage
extension UIImageView {
/// 隔离 SDWebImage 设置图像函数
func wx_setImage(urlString: String?, placeholderImage: UIImage?, isAvatar: Bool) {
// 处理url
guard let urlString = urlString,
let url = URL(string: urlString) else {
image = placeholderImage
return
}
sd_setImage(with: url, placeholderImage: placeholderImage, options: [], progress: nil) { (image, _, _, _) in
// 完成回调 - 判断是否是头像
if isAvatar {
self.image = image?.wx_avatarImage(size: self.bounds.size)
//self.image = UIImage.avatarImage(withOriginImage: image, size: self.bounds.size, andBackgroundColor: UIColor.white)
}
}
}
}
| e626f71fde0ecc277c9e190b1f8b33aa | 27.71875 | 133 | 0.568009 | false | false | false | false |
ktmswzw/FeelClient | refs/heads/master | FeelingClient/MVC/C/OpenMapViewController.swift | mit | 1 | //
// OpenMapViewController.swift
// FeelingClient
//
// Created by Vincent on 16/3/31.
// Copyright © 2016年 xecoder. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import IBAnimatable
import MobileCoreServices
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import Haneke
class OpenMapViewController: UIViewController, OpenMessageModelDelegate , MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var distinctText: AnimatableTextField!
@IBOutlet weak var mapView: MKMapView!
// @IBOutlet weak var openButton: AnimatableButton!
var msgscrentId = ""
var fromId:String = ""
var friendModel: FriendViewModel!
var disposeBag = DisposeBag()
var latitude = 0.0
var longitude = 0.0
var address = ""
var photos: [String] = []
@IBOutlet var segmentButton: UISegmentedControl!
@IBOutlet weak var imageCollection: UICollectionView!
var isOk = false
let locationManager = CLLocationManager()
var targetLocation:CLLocation = CLLocation(latitude: 0, longitude: 0) //目标点
var distance = 0.0 //两点距离
let msg: MessageApi = MessageApi.defaultMessages
var addressDict: [String : AnyObject]?
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
friendModel = FriendViewModel(delegate: self)
locationManager.delegate = self
//locationManager.distanceFilter = 1;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
self.mapView.delegate = self
self.mapView.showsUserLocation = true
self.imageCollection.delegate = self
self.imageCollection.dataSource = self
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加好友", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.save))
self.navigationItem.rightBarButtonItem?.enabled = false
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
imageCollection!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "photo")
let oneAnnotation = MyAnnotation()
oneAnnotation.coordinate = self.targetLocation.coordinate
mapView.addAnnotation(oneAnnotation)
}
@IBAction func gotoNav(sender: AnyObject) {
openTransitDirectionsForCoordinates(self.targetLocation.coordinate, addressDictionary: [:])
}
func openTransitDirectionsForCoordinates(
coord:CLLocationCoordinate2D,addressDictionary: [String : AnyObject]?) {
let placemark = MKPlacemark(coordinate: coord, addressDictionary: addressDictionary) // 1
let mapItem = MKMapItem(placemark: placemark) // 2
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeTransit] // 3
mapItem.openInMapsWithLaunchOptions(launchOptions) // 4
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
latitude = location!.coordinate.latitude
longitude = location!.coordinate.longitude
if(!isOk){
UIView.animateWithDuration(1.5, animations: { () -> Void in
let center = CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
self.mapView.region = region
let currentLocation = CLLocation(latitude: self.latitude, longitude: self.longitude)
self.distance = getDistinct(currentLocation, targetLocation: self.targetLocation)
self.distinctText.text = "距离 \(self.address) 约: \(Int(self.distance)) 米"
if(self.distance<100){
self.isOk = true
self.arrival()
self.navigationItem.rightBarButtonItem?.enabled = true
self.distinctText.text = "已开启"
}
})
}
}
func arrival()
{
msg.arrival(self.msgscrentId) { (r:BaseApi.Result) -> Void in
switch (r) {
case .Success(let r):
let m = r as! MessagesSecret
if(m.photos.count>0){
self.photos = m.photos
}
self.imageCollection.reloadData()
self.textView.text = m.content
break;
case .Failure(let msg):
self.view.makeToast(msg as! String, duration: 1, position: .Center)
break;
}
}
}
func save(){
self.navigationController?.view.makeToastActivity(.Center)
friendModel.save(self.fromId) { (r:BaseApi.Result) in
switch (r) {
case .Success(_):
self.navigationController?.view.hideToastActivity()
self.view.makeToast("添加成功", duration: 1, position: .Center)
self.navigationItem.rightBarButtonItem?.enabled = false
self.performSegueWithIdentifier("homeMain", sender: self)
break
case .Failure(let error):
self.navigationController?.view.hideToastActivity()
self.view.makeToast("添加失败:\(error)", duration: 1, position: .Center)
break
}
}
}
}
extension OpenMapViewController: FriendModelDelegate{
}
extension OpenMapViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
viewBigImages(self.photos[indexPath.row] )
}
func viewBigImages(url: String)
{
self.performSegueWithIdentifier("showImage", sender: url)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let CellIdentifier = "photo"
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! CollectionViewCell
let URLString = self.photos[indexPath.row]
let URL = NSURL(string:getPathSmall(URLString))!
cell.imageView.hnk_setImageFromURL(URL)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showImage" {
let viewController = segue.destinationViewController as! ViewImageViewController
viewController.imageUrl = getPath(sender as! String)
}
}
}
| 6d8e067dd70f661835223c199c72591a | 36.554404 | 158 | 0.645419 | false | false | false | false |
alblue/swift | refs/heads/master | test/Constraints/members.swift | apache-2.0 | 5 | // RUN: %target-typecheck-verify-swift -swift-version 5
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
_ = x.f0(i)
x.f0(i).f1(i)
g0(X.f1) // expected-error{{partial application of 'mutating' method}}
_ = x.f0(x.f2(1))
_ = x.f0(1).f2(i)
_ = yf.f0(1)
_ = yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{enum case 'none' cannot be used as an instance member}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In {
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
static func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : X { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{type 'S22490787' does not conform to protocol 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
// SR-2193: QoI: better diagnostic when a decl exists, but is not a type
enum SR_2193_Error: Error {
case Boom
}
do {
throw SR_2193_Error.Boom
} catch let e as SR_2193_Error.Boom { // expected-error {{enum case 'Boom' is not a member type of 'SR_2193_Error'}}
}
// rdar://problem/25341015
extension Sequence {
func r25341015_1() -> Int {
return max(1, 2) // expected-error {{use of 'max' refers to instance method 'max(by:)' rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}}
}
}
class C_25341015 {
static func baz(_ x: Int, _ y: Int) {} // expected-note {{'baz' declared here}}
func baz() {}
func qux() {
baz(1, 2) // expected-error {{use of 'baz' refers to instance method 'baz()' rather than static method 'baz' in class 'C_25341015'}} expected-note {{use 'C_25341015.' to reference the static method}}
}
}
struct S_25341015 {
static func foo(_ x: Int, y: Int) {} // expected-note {{'foo(_:y:)' declared here}}
func foo(z: Int) {}
func bar() {
foo(1, y: 2) // expected-error {{use of 'foo' refers to instance method 'foo(z:)' rather than static method 'foo(_:y:)' in struct 'S_25341015'}} expected-note {{use 'S_25341015.' to reference the static method}}
}
}
func r25341015() {
func baz(_ x: Int, _ y: Int) {}
class Bar {
func baz() {}
func qux() {
baz(1, 2) // expected-error {{argument passed to call that takes no arguments}}
}
}
}
func r25341015_local(x: Int, y: Int) {}
func r25341015_inner() {
func r25341015_local() {}
r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}}
}
// rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely
func foo_32854314() -> Double {
return 42
}
func bar_32854314() -> Int {
return 0
}
extension Array where Element == Int {
func foo() {
let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
}
func foo(_ x: Int, _ y: Double) {
let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
}
func bar() {
let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' nearly matches global function 'min' in module 'Swift' rather than instance method 'min()'}}
}
}
// Crash in diagnoseImplicitSelfErrors()
struct Aardvark {
var snout: Int
mutating func burrow() {
dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}}
}
func dig(_: inout Int, _: Int) {}
}
func rdar33914444() {
struct A {
enum R<E: Error> {
case e(E) // expected-note {{'e' declared here}}
}
struct S {
enum E: Error {
case e1
}
let e: R<E>
}
}
_ = A.S(e: .e1)
// expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}}
}
// SR-5324: Better diagnostic when instance member of outer type is referenced from nested type
struct Outer {
var outer: Int
struct Inner {
var inner: Int
func sum() -> Int {
return inner + outer
// expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}}
}
}
}
// rdar://problem/39514009 - don't crash when trying to diagnose members with special names
print("hello")[0] // expected-error {{value of tuple type '()' has no member 'subscript'}}
| 070529b63741f05c16f4559e88bb865d | 26.807692 | 226 | 0.662287 | false | false | false | false |
JGiola/swift | refs/heads/main | test/SILOptimizer/definite_init_protocol_init.swift | apache-2.0 | 7 | // RUN: %target-swift-frontend -enable-copy-propagation=requested-passes-only -enable-lexical-lifetimes=false -emit-sil %s -swift-version 5 -verify | %FileCheck %s
// Ensure that convenience initializers on concrete types can
// delegate to factory initializers defined in protocol
// extensions.
protocol TriviallyConstructible {
init(lower: Int)
}
extension TriviallyConstructible {
init(middle: Int) {
self.init(lower: middle)
}
init?(failingMiddle: Int) {
self.init(lower: failingMiddle)
}
init(throwingMiddle: Int) throws {
self.init(lower: throwingMiddle)
}
}
class TrivialClass : TriviallyConstructible {
required init(lower: Int) {}
// CHECK-LABEL: sil hidden @$s023definite_init_protocol_B012TrivialClassC5upperACSi_tcfC
// CHECK: bb0(%0 : $Int, [[SELF_META:%.*]] : $@thick TrivialClass.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $TrivialClass
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[METATYPE:%.*]] = unchecked_trivial_bit_cast [[SELF_META]] {{.*}} to $@thick @dynamic_self TrivialClass.Type
// CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $TrivialClass
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$s023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
// CHECK-NEXT: apply [[FN]]<@dynamic_self TrivialClass>([[RESULT]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[RESULT]]
// TODO: Once we restore arbitrary takes, the strong_retain/destroy_addr pair below will go away.
// CHECK-NEXT: strong_retain [[NEW_SELF]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[RESULT]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
convenience init(upper: Int) {
self.init(middle: upper)
}
convenience init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
convenience init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
struct TrivialStruct : TriviallyConstructible {
let x: Int
init(lower: Int) { self.x = lower }
// CHECK-LABEL: sil hidden @$s023definite_init_protocol_B013TrivialStructV5upperACSi_tcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin TrivialStruct.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $TrivialStruct
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialStruct.Type
// CHECK: [[FN:%.*]] = function_ref @$s023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
// CHECK-NEXT: apply [[FN]]<TrivialStruct>([[SELF_BOX]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[NEW_SELF]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
struct AddressOnlyStruct : TriviallyConstructible {
let x: Any
init(lower: Int) { self.x = lower }
// CHECK-LABEL: sil hidden @$s023definite_init_protocol_B017AddressOnlyStructV5upperACSi_tcfC
// CHECK: bb0(%0 : $*AddressOnlyStruct, %1 : $Int, %2 : $@thin AddressOnlyStruct.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $AddressOnlyStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $AddressOnlyStruct
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick AddressOnlyStruct.Type
// CHECK: [[FN:%.*]] = function_ref @$s023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
// CHECK-NEXT: apply [[FN]]<AddressOnlyStruct>([[SELF_BOX]], %1, [[METATYPE]])
// CHECK-NEXT: copy_addr [take] [[SELF_BOX]] to [initialization] [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: copy_addr [take] [[SELF]] to [initialization] %0
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
enum TrivialEnum : TriviallyConstructible {
case NotSoTrivial
init(lower: Int) {
self = .NotSoTrivial
}
// CHECK-LABEL: sil hidden @$s023definite_init_protocol_B011TrivialEnumO5upperACSi_tcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin TrivialEnum.Type):
// CHECK-NEXT: [[SELF:%.*]] = alloc_stack $TrivialEnum
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $TrivialEnum
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick TrivialEnum.Type
// CHECK: [[FN:%.*]] = function_ref @$s023definite_init_protocol_B022TriviallyConstructiblePAAE6middlexSi_tcfC
// CHECK-NEXT: apply [[FN]]<TrivialEnum>([[SELF_BOX]], %0, [[METATYPE]])
// CHECK-NEXT: [[NEW_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: return [[NEW_SELF]]
init(upper: Int) {
self.init(middle: upper)
}
init?(failingUpper: Int) {
self.init(failingMiddle: failingUpper)
}
init(throwingUpper: Int) throws {
try self.init(throwingMiddle: throwingUpper)
}
}
| 498cc50cef1617f59d5e2162b0c4b3b5 | 35.194631 | 163 | 0.669015 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | refs/heads/master | Food Hygiene Ratings/Formatting.swift | apache-2.0 | 1 | //
// Formatting.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 30/09/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import Foundation
class Formatting {
static let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter
}()
class func format(establishment : Establishment) -> String {
var builder = "Food Hygiene Rating\n\n"
builder.append("\(establishment.business.name)\n")
for line in establishment.address.address {
builder.append(line)
builder.append("\n")
}
builder.append("\nRating: \(establishment.rating.ratingString)\n")
if establishment.rating.hasRating(){
builder.append("Awarded: \(Formatting.dateFormatter.string(from: establishment.rating.awardedDate))\n")
builder.append("Food Hygiene and Safety: \(establishment.rating.scores.getHygieneDescription())\n")
builder.append("Structural Compliance: \(establishment.rating.scores.getStructuralDescription())\n")
builder.append("Confidence in Management: \(establishment.rating.scores.getManagementDescription())\n")
}
builder.append("\nLocal Authority Details\n")
builder.append("\(establishment.localAuthority.name)\nEmail: \(establishment.localAuthority.email)\nWebsite: \(establishment.localAuthority.web)\n")
builder.append("\nFSA Website for this business\n")
builder.append("\(FoodHygieneAPI.createBusinessUrl(fhrsId: establishment.business.fhrsId).absoluteString)\n")
return builder
}
}
| a1903b8f31d38fe631b183ae49586689 | 39.857143 | 156 | 0.676573 | false | false | false | false |
mattjgalloway/emoncms-ios | refs/heads/master | EmonCMSiOS/Apps/MyElectricAppConfigViewModel.swift | mit | 1 | //
// MyElectricAppConfigViewModel.swift
// EmonCMSiOS
//
// Created by Matt Galloway on 13/10/2016.
// Copyright © 2016 Matt Galloway. All rights reserved.
//
import Foundation
import RxSwift
import RealmSwift
final class MyElectricAppConfigViewModel {
enum SaveError: Error {
case missingFields([AppConfigField])
}
private let account: Account
private let api: EmonCMSAPI
private let realm: Realm
private let appData: MyElectricAppData
lazy var feedListHelper: FeedListHelper = {
return FeedListHelper(account: self.account, api: self.api)
}()
init(account: Account, api: EmonCMSAPI, appDataId: String?) {
self.account = account
self.api = api
self.realm = account.createRealm()
if let appDataId = appDataId {
self.appData = self.realm.object(ofType: MyElectricAppData.self, forPrimaryKey: appDataId)!
} else {
self.appData = MyElectricAppData()
}
}
private enum ConfigKeys: String {
case name
case useFeedId
case kwhFeedId
}
func configFields() -> [AppConfigField] {
return [
AppConfigFieldString(id: "name", name: "Name", optional: false),
AppConfigFieldFeed(id: "useFeedId", name: "Power Feed", optional: false, defaultName: "use"),
AppConfigFieldFeed(id: "kwhFeedId", name: "kWh Feed", optional: false, defaultName: "use_kwh"),
]
}
func configData() -> [String:Any] {
var data: [String:Any] = [:]
data[ConfigKeys.name.rawValue] = self.appData.name
if let feedId = self.appData.useFeedId {
data[ConfigKeys.useFeedId.rawValue] = feedId
}
if let feedId = self.appData.kwhFeedId {
data[ConfigKeys.kwhFeedId.rawValue] = feedId
}
return data
}
func updateWithConfigData(_ data: [String:Any]) -> Observable<String> {
return Observable.create { [weak self] observer in
guard let strongSelf = self else { return Disposables.create() }
// Validate first
var missingFields: [AppConfigField] = []
for field in strongSelf.configFields() where field.optional == false {
if data[field.id] == nil {
missingFields.append(field)
}
}
if missingFields.count > 0 {
observer.onError(SaveError.missingFields(missingFields))
} else {
do {
let appData = strongSelf.appData
try strongSelf.realm.write {
if let name = data[ConfigKeys.name.rawValue] as? String {
appData.name = name
}
if let feedId = data[ConfigKeys.useFeedId.rawValue] as? String {
appData.useFeedId = feedId
}
if let feedId = data[ConfigKeys.kwhFeedId.rawValue] as? String {
appData.kwhFeedId = feedId
}
if appData.realm == nil {
strongSelf.realm.add(appData)
}
}
observer.onNext(strongSelf.appData.uuid)
observer.onCompleted()
} catch {
observer.onError(error)
}
}
return Disposables.create()
}
}
}
| 7964480db60b71b22604a8eaa5f2cc2c | 26.576577 | 101 | 0.628879 | false | true | false | false |
SequencingDOTcom/oAuth2-Code-Example-.NET | refs/heads/master | swift/Pods/sequencing-oauth-api-swift/Pod/SQServerManager.swift | mit | 4 | //
// SQServerManager.swift
// Copyright © 2015-2016 Sequencing.com. All rights reserved
//
import UIKit
import Foundation
class SQServerManager: NSObject {
// registered application parameters
var client_id: String = ""
var client_secret: String = ""
var redirect_uri: String = ""
var scope: String = ""
// parameters for authorization request
let authURL: String = "https://sequencing.com/oauth2/authorize"
let response_type: String = "code"
// parameters for token request
let tokenURL: String = "https://sequencing.com/oauth2/token"
let grant_type: String = "authorization_code"
// parameters for refresh token request
let refreshTokenURL: String = "https://sequencing.com/oauth2/token?q=oauth2/token"
let refreshGrant_type: String = "refresh_token"
// parameters for sample files list request
let apiURL: String = "https://api.sequencing.com"
let demoPath: String = "/DataSourceList?sample=true"
// parameters for own files list request
let filesPath: String = "/DataSourceList?uploaded=true&shared=true"
// activity indicator with label
var messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
let mainVC = UIApplication.sharedApplication().windows.first!.rootViewController
// const for main queue
let kMainQueue = dispatch_get_main_queue()
// designated initializer
static let instance = SQServerManager()
func registrateParametersClientID(client_id: String, ClientSecret client_secret: String, RedirectUri redirect_uri: String, Scope scope: String) -> Void {
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
self.scope = scope
SQRequestHelper.instance.rememberRedirectUri(self.redirect_uri)
}
// MARK: - API request functions
func authorizeUser(completion: (authResult: SQAuthResult) -> Void) -> Void {
let randomState = self.randomStringWithLength(self.randomInt())
let client_id: String = self.client_id.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())!
let urlString = authURL + "?" +
"redirect_uri=" + self.redirect_uri + "&" +
"response_type=" + self.response_type + "&" +
"state=" + randomState + "&" +
"client_id=" + client_id + "&" +
"scope=" + self.scope
let urlRequest = NSURL(string: urlString)!
// ===== authorizing user request ======
let loginViewController: SQLoginViewController = SQLoginViewController.init(url: urlRequest) { (response) -> Void in
if response != nil {
// first, must check if "state" from response matches "state" in request
let stateInResponse = response?.objectForKey("state") as! String
if stateInResponse != randomState {
print("state mismatch, response is being spoofed")
SQAuthResult.instance.isAuthorized = false
completion(authResult: SQAuthResult.instance)
} else {
// state matches - we can proceed with token request
// ===== getting token request =====
self.startActivityIndicatorWithTitle("Authorizing user")
if let codeFromResponse = response?.objectForKey("code") as? String {
self.postForTokenWithCode(codeFromResponse, completion: { (token, error) -> Void in
if token != nil {
self.stopActivityIndicator()
SQAuthResult.instance.isAuthorized = true
SQAuthResult.instance.token = token!
SQTokenUpdater.instance.cancelTimer()
// THIS WILL START TIMER TO AUTOMATICALLY REFRESH ACCESS_TOKEN WHEN IT'S EXPIRED
SQTokenUpdater.instance.startTimer()
completion(authResult: SQAuthResult.instance)
} else if error != nil {
print(error)
self.stopActivityIndicator()
SQAuthResult.instance.isAuthorized = false
completion(authResult: SQAuthResult.instance)
}
})
} else {
self.stopActivityIndicator()
SQAuthResult.instance.isAuthorized = false
print("Can't authorize user. Don't forget to register application parameters")
completion(authResult: SQAuthResult.instance)
}
}
} else {
self.stopActivityIndicator()
SQAuthResult.instance.isAuthorized = false
completion(authResult: SQAuthResult.instance)
}
}
let nav = UINavigationController(rootViewController: loginViewController)
let mainVC = UIApplication.sharedApplication().windows.first!.rootViewController
mainVC!.presentViewController(nav, animated: true, completion: nil)
}
func postForTokenWithCode(code: String, completion: (token: SQToken?, error: NSError?) -> Void) -> Void {
let grant_typeString: String = "" + self.grant_type
let redirect_uriString: String = "" + self.redirect_uri
let postParameters: [String: String] = ["grant_type": grant_typeString, "code": code, "redirect_uri": redirect_uriString]
SQHttpHelper.instance.execHttpRequestWithUrl(
self.tokenURL,
method: "POST",
headers: nil,
username: self.client_id,
password: self.client_secret,
token: nil,
authScope: "Basic",
parameters: postParameters) { (responseText, response, error) -> Void in
if responseText != nil {
let jsonData = responseText?.dataUsingEncoding(NSUTF8StringEncoding)
do {
if let jsonParsed = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: []) as? NSDictionary {
let token = SQToken()
if let value = jsonParsed.objectForKey("access_token") as! String? {
token.accessToken = value
}
if let value = jsonParsed.objectForKey("expires_in") as! String? {
let myDouble: NSTimeInterval = Double(value)! - 600
token.expirationDate = NSDate(timeIntervalSinceNow: myDouble)
}
if let value = jsonParsed.objectForKey("token_type") as! String? {
token.tokenType = value
}
if let value = jsonParsed.objectForKey("scope") as! String? {
token.scope = value
}
if let value = jsonParsed.objectForKey("refresh_token") as! String? {
token.refreshToken = value
}
completion(token: token, error: nil)
}
} catch let error as NSError {
print("json error" + error.localizedDescription)
completion(token: nil, error: error)
}
} else if error != nil {
print("error: ")
print(error)
print("response: ")
print(response)
completion(token: nil, error: error)
}
}
}
func postForNewTokenWithRefreshToken(refreshToken: SQToken, completion: (updatedToken: SQToken?, error: NSError?) -> Void) -> Void {
let grant_typeString: String = "" + self.refreshGrant_type
let refresh_tokenString: String = "" + refreshToken.refreshToken
let postParameters: [String: String] = ["grant_type": grant_typeString, "refresh_token": refresh_tokenString]
SQHttpHelper.instance.execHttpRequestWithUrl(
self.refreshTokenURL,
method: "POST",
headers: nil,
username: self.client_id,
password: self.client_secret,
token: nil,
authScope: "Basic",
parameters: postParameters) { (responseText, response, error) -> Void in
if responseText != nil {
let jsonData = responseText?.dataUsingEncoding(NSUTF8StringEncoding)
do {
if let jsonParsed = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: []) as? NSDictionary {
let token = SQToken()
if let value = jsonParsed.objectForKey("access_token") as! String? {
token.accessToken = value
}
if let value = jsonParsed.objectForKey("expires_in") as! String? {
let myDouble: NSTimeInterval = Double(value)! - 600
token.expirationDate = NSDate(timeIntervalSinceNow: myDouble)
}
if let value = jsonParsed.objectForKey("token_type") as! String? {
token.tokenType = value
}
if let value = jsonParsed.objectForKey("scope") as! String? {
token.scope = value
}
if let value = jsonParsed.objectForKey("refresh_token") as! String? {
token.refreshToken = value
}
completion(updatedToken: token, error: nil)
}
} catch let error as NSError {
print("json error" + error.localizedDescription)
completion(updatedToken: nil, error: error)
}
} else if error != nil {
print("error: ")
print(error)
print("response: ")
print(response)
completion(updatedToken: nil, error: error)
}
}
}
func getForSampleFilesWithToken(token: SQToken, completion: (sampleFiles: NSArray?, error: NSError?) -> Void) -> Void {
let apiUrlForSample: String = self.apiURL + self.demoPath
SQHttpHelper.instance.execHttpRequestWithUrl(
apiUrlForSample,
method: "GET",
headers: nil,
username: nil,
password: nil,
token: token.accessToken,
authScope: "Bearer",
parameters: nil) { (responseText, response, error) -> Void in
if responseText != nil {
let jsonData = responseText?.dataUsingEncoding(NSUTF8StringEncoding)
do {
if let jsonParsed = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: []) as? NSArray {
completion(sampleFiles: jsonParsed, error: nil)
}
} catch let error as NSError {
print("json error" + error.localizedDescription)
completion(sampleFiles: nil, error: error)
}
} else if error != nil {
print("error: ")
print(error)
print("response: ")
print(response)
completion(sampleFiles: nil, error: error)
}
}
}
func getForOwnFilesWithToken(token: SQToken, completion: (ownFiles: NSArray?, error: NSError?) -> Void) -> Void {
let apiUrlForFiles: String = self.apiURL + self.filesPath
SQHttpHelper.instance.execHttpRequestWithUrl(
apiUrlForFiles,
method: "GET",
headers: nil,
username: nil,
password: nil,
token: token.accessToken,
authScope: "Bearer",
parameters: nil) { (responseText, response, error) -> Void in
if responseText != nil {
let jsonData = responseText?.dataUsingEncoding(NSUTF8StringEncoding)
do {
if let jsonParsed = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: []) as? NSArray {
completion(ownFiles: jsonParsed, error: nil)
}
} catch let error as NSError {
print("json error" + error.localizedDescription)
completion(ownFiles: nil, error: error)
}
} else if error != nil {
print("error: ")
print(error)
print("response: ")
print(response)
completion(ownFiles: nil, error: error)
}
}
}
// MARK: - Request helpers (random string and value)
func randomInt() -> Int {
return Int(arc4random_uniform(100))
}
func randomStringWithLength(length: Int) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for (var i = 0; i < length; i++) {
let rand = Int(arc4random_uniform(UInt32(base.characters.count)))
randomString += "\(base[base.startIndex.advancedBy(rand)])"
}
return randomString
}
// MARK: - Activity indicator
func startActivityIndicatorWithTitle(title: String) -> Void {
dispatch_async(kMainQueue) { () -> Void in
if self.mainVC != nil {
self.strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 150, height: 50))
self.strLabel.text = title // "Getting demo data"
self.strLabel.textColor = UIColor.grayColor()
self.messageFrame = UIView(frame: CGRect(x: self.mainVC!.view.frame.midX - 100, y: self.mainVC!.view.frame.midY - 25 , width: 250, height: 40))
self.messageFrame.layer.cornerRadius = 15
self.messageFrame.backgroundColor = UIColor.clearColor()
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
self.activityIndicator.startAnimating()
self.messageFrame.addSubview(self.activityIndicator)
self.messageFrame.addSubview(self.strLabel)
self.mainVC!.view.addSubview(self.messageFrame)
}
}
}
func stopActivityIndicator() -> Void {
dispatch_async(kMainQueue) { () -> Void in
self.activityIndicator.stopAnimating()
self.messageFrame.removeFromSuperview()
}
}
}
| b0cc19f041065c28a4b313359f31fe84 | 45.997006 | 159 | 0.529337 | false | false | false | false |
openbuild-sheffield/jolt | refs/heads/master | Sources/RouteCMS/model.CMSMarkdown200Delete.swift | gpl-2.0 | 1 | import OpenbuildExtensionPerfect
public class ModelCMSMarkdown200Delete: ResponseModel200EntityDeleted, DocumentationProtocol {
public var descriptions = [
"error": "An error has occurred, will always be false",
"message": "Will always be 'Successfully deleted the entity.'",
"deleted": "Deleted object describing the Markdown entity in it's original state."
]
public init(deleted: ModelCMSMarkdown) {
super.init(deleted: deleted)
}
public static func describeRAML() -> [String] {
if let docs = ResponseDocumentation.getRAML(key: "RouteCMS.ModelCMSMarkdown200Delete") {
return docs
} else {
let entity = ModelCMSMarkdown(
cms_markdown_id: 1,
handle: "test",
markdown: "#Markdown",
html: "<h1>Markdown</h1>"
)
let model = ModelCMSMarkdown200Delete(deleted: entity)
let aMirror = Mirror(reflecting: model)
let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions)
ResponseDocumentation.setRAML(key: "RouteCMS.ModelCMSMarkdown200Delete", lines: docs)
return docs
}
}
}
extension ModelCMSMarkdown200Delete: CustomReflectable {
open var customMirror: Mirror {
return Mirror(
self,
children: [
"error": self.error,
"message": self.message,
"deleted": self.deleted
],
displayStyle: Mirror.DisplayStyle.class
)
}
} | 062c4ccc248637b59404f5eda8b558fd | 27.368421 | 103 | 0.600248 | false | false | false | false |
morizotter/ReactKit | refs/heads/master | ReactKitTests/ArrayKVOTests.swift | mit | 2 | //
// ArrayKVOTests.swift
// ReactKitTests
//
// Created by Yasuhiro Inami on 2015/03/07.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import ReactKit
import XCTest
/// `mutableArrayValueForKey()` test
class ArrayKVOTests: _TestCase
{
func testArrayKVO()
{
let expect = self.expectationWithDescription(__FUNCTION__)
let obj1 = MyObject()
let obj2 = MyObject()
let obj3 = MyObject()
// NOTE: by using `mutableArrayValueForKey()`, this stream will send each changed values **separately**
let obj1ArrayChangedStream = KVO.stream(obj1, "array")
let obj1ArrayStream = obj1ArrayChangedStream |> map { _ -> AnyObject? in obj1.array }
let obj1ArrayChangedCountStream = obj1ArrayChangedStream
|> mapAccumulate(0, { c, _ in c + 1 }) // count up
|> asStream(NSNumber?)
// REACT: obj1.array ~> obj2.array (only sends changed values in `obj1.array`)
(obj2, "array") <~ obj1ArrayChangedStream
// REACT: obj1.array ~> obj3.array (sends whole `obj1.array`)
(obj3, "array") <~ obj1ArrayStream
// REACT: arrayChangedCount ~> obj3.number (for counting)
(obj3, "number") <~ obj1ArrayChangedCountStream
// REACT: obj1.array ~> println
^{ println("[REACT] new array = \($0)") } <~ obj1ArrayChangedStream
// NOTE: call `mutableArrayValueForKey()` after `<~` binding (KVO-addObserver) is ready
let obj1ArrayProxy = obj1.mutableArrayValueForKey("array")
println("*** Start ***")
XCTAssertEqual(obj1.array.count, 0)
XCTAssertEqual(obj2.array.count, 0)
XCTAssertEqual(obj3.array.count, 0)
XCTAssertEqual(obj3.number, 0)
self.perform {
obj1ArrayProxy.addObject("a")
XCTAssertEqual(obj1.array, ["a"])
XCTAssertEqual(obj2.array, ["a"])
XCTAssertEqual(obj3.array, obj1.array)
XCTAssertEqual(obj3.number, 1)
obj1ArrayProxy.addObject("b")
XCTAssertEqual(obj1.array, ["a", "b"])
XCTAssertEqual(obj2.array, ["b"], "`obj2.array` should be replaced to last-changed value `b`.")
XCTAssertEqual(obj3.array, obj1.array)
XCTAssertEqual(obj3.number, 2)
// adding multiple values at once
// (NOTE: `obj1ArrayChangedStream` will send each values separately)
obj1ArrayProxy.addObjectsFromArray(["c", "d"])
XCTAssertEqual(obj1.array, ["a", "b", "c", "d"])
XCTAssertEqual(obj2.array, ["d"], "`obj2.array` will be replaced to `c` then `d`, so it should be replaced to last-changed value `d`.")
XCTAssertEqual(obj3.array, obj1.array)
XCTAssertEqual(obj3.number, 4, "`obj3.number` should count number of changed elements up to `4` (not `3` in this case).")
expect.fulfill()
}
self.wait()
}
func testArrayKVO_detailedStream()
{
// NOTE: this is non-async test
if self.isAsync { return }
let expect = self.expectationWithDescription(__FUNCTION__)
let obj1 = MyObject()
let detailedStream = KVO.detailedStream(obj1, "array") // NOTE: detailedStream
var lastValue: NSArray?
var lastChange: NSKeyValueChange?
var lastIndexSet: NSIndexSet?
var reactedCount = 0
// REACT
detailedStream ~> { (value: AnyObject?, change: NSKeyValueChange, indexSet: NSIndexSet?) in
// NOTE: change in `mutableArrayValueForKey()` will always send `value` as NSArray
let array = value as? NSArray
println("[REACT] new value = \(array), change=\(change), indexSet=\(indexSet)")
lastValue = array
lastChange = change
lastIndexSet = indexSet
reactedCount++
}
// NOTE: call `mutableArrayValueForKey()` after `<~` binding (KVO-addObserver) is ready
let obj1ArrayProxy = obj1.mutableArrayValueForKey("array")
println("*** Start ***")
XCTAssertEqual(obj1.array.count, 0)
XCTAssertEqual(reactedCount, 0)
self.perform {
var indexSet: NSMutableIndexSet
// addObject
obj1ArrayProxy.addObject(1)
XCTAssertTrue(obj1.array.isEqualToArray([1]))
XCTAssertEqual(lastValue!, [1])
XCTAssertTrue(lastChange! == .Insertion)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 0)))
XCTAssertEqual(lastValue!, [1])
XCTAssertEqual(reactedCount, 1)
// addObject (once more)
obj1ArrayProxy.addObject(2)
XCTAssertTrue(obj1.array.isEqualToArray([1, 2]))
XCTAssertEqual(lastValue!, [2])
XCTAssertTrue(lastChange! == .Insertion)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 1)))
XCTAssertEqual(reactedCount, 2)
// addObjectsFromArray
obj1ArrayProxy.addObjectsFromArray([3, 4])
XCTAssertTrue(obj1.array.isEqualToArray([1, 2, 3, 4]))
XCTAssertEqual(lastValue!, [4], "Only last added value `4` should be set.")
XCTAssertTrue(lastChange! == .Insertion)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 3)))
XCTAssertEqual(reactedCount, 4, "`mutableArrayValueForKey().addObjectsFromArray()` will send `3` then `4` **separately** to stream, so `reactedCount` should be incremented as +2.")
// insertObject
obj1ArrayProxy.insertObject(0, atIndex: 0)
XCTAssertTrue(obj1.array.isEqualToArray([0, 1, 2, 3, 4]))
XCTAssertEqual(lastValue!, [0])
XCTAssertTrue(lastChange! == .Insertion)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 0)))
XCTAssertEqual(reactedCount, 5)
// insertObjects
obj1ArrayProxy.insertObjects([0.5, 1.5], atIndexes: NSIndexSet(indexes: [1, 3]))
XCTAssertTrue(obj1.array.isEqualToArray([0, 0.5, 1, 1.5, 2, 3, 4]))
XCTAssertEqual(lastValue!, [0.5, 1.5])
XCTAssertTrue(lastChange! == .Insertion)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(indexes: [1, 3])))
XCTAssertEqual(reactedCount, 6, "`mutableArrayValueForKey().insertObjects()` will send `0.5` & `1.5` **together** to stream, so `reactedCount` should be incremented as +1.")
// replaceObjectAtIndex
obj1ArrayProxy.replaceObjectAtIndex(4, withObject: 2.5)
XCTAssertTrue(obj1.array.isEqualToArray([0, 0.5, 1, 1.5, 2.5, 3, 4]))
XCTAssertEqual(lastValue!, [2.5])
XCTAssertTrue(lastChange! == .Replacement)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 4)))
XCTAssertEqual(reactedCount, 7)
// replaceObjectsAtIndexes
obj1ArrayProxy.replaceObjectsAtIndexes(NSIndexSet(indexes: [5, 6]), withObjects: [3.5, 4.5])
XCTAssertTrue(obj1.array.isEqualToArray([0, 0.5, 1, 1.5, 2.5, 3.5, 4.5]))
XCTAssertEqual(lastValue!, [3.5, 4.5])
XCTAssertTrue(lastChange! == .Replacement)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(indexes: [5,6])))
XCTAssertEqual(reactedCount, 8)
// removeObjectAtIndex
obj1ArrayProxy.removeObjectAtIndex(6)
XCTAssertTrue(obj1.array.isEqualToArray([0, 0.5, 1, 1.5, 2.5, 3.5]))
XCTAssertNil(lastValue, "lastValue should be nil (deleting element `4.5`).")
XCTAssertTrue(lastChange! == .Removal)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 6)))
XCTAssertEqual(reactedCount, 9)
// removeObjectsAtIndexes
obj1ArrayProxy.removeObjectsAtIndexes(NSIndexSet(indexes: [0, 2]))
XCTAssertTrue(obj1.array.isEqualToArray([0.5, 1.5, 2.5, 3.5]))
XCTAssertNil(lastValue, "lastValue should be nil (deleting element `0` & `1`).")
XCTAssertTrue(lastChange! == .Removal)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(indexes: [0, 2])))
XCTAssertEqual(reactedCount, 10)
// exchangeObjectAtIndex
obj1ArrayProxy.exchangeObjectAtIndex(1, withObjectAtIndex: 2) // replaces `index = 1` then `index = 2`
XCTAssertTrue(obj1.array.isEqualToArray([0.5, 2.5, 1.5, 3.5]))
XCTAssertEqual(lastValue!, [1.5], "Only last replaced value `1.5` should be set.")
XCTAssertTrue(lastChange! == .Replacement)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 2)))
XCTAssertEqual(reactedCount, 12, "`mutableArrayValueForKey().exchangeObjectAtIndex()` will send `2.5` (replacing at index=1) then `1.5` (replacing at index=2) **separately** to stream, so `reactedCount` should be incremented as +2.")
// sortUsingComparator
obj1ArrayProxy.sortUsingComparator { (element1, element2) -> NSComparisonResult in
return (element2 as! NSNumber).compare(element1 as! NSNumber)
}
XCTAssertTrue(obj1.array.isEqualToArray([3.5, 2.5, 1.5, 0.5]))
XCTAssertEqual(lastValue!, [0.5], "Only last replaced value `0.5` should be set.")
XCTAssertTrue(lastChange! == .Replacement)
XCTAssertTrue(lastIndexSet!.isEqualToIndexSet(NSIndexSet(index: 3)))
XCTAssertEqual(reactedCount, 16, "`mutableArrayValueForKey().sortUsingComparator()` will send all sorted values **separately** to stream, so `reactedCount` should be incremented as number of elements i.e. +4.")
expect.fulfill()
}
self.wait()
}
func testDynamicArray()
{
let expect = self.expectationWithDescription(__FUNCTION__)
let array = [Int]()
let dynamicArray = DynamicArray(array)
let dynamicArrayStream = dynamicArray.stream()
var buffer: [DynamicArray.ChangedTuple] = []
// REACT
dynamicArrayStream ~> { (context: DynamicArray.ChangedTuple) in
buffer.append(context)
}
println("*** Start ***")
XCTAssertEqual(dynamicArray.proxy.count, 0)
self.perform {
dynamicArray.proxy.addObject(1)
XCTAssertEqual(dynamicArray.proxy, [1])
XCTAssertEqual(array, [], "`array` will not be synced with `dynamicArray` (use ForwardingDynamicArray instead).")
XCTAssertEqual(buffer.count, 1)
XCTAssertEqual(buffer[0].0! as! [NSObject], [1])
XCTAssertEqual(buffer[0].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[0].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.addObjectsFromArray([2, 3])
XCTAssertEqual(dynamicArray.proxy, [1, 2, 3])
XCTAssertEqual(buffer.count, 3, "`[2, 3]` will be separately inserted, so `buffer.count` should increment by 2.")
XCTAssertEqual(buffer[1].0! as! [NSObject], [2])
XCTAssertEqual(buffer[1].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[1].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 1)))
XCTAssertEqual(buffer[2].0! as! [NSObject], [3])
XCTAssertEqual(buffer[2].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[2].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.insertObject(0, atIndex: 0)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2, 3])
XCTAssertEqual(buffer.count, 4)
XCTAssertEqual(buffer[3].0! as! [NSObject], [0])
XCTAssertEqual(buffer[3].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[3].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.replaceObjectAtIndex(2, withObject: 2.5)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2.5, 3])
XCTAssertEqual(buffer.count, 5)
XCTAssertEqual(buffer[4].0! as! [NSObject], [2.5])
XCTAssertEqual(buffer[4].1 as NSKeyValueChange, NSKeyValueChange.Replacement)
XCTAssertTrue((buffer[4].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.removeObjectAtIndex(2)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 3])
XCTAssertEqual(buffer.count, 6)
XCTAssertNil(buffer[5].0, "Deletion will send nil as changed value.")
XCTAssertEqual(buffer[5].1 as NSKeyValueChange, NSKeyValueChange.Removal)
XCTAssertTrue((buffer[5].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
expect.fulfill()
}
self.wait()
}
/// ForwardingDynamicArray + KVC-compliant model's array
func testForwardingDynamicArray_model()
{
let expect = self.expectationWithDescription(__FUNCTION__)
let obj1 = MyObject()
let dynamicArray = ForwardingDynamicArray(object: obj1, keyPath: "array")
let dynamicArrayStream = dynamicArray.stream()
var buffer: [DynamicArray.ChangedTuple] = []
// REACT
dynamicArrayStream ~> { (context: DynamicArray.ChangedTuple) in
buffer.append(context)
}
println("*** Start ***")
XCTAssertEqual(dynamicArray.proxy.count, 0)
self.perform {
dynamicArray.proxy.addObject(1)
XCTAssertEqual(dynamicArray.proxy, [1])
XCTAssertEqual(obj1.array, dynamicArray.proxy, "`obj1.array` will sync with `dynamicArray.proxy`.")
XCTAssertEqual(buffer.count, 1)
XCTAssertEqual(buffer[0].0! as! [NSObject], [1])
XCTAssertEqual(buffer[0].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[0].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.addObjectsFromArray([2, 3])
XCTAssertEqual(dynamicArray.proxy, [1, 2, 3])
XCTAssertEqual(obj1.array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 3, "`[2, 3]` will be separately inserted, so `buffer.count` should increment by 2.")
XCTAssertEqual(buffer[1].0! as! [NSObject], [2])
XCTAssertEqual(buffer[1].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[1].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 1)))
XCTAssertEqual(buffer[2].0! as! [NSObject], [3])
XCTAssertEqual(buffer[2].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[2].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.insertObject(0, atIndex: 0)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2, 3])
XCTAssertEqual(obj1.array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 4)
XCTAssertEqual(buffer[3].0! as! [NSObject], [0])
XCTAssertEqual(buffer[3].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[3].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.replaceObjectAtIndex(2, withObject: 2.5)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2.5, 3])
XCTAssertEqual(obj1.array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 5)
XCTAssertEqual(buffer[4].0! as! [NSObject], [2.5])
XCTAssertEqual(buffer[4].1 as NSKeyValueChange, NSKeyValueChange.Replacement)
XCTAssertTrue((buffer[4].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.removeObjectAtIndex(2)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 3])
XCTAssertEqual(obj1.array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 6)
XCTAssertNil(buffer[5].0, "Deletion will send nil as changed value.")
XCTAssertEqual(buffer[5].1 as NSKeyValueChange, NSKeyValueChange.Removal)
XCTAssertTrue((buffer[5].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
expect.fulfill()
}
self.wait()
}
/// ForwardingDynamicArray + raw NSMutableArray
func testForwardingDynamicArray_mutableArray()
{
let expect = self.expectationWithDescription(__FUNCTION__)
let array = NSMutableArray()
let dynamicArray = ForwardingDynamicArray(original: array)
let dynamicArrayStream = dynamicArray.stream()
var buffer: [DynamicArray.ChangedTuple] = []
// REACT
dynamicArrayStream ~> { (context: DynamicArray.ChangedTuple) in
buffer.append(context)
}
println("*** Start ***")
XCTAssertEqual(dynamicArray.proxy.count, 0)
self.perform {
dynamicArray.proxy.addObject(1)
XCTAssertEqual(dynamicArray.proxy, [1])
XCTAssertEqual(array, dynamicArray.proxy, "`obj1.array` will sync with `dynamicArray.proxy`.")
XCTAssertEqual(buffer.count, 1)
XCTAssertEqual(buffer[0].0! as! [NSObject], [1])
XCTAssertEqual(buffer[0].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[0].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.addObjectsFromArray([2, 3])
XCTAssertEqual(dynamicArray.proxy, [1, 2, 3])
XCTAssertEqual(array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 3, "`[2, 3]` will be separately inserted, so `buffer.count` should increment by 2.")
XCTAssertEqual(buffer[1].0! as! [NSObject], [2])
XCTAssertEqual(buffer[1].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[1].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 1)))
XCTAssertEqual(buffer[2].0! as! [NSObject], [3])
XCTAssertEqual(buffer[2].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[2].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.insertObject(0, atIndex: 0)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2, 3])
XCTAssertEqual(array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 4)
XCTAssertEqual(buffer[3].0! as! [NSObject], [0])
XCTAssertEqual(buffer[3].1 as NSKeyValueChange, NSKeyValueChange.Insertion)
XCTAssertTrue((buffer[3].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 0)))
dynamicArray.proxy.replaceObjectAtIndex(2, withObject: 2.5)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 2.5, 3])
XCTAssertEqual(array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 5)
XCTAssertEqual(buffer[4].0! as! [NSObject], [2.5])
XCTAssertEqual(buffer[4].1 as NSKeyValueChange, NSKeyValueChange.Replacement)
XCTAssertTrue((buffer[4].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
dynamicArray.proxy.removeObjectAtIndex(2)
XCTAssertEqual(dynamicArray.proxy, [0, 1, 3])
XCTAssertEqual(array, dynamicArray.proxy)
XCTAssertEqual(buffer.count, 6)
XCTAssertNil(buffer[5].0, "Deletion will send nil as changed value.")
XCTAssertEqual(buffer[5].1 as NSKeyValueChange, NSKeyValueChange.Removal)
XCTAssertTrue((buffer[5].2 as NSIndexSet).isEqualToIndexSet(NSIndexSet(index: 2)))
expect.fulfill()
}
self.wait()
}
}
class AsyncArrayKVOTests: ArrayKVOTests
{
override var isAsync: Bool { return true }
} | 4481bf22cb3b533add75426778629bcc | 44.947368 | 245 | 0.600019 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | SignalServiceKit/src/Util/ViewOnceMessages.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalCoreKit
@objc
public class ViewOnceMessages: NSObject {
// MARK: - Dependencies
private class var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
private class var messageSenderJobQueue: MessageSenderJobQueue {
return SSKEnvironment.shared.messageSenderJobQueue
}
private class var tsAccountManager: TSAccountManager {
return TSAccountManager.sharedInstance()
}
// MARK: - Events
private class func nowMs() -> UInt64 {
return NSDate.ows_millisecondTimeStamp()
}
@objc
public class func appDidBecomeReady() {
AssertIsOnMainThread()
DispatchQueue.global().async {
self.checkForAutoCompletion()
}
}
// "Check for auto-completion", e.g. complete messages whether or
// not they have been read after N days. Also complete outgoing
// sent messages. We need to repeat this check periodically while
// the app is running.
private class func checkForAutoCompletion() {
// Find all view-once messages which are not yet complete.
// Complete messages if necessary.
databaseStorage.write { (transaction) in
let messages = AnyViewOnceMessageFinder().allMessagesWithViewOnceMessage(transaction: transaction)
for message in messages {
completeIfNecessary(message: message, transaction: transaction)
}
}
// We need to "check for auto-completion" once per day.
DispatchQueue.global().asyncAfter(wallDeadline: .now() + kDayInterval) {
self.checkForAutoCompletion()
}
}
@objc
public class func completeIfNecessary(message: TSMessage,
transaction: SDSAnyWriteTransaction) {
guard message.isViewOnceMessage,
!message.isViewOnceComplete else {
return
}
// If message should auto-complete, complete.
guard !shouldMessageAutoComplete(message) else {
markAsComplete(message: message,
sendSyncMessages: true,
transaction: transaction)
return
}
// If outgoing message and is "sent", complete.
guard !isOutgoingSent(message: message) else {
markAsComplete(message: message,
sendSyncMessages: true,
transaction: transaction)
return
}
// Message should not yet complete.
}
private class func isOutgoingSent(message: TSMessage) -> Bool {
guard message.isViewOnceMessage else {
owsFailDebug("Unexpected message.")
return false
}
// If outgoing message and is "sent", complete.
guard let outgoingMessage = message as? TSOutgoingMessage else {
return false
}
guard outgoingMessage.messageState == .sent else {
return false
}
return true
}
// We auto-complete messages after 30 days, even if the user hasn't seen them.
private class func shouldMessageAutoComplete(_ message: TSMessage) -> Bool {
let autoCompleteDeadlineMs = min(message.timestamp, message.receivedAtTimestamp) + 30 * kDayInMs
return nowMs() >= autoCompleteDeadlineMs
}
@objc
public class func markAsComplete(message: TSMessage,
sendSyncMessages: Bool,
transaction: SDSAnyWriteTransaction) {
guard message.isViewOnceMessage else {
owsFailDebug("Not a view-once message.")
return
}
guard !message.isViewOnceComplete else {
// Already completed, no need to complete again.
return
}
message.updateWithViewOnceCompleteAndRemoveRenderableContent(with: transaction)
if sendSyncMessages {
sendSyncMessage(forMessage: message, transaction: transaction)
}
}
// MARK: - Sync Messages
private class func sendSyncMessage(forMessage message: TSMessage,
transaction: SDSAnyWriteTransaction) {
guard let senderAddress = senderAddress(forMessage: message) else {
owsFailDebug("Could not send sync message; no local number.")
return
}
guard let thread = TSAccountManager.getOrCreateLocalThread(transaction: transaction) else {
owsFailDebug("Missing thread.")
return
}
let messageIdTimestamp: UInt64 = message.timestamp
let readTimestamp: UInt64 = nowMs()
let syncMessage = OWSViewOnceMessageReadSyncMessage(thread: thread,
senderAddress: senderAddress,
messageIdTimestamp: messageIdTimestamp,
readTimestamp: readTimestamp)
messageSenderJobQueue.add(message: syncMessage.asPreparer, transaction: transaction)
}
@objc
public class func processIncomingSyncMessage(_ message: SSKProtoSyncMessageViewOnceOpen,
envelope: SSKProtoEnvelope,
transaction: SDSAnyWriteTransaction) {
if tryToApplyIncomingSyncMessage(message,
envelope: envelope,
transaction: transaction) {
return
}
// Unpack and verify the proto & envelope contents.
guard let senderAddress = message.senderAddress, senderAddress.isValid else {
owsFailDebug("Invalid senderAddress.")
return
}
let messageIdTimestamp: UInt64 = message.timestamp
guard messageIdTimestamp > 0,
SDS.fitsInInt64(messageIdTimestamp) else {
owsFailDebug("Invalid messageIdTimestamp.")
return
}
let readTimestamp: UInt64 = envelope.timestamp
guard readTimestamp > 0,
SDS.fitsInInt64(readTimestamp) else {
owsFailDebug("Invalid readTimestamp.")
return
}
// Persist this "view-once read receipt".
let key = readReceiptKey(senderAddress: senderAddress, messageIdTimestamp: messageIdTimestamp)
store.setUInt64(readTimestamp, key: key, transaction: transaction)
}
// Returns true IFF the read receipt is applied to an existing message.
private class func tryToApplyIncomingSyncMessage(_ message: SSKProtoSyncMessageViewOnceOpen,
envelope: SSKProtoEnvelope,
transaction: SDSAnyWriteTransaction) -> Bool {
let messageSenderAddress = message.senderAddress
let messageIdTimestamp: UInt64 = message.timestamp
guard messageIdTimestamp > 0,
SDS.fitsInInt64(messageIdTimestamp) else {
owsFailDebug("Invalid messageIdTimestamp.")
return false
}
let filter = { (interaction: TSInteraction) -> Bool in
guard interaction.timestamp == messageIdTimestamp else {
owsFailDebug("Timestamps don't match: \(interaction.timestamp) != \(messageIdTimestamp)")
return false
}
guard let message = interaction as? TSMessage else {
return false
}
guard let senderAddress = senderAddress(forMessage: message) else {
owsFailDebug("Could not process sync message; no local number.")
return false
}
guard senderAddress == messageSenderAddress else {
return false
}
guard message.isViewOnceMessage else {
return false
}
return true
}
let interactions: [TSInteraction]
do {
interactions = try InteractionFinder.interactions(withTimestamp: messageIdTimestamp, filter: filter, transaction: transaction)
} catch {
owsFailDebug("Couldn't find interactions: \(error)")
return false
}
guard interactions.count > 0 else {
return false
}
if interactions.count > 1 {
owsFailDebug("More than one message from the same sender with the same timestamp found.")
}
for interaction in interactions {
guard let message = interaction as? TSMessage else {
owsFailDebug("Invalid interaction: \(type(of: interaction))")
continue
}
// Mark as complete.
markAsComplete(message: message,
sendSyncMessages: false,
transaction: transaction)
}
return true
}
@objc
public class func applyEarlyReadReceipts(forIncomingMessage message: TSIncomingMessage,
transaction: SDSAnyWriteTransaction) {
guard message.isViewOnceMessage else {
return
}
guard let senderAddress = senderAddress(forMessage: message) else {
owsFailDebug("Could not apply early read receipts; no local number.")
return
}
let messageIdTimestamp: UInt64 = message.timestamp
// Check for persisted "view-once read receipt".
let key = readReceiptKey(senderAddress: senderAddress, messageIdTimestamp: messageIdTimestamp)
guard store.hasValue(forKey: key, transaction: transaction) else {
// No early read receipt applies, abort.
return
}
// Remove persisted "view-once read receipt".
store.removeValue(forKey: key, transaction: transaction)
// Mark as complete.
markAsComplete(message: message,
sendSyncMessages: false,
transaction: transaction)
}
private class func senderAddress(forMessage message: TSMessage) -> SignalServiceAddress? {
if let incomingMessage = message as? TSIncomingMessage {
return incomingMessage.authorAddress
} else if message as? TSOutgoingMessage != nil {
guard let localAddress = tsAccountManager.localAddress else {
owsFailDebug("Could not process sync message; no local number.")
return nil
}
// We also need to send and receive "per-message expiration read" sync
// messages for outgoing messages, unlike normal read receipts.
return localAddress
} else {
owsFailDebug("Unexpected message type.")
return nil
}
}
private static let store = SDSKeyValueStore(collection: "viewOnceMessages")
private class func readReceiptKey(senderAddress: SignalServiceAddress,
messageIdTimestamp: UInt64) -> String {
return "\(senderAddress.stringForDisplay).\(messageIdTimestamp)"
}
}
// MARK: -
public protocol ViewOnceMessageFinder {
associatedtype ReadTransaction
typealias EnumerateTSMessageBlock = (TSMessage, UnsafeMutablePointer<ObjCBool>) -> Void
func allMessagesWithViewOnceMessage(transaction: ReadTransaction) -> [TSMessage]
func enumerateAllIncompleteViewOnceMessages(transaction: ReadTransaction, block: @escaping EnumerateTSMessageBlock)
}
// MARK: -
extension ViewOnceMessageFinder {
public func allMessagesWithViewOnceMessage(transaction: ReadTransaction) -> [TSMessage] {
var result: [TSMessage] = []
self.enumerateAllIncompleteViewOnceMessages(transaction: transaction) { message, _ in
result.append(message)
}
return result
}
}
// MARK: -
public class AnyViewOnceMessageFinder {
lazy var grdbAdapter = GRDBViewOnceMessageFinder()
lazy var yapAdapter = YAPDBViewOnceMessageFinder()
}
// MARK: -
extension AnyViewOnceMessageFinder: ViewOnceMessageFinder {
public func enumerateAllIncompleteViewOnceMessages(transaction: SDSAnyReadTransaction, block: @escaping EnumerateTSMessageBlock) {
switch transaction.readTransaction {
case .grdbRead(let grdbRead):
grdbAdapter.enumerateAllIncompleteViewOnceMessages(transaction: grdbRead, block: block)
case .yapRead(let yapRead):
yapAdapter.enumerateAllIncompleteViewOnceMessages(transaction: yapRead, block: block)
}
}
}
// MARK: -
class GRDBViewOnceMessageFinder: ViewOnceMessageFinder {
func enumerateAllIncompleteViewOnceMessages(transaction: GRDBReadTransaction, block: @escaping EnumerateTSMessageBlock) {
let sql = """
SELECT * FROM \(InteractionRecord.databaseTableName)
WHERE \(interactionColumn: .isViewOnceMessage) IS NOT NULL
AND \(interactionColumn: .isViewOnceMessage) == TRUE
AND \(interactionColumn: .isViewOnceComplete) IS NOT NULL
AND \(interactionColumn: .isViewOnceComplete) == FALSE
"""
let cursor = TSInteraction.grdbFetchCursor(sql: sql,
transaction: transaction)
var stop: ObjCBool = false
// GRDB TODO make cursor.next fail hard to remove this `try!`
while let next = try! cursor.next() {
guard let message = next as? TSMessage else {
owsFailDebug("expecting message but found: \(next)")
return
}
guard message.isViewOnceMessage,
!message.isViewOnceComplete else {
owsFailDebug("expecting incomplete view-once message but found: \(message)")
return
}
block(message, &stop)
if stop.boolValue {
return
}
}
}
}
// MARK: -
class YAPDBViewOnceMessageFinder: ViewOnceMessageFinder {
public func enumerateAllIncompleteViewOnceMessages(transaction: YapDatabaseReadTransaction, block: @escaping EnumerateTSMessageBlock) {
guard let dbView = TSDatabaseView.incompleteViewOnceMessagesDatabaseView(transaction) as? YapDatabaseViewTransaction else {
owsFailDebug("Couldn't load db view.")
return
}
dbView.safe_enumerateKeysAndObjects(inGroup: TSIncompleteViewOnceMessagesGroup, extensionName: TSIncompleteViewOnceMessagesDatabaseViewExtensionName) { (_: String, _: String, object: Any, _: UInt, stopPointer: UnsafeMutablePointer<ObjCBool>) in
guard let message = object as? TSMessage else {
owsFailDebug("Invalid database entity: \(type(of: object)).")
return
}
guard message.isViewOnceMessage,
!message.isViewOnceComplete else {
owsFailDebug("expecting incomplete view-once message but found: \(message)")
return
}
block(message, stopPointer)
}
}
}
| dcfa37d460ee4a99ee575d4d81017bcb | 37.438287 | 252 | 0.612779 | false | false | false | false |
MessageKit/MessageKit | refs/heads/main | Example/Sources/Models/CustomTextLayoutSizeCalculator.swift | mit | 1 | //
// CustomTextMessageSizeCalculator.swift
// ChatExample
//
// Created by Vignesh J on 30/04/21.
// Copyright © 2021 MessageKit. All rights reserved.
//
import MessageKit
import UIKit
class CustomTextLayoutSizeCalculator: CustomLayoutSizeCalculator {
var messageLabelFont = UIFont.preferredFont(forTextStyle: .body)
var cellMessageContainerRightSpacing: CGFloat = 16
override func messageContainerSize(
for message: MessageType,
at indexPath: IndexPath)
-> CGSize
{
let size = super.messageContainerSize(
for: message,
at: indexPath)
let labelSize = messageLabelSize(
for: message,
at: indexPath)
let selfWidth = labelSize.width +
cellMessageContentHorizontalPadding +
cellMessageContainerRightSpacing
let width = max(selfWidth, size.width)
let height = size.height + labelSize.height
return CGSize(
width: width,
height: height)
}
func messageLabelSize(
for message: MessageType,
at _: IndexPath)
-> CGSize
{
let attributedText: NSAttributedString
let textMessageKind = message.kind
switch textMessageKind {
case .attributedText(let text):
attributedText = text
case .text(let text), .emoji(let text):
attributedText = NSAttributedString(string: text, attributes: [.font: messageLabelFont])
default:
fatalError("messageLabelSize received unhandled MessageDataType: \(message.kind)")
}
let maxWidth = messageContainerMaxWidth -
cellMessageContentHorizontalPadding -
cellMessageContainerRightSpacing
return attributedText.size(consideringWidth: maxWidth)
}
func messageLabelFrame(
for message: MessageType,
at indexPath: IndexPath)
-> CGRect
{
let origin = CGPoint(
x: cellMessageContentHorizontalPadding / 2,
y: cellMessageContentVerticalPadding / 2)
let size = messageLabelSize(
for: message,
at: indexPath)
return CGRect(
origin: origin,
size: size)
}
}
| d1c88a19a5d27211173d9c14d7f1e660 | 24.846154 | 94 | 0.700397 | false | false | false | false |
alblue/swift | refs/heads/master | test/SILOptimizer/static_strings.swift | apache-2.0 | 16 | // RUN: %target-swift-frontend -O -emit-ir %s | %FileCheck %s
// RUN: %target-swift-frontend -Osize -emit-ir %s | %FileCheck %s
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -module-name=test %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT
// REQUIRES: executable_test,swift_stdlib_no_asserts,optimized_stdlib
// REQUIRES: CPU=arm64 || CPU=x86_64
// This is an end-to-end test to ensure that the optimizer generates
// optimal code for static String variables.
public struct S {
// CHECK: {{^@"}}[[SMALL:.*smallstr.*pZ]]" ={{.*}} global {{.*}} inttoptr
public static let smallstr = "abc123a"
// CHECK: {{^@"}}[[LARGE:.*largestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
public static let largestr = "abc123asd3sdj3basfasdf"
// CHECK: {{^@"}}[[UNICODE:.*unicodestr.*pZ]]" ={{.*}} global {{.*}} inttoptr {{.*}} add
public static let unicodestr = "❄️gastroperiodyni"
}
// unsafeMutableAddressor for S.smallstr
// CHECK: define {{.*smallstr.*}}u"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}} @"[[SMALL]]"
// CHECK-NEXT: }
// getter for S.smallstr
// CHECK: define {{.*smallstr.*}}gZ"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
// unsafeMutableAddressor for S.largestr
// CHECK: define {{.*largestr.*}}u"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}} @"[[LARGE]]"
// CHECK-NEXT: }
// getter for S.largestr
// CHECK: define {{.*largestr.*}}gZ"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
// unsafeMutableAddressor for S.unicodestr
// CHECK: define {{.*unicodestr.*}}u"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}} @"[[UNICODE]]"
// CHECK-NEXT: }
// getter for S.unicodestr
// CHECK: define {{.*unicodestr.*}}gZ"
// CHECK-NEXT: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
// CHECK-LABEL: define {{.*}}get_smallstr
// CHECK: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
@inline(never)
public func get_smallstr() -> String {
return S.smallstr
}
// CHECK-LABEL: define {{.*}}get_largestr
// CHECK: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
@inline(never)
public func get_largestr() -> String {
return S.largestr
}
// CHECK-LABEL: define {{.*}}get_unicodestr
// CHECK: entry:
// CHECK-NEXT: ret {{.*}}
// CHECK-NEXT: }
@inline(never)
public func get_unicodestr() -> String {
return S.unicodestr
}
// Also check if the generated code is correct.
// CHECK-OUTPUT: abc123a
// CHECK-OUTPUT: abc123asd3sdj3basfasdf
// CHECK-OUTPUT: ❄️gastroperiodyni
print(get_smallstr())
print(get_largestr())
print(get_unicodestr())
// Really load the globals from their addresses.
@_optimize(none)
func print_strings_from_addressors() {
print(S.smallstr)
print(S.largestr)
print(S.unicodestr)
}
// CHECK-OUTPUT: abc123a
// CHECK-OUTPUT: abc123asd3sdj3basfasdf
// CHECK-OUTPUT: ❄️gastroperiodyni
print_strings_from_addressors()
| d98449cbeedca56a6f0ac05639c86e7b | 26.149533 | 90 | 0.634768 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Scenes/Animate 3D graphic/Animate3DGraphicViewController.swift | apache-2.0 | 1 | //
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class Animate3DGraphicViewController: UIViewController {
@IBOutlet private var sceneView: AGSSceneView!
@IBOutlet private var mapView: AGSMapView!
@IBOutlet private var playBBI: UIBarButtonItem!
private var missionFileNames = ["GrandCanyon.csv", "Hawaii.csv", "Pyrenees.csv", "Snowdon.csv"]
private var selectedMissionIndex = 0
private var sceneGraphicsOverlay = AGSGraphicsOverlay()
private var mapGraphicsOverlay = AGSGraphicsOverlay()
private var frames: [Frame] = []
private var planeModelGraphic: AGSGraphic?
private var triangleGraphic: AGSGraphic?
private var routeGraphic: AGSGraphic?
private var currentFrameIndex = 0
private var animationTimer: Timer?
private var animationSpeed = 50
private var orbitGeoElementCameraController: AGSOrbitGeoElementCameraController?
private weak var planeStatsViewController: PlaneStatsViewController?
private weak var missionSettingsViewController: MissionSettingsViewController?
private var isAnimating = false {
didSet {
playBBI?.title = isAnimating ? "Pause" : "Play"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["Animate3DGraphicViewController", "MissionSettingsViewController", "CameraSettingsViewController", "PlaneStatsViewController", "OptionsTableViewController"]
// map
let map = AGSMap(basemapStyle: .arcGISStreets)
mapView.map = map
mapView.interactionOptions.isEnabled = false
mapView.layer.borderColor = UIColor.white.cgColor
mapView.layer.borderWidth = 2
// hide attribution text for map view
mapView.isAttributionTextVisible = false
// Initalize scene with imagery basemap style.
let scene = AGSScene(basemapStyle: .arcGISImagery)
// assign scene to scene view
sceneView.scene = scene
/// The url of the Terrain 3D ArcGIS REST Service.
let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
// elevation source
let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)
// surface
let surface = AGSSurface()
surface.elevationSources.append(elevationSource)
scene.baseSurface = surface
// graphics overlay for scene view
sceneGraphicsOverlay.sceneProperties?.surfacePlacement = .absolute
sceneView.graphicsOverlays.add(sceneGraphicsOverlay)
// renderer for scene graphics overlay
let renderer = AGSSimpleRenderer()
// expressions
renderer.sceneProperties?.headingExpression = "[HEADING]"
renderer.sceneProperties?.pitchExpression = "[PITCH]"
renderer.sceneProperties?.rollExpression = "[ROLL]"
// set renderer on the overlay
sceneGraphicsOverlay.renderer = renderer
// graphics overlay for map view
mapView.graphicsOverlays.add(mapGraphicsOverlay)
// renderer for map graphics overlay
let renderer2D = AGSSimpleRenderer()
renderer2D.rotationExpression = "[ANGLE]"
mapGraphicsOverlay.renderer = renderer2D
// route graphic
let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: .blue, width: 1)
let routeGraphic = AGSGraphic(geometry: nil, symbol: lineSymbol, attributes: nil)
self.routeGraphic = routeGraphic
mapGraphicsOverlay.graphics.add(routeGraphic)
addPlane2D()
// add the plane model
addPlane3D()
// setup camera to follow the plane
setupCamera()
// select the first mission by default
changeMissionAction()
}
private func addPlane2D() {
let triangleSymbol = AGSSimpleMarkerSymbol(style: .triangle, color: .red, size: 10)
let triangleGraphic = AGSGraphic(geometry: nil, symbol: triangleSymbol, attributes: nil)
self.triangleGraphic = triangleGraphic
mapGraphicsOverlay.graphics.add(triangleGraphic)
}
private func addPlane3D() {
// model symbol
let planeModelSymbol = AGSModelSceneSymbol(name: "Bristol", extension: "dae", scale: 20)
planeModelSymbol.anchorPosition = .center
// arbitrary geometry for time being, the geometry will update with animation
let point = AGSPoint(x: 0, y: 0, z: 0, spatialReference: .wgs84())
// create graphic for the model
let planeModelGraphic = AGSGraphic()
self.planeModelGraphic = planeModelGraphic
planeModelGraphic.geometry = point
planeModelGraphic.symbol = planeModelSymbol
// add graphic to the graphics overlay
sceneGraphicsOverlay.graphics.add(planeModelGraphic)
}
private func setupCamera() {
guard let planeModelGraphic = planeModelGraphic else {
return
}
// AGSOrbitGeoElementCameraController to follow plane graphic
// initialize object specifying the target geo element and distance to keep from it
let orbitGeoElementCameraController = AGSOrbitGeoElementCameraController(targetGeoElement: planeModelGraphic, distance: 1000)
self.orbitGeoElementCameraController = orbitGeoElementCameraController
// set camera to align its heading with the model
orbitGeoElementCameraController.isAutoHeadingEnabled = true
// will keep the camera still while the model pitches or rolls
orbitGeoElementCameraController.isAutoPitchEnabled = false
orbitGeoElementCameraController.isAutoRollEnabled = false
// min and max distance values between the model and the camera
orbitGeoElementCameraController.minCameraDistance = 500
orbitGeoElementCameraController.maxCameraDistance = 8000
// set the camera controller on scene view
sceneView.cameraController = orbitGeoElementCameraController
}
private func loadMissionData(_ name: String) {
// get the path of the specified file in the bundle
if let path = Bundle.main.path(forResource: name, ofType: nil) {
// get content of the file
if let content = try? String(contentsOfFile: path) {
// split content into array of lines separated by new line character
// each line is one frame
let lines = content.components(separatedBy: CharacterSet.newlines)
// create a frame object for each line
frames = lines.map { (line) -> Frame in
let details = line.components(separatedBy: ",")
precondition(details.count == 6)
let position = AGSPoint(x: Double(details[0])!,
y: Double(details[1])!,
z: Double(details[2])!,
spatialReference: .wgs84())
// load position, heading, pitch and roll for each frame
return Frame(position: position,
heading: Measurement(value: Double(details[3])!, unit: UnitAngle.degrees),
pitch: Measurement(value: Double(details[4])!, unit: UnitAngle.degrees),
roll: Measurement(value: Double(details[5])!, unit: UnitAngle.degrees))
}
}
} else {
print("Mission file not found")
}
}
private func startAnimation() {
// invalidate timer to stop previous ongoing animation
self.animationTimer?.invalidate()
// duration or interval
let duration = 1 / Double(animationSpeed)
// new timer
let animationTimer = Timer(timeInterval: duration, repeats: true) { [weak self] _ in
self?.animate()
}
self.animationTimer = animationTimer
RunLoop.main.add(animationTimer, forMode: .common)
}
private func animate() {
// validations
guard !frames.isEmpty,
let planeModelGraphic = planeModelGraphic,
let triangleGraphic = triangleGraphic else {
return
}
// if animation is complete
if currentFrameIndex >= frames.count {
// invalidate timer
animationTimer?.invalidate()
// update state
isAnimating = false
// reset index
currentFrameIndex = 0
return
}
// else get the frame
let frame = frames[currentFrameIndex]
// update the properties on the model
planeModelGraphic.geometry = frame.position
planeModelGraphic.attributes["HEADING"] = frame.heading.value
planeModelGraphic.attributes["PITCH"] = frame.pitch.value
planeModelGraphic.attributes["ROLL"] = frame.roll.value
// 2D plane
triangleGraphic.geometry = frame.position
// set viewpoint for map view
let viewpoint = AGSViewpoint(center: frame.position, scale: 100000, rotation: 360 + frame.heading.value)
mapView.setViewpoint(viewpoint)
// update progress
missionSettingsViewController?.progress = Float(currentFrameIndex) / Float(frames.count)
// update stats
planeStatsViewController?.frame = frame
// increment current frame index
currentFrameIndex += 1
}
// MARK: - Actions
@IBAction func changeMissionAction() {
// invalidate timer
animationTimer?.invalidate()
// set play button
isAnimating = false
// new mission name
let missionFileName = missionFileNames[selectedMissionIndex]
loadMissionData(missionFileName)
// create a polyline from position in each frame to be used as path
let points = frames.map { (frame) -> AGSPoint in
return frame.position
}
let polylineBuilder = AGSPolylineBuilder(points: points)
routeGraphic?.geometry = polylineBuilder.toGeometry()
// set current frame to zero
currentFrameIndex = 0
// animate to first frame
animate()
}
@IBAction func playAction(sender: UIBarButtonItem) {
if isAnimating {
animationTimer?.invalidate()
} else {
startAnimation()
}
isAnimating.toggle()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// dismiss any shown view controllers
dismiss(animated: false)
if let controller = segue.destination as? CameraSettingsViewController {
controller.orbitGeoElementCameraController = orbitGeoElementCameraController
// pop over settings
controller.presentationController?.delegate = self
// preferred content size
if traitCollection.horizontalSizeClass == .regular,
traitCollection.verticalSizeClass == .regular {
controller.preferredContentSize = CGSize(width: 300, height: 380)
} else {
controller.preferredContentSize = CGSize(width: 300, height: 250)
}
} else if let planeStatsViewController = segue.destination as? PlaneStatsViewController {
self.planeStatsViewController = planeStatsViewController
let frame = frames[currentFrameIndex]
// Update stats.
planeStatsViewController.frame = frame
// pop over settings
planeStatsViewController.presentationController?.delegate = self
} else if let navController = segue.destination as? UINavigationController,
let controller = navController.viewControllers.first as? MissionSettingsViewController {
self.missionSettingsViewController = controller
// initial values
controller.missionFileNames = missionFileNames
controller.selectedMissionIndex = selectedMissionIndex
controller.animationSpeed = animationSpeed
controller.progress = Float(currentFrameIndex) / Float(frames.count)
// pop over settings
navController.presentationController?.delegate = self
controller.preferredContentSize = CGSize(width: 300, height: 200)
controller.delegate = self
}
}
}
extension Animate3DGraphicViewController: MissionSettingsViewControllerDelegate {
func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didSelectMissionAtIndex index: Int) {
selectedMissionIndex = index
changeMissionAction()
}
func missionSettingsViewController(_ missionSettingsViewController: MissionSettingsViewController, didChangeSpeed speed: Int) {
animationSpeed = speed
if isAnimating {
animationTimer?.invalidate()
startAnimation()
}
}
}
extension Animate3DGraphicViewController: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// for popover or non modal presentation
return .none
}
}
struct Frame {
let position: AGSPoint
let heading: Measurement<UnitAngle>
let pitch: Measurement<UnitAngle>
let roll: Measurement<UnitAngle>
init(position: AGSPoint, heading: Measurement<UnitAngle>, pitch: Measurement<UnitAngle>, roll: Measurement<UnitAngle>) {
self.position = position
self.heading = heading
self.pitch = pitch
self.roll = roll
}
var altitude: Measurement<UnitLength> {
return Measurement(value: position.z, unit: UnitLength.meters)
}
}
| 7e8b95e54530b5c10ffaeb5e9b880065 | 38.582245 | 241 | 0.636873 | false | false | false | false |
acastano/swift-bootstrap | refs/heads/master | foundationkit/Sources/Classes/Version/VersionHelpers.swift | apache-2.0 | 1 |
import Foundation
typealias BoolBoolBoolErrorCompletion = (Bool, Bool, Bool, NSError?) -> ()
open class VersionHelpers {
open class func newAppAvailable(_ newVersion:String?, newBuild: String?) -> Bool {
var new = false
if let newVersion = newVersion, let newBuild = newBuild {
let locale = Locale(identifier:"en_GB")
let options = NSString.CompareOptions.numeric
let currentVersion = Device.currentVersion()
let isNewVersion = newVersion.compare(currentVersion, options:options, range:nil, locale:locale) == .orderedDescending
new = isNewVersion
if new == false && (newVersion.compare(currentVersion, options:options, range:nil, locale:locale) == .orderedSame) {
let currentBuild = Device.currentBuild()
let newBuild = newBuild.compare(currentBuild, options:options, range:nil, locale:locale) == .orderedDescending
new = newBuild
}
}
return new
}
}
| 07c0e06043387400786175bb5fe2b099 | 29.317073 | 130 | 0.527755 | false | false | false | false |
appcorn/cordova-plugin-siths-manager | refs/heads/master | src/ios/SITHSManager/SITHSManager.swift | mit | 1 | //
// Written by Martin Alléus, Appcorn AB, [email protected]
//
// Copyright 2017 Svensk e-identitet AB
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
import ExternalAccessory
/**
The current state of the card reader.
- Unknown: The state of the reader has not yet been determined. This is the initial state.
- Error: An error has occured. The specifics of the error is represented as `SITHSManagerError` in the `error`
associated value.
- ReaderDisconnected: There is no card reader connected.
- ReaderConnected: There is a reader connected, but no inserted card.
- UnknownCardInserted: There is a smart card inserted to a connected reader, but it does not appear to be a SITHS Card.
- ReadingFromCard: The SITHS Manager is currently reading from an inserted SITHS card, parsing any certificates found.
- CardWithoutCertificatesInserted: There is a SITHS Card inserted to a connected reader, but the SITHS Manager failed to read any
certificates.
- CardInserted: The reader is connected, and there is a SITHS card, containing at least one certificate, connected. The
parsed certificates are accessed in the `certificates` assoicated value (an array guaranteed to have at
least one element).
*/
public enum SITHSManagerState: Equatable {
case unknown
case error(error: SITHSManagerError)
case readerDisconnected
case readerConnected
case unknownCardInserted
case readingFromCard
case cardWithoutCertificatesInserted
case cardInserted(certificates: [SITHSCardCertificate])
}
public func ==(lhs: SITHSManagerState, rhs: SITHSManagerState) -> Bool {
switch (lhs, rhs) {
case (.unknown, .unknown),
(.readerDisconnected, .readerDisconnected),
(.readerConnected, .readerConnected),
(.unknownCardInserted, .unknownCardInserted),
(.readingFromCard, .readingFromCard),
(.cardWithoutCertificatesInserted, .cardWithoutCertificatesInserted):
return true
case let (.error(a), .error(b)):
return a == b
case let (.cardInserted(a), .cardInserted(b)):
return a == b
case (.unknown, _),
(.readerDisconnected, _),
(.readerConnected, _),
(.unknownCardInserted, _),
(.readingFromCard, _),
(.cardWithoutCertificatesInserted, _),
(.error, _),
(.cardInserted, _):
return false
}
}
/**
A SITHS Manager error.
- SmartcardError: An error given by the Precise Biometrics Tactivo SDK. The error code, and descibing message, is sent as associated
values.
- InternalError: There has been an internal error in the card communication or data parsing. If there is more information, it's contained
in the `error` associated value.
*/
public enum SITHSManagerError: Error, Equatable {
case smartcardError(message: String, code: Int)
case internalError(error: Error?)
}
public func ==(lhs: SITHSManagerError, rhs: SITHSManagerError) -> Bool {
switch (lhs, rhs) {
case let (.smartcardError(messageA, codeA), .smartcardError(messageB, codeB)):
return messageA == messageB && codeA == codeB
case (.internalError, .internalError):
// TODO: This does not properly compare the internal errors
return false
case (.smartcardError, _),
(.internalError, _):
return false
}
}
/**
The `SITHSManager` provides a wrapper around the Precise Biometrics Tactivo SDK. More specifically, this calls combines system
notifications with the `PBAccessory` and `PBSmartcard` classes to detect and respond to smart card reader and card state changes.
The class will also communicate with any inserted smart card via APDU messages to fetch the data directory structure and embedded
certificates. The class uses `ASN1Parser` to parse the SITHS card ASN.1 DER/BER data.
*/
open class SITHSManager {
fileprivate struct SmartcardManagerConfiguration {
/// Maximum number of card reader connection retries.
static let FetchStatusMaxRetries: Int = 5
/// Card reader connection retry timeout
static let FetchStatusRetryTimeout: TimeInterval = 0.2
/// Number of trailing bytes of card file contents that are allowed to be 0xFF until file is considered completely read. Set to nil
/// to disable this functionality.
static let ResponseDataTerminatingTrailingFFLimit: Int? = 10
}
// Observation and dispatch
fileprivate var observers: [ObserverProxy] = []
fileprivate let smartcardQueue: DispatchQueue
fileprivate var retryingConnection: Bool = false
fileprivate var applicationInactive: Bool = false
// Communication objects
fileprivate let smartcard = PBSmartcard()
fileprivate let accessory = PBAccessory.sharedClass()
/// The current state of the SITHS Manager. When changed, the `stateClosure` is called.
open var state: SITHSManagerState {
get {
return internalState
}
}
/**
The state change obcserver closure block. Will be called every time the state changes. The state can also be read directly from the
`state` property.
*/
open var stateClosure: ((SITHSManagerState) -> ())?
/**
The debug log closure block. Is called continously during state changes and SITHS card communication, and is quite verbose.
Note: Since debugging via the console when connected to a card reader is hard, it's adviced to log to screen or file.
*/
open var debugLogClosure: ((String) -> ())?
fileprivate var internalState: SITHSManagerState = .unknown {
didSet {
if internalState != oldValue {
DispatchQueue.main.async {
self.stateClosure?(self.internalState)
}
}
}
}
/**
Initiates the SmartcardManager.
- returns: A new SmartcardManager instance. Make sure to store a reference to this instance, since notification state changes will stop
as soon as this instance is deallocated.
*/
public init() {
smartcardQueue = DispatchQueue(label: "Smartcard Queue", attributes: .concurrent)
// Register for notifications
observers.append(ObserverProxy(name: .init(rawValue: "PB_CARD_INSERTED"), object: nil, closure: cardInserted))
observers.append(ObserverProxy(name: .init(rawValue: "PB_CARD_REMOVED"), object: nil, closure: cardRemoved))
observers.append(ObserverProxy(name: .PBAccessoryDidConnect, object: nil, closure: accessoryConnected))
observers.append(ObserverProxy(name: .PBAccessoryDidDisconnect, object: nil, closure: accessoryDisconnected))
observers.append(ObserverProxy(name: .UIApplicationDidBecomeActive, object: nil, closure: applicationDidBecomeActive))
observers.append(ObserverProxy(name: .UIApplicationWillResignActive, object: nil, closure: applicationWillResignActive))
}
fileprivate func applicationDidBecomeActive(notification: Notification) {
log(message: "Application Did Become Active Notification")
applicationInactive = false
smartcardQueue.async {
self.openSmartcard()
self.checkSmartcard()
}
}
fileprivate func applicationWillResignActive(notification: Notification) {
log(message: "Application Will Resign Active Notification")
applicationInactive = true
smartcardQueue.async {
self.closeSmartcard()
}
}
fileprivate func cardInserted(notification: Notification) {
log(message: "Card Inserted Notification")
smartcardQueue.async {
self.checkSmartcard()
}
}
fileprivate func cardRemoved(notification: Notification) {
log(message: "Card Removed Notification")
internalState = .readerConnected
}
fileprivate func accessoryConnected(notification: Notification) {
log(message: "Accessory Connected Notification")
if applicationInactive {
// Ignore accessory connection state notifications when application is not active.
return
}
smartcardQueue.async {
self.checkSmartcard()
}
}
fileprivate func accessoryDisconnected(notification: Notification) {
log(message: "Accessory Disconnected Notification")
if applicationInactive {
// Ignore accessory connection state notifications when application is not active.
return
}
internalState = .readerDisconnected
}
fileprivate func openSmartcard() {
let result = smartcard.open()
log(message: "OpenSmartcard status \(result)")
guard result == PBSmartcardStatusSuccess else {
setErrorState(error: getError(status: result))
return
}
}
fileprivate func checkSmartcard(retryCount: Int = 0) {
if retryCount == 0 && retryingConnection {
return
} else {
retryingConnection = false
}
let status = smartcard.getSlotStatus()
log(message: "CheckSmartcard status \(status), retry \(retryCount)")
switch status {
case PBSmartcardSlotStatusEmpty:
internalState = .readerConnected
case PBSmartcardSlotStatusPresent, PBSmartcardSlotStatusPresentConnected:
let result = smartcard.connect(PBSmartcardProtocolTx)
log(message: "Connect status \(result)")
if result == PBSmartcardStatusNoSmartcard {
internalState = .readerConnected
return
} else if result != PBSmartcardStatusSuccess {
setErrorState(error: getError(status: result))
return
}
var certificates = [SITHSCardCertificate]()
do {
log(message: "Selecting EID")
// Select the SITHS card EID
let command = SmartcardCommandAPDU(
instructionClass: 0x00,
instructionCode: 0xA4,
instructionParameters: [0x04, 0x00],
commandData: Data(bytes: [0xA0, 0x00, 0x00, 0x00, 0x63, 0x50, 0x4B, 0x43, 0x53, 0x2D, 0x31, 0x35]),
expectedResponseBytes: nil
)
let response = try transmit(command: command)
log(message: "Got response: \(response)")
switch response.processingStatus {
case .successWithResponse:
internalState = .readingFromCard
// The initial address is the EF.ODF file identifier
var identifiers: [[UInt8]] = [[0x50, 0x31]]
var readIdentifiers: [[UInt8]] = []
while identifiers.count > 0 {
let identifier = identifiers.removeFirst()
readIdentifiers.append(identifier)
log(message: "Read loop iteration, reading from identifier \(identifier.hexString())")
let _ = try transmitSelectFileAndGetResponse(identifier: identifier)
let efData = try transmitReadBinary()
let efParser = ASN1Parser(data: efData)
while let parsed = efParser.parseElement() {
log(message: "Parsed: \(parsed)")
if let foundIdentifier = getCardEFIdentifier(element: parsed.element) {
if !identifiers.contains(where: { $0 == foundIdentifier }) && !readIdentifiers.contains(where: { $0 == foundIdentifier }) {
identifiers.append(foundIdentifier)
}
}
if let certificate = parsed.cardCertificate {
certificates.append(certificate)
}
}
}
default:
log(message: "Could not correctly set EID, unkown card")
internalState = .unknownCardInserted
return
}
} catch let error as SITHSManagerError {
setErrorState(error: error)
return
} catch {
setErrorState(error: .internalError(error: error))
return
}
let serialStrings = certificates.map { return $0.serialString }
log(message: "SITHS Card communication complete, found certificates with serial HEX-strings: \(serialStrings)")
guard certificates.count > 0 else {
log(message: "No certificates in response")
internalState = .cardWithoutCertificatesInserted
return
}
internalState = .cardInserted(certificates: certificates)
case PBSmartcardSlotStatusUnknown:
if !(accessory?.isConnected)! {
internalState = .readerDisconnected
} else {
fallthrough
}
default:
if retryCount < SmartcardManagerConfiguration.FetchStatusMaxRetries {
// Retry connection, do not update state yet
retryingConnection = true
smartcardQueue.asyncAfter(deadline: .now() + SmartcardManagerConfiguration.FetchStatusRetryTimeout) {
self.checkSmartcard(retryCount: retryCount + 1)
}
} else {
// Max number of retries, set state to unknown
internalState = .unknown
}
}
}
fileprivate func getCardEFIdentifier(element: ASN1Element) -> [UInt8]? {
switch element {
case .contextSpecific(_, let elementsOrRawValue):
switch elementsOrRawValue {
case .elements(let elements):
switch elements[0] {
case .sequence(let elements):
guard elements.count == 1 else {
log(message: "Application Sequence did not contain one value, skip")
// Application Sequence did not contain one value, skip
break
}
switch elements[0] {
case .octetString(let value):
switch value {
case .rawValue(let value):
guard value.count == 4 else {
log(message: "Octet String raw value was not 4 bytes, skip")
// Octet String raw value was not 4 bytes, skip
break
}
var bytes = [UInt8](value)
guard bytes[0...1] == [0x3F, 0x00] else {
log(message: "First bytes was not 3F00, skip")
// First bytes was not 3F00, skip
break
}
let identifier = [UInt8](value[2...3])
log(message: "Found identifier \(identifier)")
return identifier
case .elements:
log(message: "Sequence Octet String was not raw value, skip")
// Sequence Octet String was not raw value, skip
break
}
default:
log(message: "Sequence element was not Octet String, skip")
// Sequence element was not Octet String, skip
break
}
default:
log(message: "First Context Specific element is not Sequence, skip")
// First Context Specific element is not Sequence, skip
break
}
case .rawValue:
log(message: "Context Specific element did not contain parsed elements, skip")
// Context Specific element did not contain parsed elements, skip
break
}
case .sequence(let elements):
guard let element = elements[safe: 2] else {
log(message: "Root Sequence does not have enough elements, skip")
// Root Sequence does not have enough elements, skip
break
}
switch element {
case .contextSpecific(number: 1, let value):
switch value {
case .elements(let elements):
guard let element = elements.first else {
log(message: "Context Specific does not have enough elements, skip")
// Context Specific does not have enough elements, skip
break
}
switch element {
case .sequence(let elements):
guard let element = elements.first else {
log(message: "First Sequence does not have enough elements, skip")
// First Sequence does not have enough elements, skip
break
}
switch element {
case .sequence(let elements):
guard let element = elements.first else {
log(message: "First Sequence does not have enough elements, skip")
// First Sequence does not have enough elements, skip
break
}
switch element {
case .octetString(let value):
switch value {
case .rawValue(let value):
guard value.count == 4 else {
log(message: "Octet String raw value was not 4 bytes, skip")
// Octet String raw value was not 4 bytes, skip
break
}
var bytes = [UInt8](value)
guard bytes[0...1] == [0x3F, 0x00] else {
log(message: "First bytes was not 3F00, skip")
// First bytes was not 3F00, skip
break
}
let identifier = [UInt8](value[2...3])
log(message: "Found identifier \(identifier)")
return identifier
default:
log(message: "Sequence Octet String was not raw value, skip")
// Sequence Octet String was not raw value, skip
break
}
default:
log(message: "Sequence element was not Octet String, skip")
// Sequence element was not Octet String, skip
break
}
default:
log(message: "Sequence element was not Sequence, skip")
// Sequence element was not Sequence, skip
break
}
default:
log(message: "Context Specific element was not Sequence, skip")
// Context Specific element was not Sequence, skip
break
}
default:
log(message: "Context Specific element did not contain parsed elements, skip")
// Context Specific element did not contain parsed elements, skip
break
}
default:
log(message: "Root sequence element was not Context Specific, skip")
// Root sequence element was not Context Specific, skip
break
}
default:
log(message: "Root element is not Sequence or Context Specific, skip")
// Root element is not Sequence or Context Specific, skip
break
}
return nil
}
fileprivate func transmitSelectFileAndGetResponse(identifier: [UInt8]) throws -> Data {
// The SELECT FILE command
let selectFileCommand = SmartcardCommandAPDU(
instructionClass: 0x00,
instructionCode: 0xA4,
instructionParameters: [0x00, 0x00],
commandData: Data(bytes: identifier),
expectedResponseBytes: nil
)
let selectFileResponse = try transmit(command: selectFileCommand)
let availableBytes: UInt8
switch selectFileResponse.processingStatus {
case .successWithResponse(let internalAvailableBytes):
availableBytes = internalAvailableBytes
default:
throw SITHSManagerError.internalError(error: nil)
}
// The GET RESPONSE command
let getResponseCommand = SmartcardCommandAPDU(
instructionClass: 0x00,
instructionCode: 0xC0,
instructionParameters: [0x00, 0x00],
commandData: nil,
expectedResponseBytes: UInt16(availableBytes)
)
let getResponseResponse = try transmit(command: getResponseCommand)
switch getResponseResponse.processingStatus {
case .success:
guard let responseData = getResponseResponse.responseData else {
throw SITHSManagerError.internalError(error: nil)
}
return responseData
default:
throw SITHSManagerError.internalError(error: nil)
}
}
fileprivate func transmitReadBinary() throws -> Data {
var dataBuffer = Data()
var offset: UInt16 = 0
var chunkSize: UInt16 = 0xFF
var readingDone = false
while !readingDone {
if chunkSize < 0xFF {
readingDone = true
}
let readBinaryCommand = SmartcardCommandAPDU(
instructionClass: 0x00,
instructionCode: 0xB0,
instructionParameters: [
UInt8(truncatingBitPattern: offset >> 8),
UInt8(truncatingBitPattern: offset)
],
commandData: nil,
expectedResponseBytes: chunkSize
)
let readBinaryResponse = try transmit(command: readBinaryCommand)
switch readBinaryResponse.processingStatus {
case .incorrectExpectedResponseBytes(let correctExpectedResponseBytes):
chunkSize = UInt16(correctExpectedResponseBytes)
case .success:
guard let responseData = readBinaryResponse.responseData else {
throw SITHSManagerError.internalError(error: nil)
}
// Look at the last bytes of the response
if let limit = SmartcardManagerConfiguration.ResponseDataTerminatingTrailingFFLimit, responseData.count >= limit {
var onlyFF = true
// Loop through and check for 0xFF
for i in responseData.count-limit..<responseData.count {
if responseData[i] != 0xFF {
onlyFF = false
break
}
}
// Last bytes are all 0xFF, assuming file content is finished
if onlyFF {
readingDone = true
}
}
offset += UInt16(responseData.count)
dataBuffer.append(responseData)
default:
throw SITHSManagerError.internalError(error: nil)
}
}
return dataBuffer
}
fileprivate func transmit(command: SmartcardCommandAPDU) throws -> SmartcardResponseAPDU {
var mergedCommand = try command.mergedCommand()
var receivedDataLength: UInt16 = 0xFF
if let expectedBytes = command.expectedResponseBytes {
receivedDataLength = expectedBytes + 2
}
var receivedData = Data(count: Int(receivedDataLength))
log(message: "Transmitting \(mergedCommand.count) >>> \(mergedCommand.hexString())")
let result = receivedData.withUnsafeMutableBytes { (receivedDataPointer: UnsafeMutablePointer<UInt8>) in
return mergedCommand.withUnsafeMutableBytes { (mergedCommandPointer: UnsafeMutablePointer<UInt8>) in
return self.smartcard.transmit(mergedCommandPointer,
withCommandLength: UInt16(mergedCommand.count),
andResponseBuffer: receivedDataPointer,
andResponseLength: &receivedDataLength)
}
}
if receivedData.count > Int(receivedDataLength) {
receivedData.removeSubrange(Int(receivedDataLength)..<receivedData.count)
}
log(message: "Received \(receivedDataLength) <<< \(receivedData.hexString())")
log(message: "Transmit status \(result)")
guard result == PBSmartcardStatusSuccess else {
throw getError(status: result)
}
let response = try SmartcardResponseAPDU(data: receivedData)
log(message: "Processed response \(response)")
return response
}
fileprivate func closeSmartcard() {
let result = smartcard.close()
log(message: "CloseSmartcard status \(result)")
}
fileprivate func getError(status: PBSmartcardStatus) -> SITHSManagerError {
let message: String
let code = Int(status.rawValue)
switch status {
case PBSmartcardStatusSuccess:
message = "No error was encountered"
case PBSmartcardStatusInvalidParameter:
message = "One or more of the supplied parameters could not be properly interpreted"
case PBSmartcardStatusSharingViolation:
message = "The smart card cannot be accessed because of other connections outstanding"
case PBSmartcardStatusNoSmartcard:
message = "The operation requires a Smart Card, but no Smart Card is currently in the device"
case PBSmartcardStatusProtocolMismatch:
message = "The requested protocols are incompatible with the protocol currently in use with the smart card"
case PBSmartcardStatusNotReady:
message = "The reader or smart card is not ready to accept commands"
case PBSmartcardStatusInvalidValue:
message = "One or more of the supplied parameters values could not be properly interpreted"
case PBSmartcardStatusReaderUnavailable:
message = "The reader is not currently available for use"
case PBSmartcardStatusUnexpected:
message = "An unexpected card error has occurred"
case PBSmartcardStatusUnsupportedCard:
message = "The reader cannot communicate with the card, due to ATR string configuration conflicts"
case PBSmartcardStatusUnresponsiveCard:
message = "The smart card is not responding to a reset"
case PBSmartcardStatusUnpoweredCard:
message = "Power has been removed from the smart card, so that further communication is not possible"
case PBSmartcardStatusResetCard:
message = "The smart card has been reset, so any shared state information is invalid"
case PBSmartcardStatusRemovedCard:
message = "The smart card has been removed, so further communication is not possible"
case PBSmartcardStatusNotConnected:
message = "No open connection to the card"
case PBSmartcardStatusInternalSessionLost:
message = "An internal session was terminated by iOS"
case PBSmartcardStatusProtocolNotIncluded:
message = "All necessary supported protocols are not defined in the plist file"
case PBSmartcardStatusNotSupported:
message = "The operation is not supported on your current version of iOS or with the current Tactivo firmware"
default:
message = "Undefined error"
}
return SITHSManagerError.smartcardError(message: message, code: code)
}
fileprivate func setErrorState(error: SITHSManagerError) {
if applicationInactive {
// We're suppressing all error states while application is inactive. This will be resolved again when the application enters forground
// and a new connection is made (that of course then could result in the same error, and will then be set as state correctly)
return
}
internalState = .error(error: error)
}
func log(message: String) {
DispatchQueue.main.async {
self.debugLogClosure?(message)
}
}
}
| c69b6d532f34e117d645503880e3f591 | 41.968056 | 155 | 0.577335 | false | false | false | false |
robinckanatzar/mcw | refs/heads/master | my-core-wellness/my-core-wellness/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// my-core-wellness
//
// Created by Robin Kanatzar on 2/16/17.
// Copyright © 2017 Robin Kanatzar. All rights reserved.
//
import UIKit
import CoreData
import Firebase
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var eventStore: EKEventStore?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
var navigationBarAppearace = UINavigationBar.appearance()
var toolBarAppearance = UIToolbar.appearance()
navigationBarAppearace.tintColor = UIColor(red: 85/255.0, green: 85/255.0, blue: 85/255.0, alpha: 1.0)
navigationBarAppearace.barTintColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) // Bar's background color
navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red: 85/255.0, green: 85/255.0, blue: 85/255.0, alpha: 1.0)] // Title's text color
toolBarAppearance.tintColor = UIColor(red: 85/255.0, green: 85/255.0, blue: 85/255.0, alpha: 1.0)
toolBarAppearance.barTintColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) // Bar's background color
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "my_core_wellness")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| e523c0533b8d3eec0308f6b6abe5e978 | 49.899083 | 285 | 0.68349 | false | false | false | false |
jopamer/swift | refs/heads/master | test/SILGen/materializeForSet.swift | apache-2.0 | 1 |
// RUN: %target-swift-emit-silgen -module-name materializeForSet %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name materializeForSet -enforce-exclusivity=unchecked %s | %FileCheck --check-prefix=UNCHECKED %s
class Base {
var stored: Int = 0
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet4BaseC6storedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $Base):
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some
// CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// UNCHECKED-LABEL: sil hidden [transparent] @$S17materializeForSet4BaseC6storedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// UNCHECKED: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $Base):
// UNCHECKED: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored
// UNCHECKED: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// UNCHECKED: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none
// UNCHECKED: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>)
// UNCHECKED: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// UNCHECKED: }
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Base, @thick Base.Type) -> () {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @trivial $*Base, [[SELFTYPE:%.*]] : @trivial $@thick Base.Type):
// CHECK: [[T0:%.*]] = load_borrow [[SELF]]
// CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T2:%.*]] = load [trivial] [[T1]] : $*Int
// CHECK: [[SETTER:%.*]] = function_ref @$S17materializeForSet4BaseC8computedSivs
// CHECK: apply [[SETTER]]([[T2]], [[T0]])
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet4BaseC8computedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $Base):
// CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet4BaseC8computedSivg
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [trivial] [[ADDR]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]]
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet4BaseC8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Base, @thick Base.Type) -> ()
// CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]]
// CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
var computed: Int {
get { return 0 }
set(value) {}
}
var storedFunction: () -> Int = { 0 }
final var finalStoredFunction: () -> Int = { 0 }
var computedFunction: () -> Int {
get { return {0} }
set {}
}
static var staticFunction: () -> Int {
get { return {0} }
set {}
}
}
class Derived : Base {}
protocol Abstractable {
associatedtype Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
static var staticFunction: () -> Result { get set }
}
// Validate that we thunk materializeForSet correctly when there's
// an abstraction pattern present.
extension Derived : Abstractable {}
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycvmytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed Derived, @thick Derived.Type) -> ()
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived, %3 : @trivial $@thick Derived.Type):
// CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegr_SiIegd_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (@escaping () -> Int) -> ()
// CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]])
// CHECK-NEXT: end_borrow [[T0]] from %2
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction{{[_0-9a-zA-Z]*}}vmTW
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_guaranteed () -> Int
// CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]])
// CHECK-NEXT: store [[RESULT]] to [init] [[TEMP]]
// CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegd_SiIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> Int) -> @out Int
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[RESULT]])
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]]
// CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[T2:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycvmytfU_TW
// CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]]
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]]
// CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: end_borrow [[T0]] from %2
// CHECK-NEXT: return [[T4]]
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycvmytfU_TW :
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived, %3 : @trivial $@thick Derived.Type):
// CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegr_SiIegd_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: assign [[NEWVALUE]] to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: end_borrow [[T0]] from %2
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// UNCHECKED-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycvmytfU_TW :
// UNCHECKED: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived, %3 : @trivial $@thick Derived.Type):
// UNCHECKED-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// UNCHECKED-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// UNCHECKED-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// UNCHECKED-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int
// UNCHECKED-NEXT: // function_ref
// UNCHECKED-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegr_SiIegd_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out Int) -> Int
// UNCHECKED-NEXT: [[NEWVALUE:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[VALUE]])
// UNCHECKED-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// UNCHECKED-NEXT: assign [[NEWVALUE]] to [[ADDR]]
// UNCHECKED-NEXT: end_borrow [[T0]] from %2
// UNCHECKED-NEXT: tuple ()
// UNCHECKED-NEXT: return
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction{{[_0-9a-zA-Z]*}}vmTW
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegd_SiIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> Int) -> @out Int
// CHECK-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[RESULT]])
// CHECK-NEXT: end_access [[READ]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]]
// CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[T2:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycvmytfU_TW
// CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]]
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]]
// CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: end_borrow [[T0]] from %2
// CHECK-NEXT: return [[T4]]
// UNCHECKED-LABEL: sil private [transparent] [thunk] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction{{[_0-9a-zA-Z]*}}vmTW
// UNCHECKED: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $*Derived):
// UNCHECKED-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// UNCHECKED-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived
// UNCHECKED-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// UNCHECKED-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// UNCHECKED-NEXT: [[RESULT:%.*]] = load [copy] [[ADDR]]
// UNCHECKED-NEXT: function_ref
// UNCHECKED-NEXT: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegd_SiIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> Int) -> @out Int
// UNCHECKED-NEXT: [[T1:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[RESULT]])
// UNCHECKED-NEXT: store [[T1]] to [init] [[RESULT_ADDR]]
// UNCHECKED-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
// UNCHECKED-NEXT: function_ref
// UNCHECKED-NEXT: [[T2:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycvmytfU_TW
// UNCHECKED-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]]
// UNCHECKED-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]]
// UNCHECKED-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// UNCHECKED-NEXT: end_borrow [[T0]] from %2
// UNCHECKED-NEXT: return [[T4]]
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycvmZytfU_TW
// CHECK: bb0([[ARG1:%.*]] : @trivial $Builtin.RawPointer, [[ARG2:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[ARG3:%.*]] : @trivial $*@thick Derived.Type, [[ARG4:%.*]] : @trivial $@thick Derived.Type.Type):
// CHECK-NEXT: [[SELF:%.*]] = load [trivial] [[ARG3]] : $*@thick Derived.Type
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type
// CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address [[ARG1]] : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [take] [[BUFFER]] : $*@callee_guaranteed () -> @out Int
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegr_SiIegd_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@guaranteed @callee_guaranteed () -> @out Int) -> Int
// CHECK: [[SETTER_FN:%.*]] = function_ref @$S17materializeForSet4BaseC14staticFunctionSiycvsZ : $@convention(method) (@owned @callee_guaranteed () -> Int, @thick Base.Type) -> ()
// CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_guaranteed () -> Int, @thick Base.Type) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycvmZTW
// CHECK: bb0(%0 : @trivial $Builtin.RawPointer, %1 : @trivial $*Builtin.UnsafeValueBuffer, %2 : @trivial $@thick Derived.Type):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type
// CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_guaranteed () -> Int
// CHECK: [[GETTER:%.*]] = function_ref @$S17materializeForSet4BaseC14staticFunctionSiycvgZ : $@convention(method) (@thick Base.Type) -> @owned @callee_guaranteed () -> Int
// CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_guaranteed () -> Int
// CHECK-NEXT: store [[VALUE]] to [init] [[OUT]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: [[VALUE:%.*]] = load [copy] [[OUT]] : $*@callee_guaranteed () -> Int
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @$SSiIegd_SiIegr_TR : $@convention(thin) (@guaranteed @callee_guaranteed () -> Int) -> @out Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: store [[NEWVALUE]] to [init] [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int
// CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_guaranteed () -> @out Int to $Builtin.RawPointer
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycvmZytfU_TW : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed @thick Derived.Type, @thick Derived.Type.Type) -> ()
// CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method: Abstractable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_guaranteed () -> Int
// CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
protocol ClassAbstractable : class {
associatedtype Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
static var staticFunction: () -> Result { get set }
}
extension Derived : ClassAbstractable {}
protocol Signatures {
associatedtype Result
var computedFunction: () -> Result { get set }
}
protocol Implementations {}
extension Implementations {
var computedFunction: () -> Int {
get { return {0} }
set {}
}
}
class ImplementingClass : Implementations, Signatures {}
struct ImplementingStruct : Implementations, Signatures {
var ref: ImplementingClass?
}
class HasDidSet : Base {
override var stored: Int {
didSet {}
}
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet06HasDidC0C6storedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $HasDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet06HasDidC0C6storedSivg
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [trivial] [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasDidSet, @thick HasDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
override var computed: Int {
get { return 0 }
set(value) {}
}
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet06HasDidC0C8computedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $HasDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet06HasDidC0C8computedSivg
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [trivial] [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet06HasDidC0C8computedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasDidSet, @thick HasDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
}
class HasStoredDidSet {
var stored: Int = 0 {
didSet {}
}
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasStoredDidSet, @thick HasStoredDidSet.Type) -> () {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @trivial $*HasStoredDidSet, [[METATYPE:%.*]] : @trivial $@thick HasStoredDidSet.Type):
// CHECK: [[SELF_VALUE:%.*]] = load_borrow [[SELF]] : $*HasStoredDidSet
// CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[VALUE:%.*]] = load [trivial] [[BUFFER_ADDR]] : $*Int
// CHECK: [[SETTER_FN:%.*]] = function_ref @$S17materializeForSet012HasStoredDidC0C6storedSivs : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> ()
// CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> ()
// CHECK: return
// CHECK: }
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet012HasStoredDidC0C6storedSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $HasStoredDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasStoredDidSet, #HasStoredDidSet.stored
// CHECK: [[T1:%.*]] = begin_access [read] [dynamic] [[T0]] : $*Int
// CHECK: [[VALUE:%.*]] = load [trivial] [[T1]] : $*Int
// CHECK: end_access [[T1]] : $*Int
// CHECK: store [[VALUE]] to [trivial] [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @$S17materializeForSet012HasStoredDidC0C6storedSivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasStoredDidSet, @thick HasStoredDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
}
class HasWeak {
weak var weakvar: HasWeak?
}
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet7HasWeakC7weakvarACSgXwvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $HasWeak):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak>
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[T0]] : $*@sil_weak Optional<HasWeak>
// CHECK: [[T1:%.*]] = load_weak [[READ]] : $*@sil_weak Optional<HasWeak>
// CHECK: end_access [[READ]] : $*@sil_weak Optional<HasWeak>
// CHECK: store [[T1]] to [init] [[T2]] : $*Optional<HasWeak>
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasWeak, @thick HasWeak.Type) -> ()
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// UNCHECKED-LABEL: sil hidden [transparent] @$S17materializeForSet7HasWeakC7weakvarACSgXwvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// UNCHECKED: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @guaranteed $HasWeak):
// UNCHECKED: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak>
// UNCHECKED: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar
// UNCHECKED: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak>
// UNCHECKED: store [[T1]] to [init] [[T2]] : $*Optional<HasWeak>
// UNCHECKED: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// UNCHECKED: [[T0:%.*]] = function_ref @$S17materializeForSet7HasWeakC7weakvarACSgXwvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed HasWeak, @thick HasWeak.Type) -> ()
// UNCHECKED: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>)
// UNCHECKED: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// UNCHECKED: }
// rdar://22109071
// Test that we don't use materializeForSet from a protocol extension.
protocol Magic {}
extension Magic {
var hocus: Int {
get { return 0 }
set {}
}
}
struct Wizard : Magic {}
func improve(_ x: inout Int) {}
func improveWizard(_ wizard: inout Wizard) {
improve(&wizard.hocus)
}
// CHECK-LABEL: sil hidden @$S17materializeForSet13improveWizardyyAA0E0VzF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Wizard
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int
// Call the getter and materialize the result in the temporary.
// CHECK-NEXT: [[T0:%.*]] = load [trivial] [[WRITE:.*]] : $*Wizard
// CHECK: [[WTEMP:%.*]] = alloc_stack $Wizard
// CHECK-NEXT: store [[T0]] to [trivial] [[WTEMP]]
// CHECK: [[GETTER:%.*]] = function_ref @$S17materializeForSet5MagicPAAE5hocusSivg
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]])
// CHECK-NEXT: dealloc_stack [[WTEMP]]
// CHECK-NEXT: store [[T0]] to [trivial] [[TEMP]]
// Call improve.
// CHECK: [[IMPROVE:%.*]] = function_ref @$S17materializeForSet7improveyySizF :
// CHECK-NEXT: apply [[IMPROVE]]([[TEMP]])
// CHECK-NEXT: [[T0:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[SETTER:%.*]] = function_ref @$S17materializeForSet5MagicPAAE5hocusSivs
// CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WRITE]])
// CHECK-NEXT: end_access [[WRITE]] : $*Wizard
// CHECK-NEXT: dealloc_stack [[TEMP]]
protocol Totalled {
var total: Int { get set }
}
struct Bill : Totalled {
var total: Int
}
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet4BillV5totalSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @trivial $*Bill):
// CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt
// CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet4BillVAA8TotalledA2aDP5totalSivmTW : $@convention(witness_method: Totalled) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : @trivial $*Bill):
// CHECK: [[T0:%.*]] = function_ref @$S17materializeForSet4BillV5totalSivm
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]])
// CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[T1]]
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[T1]]
// CHECK-NEXT: [[T1:%.*]] = tuple ([[LEFT]] : $Builtin.RawPointer, [[RIGHT]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: return [[T1]] :
protocol AddressOnlySubscript {
associatedtype Index
subscript(i: Index) -> Index { get set }
}
struct Foo<T>: AddressOnlySubscript {
subscript(i: T) -> T {
get { return i }
set { print("\(i) = \(newValue)") }
}
}
func increment(_ x: inout Int) { x += 1 }
// Generic subscripts.
protocol GenericSubscriptProtocol {
subscript<T>(_: T) -> T { get set }
}
struct GenericSubscriptWitness : GenericSubscriptProtocol {
subscript<T>(_: T) -> T { get { } set { } }
}
// -- materializeForSet for a generic subscript gets open-coded in terms of
// the concrete getter/setter.
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet23GenericSubscriptWitnessVAA0dE8ProtocolA2aDPyqd__qd__cluimytfU_TW
// CHECK: function_ref @$S17materializeForSet23GenericSubscriptWitnessVyxxcluis
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet23GenericSubscriptWitnessVAA0dE8ProtocolA2aDPyqd__qd__cluimTW
// CHECK: function_ref @$S17materializeForSet23GenericSubscriptWitnessVyxxcluig
extension GenericSubscriptProtocol {
subscript<T>(t: T) -> T { get { } set { } }
}
struct GenericSubscriptDefaultWitness : GenericSubscriptProtocol { }
// Make sure we correctly infer the 'T : Magic' requirement on all the accessors
// of the subscript.
struct GenericTypeWithRequirement<T : Magic> {}
protocol InferredRequirementOnSubscriptProtocol {
subscript<T>(i: Int) -> GenericTypeWithRequirement<T> { get set }
}
struct InferredRequirementOnSubscript : InferredRequirementOnSubscriptProtocol {
subscript<T>(i: Int) -> GenericTypeWithRequirement<T> {
get { }
set { }
}
}
// CHECK-LABEL: sil hidden @$S17materializeForSet30InferredRequirementOnSubscriptVyAA015GenericTypeWithE0VyxGSicAA5MagicRzluig : $@convention(method) <T where T : Magic> (Int, InferredRequirementOnSubscript) -> GenericTypeWithRequirement<T>
// CHECK-LABEL: sil hidden @$S17materializeForSet30InferredRequirementOnSubscriptVyAA015GenericTypeWithE0VyxGSicAA5MagicRzluis : $@convention(method) <T where T : Magic> (GenericTypeWithRequirement<T>, Int, @inout InferredRequirementOnSubscript) -> ()
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet30InferredRequirementOnSubscriptVAA0defG8ProtocolA2aDPyAA015GenericTypeWithE0Vyqd__GSicAA5MagicRd__luimTW
// Test for materializeForSet vs static properties of structs.
protocol Beverage {
static var abv: Int { get set }
}
struct Beer : Beverage {
static var abv: Int {
get {
return 7
}
set { }
}
}
struct Wine<Color> : Beverage {
static var abv: Int {
get {
return 14
}
set { }
}
}
// Make sure we can perform an inout access of such a property too.
func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) {
increment(&t.abv)
}
// Test for materializeForSet vs overridden computed property of classes.
class BaseForOverride {
var valueStored: Int
var valueComputed: Int { get { } set { } }
init(valueStored: Int) {
self.valueStored = valueStored
}
}
class DerivedForOverride : BaseForOverride {
override var valueStored: Int { get { } set { } }
override var valueComputed: Int { get { } set { } }
}
// Test for materializeForSet vs static properties of classes.
class ReferenceBeer {
class var abv: Int {
get {
return 7
}
set { }
}
}
func inoutAccessOfClassProperty() {
increment(&ReferenceBeer.abv)
}
// Test for materializeForSet when Self is re-abstracted.
//
// We have to open-code the materializeForSelf witness, and not screw up
// the re-abstraction.
protocol Panda {
var x: (Self) -> Self { get set }
}
func id<T>(_ t: T) -> T { return t }
extension Panda {
var x: (Self) -> Self {
get { return id }
set { }
}
}
struct TuxedoPanda : Panda { }
// CHECK-LABEL: sil private [transparent] @$S17materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
// FIXME: Useless re-abstractions
// CHECK: function_ref @$S17materializeForSet11TuxedoPandaVACIegnr_A2CIegyd_TR : $@convention(thin) (TuxedoPanda, @guaranteed @callee_guaranteed (@in_guaranteed TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda
// CHECK: function_ref @$S17materializeForSet11TuxedoPandaVACIegyd_A2CIegnr_TR : $@convention(thin) (@in_guaranteed TuxedoPanda, @guaranteed @callee_guaranteed (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda
// CHECK: function_ref @$S17materializeForSet5PandaPAAE1xyxxcvs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> ()
// CHECK: }
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmTW
// Call the getter:
// CHECK: function_ref @$S17materializeForSet5PandaPAAE1xyxxcvg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_guaranteed (@in_guaranteed τ_0_0) -> @out τ_0_0
// Result of calling the getter is re-abstracted to the maximally substituted type
// by SILGenFunction::emitApply():
// CHECK: function_ref @$S17materializeForSet11TuxedoPandaVACIegnr_A2CIegyd_TR : $@convention(thin) (TuxedoPanda, @guaranteed @callee_guaranteed (@in_guaranteed TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda
// ... then we re-abstract to the requirement signature:
// FIXME: Peephole this away with the previous one since there's actually no
// abstraction change in this case.
// CHECK: function_ref @$S17materializeForSet11TuxedoPandaVACIegyd_A2CIegnr_TR : $@convention(thin) (@in_guaranteed TuxedoPanda, @guaranteed @callee_guaranteed (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda
// The callback:
// CHECK: function_ref @$S17materializeForSet11TuxedoPandaVAA0E0A2aDP1xyxxcvmytfU_TW : $@convention(witness_method: Panda) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
// CHECK: }
// Test for materializeForSet vs lazy properties of structs.
struct LazyStructProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @$S17materializeForSet31inoutAccessOfLazyStructProperty1lyAA0ghI0Vz_tF
// CHECK: function_ref @$S17materializeForSet18LazyStructPropertyV3catSivg
// CHECK: function_ref @$S17materializeForSet18LazyStructPropertyV3catSivs
func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) {
increment(&l.cat)
}
// Test for materializeForSet vs lazy properties of classes.
// CHECK-LABEL: sil hidden [transparent] @$S17materializeForSet17LazyClassPropertyC3catSivm
class LazyClassProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @$S17materializeForSet30inoutAccessOfLazyClassProperty1lyAA0ghI0Cz_tF
// CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1
func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) {
increment(&l.cat)
}
// Test for materializeForSet vs lazy properties of final classes.
final class LazyFinalClassProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @$S17materializeForSet35inoutAccessOfLazyFinalClassProperty1lyAA0ghiJ0Cz_tF
// CHECK: function_ref @$S17materializeForSet22LazyFinalClassPropertyC3catSivg
// CHECK: function_ref @$S17materializeForSet22LazyFinalClassPropertyC3catSivs
func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) {
increment(&l.cat)
}
// Make sure the below doesn't crash SILGen
struct FooClosure {
var computed: (((Int) -> Int) -> Int)? {
get { return stored }
set {}
}
var stored: (((Int) -> Int) -> Int)? = nil
}
// CHECK-LABEL: $S17materializeForSet22testMaterializedSetteryyF
func testMaterializedSetter() {
// CHECK: function_ref @$S17materializeForSet10FooClosureVACycfC
var f = FooClosure()
// CHECK: function_ref @$S17materializeForSet10FooClosureV8computedS3iXEcSgvg
// CHECK: function_ref @$S17materializeForSet10FooClosureV8computedS3iXEcSgvs
f.computed = f.computed
}
// Odd corner case -- mutating getter, non-mutating setter
protocol BackwardMutationProtocol {
var value: Int {
mutating get
nonmutating set
}
}
struct BackwardMutation : BackwardMutationProtocol {
var value: Int {
mutating get { return 0 }
nonmutating set { }
}
}
func doBackwardMutation(m: inout BackwardMutationProtocol) {
m.value += 1
}
// materializeForSet for a constrained-extension protocol witness requires
// open coding.
protocol ConditionalSubscript {
subscript(_: Int) -> Self { get set }
}
struct HasConditionalSubscript<T> {}
extension HasConditionalSubscript: ConditionalSubscript where T: ConditionalSubscript {
subscript(_: Int) -> HasConditionalSubscript<T> {
get { return self }
set { }
}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S17materializeForSet23HasConditionalSubscriptVyxGAA0eF0A2aERzlAaEPyxSicimTW
// CHECK: function_ref @$S17materializeForSet23HasConditionalSubscriptVA2A0eF0RzlEyACyxGSicig
// CHECK-LABEL: sil_vtable DerivedForOverride {
// CHECK: #BaseForOverride.valueStored!getter.1: (BaseForOverride) -> () -> Int : @$S17materializeForSet07DerivedB8OverrideC11valueStoredSivg
// CHECK: #BaseForOverride.valueStored!setter.1: (BaseForOverride) -> (Int) -> () : @$S17materializeForSet07DerivedB8OverrideC11valueStoredSivs
// CHECK: #BaseForOverride.valueStored!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S17materializeForSet07DerivedB8OverrideC11valueStoredSivm
// CHECK: #BaseForOverride.valueComputed!getter.1: (BaseForOverride) -> () -> Int : @$S17materializeForSet07DerivedB8OverrideC13valueComputedSivg
// CHECK: #BaseForOverride.valueComputed!setter.1: (BaseForOverride) -> (Int) -> () : @$S17materializeForSet07DerivedB8OverrideC13valueComputedSivs
// CHECK: #BaseForOverride.valueComputed!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : @$S17materializeForSet07DerivedB8OverrideC13valueComputedSivm
// CHECK: }
// CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet {
// CHECK: method #Totalled.total!getter.1: {{.*}} : @$S17materializeForSet4BillVAA8TotalledA2aDP5totalSivgTW
// CHECK: method #Totalled.total!setter.1: {{.*}} : @$S17materializeForSet4BillVAA8TotalledA2aDP5totalSivsTW
// CHECK: method #Totalled.total!materializeForSet.1: {{.*}} : @$S17materializeForSet4BillVAA8TotalledA2aDP5totalSivmTW
// CHECK: }
| 2bb13e7e324ff5f02c03f6d9043ff023 | 56.998569 | 307 | 0.681952 | false | false | false | false |
devincoughlin/swift | refs/heads/master | stdlib/public/core/StringStorage.swift | apache-2.0 | 3 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Having @objc stuff in an extension creates an ObjC category, which we don't
// want.
#if _runtime(_ObjC)
internal protocol _AbstractStringStorage: _NSCopying {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
var UTF16Length: Int { get }
}
internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */
internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */
@_effects(readonly)
private func _isNSString(_ str:AnyObject) -> UInt8 {
return _swift_stdlib_isNSString(str)
}
#else
internal protocol _AbstractStringStorage {
var asString: String { get }
var count: Int { get }
var isASCII: Bool { get }
var start: UnsafePointer<UInt8> { get }
}
#endif
extension _AbstractStringStorage {
// ObjC interfaces.
#if _runtime(_ObjC)
@inline(__always)
@_effects(releasenone)
internal func _getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange
) {
_precondition(aRange.location >= 0 && aRange.length >= 0,
"Range out of bounds")
_precondition(aRange.location + aRange.length <= Int(count),
"Range out of bounds")
let range = Range(
uncheckedBounds: (aRange.location, aRange.location+aRange.length))
let str = asString
str._copyUTF16CodeUnits(
into: UnsafeMutableBufferPointer(start: buffer, count: range.count),
range: range)
}
@inline(__always)
@_effects(releasenone)
internal func _getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt
) -> Int8 {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true),
(_cocoaUTF8Encoding, _):
guard maxLength >= count + 1 else { return 0 }
outputPtr.initialize(from: start, count: count)
outputPtr[count] = 0
return 1
default:
return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding)
}
}
@inline(__always)
@_effects(readonly)
internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? {
switch (encoding, isASCII) {
case (_cocoaASCIIEncoding, true),
(_cocoaUTF8Encoding, _):
return start
default:
return _cocoaCStringUsingEncodingTrampoline(self, encoding)
}
}
@_effects(readonly)
internal func _nativeIsEqual<T:_AbstractStringStorage>(
_ nativeOther: T
) -> Int8 {
if count != nativeOther.count {
return 0
}
return (start == nativeOther.start ||
(memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0
}
@inline(__always)
@_effects(readonly)
internal func _isEqual(_ other: AnyObject?) -> Int8 {
guard let other = other else {
return 0
}
if self === other {
return 1
}
// Handle the case where both strings were bridged from Swift.
// We can't use String.== because it doesn't match NSString semantics.
let knownOther = _KnownCocoaString(other)
switch knownOther {
case .storage:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: __StringStorage.self))
case .shared:
return _nativeIsEqual(
_unsafeUncheckedDowncast(other, to: __SharedStringStorage.self))
#if !(arch(i386) || arch(arm))
case .tagged:
fallthrough
#endif
case .cocoa:
// We're allowed to crash, but for compatibility reasons NSCFString allows
// non-strings here.
if _isNSString(other) != 1 {
return 0
}
// At this point we've proven that it is an NSString of some sort, but not
// one of ours.
defer { _fixLifetime(other) }
let otherUTF16Length = _stdlib_binary_CFStringGetLength(other)
// CFString will only give us ASCII bytes here, but that's fine.
// We already handled non-ASCII UTF8 strings earlier since they're Swift.
if let otherStart = _cocoaASCIIPointer(other) {
//We know that otherUTF16Length is also its byte count at this point
if count != otherUTF16Length {
return 0
}
return (start == otherStart ||
(memcmp(start, otherStart, count) == 0)) ? 1 : 0
}
if UTF16Length != otherUTF16Length {
return 0
}
/*
The abstract implementation of -isEqualToString: falls back to -compare:
immediately, so when we run out of fast options to try, do the same.
We can likely be more clever here if need be
*/
return _cocoaStringCompare(self, other) == 0 ? 1 : 0
}
}
#endif //_runtime(_ObjC)
}
private typealias CountAndFlags = _StringObject.CountAndFlags
//
// TODO(String docs): Documentation about the runtime layout of these instances,
// which is a little complex. The second trailing allocation holds an
// Optional<_StringBreadcrumbs>.
//
// NOTE: older runtimes called this class _StringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __StringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
#if arch(i386) || arch(arm)
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
internal var _realCapacity: Int
internal var _count: Int
internal var _flags: UInt16
internal var _reserved: UInt16
@inline(__always)
internal var count: Int { return _count }
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
// The capacity of our allocation. Note that this includes the nul-terminator,
// which is not available for overriding.
internal var _realCapacityAndFlags: UInt64
internal var _countAndFlags: _StringObject.CountAndFlags
@inline(__always)
internal var count: Int { return _countAndFlags.count }
// The total allocated storage capacity. Note that this includes the required
// nul-terminator.
@inline(__always)
internal var _realCapacity: Int {
return Int(truncatingIfNeeded:
_realCapacityAndFlags & CountAndFlags.countMask)
}
#endif
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var UTF16Length: Int {
@_effects(readonly) @inline(__always) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other: AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While __StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
private init(_doNotCallMe: ()) {
_internalInvariantFailure("Use the create method")
}
deinit {
_breadcrumbsAddress.deinitialize(count: 1)
}
}
// Determine the actual number of code unit capacity to request from malloc. We
// round up the nearest multiple of 8 that isn't a mulitple of 16, to fully
// utilize malloc's small buckets while accounting for the trailing
// _StringBreadCrumbs.
//
// NOTE: We may still under-utilize the spare bytes from the actual allocation
// for Strings ~1KB or larger, though at this point we're well into our growth
// curve.
private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int {
#if arch(i386) || arch(arm)
// FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so
// that the instance size will be a multiple of 4.
let bias = Int(bitPattern: _StringObject.nativeBias)
let minimum = bias + desiredCapacity + 1
let size = (minimum + 3) & ~3
_internalInvariant(size % 4 == 0)
let capacity = size - bias
_internalInvariant(capacity > desiredCapacity)
return capacity
#else
// Bigger than _SmallString, and we need 1 extra for nul-terminator.
let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity)
_internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length")
// Round up to the nearest multiple of 8 that isn't also a multiple of 16.
let capacity = ((minCap + 7) & -16) + 8
_internalInvariant(
capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0)
return capacity
#endif
}
// Creation
extension __StringStorage {
@_effects(releasenone)
private static func create(
realCodeUnitCapacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
let storage = Builtin.allocWithTailElems_2(
__StringStorage.self,
realCodeUnitCapacity._builtinWordValue, UInt8.self,
1._builtinWordValue, Optional<_StringBreadcrumbs>.self)
#if arch(i386) || arch(arm)
storage._realCapacity = realCodeUnitCapacity
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._realCapacityAndFlags =
UInt64(truncatingIfNeeded: realCodeUnitCapacity)
storage._countAndFlags = countAndFlags
#endif
storage._breadcrumbsAddress.initialize(to: nil)
storage.terminator.pointee = 0 // nul-terminated
// NOTE: We can't _invariantCheck() now, because code units have not been
// initialized. But, _StringGuts's initializer will.
return storage
}
@_effects(releasenone)
private static func create(
capacity: Int, countAndFlags: CountAndFlags
) -> __StringStorage {
_internalInvariant(capacity >= countAndFlags.count)
let realCapacity = determineCodeUnitCapacity(capacity)
_internalInvariant(realCapacity > capacity)
return __StringStorage.create(
realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags)
}
// The caller is expected to check UTF8 validity and ASCII-ness and update
// the resulting StringStorage accordingly
internal static func create(
uninitializedCapacity capacity: Int,
initializingUncheckedUTF8With initializer: (
_ buffer: UnsafeMutableBufferPointer<UInt8>
) throws -> Int
) rethrows -> __StringStorage {
let storage = __StringStorage.create(
capacity: capacity,
countAndFlags: CountAndFlags(mortalCount: 0, isASCII: false)
)
let buffer = UnsafeMutableBufferPointer(start: storage.mutableStart,
count: capacity)
let count = try initializer(buffer)
let countAndFlags = CountAndFlags(mortalCount: count, isASCII: false)
#if arch(i386) || arch(arm)
storage._count = countAndFlags.count
storage._flags = countAndFlags.flags
#else
storage._countAndFlags = countAndFlags
#endif
storage.terminator.pointee = 0 // nul-terminated
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>,
capacity: Int,
isASCII: Bool
) -> __StringStorage {
let countAndFlags = CountAndFlags(
mortalCount: bufPtr.count, isASCII: isASCII)
_internalInvariant(capacity >= bufPtr.count)
let storage = __StringStorage.create(
capacity: capacity, countAndFlags: countAndFlags)
let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
storage.mutableStart.initialize(from: addr, count: bufPtr.count)
storage._invariantCheck()
return storage
}
@_effects(releasenone)
internal static func create(
initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool
) -> __StringStorage {
return __StringStorage.create(
initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII)
}
}
// Usage
extension __StringStorage {
@inline(__always)
private var mutableStart: UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self))
}
@inline(__always)
private var mutableEnd: UnsafeMutablePointer<UInt8> {
return mutableStart + count
}
@inline(__always)
internal var start: UnsafePointer<UInt8> {
return UnsafePointer(mutableStart)
}
@inline(__always)
private final var end: UnsafePointer<UInt8> {
return UnsafePointer(mutableEnd)
}
// Point to the nul-terminator.
@inline(__always)
private final var terminator: UnsafeMutablePointer<UInt8> {
return mutableEnd
}
@inline(__always)
internal var codeUnits: UnsafeBufferPointer<UInt8> {
return UnsafeBufferPointer(start: start, count: count)
}
// @opaque
internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> {
let raw = Builtin.getTailAddr_Word(
start._rawValue,
_realCapacity._builtinWordValue,
UInt8.self,
Optional<_StringBreadcrumbs>.self)
return UnsafeMutablePointer(raw)
}
// The total capacity available for code units. Note that this excludes the
// required nul-terminator.
internal var capacity: Int {
return _realCapacity &- 1
}
// The unused capacity available for appending. Note that this excludes the
// required nul-terminator.
//
// NOTE: Callers who wish to mutate this storage should enfore nul-termination
@inline(__always)
private var unusedStorage: UnsafeMutableBufferPointer<UInt8> {
return UnsafeMutableBufferPointer(
start: mutableEnd, count: unusedCapacity)
}
// The capacity available for appending. Note that this excludes the required
// nul-terminator.
internal var unusedCapacity: Int { return _realCapacity &- count &- 1 }
#if !INTERNAL_CHECKS_ENABLED
@inline(__always) internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self))
let rawStart = UnsafeRawPointer(start)
_internalInvariant(unusedCapacity >= 0)
_internalInvariant(count <= capacity)
_internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart)
_internalInvariant(self._realCapacity > self.count, "no room for nul-terminator")
_internalInvariant(self.terminator.pointee == 0, "not nul terminated")
let str = asString
_internalInvariant(str._guts._object.isPreferredRepresentation)
_countAndFlags._invariantCheck()
if isASCII {
_internalInvariant(_allASCII(self.codeUnits))
}
if let crumbs = _breadcrumbsAddress.pointee {
crumbs._invariantCheck(for: self.asString)
}
_internalInvariant(_countAndFlags.isNativelyStored)
_internalInvariant(_countAndFlags.isTailAllocated)
}
#endif // INTERNAL_CHECKS_ENABLED
}
// Appending
extension __StringStorage {
// Perform common post-RRC adjustments and invariant enforcement.
@_effects(releasenone)
internal func _updateCountAndFlags(newCount: Int, newIsASCII: Bool) {
let countAndFlags = CountAndFlags(
mortalCount: newCount, isASCII: newIsASCII)
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
self.terminator.pointee = 0
// TODO(String performance): Consider updating breadcrumbs when feasible.
self._breadcrumbsAddress.pointee = nil
_invariantCheck()
}
// Perform common post-append adjustments and invariant enforcement.
@_effects(releasenone)
private func _postAppendAdjust(
appendedCount: Int, appendedIsASCII isASCII: Bool
) {
let oldTerminator = self.terminator
_updateCountAndFlags(
newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII)
_internalInvariant(oldTerminator + appendedCount == self.terminator)
}
@_effects(releasenone)
internal func appendInPlace(
_ other: UnsafeBufferPointer<UInt8>, isASCII: Bool
) {
_internalInvariant(self.capacity >= other.count)
let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked
let srcCount = other.count
self.mutableEnd.initialize(from: srcAddr, count: srcCount)
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
@_effects(releasenone)
internal func appendInPlace<Iter: IteratorProtocol>(
_ other: inout Iter, isASCII: Bool
) where Iter.Element == UInt8 {
var srcCount = 0
while let cu = other.next() {
_internalInvariant(self.unusedCapacity >= 1)
unusedStorage[srcCount] = cu
srcCount += 1
}
_postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII)
}
internal func clear() {
_updateCountAndFlags(newCount: 0, newIsASCII: true)
}
}
// Removing
extension __StringStorage {
@_effects(releasenone)
internal func remove(from lower: Int, to upper: Int) {
_internalInvariant(lower <= upper)
let lowerPtr = mutableStart + lower
let upperPtr = mutableStart + upper
let tailCount = mutableEnd - upperPtr
lowerPtr.moveInitialize(from: upperPtr, count: tailCount)
_updateCountAndFlags(
newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII)
}
// Reposition a tail of this storage from src to dst. Returns the length of
// the tail.
@_effects(releasenone)
internal func _slideTail(
src: UnsafeMutablePointer<UInt8>,
dst: UnsafeMutablePointer<UInt8>
) -> Int {
_internalInvariant(dst >= mutableStart && src <= mutableEnd)
let tailCount = mutableEnd - src
dst.moveInitialize(from: src, count: tailCount)
return tailCount
}
@_effects(releasenone)
internal func replace(
from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8>
) {
_internalInvariant(lower <= upper)
let replCount = replacement.count
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
lowerPtr.moveInitialize(
from: UnsafeMutablePointer(
mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked),
count: replCount)
let isASCII = self.isASCII && _allASCII(replacement)
_updateCountAndFlags(newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
@_effects(releasenone)
internal func replace<C: Collection>(
from lower: Int,
to upper: Int,
with replacement: C,
replacementCount replCount: Int
) where C.Element == UInt8 {
_internalInvariant(lower <= upper)
_internalInvariant(replCount - (upper - lower) <= unusedCapacity)
// Position the tail.
let lowerPtr = mutableStart + lower
let tailCount = _slideTail(
src: mutableStart + upper, dst: lowerPtr + replCount)
// Copy in the contents.
var isASCII = self.isASCII
var srcCount = 0
for cu in replacement {
if cu >= 0x80 { isASCII = false }
lowerPtr[srcCount] = cu
srcCount += 1
}
_internalInvariant(srcCount == replCount)
_updateCountAndFlags(
newCount: lower + replCount + tailCount, newIsASCII: isASCII)
}
}
// For shared storage and bridging literals
// NOTE: older runtimes called this class _SharedStringStorage. The two
// must coexist without conflicting ObjC class names, so it was
// renamed. The old name must not be used in the new runtime.
final internal class __SharedStringStorage
: __SwiftNativeNSString, _AbstractStringStorage {
internal var _owner: AnyObject?
internal var start: UnsafePointer<UInt8>
#if arch(i386) || arch(arm)
internal var _count: Int
internal var _flags: UInt16
@inline(__always)
internal var _countAndFlags: _StringObject.CountAndFlags {
return CountAndFlags(count: _count, flags: _flags)
}
#else
internal var _countAndFlags: _StringObject.CountAndFlags
#endif
internal var _breadcrumbs: _StringBreadcrumbs? = nil
internal var count: Int { return _countAndFlags.count }
internal init(
immortal ptr: UnsafePointer<UInt8>,
countAndFlags: _StringObject.CountAndFlags
) {
self._owner = nil
self.start = ptr
#if arch(i386) || arch(arm)
self._count = countAndFlags.count
self._flags = countAndFlags.flags
#else
self._countAndFlags = countAndFlags
#endif
super.init()
self._invariantCheck()
}
@inline(__always)
final internal var isASCII: Bool { return _countAndFlags.isASCII }
final internal var asString: String {
@_effects(readonly) @inline(__always) get {
return String(_StringGuts(self))
}
}
#if _runtime(_ObjC)
@objc(length)
final internal var UTF16Length: Int {
@_effects(readonly) get {
return asString.utf16.count // UTF16View special-cases ASCII for us.
}
}
@objc
final internal var hash: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaHashASCIIBytes(start, length: count)
}
return _cocoaHashString(self)
}
}
@objc(characterAtIndex:)
@_effects(readonly)
final internal func character(at offset: Int) -> UInt16 {
let str = asString
return str.utf16[str._toUTF16Index(offset)]
}
@objc(getCharacters:range:)
@_effects(releasenone)
final internal func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
) {
_getCharacters(buffer, aRange)
}
@objc
final internal var fastestEncoding: UInt {
@_effects(readonly) get {
if isASCII {
return _cocoaASCIIEncoding
}
return _cocoaUTF8Encoding
}
}
@objc(_fastCStringContents:)
@_effects(readonly)
final internal func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>? {
if isASCII {
return start._asCChar
}
return nil
}
@objc(UTF8String)
@_effects(readonly)
final internal func _utf8String() -> UnsafePointer<UInt8>? {
return start
}
@objc(cStringUsingEncoding:)
@_effects(readonly)
final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? {
return _cString(encoding: encoding)
}
@objc(getCString:maxLength:encoding:)
@_effects(releasenone)
final internal func getCString(
_ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt
) -> Int8 {
return _getCString(outputPtr, maxLength, encoding)
}
@objc(isEqualToString:)
@_effects(readonly)
final internal func isEqual(to other:AnyObject?) -> Int8 {
return _isEqual(other)
}
@objc(copyWithZone:)
final internal func copy(with zone: _SwiftNSZone?) -> AnyObject {
// While __StringStorage instances aren't immutable in general,
// mutations may only occur when instances are uniquely referenced.
// Therefore, it is safe to return self here; any outstanding Objective-C
// reference will make the instance non-unique.
return self
}
#endif // _runtime(_ObjC)
}
extension __SharedStringStorage {
#if !INTERNAL_CHECKS_ENABLED
@inline(__always)
internal func _invariantCheck() {}
#else
internal func _invariantCheck() {
if let crumbs = _breadcrumbs {
crumbs._invariantCheck(for: self.asString)
}
_countAndFlags._invariantCheck()
_internalInvariant(!_countAndFlags.isNativelyStored)
_internalInvariant(!_countAndFlags.isTailAllocated)
let str = asString
_internalInvariant(!str._guts._object.isPreferredRepresentation)
}
#endif // INTERNAL_CHECKS_ENABLED
}
| 34634ad784fb2d151caac5e9023fff39 | 29.105077 | 86 | 0.690458 | false | false | false | false |
ubclaunchpad/RocketCast | refs/heads/master | RocketCast/Episode.swift | mit | 1 | //
// Episode.swift
// RocketCast
//
// Created by James Park on 2016-09-21.
// Copyright © 2016 UBCLaunchPad. All rights reserved.
//
import Foundation
import CoreData
class Episode: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
func getDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "MMM d"
if let episodeDate = self.date {
return dateFormatter.string(from: episodeDate)
}
return dateFormatter.string(from: Date())
}
func getDuration() -> String {
guard let timeArray = self.duration?.components(separatedBy: ":") else {
return ""
}
guard let digitOne = Int((timeArray[0])) else {
return ""
}
if timeArray.count == 1 {
let hour = (digitOne >= 3600 ? digitOne % 3600 : 0)
let minutes = (digitOne - (hour * 3600)) % 60
if hour > 1 {
return "\(hour) hours \(minutes) min"
} else {
return (hour > 0 ? "\(hour) hour \(minutes) min" : "\(minutes) min")
}
} else if timeArray.count == 2 {
return "\(timeArray[0]) \(PodcastInfoStrings.minute)"
} else if timeArray.count == 3 {
guard let digitTwo = Int((timeArray[1])) else {
return ""
}
return "\(digitOne) \(digitOne > 1 ? PodcastInfoStrings.pluralHour : PodcastInfoStrings.singularHour) \(digitTwo) \(PodcastInfoStrings.minute)"
}
return ""
}
}
| b046d4f009f1aedafb7c6d835aa95a19 | 31.627451 | 155 | 0.558293 | false | false | false | false |
drewag/Swiftlier | refs/heads/master | Sources/Swiftlier/Model/Types/Age.swift | mit | 1 | //
// Age.swift
// web
//
// Created by Andrew J Wagner on 3/1/17.
//
//
import Foundation
public struct Age: Codable {
public let years: Int
public init?(date: Date?) {
guard let date = date else {
return nil
}
self.init(date: date)
}
public init(date: Date) {
#if os(Linux)
let seconds = Date.now.timeIntervalSince1970 - date.timeIntervalSince1970
self.years = Int(seconds / 365 / 24 / 60 / 60)
#else
let components = Calendar.current.dateComponents(
Set([Calendar.Component.year]),
from: date,
to: Date.now
)
self.years = components.year!
#endif
}
}
| 6035578b830ca98861e8b031866a698c | 21 | 85 | 0.52139 | false | false | false | false |
charleshkang/Weatherr | refs/heads/master | C4QWeather/C4QWeather/WeatherStatus.swift | mit | 1 | //
// WeatherStatus.swift
// C4QWeather
//
// Created by Charles Kang on 11/21/16.
// Copyright © 2016 Charles Kang. All rights reserved.
//
import Foundation
enum Result<T> {
case success(T)
case failure(RequestError)
}
enum SuccessStatusCode: Int {
case ok = 200
case created = 201
}
enum RequestError: Error {
case invalidQuery
case noContent
case notFound
case methodNotAllowed
case unexpectedError
init(code: Int) {
switch code {
case 204: self = .noContent
case 404: self = .notFound
case 405: self = .methodNotAllowed
default: self = .unexpectedError
}
}
}
| 2ae4daadf6045151e7592f135aa32526 | 16.538462 | 55 | 0.614035 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | refs/heads/master | ch18-Performmance/ZipText/ZipText/ZipTextView.swift | mit | 1 | //
// ZipTextView.swift
// ZipText
//
// Created by WJ on 15/11/18.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kFontSize:CGFloat = 16.0
class ZipTextView: UIView {
var index = 0
var text = ""
var timer:Timer!
init(frame:CGRect,text:String){
super.init(frame: frame)
self.backgroundColor = UIColor.red
self.text = text
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ZipTextView.appendNextCharacter), userInfo: nil, repeats: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func appendNextCharacter(){
for i in 0...self.index{
if i < (text as NSString).length{
let label = UILabel()
label.text = (text as NSString).substring(with: NSMakeRange(i , 1))
label.sizeToFit()
label.isOpaque = false
var frame = label.frame
frame.origin = originAtIndex(i, fontSize: label.font.pointSize)
label.frame = frame
self.addSubview(label)
}
}
self.index += 1
}
func originAtIndex(_ index:Int,fontSize:CGFloat)->CGPoint{
if index == 0{
return CGPoint.zero
}
var origin = self.originAtIndex(index-1, fontSize: fontSize )
let prevCharacter = (text as NSString).substring(with: NSMakeRange(index-1, 1))
let prevCharacterSize = (prevCharacter as NSString).size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize)])
origin.x += prevCharacterSize.width
if origin.x > self.bounds.width{
origin.x = 0
origin.y += prevCharacterSize.height
}
return origin
}
}
| ea429e961ca1d672d944b0c191975efb | 30.37931 | 154 | 0.601099 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_use.swift | apache-2.0 | 3 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOySiGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^\)]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^\)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOySiGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOySiGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] [[ALIGNMENT]],
// CHECK-SAME: [[INT]] [[ALIGNMENT]],
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 0,
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOySiGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOySiGwup{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOySiGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First> {
case only(First)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i64 }>* @"$s4main5ValueOySiGMf" to %swift.full_type*), i32 0, i32 1)
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.only(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i64 }>* @"$s4main5ValueOySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* %2,
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| fdcb4976b950cc61e980c21a714068ce | 50.963855 | 263 | 0.577093 | false | false | false | false |
qRoC/Loobee | refs/heads/master | Tests/LoobeeTests/Library/AssertionConcern/Assertion/IsBlankStringTypesTests.swift | mit | 1 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
import XCTest
#if canImport(Loobee)
@testable import Loobee
#else
@testable import LoobeeAssertionConcern
#endif
internal final class IsBlankStringTypesTests: BaseAssertionsTests {
///
internal let newLineString = "\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}\u{2028}\u{2029}"
///
internal let whitespaceString = "\u{0009}\u{0020}\u{2029}\u{3000}"
///
func testIsBlankForEmptyString() {
self.assertMustBeValid(assert(isBlank: ""))
}
///
func testIsBlankForNewlineString() {
self.assertMustBeValid(assert(isBlank: newLineString))
}
///
func testIsBlankForWhitespaceString() {
self.assertMustBeValid(assert(isBlank: whitespaceString))
}
///
func testIsBlankForNotEmptyString() {
self.assertMustBeNotValid(assert(isBlank: "a"))
}
///
func testIsBlankForNotNewlineString() {
let testString = newLineString + "a" + newLineString
self.assertMustBeNotValid(assert(isBlank: testString))
}
///
func testIsBlankForNotWhitespaceString() {
let testString = whitespaceString + "a" + whitespaceString
self.assertMustBeNotValid(assert(isBlank: testString))
}
///
func testIsNotBlankForEmptyString() {
self.assertMustBeNotValid(assert(isNotBlank: ""))
}
///
func testIsNotBlankForNewlineString() {
self.assertMustBeNotValid(assert(isNotBlank: newLineString))
}
///
func testIsNotBlankForWhitespaceString() {
self.assertMustBeNotValid(assert(isNotBlank: whitespaceString))
}
///
func testIsNotBlankForNotEmptyString() {
self.assertMustBeValid(assert(isNotBlank: "a"))
}
///
func testIsNotBlankForNotNewlineString() {
let testString = newLineString + "a" + newLineString
self.assertMustBeValid(assert(isNotBlank: testString))
}
///
func testIsNotBlankForNotWhitespaceString() {
let testString = whitespaceString + "a" + whitespaceString
self.assertMustBeValid(assert(isNotBlank: testString))
}
///
func testIsBlankDefaultMessage() {
let message = kIsBlankDefaultMessage.description
self.assertMustBeNotValid(
assert(isBlank: "a"),
withMessage: message
)
}
///
func testIsBlankCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert(isBlank: "a", orNotification: message),
withMessage: message
)
}
///
func testIsNotBlankDefaultMessage() {
let message = kIsNotBlankDefaultMessage.description
self.assertMustBeNotValid(
assert(isNotBlank: ""),
withMessage: message
)
}
///
func testIsNotBlankCustomMessage() {
let message = "Test"
self.assertMustBeNotValid(
assert(isNotBlank: "", orNotification: message),
withMessage: message
)
}
}
| a87082bb93951b0eda9acfda7f3cd65e | 23.813953 | 91 | 0.642299 | false | true | false | false |
dduan/swift | refs/heads/master | test/1_stdlib/Filter.swift | apache-2.0 | 2 | //===--- Filter.swift - tests for lazy filtering --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
let FilterTests = TestSuite("Filter")
// Check that the generic parameter is called 'Base'.
protocol TestProtocol1 {}
extension LazyFilterIterator where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterSequence where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterIndex where BaseElements : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension LazyFilterCollection where Base : TestProtocol1 {
var _baseIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
FilterTests.test("filtering collections") {
let f0 = LazyFilterCollection(_base: 0..<30) { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = LazyFilterCollection(_base: 1..<30) { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
FilterTests.test("filtering sequences") {
let f0 = (0..<30).makeIterator().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([0, 7, 14, 21, 28], f0)
let f1 = (1..<30).makeIterator().lazy.filter { $0 % 7 == 0 }
expectEqualSequence([7, 14, 21, 28], f1)
}
runAllTests()
| a246b600e9fe56210742ba38d485a510 | 28.428571 | 80 | 0.672816 | false | true | false | false |
swordray/ruby-china-ios | refs/heads/master | RubyChina/Classes/Views/Topics/TopicsCell.swift | mit | 1 | //
// TopicsCell.swift
// RubyChina
//
// Created by Jianqiu Xiao on 2018/3/23.
// Copyright © 2018 Jianqiu Xiao. All rights reserved.
//
import UIKit
class TopicsCell: UITableViewCell {
private var nodeButton: UIButton!
private var repliedAtLabel: UILabel!
private var repliesCountLabel: UILabel!
private var titleLabel: UILabel!
public var topic: Topic? { didSet { didSetTopic() } }
private var userAvatarView: UIImageView!
private var userLoginLabel: UILabel!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
accessoryType = .disclosureIndicator
let stackView = UIStackView()
stackView.alignment = .center
stackView.spacing = 15
contentView.addSubview(stackView)
stackView.snp.makeConstraints { $0.edges.equalTo(contentView.layoutMarginsGuide).priority(999) }
userAvatarView = UIImageView()
userAvatarView.backgroundColor = .secondarySystemBackground
userAvatarView.clipsToBounds = true
userAvatarView.layer.cornerRadius = 22
userAvatarView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
userAvatarView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
stackView.addArrangedSubview(userAvatarView)
userAvatarView.snp.makeConstraints { $0.size.equalTo(44) }
let contentStackView = UIStackView()
contentStackView.axis = .vertical
contentStackView.spacing = 8
contentStackView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
contentStackView.setContentHuggingPriority(.defaultLow, for: .horizontal)
stackView.addArrangedSubview(contentStackView)
titleLabel = UILabel()
titleLabel.font = .preferredFont(forTextStyle: .body)
titleLabel.numberOfLines = 3
contentStackView.addArrangedSubview(titleLabel)
let detailStackView = UIStackView()
detailStackView.spacing = 8
contentStackView.addArrangedSubview(detailStackView)
nodeButton = UIButton()
nodeButton.backgroundColor = .quaternarySystemFill
nodeButton.clipsToBounds = true
nodeButton.contentEdgeInsets = UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3)
nodeButton.isUserInteractionEnabled = false
nodeButton.layer.cornerRadius = 3
nodeButton.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
nodeButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
nodeButton.setTitleColor(.secondaryLabel, for: .normal)
nodeButton.titleLabel?.font = .preferredFont(forTextStyle: .subheadline)
detailStackView.addArrangedSubview(nodeButton)
userLoginLabel = UILabel()
userLoginLabel.font = .preferredFont(forTextStyle: .subheadline)
userLoginLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
userLoginLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
userLoginLabel.textColor = .secondaryLabel
detailStackView.addArrangedSubview(userLoginLabel)
repliedAtLabel = UILabel()
repliedAtLabel.font = .preferredFont(forTextStyle: .subheadline)
repliedAtLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
repliedAtLabel.textColor = .tertiaryLabel
detailStackView.addArrangedSubview(repliedAtLabel)
repliesCountLabel = UILabel()
repliesCountLabel.font = .preferredFont(forTextStyle: .body)
repliesCountLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
repliesCountLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal)
repliesCountLabel.textColor = .secondaryLabel
stackView.addArrangedSubview(repliesCountLabel)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func didSetTopic() {
userAvatarView.isHidden = topic?.user == nil
userAvatarView.setImage(withURL: topic?.user?.avatarURL)
titleLabel.text = topic?.title
nodeButton.isHidden = (viewController as? TopicsController)?.node != nil
nodeButton.setTitle(topic?.nodeName, for: .normal)
userLoginLabel.isHidden = topic?.user == nil
userLoginLabel.text = topic?.user?.login
repliedAtLabel.text = topic?.repliedAt?.toRelative()
repliesCountLabel.text = String(topic?.repliesCount ?? 0)
if topic?.user != nil {
let size = CGSize(width: 44, height: 1)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imageView?.image = image
}
}
}
| 8d6b9a0cf9afa8aed1aba03acb459f20 | 42.54386 | 104 | 0.71394 | false | false | false | false |
BenziAhamed/Nevergrid | refs/heads/master | NeverGrid/Source/MoveInAsClone.swift | isc | 1 | //
// MoveInAsClone.swift
// MrGreen
//
// Created by Benzi on 15/08/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import SpriteKit
/// action that runs an animated entry of the
/// newly cloned clone
class MoveInAsClone : EntityAction {
override var description:String { return "MoveInAsClone" }
override func perform() -> SKAction? {
let location = world.location.get(entity)
let enemy = world.enemy.get(entity)
enemy.enabled = true
let cell = world.level.cells.get(location)!
cell.occupiedBy = entity
let moveTo = SKAction.moveTo(world.gs.getEntityPosition(location), duration: ActionFactory.Timing.EntityMove)
let fadeIn = SKAction.fadeInWithDuration(ActionFactory.Timing.EntityMove)
return SKAction.group([moveTo,fadeIn])
}
}
| 519732192e7a10aadcacc17f6bda1e19 | 24.657143 | 117 | 0.657016 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Pods/LeanCloud/Sources/Storage/ObjectProfiler.swift | gpl-3.0 | 1 | //
// ObjectProfiler.swift
// LeanCloud
//
// Created by Tang Tianyong on 2/23/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
extension LCError {
static let circularReference = LCError(
code: .inconsistency,
reason: "Circular reference.")
}
class ObjectProfiler {
private init() {
registerClasses()
}
static let shared = ObjectProfiler()
/// Registered object class table indexed by class name.
var objectClassTable: [String: LCObject.Type] = [:]
/**
Property list table indexed by synthesized class identifier number.
- note: Any properties declared by superclass are not included in each property list.
*/
var propertyListTable: [UInt: [objc_property_t]] = [:]
/**
Register an object class.
- parameter aClass: The object class to be registered.
*/
func registerClass(_ aClass: LCObject.Type) {
synthesizeProperty(aClass)
cache(objectClass: aClass)
}
/**
Synthesize all non-computed properties for object class.
- parameter aClass: The object class need to be synthesized.
*/
func synthesizeProperty(_ aClass: LCObject.Type) {
let properties = synthesizableProperties(aClass)
properties.forEach { synthesizeProperty($0, aClass) }
cache(properties: properties, aClass)
}
/**
Cache an object class.
- parameter aClass: The class to be cached.
*/
func cache(objectClass: LCObject.Type) {
objectClassTable[objectClass.objectClassName()] = objectClass
}
/**
Cache a property list.
- parameter properties: The property list to be cached.
- parameter aClass: The class of property list.
*/
func cache(properties: [objc_property_t], _ aClass: AnyClass) {
propertyListTable[UInt(bitPattern: ObjectIdentifier(aClass))] = properties
}
/**
Register object classes.
This method will scan the loaded classes list at runtime to find out object classes.
- note: When subclass and superclass have the same class name,
subclass will be registered for the class name.
*/
func registerClasses() {
/* Only register builtin classes. */
let builtinClasses = [LCObject.self, LCRole.self, LCUser.self, LCFile.self, LCInstallation.self]
builtinClasses.forEach { type in
registerClass(type)
}
}
/**
Find all synthesizable properties of object class.
A synthesizable property must satisfy following conditions:
* It is a non-computed property.
* It is a LeanCloud data type property.
- note: Any synthesizable properties declared by superclass are not included.
- parameter aClass: The object class.
- returns: An array of synthesizable properties.
*/
func synthesizableProperties(_ aClass: LCObject.Type) -> [objc_property_t] {
return Runtime.nonComputedProperties(aClass).filter { hasLCValue($0) }
}
/**
Check whether a property has LeanCloud data type.
- parameter property: Target property.
- returns: true if property type has LeanCloud data type, false otherwise.
*/
func hasLCValue(_ property: objc_property_t) -> Bool {
return getLCValue(property) != nil
}
/**
Get concrete LCValue subclass of property.
- parameter property: The property to be inspected.
- returns: Concrete LCValue subclass, or nil if property type is not LCValue.
*/
func getLCValue(_ property: objc_property_t) -> LCValue.Type? {
guard let typeEncoding: String = Runtime.typeEncoding(property) else {
return nil
}
guard typeEncoding.hasPrefix("@\"") else {
return nil
}
let startIndex: String.Index = typeEncoding.index(typeEncoding.startIndex, offsetBy: 2)
let endIndex: String.Index = typeEncoding.index(typeEncoding.endIndex, offsetBy: -1)
let name: Substring = typeEncoding[startIndex..<endIndex]
if let subclass = objc_getClass(String(name)) as? AnyClass {
if let type = subclass as? LCValue.Type {
return type
}
}
return nil
}
/**
Get concrete LCValue subclass of an object property.
- parameter object: Target object.
- parameter propertyName: The name of property to be inspected.
- returns: Concrete LCValue subclass, or nil if property type is not LCValue.
*/
func getLCValue(_ object: LCObject, _ propertyName: String) -> LCValue.Type? {
let property = class_getProperty(object_getClass(object), propertyName)
if property != nil {
return getLCValue(property!)
} else {
return nil
}
}
/**
Check if object has a property of type LCValue for given name.
- parameter object: Target object.
- parameter propertyName: The name of property to be inspected.
- returns: true if object has a property of type LCValue for given name, false otherwise.
*/
func hasLCValue(_ object: LCObject, _ propertyName: String) -> Bool {
return getLCValue(object, propertyName) != nil
}
/**
Synthesize a single property for class.
- parameter property: Property which to be synthesized.
- parameter aClass: Class of property.
*/
func synthesizeProperty(_ property: objc_property_t, _ aClass: AnyClass) {
let getterName = Runtime.propertyName(property)
let setterName = "set\(getterName.firstUppercaseString):"
class_replaceMethod(aClass, Selector(getterName), unsafeBitCast(self.propertyGetter, to: IMP.self), "@@:")
class_replaceMethod(aClass, Selector(setterName), unsafeBitCast(self.propertySetter, to: IMP.self), "v@:@")
}
/**
Iterate all object properties of type LCValue.
- parameter object: The object to be inspected.
- parameter body: The body for each iteration.
*/
func iterateProperties(_ object: LCObject, body: (String, objc_property_t) -> Void) {
var visitedKeys: Set<String> = []
var aClass: AnyClass? = object_getClass(object)
repeat {
guard aClass != nil else { return }
let properties = propertyListTable[UInt(bitPattern: ObjectIdentifier(aClass!))]
properties?.forEach { property in
let key = Runtime.propertyName(property)
if !visitedKeys.contains(key) {
visitedKeys.insert(key)
body(key, property)
}
}
aClass = class_getSuperclass(aClass)
} while aClass != LCObject.self
}
/**
Get deepest descendant newborn orphan objects of an object recursively.
- parameter object: The root object.
- parameter parent: The parent object for each iteration.
- parameter visited: The visited objects.
- parameter output: A set of deepest descendant newborn orphan objects.
- returns: true if object has newborn orphan object, false otherwise.
*/
@discardableResult
func deepestNewbornOrphans(_ object: LCValue, parent: LCValue?, output: inout Set<LCObject>) -> Bool {
var hasNewbornOrphan = false
switch object {
case let object as LCObject:
object.forEachChild { child in
if deepestNewbornOrphans(child, parent: object, output: &output) {
hasNewbornOrphan = true
}
}
/* Check if object is a newborn orphan.
If parent is not an LCObject, we think that it is an orphan. */
if !object.hasObjectId && !(parent is LCObject) {
if !hasNewbornOrphan {
output.insert(object)
}
hasNewbornOrphan = true
}
default:
(object as! LCValueExtension).forEachChild { child in
if deepestNewbornOrphans(child, parent: object, output: &output) {
hasNewbornOrphan = true
}
}
}
return hasNewbornOrphan
}
/**
Get deepest descendant newborn orphan objects.
- parameter objects: An array of root object.
- returns: A set of deepest descendant newborn orphan objects.
*/
func deepestNewbornOrphans(_ objects: [LCObject]) -> [LCObject] {
var result: [LCObject] = []
objects.forEach { object in
var output: Set<LCObject> = []
deepestNewbornOrphans(object, parent: nil, output: &output)
output.remove(object)
result.append(contentsOf: Array(output))
}
return result
}
private enum VisitState: Int {
case unvisited
case visiting
case visited
}
/**
Get toposort of objects.
- parameter objects: An array of objects need to be sorted.
- returns: An toposort of objects.
*/
func toposort(_ objects: [LCObject]) throws -> [LCObject] {
var result: [LCObject] = []
var visitStateTable: [Int: VisitState] = [:]
try toposortStart(objects.unique, &result, &visitStateTable)
return result.unique
}
private func toposortStart(_ objects: [LCObject], _ result: inout [LCObject], _ visitStateTable: inout [Int: VisitState]) throws {
try objects.forEach { object in
try toposortVisit(object, objects, &result, &visitStateTable)
}
}
private func toposortVisit(_ value: LCValue, _ objects: [LCObject], _ result: inout [LCObject], _ visitStateTable: inout [Int: VisitState]) throws {
guard let value = value as? LCValueExtension else {
return
}
guard let object = value as? LCObject else {
try value.forEachChild { child in
try toposortVisit(child, objects, &result, &visitStateTable)
}
return
}
let key = ObjectIdentifier(object).hashValue
let visitState = visitStateTable[key] ?? .unvisited
switch visitState {
case .unvisited:
visitStateTable[key] = .visiting
try object.forEachChild { child in
try toposortVisit(child, objects, &result, &visitStateTable)
}
visitStateTable[key] = .visited
if objects.contains(object) {
result.append(object)
}
case .visiting:
throw LCError.circularReference
case .visited:
break
}
}
/**
Get all objects of object family.
- parameter objects: An array of objects.
- returns: An array of objects in family.
*/
func family(_ objects: [LCObject]) throws -> [LCObject] {
var result: [LCObject] = []
var visitStateTable: [Int: VisitState] = [:]
try familyVisit(objects.unique, &result, &visitStateTable)
return result.unique
}
private func familyVisit(_ objects: [LCObject], _ result: inout [LCObject], _ visitStateTable: inout [Int: VisitState]) throws {
try objects.forEach { try familyVisit($0, &result, &visitStateTable) }
}
private func familyVisit(_ value: LCValue, _ result: inout [LCObject], _ visitStateTable: inout [Int: VisitState]) throws {
guard let value = value as? LCValueExtension else {
return
}
guard let object = value as? LCObject else {
try value.forEachChild { child in
try familyVisit(child, &result, &visitStateTable)
}
return
}
let key = ObjectIdentifier(object).hashValue
let visitState = visitStateTable[key] ?? .unvisited
switch visitState {
case .unvisited:
visitStateTable[key] = .visiting
try object.forEachChild { child in
try familyVisit(child, &result, &visitStateTable)
}
visitStateTable[key] = .visited
result.append(object)
case .visiting:
throw LCError.circularReference
case .visited:
break
}
}
/**
Validate circular reference in object graph.
This method will check object and its all descendant objects.
- parameter objects: The objects to validate.
*/
func validateCircularReference(_ objects: [LCObject]) throws {
var visitStateTable: [Int: VisitState] = [:]
try objects.unique.forEach { object in
try validateCircularReference(object, &visitStateTable)
}
}
/**
Validate circular reference in object graph iteratively.
- parameter value: The value to validate.
- parameter visitStateTable: The visit state table.
*/
private func validateCircularReference(_ value: LCValue, _ visitStateTable: inout [Int: VisitState]) throws {
guard let value = value as? LCValueExtension else {
return
}
guard let object = value as? LCObject else {
try value.forEachChild { child in
try validateCircularReference(child, &visitStateTable)
}
return
}
let key = ObjectIdentifier(object).hashValue
let visitState = visitStateTable[key] ?? .unvisited
switch visitState {
case .unvisited:
visitStateTable[key] = .visiting
try object.forEachChild { child in
try validateCircularReference(child, &visitStateTable)
}
visitStateTable[key] = .visited
case .visiting:
throw LCError.circularReference
case .visited:
break
}
}
/**
Check whether value is a boolean.
- parameter jsonValue: The value to check.
- returns: true if value is a boolean, false otherwise.
*/
func isBoolean(_ jsonValue: Any) -> Bool {
switch String(describing: type(of: jsonValue)) {
case "__NSCFBoolean", "Bool": return true
default: return false
}
}
/**
Get object class by name.
- parameter className: The name of object class.
- returns: The class.
*/
func objectClass(_ className: String) -> LCObject.Type? {
return objectClassTable[className]
}
/**
Create LCObject object for class name.
- parameter className: The class name of LCObject type.
- returns: An LCObject object for class name.
*/
func object(className: String) -> LCObject {
if let objectClass = objectClass(className) {
return objectClass.init()
} else {
return LCObject(className: className)
}
}
/**
Convert a dictionary to an object with specified class name.
- parameter dictionary: The source dictionary to be converted.
- parameter className: The object class name.
- returns: An LCObject object.
*/
func object(dictionary: [String: Any], className: String) throws -> LCObject {
let result = object(className: className)
let keyValues = try dictionary.compactMapValue { try object(jsonValue: $0) }
keyValues.forEach { (key, value) in
result.update(key, value)
}
return result
}
/**
Convert a dictionary to an object of specified data type.
- parameter dictionary: The source dictionary to be converted.
- parameter dataType: The data type.
- returns: An LCValue object, or nil if object can not be decoded.
*/
func object(dictionary: [String: Any], dataType: HTTPClient.DataType) throws -> LCValue? {
switch dataType {
case .object,
.pointer:
let className = dictionary["className"] as? String ?? LCObject.objectClassName()
return try object(dictionary: dictionary, className: className)
case .relation:
return LCRelation(dictionary: dictionary)
case .geoPoint:
return LCGeoPoint(dictionary: dictionary)
case .bytes:
return LCData(dictionary: dictionary)
case .date:
return LCDate(dictionary: dictionary)
case .file:
return try object(dictionary: dictionary, className: LCFile.objectClassName())
}
}
/**
Convert a dictionary to an LCValue object.
- parameter dictionary: The source dictionary to be converted.
- returns: An LCValue object.
*/
private func object(dictionary: [String: Any]) throws -> LCValue {
var result: LCValue!
if let type = dictionary["__type"] as? String {
if let dataType = HTTPClient.DataType(rawValue: type) {
result = try object(dictionary: dictionary, dataType: dataType)
}
}
if result == nil {
result = LCDictionary(try dictionary.compactMapValue { try object(jsonValue: $0) })
}
return result
}
/**
Convert JSON value to LCValue object.
- parameter jsonValue: The JSON value.
- returns: An LCValue object of the corresponding JSON value.
*/
func object(jsonValue: Any) throws -> LCValue {
switch jsonValue {
/* Note: a bool is also a number, we must match it first. */
case let bool where isBoolean(bool):
return LCBool(bool as! Bool)
case let number as NSNumber:
return LCNumber(number.doubleValue)
case let string as String:
return LCString(string)
case let array as [Any]:
return LCArray(try array.map { try object(jsonValue: $0) })
case let dictionary as [String: Any]:
return try object(dictionary: dictionary)
case let data as Data:
return LCData(data)
case let date as Date:
return LCDate(date)
case is NSNull:
return LCNull()
case let object as LCValue:
return object
default:
break
}
throw LCError(code: .invalidType, reason: "Unrecognized object.")
}
/**
Convert an object object to JSON value.
- parameter object: The object to be converted.
- returns: The JSON value of object.
*/
func lconValue(_ object: Any) -> Any? {
switch object {
case let array as [Any]:
return array.compactMap { lconValue($0) }
case let dictionary as [String: Any]:
return dictionary.compactMapValue { lconValue($0) }
case let object as LCValue:
return (object as? LCValueExtension)?.lconValue
case let query as LCQuery:
return query.lconValue
default:
return object
}
}
/**
Update object with a dictionary.
- parameter object: The object to be updated.
- parameter dictionary: A dictionary of key-value pairs.
*/
func updateObject(_ object: LCObject, _ dictionary: [String: Any]) {
dictionary.forEach { (key, value) in
object.update(key, try! self.object(jsonValue: value))
}
}
/**
Get property name from a setter selector.
- parameter selector: The setter selector.
- returns: A property name correspond to the setter selector.
*/
func propertyName(_ setter: Selector) -> String {
var propertyName = NSStringFromSelector(setter)
let startIndex: String.Index = propertyName.index(propertyName.startIndex, offsetBy: 3)
let endIndex: String.Index = propertyName.index(propertyName.endIndex, offsetBy: -1)
propertyName = String(propertyName[startIndex..<endIndex])
return propertyName
}
/**
Get property value for given name from an object.
- parameter object: The object that owns the property.
- parameter propertyName: The property name.
- returns: The property value, or nil if such a property not found.
*/
func propertyValue(_ object: LCObject, _ propertyName: String) -> LCValue? {
guard hasLCValue(object, propertyName) else {
return nil
}
return Runtime.instanceVariableValue(object, propertyName) as? LCValue
}
/**
Getter implementation of LeanCloud data type property.
*/
let propertyGetter: @convention(c) (LCObject, Selector) -> Any? = {
(object: LCObject, cmd: Selector) -> Any? in
let key = NSStringFromSelector(cmd)
return object.get(key)
}
/**
Setter implementation of LeanCloud data type property.
*/
let propertySetter: @convention(c) (LCObject, Selector, Any?) -> Void = {
(object: LCObject, cmd: Selector, value: Any?) -> Void in
let key = ObjectProfiler.shared.propertyName(cmd)
let value = value as? LCValue
if ObjectProfiler.shared.getLCValue(object, key) == nil {
try? object.set(key.firstLowercaseString, lcValue: value)
} else {
try? object.set(key, lcValue: value)
}
}
}
| ee28b3a689b7722f83cc05629a56d641 | 29.945985 | 152 | 0.610199 | false | false | false | false |
Sephiroth87/C-swifty4 | refs/heads/master | C64/Files/Disk.swift | mit | 1 | //
// Disk.swift
// C-swifty4
//
// Created by Fabio Ritrovato on 18/11/2015.
// Copyright © 2015 orange in a day. All rights reserved.
//
internal final class Track {
private let data: [UInt8]
let length: UInt
init(data: [UInt8]) {
self.data = data
self.length = UInt(data.count) * 8
}
func readBit(_ offset: UInt) -> UInt8 {
return data[Int(offset / 8)] & UInt8(0x80 >> (offset % 8)) != 0x00 ? 0x01 : 0x00
}
}
let gcr: [UInt64] = [0x0A, 0x0B, 0x12, 0x13, 0x0E, 0x0F, 0x16, 0x17, 0x09, 0x19, 0x1A, 0x1B, 0x0D, 0x1D, 0x1E, 0x15]
private func encodeGCR(_ bytes: [UInt8]) -> [UInt8] {
var encoded: UInt64 = 0
encoded |= gcr[Int(bytes[0] >> 4)] << 35
encoded |= gcr[Int(bytes[0] & 0x0F)] << 30
encoded |= gcr[Int(bytes[1] >> 4)] << 25
encoded |= gcr[Int(bytes[1] & 0x0F)] << 20
encoded |= gcr[Int(bytes[2] >> 4)] << 15
encoded |= gcr[Int(bytes[2] & 0x0F)] << 10
encoded |= gcr[Int(bytes[3] >> 4)] << 5
encoded |= gcr[Int(bytes[3] & 0x0F)]
return [UInt8(truncatingIfNeeded: encoded >> 32), UInt8(truncatingIfNeeded: encoded >> 24), UInt8(truncatingIfNeeded: encoded >> 16), UInt8(truncatingIfNeeded: encoded >> 8), UInt8(truncatingIfNeeded: encoded)]
}
internal final class Disk {
static let sectorsPerTrack: [UInt8] = [0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 19, 19, 19, 19, 19, 19, 19, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17]
let tracksCount: Int
let tracks: [Track]
init(d64Data: UnsafeBufferPointer<UInt8>) {
switch d64Data.count {
case 174848:
tracksCount = 35
default:
print("Unsupported d64 file")
tracksCount = 0
}
var tracks = [Track]()
tracks.append(Track(data: [])) //Track 0
let diskIDLow = d64Data[0x16500 + 0xA2]
let diskIDHigh = d64Data[0x16500 + 0xA3]
var dataOffset = 0
for trackNumber in 1...UInt8(tracksCount) {
var trackData = [UInt8]()
trackData.reserveCapacity(7928) // Max track size
for sectorNumber in 0..<Disk.sectorsPerTrack[Int(trackNumber)] {
// Header SYNC
trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF);
// Header info
let headerChecksum = UInt8(sectorNumber) ^ trackNumber ^ diskIDLow ^ diskIDHigh
trackData.append(contentsOf: encodeGCR([0x08, headerChecksum, sectorNumber, trackNumber]))
trackData.append(contentsOf: encodeGCR([diskIDLow, diskIDHigh, 0x0F, 0x0F]))
// Header gap
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
// Data SYNC
trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF);
// Data block
var dataChecksum: UInt8 = d64Data[dataOffset] ^ d64Data[dataOffset + 1] ^ d64Data[dataOffset + 2]
trackData.append(contentsOf: encodeGCR([0x07, d64Data[dataOffset + 0], d64Data[dataOffset + 1], d64Data[dataOffset + 2]]))
for i in stride(from: (dataOffset + 3), to: dataOffset + 255, by: 4) {
dataChecksum ^= d64Data[i] ^ d64Data[i+1] ^ d64Data[i+2] ^ d64Data[i+3]
trackData.append(contentsOf: encodeGCR([d64Data[i], d64Data[i+1], d64Data[i+2], d64Data[i+3]]))
}
dataChecksum ^= d64Data[dataOffset + 255]
trackData.append(contentsOf: encodeGCR([d64Data[dataOffset + 255], dataChecksum, 0x00, 0x0]))
// Inter-sector gap
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
if sectorNumber % 2 == 1 {
if trackNumber >= 18 && trackNumber <= 24 {
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
} else if trackNumber >= 25 && trackNumber <= 30 {
trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55);
} else if trackNumber >= 31 {
trackData.append(0x55);
}
}
dataOffset += 256
}
tracks.append(Track(data: trackData))
}
self.tracks = tracks
}
}
| b68c7c17b6085aa1edb28a052280a37a | 47.932692 | 214 | 0.579682 | false | false | false | false |
Book11/sinaWeibo | refs/heads/master | SinaWeibo02/SinaWeibo02/Classes/Module/Message/Controller/ZBMessageViewController.swift | mit | 1 | //
// ZBMessageViewController.swift
// SinaWeibo02
//
// Created by Macx on 16/4/13.
// Copyright © 2016年 Macx. All rights reserved.
//
import UIKit
class ZBMessageViewController: ZBBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| cc74b183c412c75695985a937816818e | 32.989474 | 157 | 0.6869 | false | false | false | false |
darren90/Gankoo_Swift | refs/heads/master | Gankoo/Gankoo/Lib/Vendor/Whisper/WhisperView.swift | apache-2.0 | 3 | import UIKit
public protocol NotificationControllerDelegate: class {
func notificationControllerWillHide()
}
open class WhisperView: UIView {
struct Dimensions {
static let height: CGFloat = 24
static let offsetHeight: CGFloat = height * 2
static let imageSize: CGFloat = 14
static let loaderTitleOffset: CGFloat = 5
}
lazy fileprivate(set) var transformViews: [UIView] = [self.titleLabel, self.complementImageView]
open lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont(name: "HelveticaNeue", size: 13)
label.frame.size.width = UIScreen.main.bounds.width - 60
return label
}()
lazy var complementImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
open weak var delegate: NotificationControllerDelegate?
open var height: CGFloat
var whisperImages: [UIImage]?
// MARK: - Initializers
init(height: CGFloat, message: Message) {
self.height = height
self.whisperImages = message.images
super.init(frame: CGRect.zero)
titleLabel.text = message.title
titleLabel.textColor = message.textColor
backgroundColor = message.backgroundColor
if let images = whisperImages , images.count > 1 {
complementImageView.animationImages = images
complementImageView.animationDuration = 0.7
complementImageView.startAnimating()
} else {
complementImageView.image = whisperImages?.first
}
frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: Dimensions.height)
for subview in transformViews { addSubview(subview) }
titleLabel.sizeToFit()
setupFrames()
clipsToBounds = true
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Layout
extension WhisperView {
func setupFrames() {
if whisperImages != nil {
titleLabel.frame = CGRect(
x: (frame.width - titleLabel.frame.width) / 2 + 20,
y: 0,
width: titleLabel.frame.width,
height: frame.height)
complementImageView.frame = CGRect(
x: titleLabel.frame.origin.x - Dimensions.imageSize - Dimensions.loaderTitleOffset,
y: (Dimensions.height - Dimensions.imageSize) / 2,
width: Dimensions.imageSize,
height: Dimensions.imageSize)
} else {
titleLabel.frame = CGRect(
x: (frame.width - titleLabel.frame.width) / 2,
y: 0,
width: titleLabel.frame.width,
height: frame.height)
}
}
}
| 2f3fa1b10214051ce951cf2e9415269c | 26.621053 | 98 | 0.682165 | false | false | false | false |
drunknbass/Emby.ApiClient.Swift | refs/heads/master | Emby.ApiClient/model/dto/BaseItemDto.swift | mit | 1 | //
// BaseItemDto.swift
// Emby.ApiClient
//
import Foundation
public class BaseItemDto {
var name: String?
var serverId: String?
var id: String?
var etag: String?
var playlistItemid: String?
var dateCreated: NSDate?
var dateLastMediaAdded: NSDate?
var extraType: ExtraType?
var airsBeforeSeasonNumber: Int?
var airsAfterSeasonNumber: Int?
var airsBeforeEpisodeNumber: Int?
var absoluteEpisodeNumber: Int?
var displaySpecialWithSeasons: Bool?
var canDelete: Bool?
var canDownload: Bool?
var hasSubtitles: Bool?
var preferredMetadataLanguage: String?
var preferredMetadataCountryCode: String?
var awardSummary: String?
var shareUrl: String?
var metascore: Float?
var hasDynamicCategories: Bool?
var animeSeriesIndex: Int?
var supportsSync: Bool?
var hasSyncJob: Bool?
var isSynced: Bool?
var syncStatus: SyncJobStatus?
var syncPercent: Double?
var dvdSeasonNumber: Int?
var dvdEpisodeNumber: Int?
var sortName: String?
var forcedSortName: String?
var video3dFormat: Video3DFormat?
var premierDate: NSDate?
var externalUrls: [ExternalUrl]?
var mediaSources: [MediaSourceInfo]?
var criticRating: Float?
var gameSystem: String?
var criticRatingSummary: String?
var multiPartGameFiles: [String]?
var path: String?
var officialRating: String?
var customRating: String?
var channelId: String?
var channelName: String?
var overview: String?
var shortOverview: String?
var tmdbCollectionName: String?
var tagLines: [String]?
var genres: [String]?
var seriesGenres: [String]?
var communityRating: Float?
var voteCount: Int?
var cumulativeRunTimeTicks: Int?
var originalRunTimeTicks: Int?
var runTimeTicks: Int?
var playAccess: PlayAccess?
var aspectRation: String?
var productionYear: Int?
var players: Int?
var isPlaceHolder: Bool?
var indexNumber: Int?
var indexNumberEnd: Int?
var parentIndexNumber: Int?
var remoteTrailers: [MediaUrl]?
var soundtrackIds: [String]?
var providerIds: [String:String]?
var isHd: Bool?
var isFolder: Bool?
var parentId: String?
var type: String?
var people: [BaseItemPerson]?
var studios: [StudioDto]?
var parentLogoItemId: String?
var parentBackdropItemId: String?
var parentBackdropImageTags: [String]?
var localTrailerCount: Int?
var userData: UserItemDataDto?
var seasonUserData: UserItemDataDto?
var recursiveItemCount: Int?
var childCount: Int?
var seriesName: String?
var seriesId: String?
var seasonId: String?
var specialFeatureCount: Int?
var displayPreferencesId: String?
var status: String?
var seriesStatus: SeriesStatus? {
get {
if let status = self.status {
return SeriesStatus(rawValue: status)
} else {
return nil
}
}
set {
status = newValue!.rawValue
}
}
var recordingStatus: RecordingStatus? {
get {
if let status = self.status {
return RecordingStatus(rawValue: status)
} else {
return nil
}
}
set {
status = newValue!.rawValue
}
}
var airTime: String?
var airDays: [String]?
var indexOptions: [String]?
var tags: [String]?
var keywords: [String]?
var primaryImageAspectRatio: Double?
var originalPrimaryImageAspectRatio: Double?
var artists: [String]?
var artistItems: [NameIdPair]?
var album: String?
var collectionType: String?
var displayOrder: String?
var albumId: String?
var albumPrimaryImageTag: String?
var seriesPrimaryImageTag: String?
var albumArtist: String?
var albumArtists: [NameIdPair]?
var seasonName: String?
var mediaStreams: [MediaStream]?
var videoType: VideoType?
var displayMediaType: String?
var partCount: Int?
var mediaSourceCount: Int?
var supportsPlayLists: Bool {
get {
return (runTimeTicks != nil) || ((isFolder != nil) && isFolder!) || isGenre || isMusicGenre || isArtist
}
}
public func isType(type: String) -> Bool {
return self.type == type
}
var imageTags: [ImageType: String]?
var backdropImageTags: [String]?
var screenshotImageTags: [String]?
var parentLogoImageTag: String?
var parentArtItemId: String?
var parentArtImageTag: String?
var seriesThumbImageTag: String?
var seriesStudio: String?
var parentThumbItemId: String?
var parentThumbImageTag: String?
var parentPrimaryImageItemId: String?
var parentPrimaryImageTag: String?
var chapters: [ChapterInfoDto]?
var locationType: LocationType?
var isoType: IsoType?
var mediaType: String?
var endDate: NSDate?
var homePageUrl: String?
var productionLocations: [String]?
var budget: Double?
var revenue: Double?
var lockedFields: [MetadataFields]?
var movieCount: Int?
var seriesCount: Int?
var episodeCount: Int?
var gameCount: Int?
var songCount: Int?
var albumCount: Int?
var musicVideoCount: Int?
var lockData: Bool?
var width: Int?
var height: Int?
var cameraMake: String?
var cameraModel: String?
var software: String?
var exposureTime: Double?
var focalLength: Double?
var imageOrientation: ImageOrientation?
var aperture: Double?
var shutterSpeed: Double?
var latitude: Double?
var longitude: Double?
var altitude: Double?
var isoSpeedRating: Int?
var recordingCount: Int?
var seriesTimerId: String?
var canResume: Bool {
get {
if let playbackPositionTicks = userData?.playbackPositionTicks {
return playbackPositionTicks > 0
} else {
return false
}
}
}
var resumePositionTicks: Int {
get {
if let playbackPositionTicks = userData?.playbackPositionTicks {
return playbackPositionTicks
} else {
return 0
}
}
}
var backdropCount: Int {
get {
return (backdropImageTags != nil) ? backdropImageTags!.count : 0
}
}
var screenshotCount: Int {
get {
return (screenshotImageTags != nil) ? screenshotImageTags!.count : 0
}
}
var hasBanner: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Banner] != nil : false
}
}
var hasArtImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Art] != nil : false
}
}
var hasLogo: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Logo] != nil : false
}
}
var hasThumb: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Thumb] != nil : false
}
}
var hasPrimaryImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Primary] != nil : false
}
}
var hasDiscImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Disc] != nil : false
}
}
var hasBoxImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Box] != nil : false
}
}
var hasBoxRearImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.BoxRear] != nil : false
}
}
var hasMenuImage: Bool {
get {
return (imageTags != nil) ? imageTags![ImageType.Menu] != nil : false
}
}
var isVideo: Bool {
get {
return mediaType == MediaType.Video.rawValue
}
}
var isGame: Bool {
get {
return mediaType == MediaType.Game.rawValue
}
}
var isPerson: Bool {
get {
return mediaType == "Person"
}
}
var isRoot: Bool {
get {
return mediaType == "AggregateFolder"
}
}
var isMusicGenre: Bool {
get {
return mediaType == "MusicGenre"
}
}
var isGameGenre: Bool {
get {
return mediaType == "GameGenre"
}
}
var isGenre: Bool {
get {
return mediaType == "Genre"
}
}
var isArtist: Bool {
get {
return mediaType == "MusicArtist"
}
}
var isAlbum: Bool {
get {
return mediaType == "MusicAlbum"
}
}
var IsStudio: Bool {
get {
return mediaType == "Studio"
}
}
var supportsSimilarItems: Bool {
get {
return isType("Movie") || isType("Series") || isType("MusicAlbum") || isType("MusicArtist") || isType("Program") || isType("Recording") || isType("ChannelVideoItem") || isType("Game")
}
}
var programId: String?
var channelPrimaryImageTag: String?
var startDate: NSDate?
var completionPercentage: Double?
var isRepeat: Bool?
var episodeTitle: String?
var channelType: ChannelType?
var audio: ProgramAudio?
var isMovie: Bool?
var isSports: Bool?
var isSeries: Bool?
var isLive: Bool?
var isNews: Bool?
var isKids: Bool?
var isPremiere: Bool?
var timerId: String?
var currentProgram: BaseItemDto?
} | 35344edf5fb431bc507cbfd6b95295f9 | 25.048257 | 195 | 0.591354 | false | false | false | false |
algolia/algolia-swift-demo | refs/heads/master | Source/AppDelegate.swift | mit | 1 | //
// Copyright (c) 2015 Algolia
// http://www.algolia.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 Reachability
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
static let colorForLocalOrigin = UIColor(red: 0.9, green: 0.97, blue: 1.0, alpha: 1.0)
var window: UIWindow?
var reachability: Reachability!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Listen for network reachability changes.
self.reachability = Reachability.forInternetConnection()
self.reachability.reachableBlock = {
(reachability: Reachability?) -> Void in
// Nothing to do
}
self.reachability.unreachableBlock = {
(reachability: Reachability?) -> Void in
// Nothing to do
}
self.reachability.startNotifier()
// Set up an on-disk URL cache.
let urlCache = URLCache(memoryCapacity: 0, diskCapacity:50 * 1024 * 1024, diskPath:nil)
URLCache.shared = urlCache
return true
}
}
| 7ed2e2de4d6408b114ebd489e6b8836e | 39.054545 | 144 | 0.706764 | false | false | false | false |
kperryua/swift | refs/heads/master | stdlib/public/SDK/Foundation/NSExpression.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSExpression {
// + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...;
public
convenience init(format expressionFormat: String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: expressionFormat, arguments: va_args)
}
}
| fa8be717972a2c775680472bb4eeec01 | 37.727273 | 80 | 0.590376 | false | false | false | false |
JPIOS/JDanTang | refs/heads/master | JDanTang/JDanTang/Class/MainClass/Home/Home/Model/ChoicenessModel.swift | apache-2.0 | 1 | //
// ChoicenessModel.swift
// JDanTang
//
// Created by 家朋 on 2017/7/31.
// Copyright © 2017年 mac_KY. All rights reserved.
//
import UIKit
class ChoicenessModel: NSObject {
var contentUrl : String!
var coverImageUrl : String!
var createdAt : Int!
var editorId : AnyObject!
var id : Int!
var labels : [AnyObject]!
var liked : Bool!
var likesCount : Int!
var publishedAt : Int!
var shareMsg : String!
var shortTitle : String!
var status : Int!
var template : String!
var title : String!
var type : String!
var updatedAt : Int!
var url : String!
/**
* 用字典来初始化一个实例并设置各个属性值
*/
init(fromDictionary dictionary: NSDictionary){
contentUrl = dictionary["content_url"] as? String
coverImageUrl = dictionary["cover_image_url"] as? String
createdAt = dictionary["created_at"] as? Int
editorId = dictionary["editor_id"] as? AnyObject
id = dictionary["id"] as? Int
labels = dictionary["labels"] as? [AnyObject]
liked = dictionary["liked"] as? Bool
likesCount = dictionary["likes_count"] as? Int
publishedAt = dictionary["published_at"] as? Int
shareMsg = dictionary["share_msg"] as? String
shortTitle = dictionary["short_title"] as? String
status = dictionary["status"] as? Int
template = dictionary["template"] as? String
title = dictionary["title"] as? String
type = dictionary["type"] as? String
updatedAt = dictionary["updated_at"] as? Int
url = dictionary["url"] as? String
}
}
| 677478bd5f3a3ff95ef8626d15eb5917 | 27.491228 | 64 | 0.612069 | false | false | false | false |
NikAshanin/Design-Patterns-In-Swift-Compare-Kotlin | refs/heads/master | Behavioral/Mediator/mediator.swift | mit | 1 | // Implementation
protocol Receiver {
associatedtype MessageType
func receive(message: MessageType)
}
protocol Sender {
associatedtype MessageType
associatedtype ReceiverType: Receiver
var recipients: [ReceiverType] { get }
func send(message: MessageType)
}
struct Programmer: Receiver {
let name: String
init(name: String) {
self.name = name
}
func receive(message: String) {
print("\(name) received: \(message)")
}
}
final class MessageMediator: Sender {
internal var recipients: [Programmer] = []
func add(recipient: Programmer) {
recipients.append(recipient)
}
func send(message: String) {
for recipient in recipients {
recipient.receive(message: message)
}
}
}
// Usage
func spamMonster(message: String, worker: MessageMediator) {
worker.send(message: message)
}
let messagesMediator = MessageMediator()
let user0 = Programmer(name: "Linus Torvalds")
let user1 = Programmer(name: "Avadis 'Avie' Tevanian")
messagesMediator.add(recipient: user0)
messagesMediator.add(recipient: user1)
spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator)
| 69daa8b563df68e9f501f65253744a5c | 21.232143 | 96 | 0.674699 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/core/ContiguousArrayBuffer.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Class used whose sole instance is used as storage for empty
/// arrays. The instance is defined in the runtime and statically
/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
@objc_non_lazy_realization
internal final class _EmptyArrayStorage
: _ContiguousArrayStorageBase {
init(_doNotCallMe: ()) {
_sanityCheckFailure("creating instance of _EmptyArrayStorage")
}
var countAndCapacity: _ArrayBody
#if _runtime(_ObjC)
override func _withVerbatimBridgedUnsafeBuffer<R>(
@noescape body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
return try body(UnsafeBufferPointer(start: nil, count: 0))
}
// FIXME(ABI): remove 'Void' arguments here and elsewhere in this file, they
// are a workaround for an old compiler limitation.
@warn_unused_result
override func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
return 0
}
@warn_unused_result
override func _getNonVerbatimBridgedHeapBuffer(
dummy: Void
) -> _HeapBuffer<Int, AnyObject> {
return _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, 0, 0)
}
#endif
@warn_unused_result
override func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
return false
}
/// A type that every element in the array is.
override var staticElementType: Any.Type {
return Void.self
}
}
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
internal var _emptyArrayStorage : _EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
}
// FIXME: This whole class is a workaround for
// <rdar://problem/18560464> Can't override generic method in generic
// subclass. If it weren't for that bug, we'd override
// _withVerbatimBridgedUnsafeBuffer directly in
// _ContiguousArrayStorage<Element>.
class _ContiguousArrayStorage1 : _ContiguousArrayStorageBase {
#if _runtime(_ObjC)
/// If the `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
final override func _withVerbatimBridgedUnsafeBuffer<R>(
@noescape body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
var result: R? = nil
try self._withVerbatimBridgedUnsafeBufferImpl {
result = try body($0)
}
return result
}
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
internal func _withVerbatimBridgedUnsafeBufferImpl(
@noescape body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
_sanityCheckFailure(
"Must override _withVerbatimBridgedUnsafeBufferImpl in derived classes")
}
#endif
}
// The class that implements the storage for a ContiguousArray<Element>
final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorage1 {
deinit {
__manager._elementPointer.deinitialize(
count: __manager._valuePointer.pointee.count)
__manager._valuePointer.deinitialize()
_fixLifetime(__manager)
}
#if _runtime(_ObjC)
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
internal final override func _withVerbatimBridgedUnsafeBufferImpl(
@noescape body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
if _isBridgedVerbatimToObjectiveC(Element.self) {
let count = __manager.value.count
let elements = UnsafePointer<AnyObject>(__manager._elementPointer)
defer { _fixLifetime(__manager) }
try body(UnsafeBufferPointer(start: elements, count: count))
}
}
/// Returns the number of elements in the array.
///
/// - Precondition: `Element` is bridged non-verbatim.
@warn_unused_result
override internal func _getNonVerbatimBridgedCount(dummy: Void) -> Int {
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
return __manager.value.count
}
/// Bridge array elements and return a new buffer that owns them.
///
/// - Precondition: `Element` is bridged non-verbatim.
@warn_unused_result
override internal func _getNonVerbatimBridgedHeapBuffer(dummy: Void) ->
_HeapBuffer<Int, AnyObject> {
_sanityCheck(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
let count = __manager.value.count
let result = _HeapBuffer<Int, AnyObject>(
_HeapBufferStorage<Int, AnyObject>.self, count, count)
let resultPtr = result.baseAddress
let p = __manager._elementPointer
for i in 0..<count {
(resultPtr + i).initialize(with: _bridgeToObjectiveCUnconditional(p[i]))
}
_fixLifetime(__manager)
return result
}
#endif
/// Returns `true` if the `proposedElementType` is `Element` or a subclass of
/// `Element`. We can't store anything else without violating type
/// safety; for example, the destructor has static knowledge that
/// all of the elements can be destroyed as `Element`.
@warn_unused_result
override func canStoreElements(
ofDynamicType proposedElementType: Any.Type
) -> Bool {
#if _runtime(_ObjC)
return proposedElementType is Element.Type
#else
// FIXME: Dynamic casts don't currently work without objc.
// rdar://problem/18801510
return false
#endif
}
/// A type that every element in the array is.
override var staticElementType: Any.Type {
return Element.self
}
internal // private
typealias Manager = ManagedBufferPointer<_ArrayBody, Element>
internal // private
var __manager : Manager {
return Manager(_uncheckedUnsafeBufferObject: self)
}
}
public struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol {
/// Make a buffer with uninitialized elements. After using this
/// method, you must either initialize the `count` elements at the
/// result's `.firstElementAddress` or set the result's `.count`
/// to zero.
public init(uninitializedCount: Int, minimumCapacity: Int) {
let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity)
if realMinimumCapacity == 0 {
self = _ContiguousArrayBuffer<Element>()
}
else {
__bufferPointer = ManagedBufferPointer(
_uncheckedBufferClass: _ContiguousArrayStorage<Element>.self,
minimumCapacity: realMinimumCapacity)
_initStorageHeader(
count: uninitializedCount, capacity: __bufferPointer.capacity)
_fixLifetime(__bufferPointer)
}
}
/// Initialize using the given uninitialized `storage`.
/// The storage is assumed to be uninitialized. The returned buffer has the
/// body part of the storage initialized, but not the elements.
///
/// - Warning: The result has uninitialized elements.
///
/// - Warning: storage may have been stack-allocated, so it's
/// crucial not to call, e.g., `malloc_size` on it.
internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {
__bufferPointer = ManagedBufferPointer(
_uncheckedUnsafeBufferObject: storage)
_initStorageHeader(count: count, capacity: count)
_fixLifetime(__bufferPointer)
}
internal init(_ storage: _ContiguousArrayStorageBase) {
__bufferPointer = ManagedBufferPointer(
_uncheckedUnsafeBufferObject: storage)
}
/// Initialize the body part of our storage.
///
/// - Warning: does not initialize elements
internal func _initStorageHeader(count count: Int, capacity: Int) {
#if _runtime(_ObjC)
let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)
#else
let verbatim = false
#endif
__bufferPointer._valuePointer.initialize(with:
_ArrayBody(
count: count,
capacity: capacity,
elementTypeIsBridgedVerbatim: verbatim))
}
/// True, if the array is native and does not need a deferred type check.
var arrayPropertyIsNativeTypeChecked : Bool {
return true
}
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
public var firstElementAddress: UnsafeMutablePointer<Element> {
return __bufferPointer._elementPointer
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
public func withUnsafeBufferPointer<R>(
@noescape body: UnsafeBufferPointer<Element> throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: firstElementAddress,
count: count))
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
public mutating func withUnsafeMutableBufferPointer<R>(
@noescape body: UnsafeMutableBufferPointer<Element> throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
//===--- _ArrayBufferProtocol conformance -----------------------------------===//
/// Create an empty buffer.
public init() {
__bufferPointer = ManagedBufferPointer(
_uncheckedUnsafeBufferObject: _emptyArrayStorage)
}
public init(_ buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {
_sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
self = buffer
}
@warn_unused_result
public mutating func requestUniqueMutableBackingBuffer(
minimumCapacity minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>? {
if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) {
return self
}
return nil
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
@warn_unused_result
public mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool {
return isUniquelyReferencedOrPinned()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@warn_unused_result
public func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
return self
}
@warn_unused_result
func getElement(i: Int) -> Element {
_sanityCheck(i >= 0 && i < count, "Array index out of range")
return firstElementAddress[i]
}
/// Get or set the value of the ith element.
public subscript(i: Int) -> Element {
get {
return getElement(i)
}
nonmutating set {
_sanityCheck(i >= 0 && i < count, "Array index out of range")
// FIXME: Manually swap because it makes the ARC optimizer happy. See
// <rdar://problem/16831852> check retain/release order
// firstElementAddress[i] = newValue
var nv = newValue
let tmp = nv
nv = firstElementAddress[i]
firstElementAddress[i] = tmp
}
}
/// The number of elements the buffer stores.
public var count: Int {
get {
return __bufferPointer.value.count
}
nonmutating set {
_sanityCheck(newValue >= 0)
_sanityCheck(
newValue <= capacity,
"Can't grow an array buffer past its capacity")
__bufferPointer._valuePointer.pointee.count = newValue
}
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
@inline(__always)
func _checkValidSubscript(index : Int) {
_precondition(
(index >= 0) && (index < __bufferPointer.value.count),
"Index out of range"
)
}
/// The number of elements the buffer can store without reallocation.
public var capacity: Int {
return __bufferPointer.value.capacity
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer past-the-end of the
/// just-initialized memory.
public func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_sanityCheck(bounds.startIndex >= 0)
_sanityCheck(bounds.endIndex >= bounds.startIndex)
_sanityCheck(bounds.endIndex <= count)
let initializedCount = bounds.endIndex - bounds.startIndex
target.initializeFrom(
firstElementAddress + bounds.startIndex,
count: initializedCount)
_fixLifetime(owner)
return target + initializedCount
}
/// Returns a `_SliceBuffer` containing the given `bounds` of values
/// from this buffer.
public subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
return _SliceBuffer(
owner: __bufferPointer.buffer,
subscriptBaseAddress: subscriptBaseAddress,
indices: bounds,
hasNativeBuffer: true)
}
set {
fatalError("not implemented")
}
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
///
/// - Note: This does not mean the buffer is mutable. Other factors
/// may need to be considered, such as whether the buffer could be
/// some immutable Cocoa container.
@warn_unused_result
public mutating func isUniquelyReferenced() -> Bool {
return __bufferPointer.holdsUniqueReference()
}
/// Returns `true` iff this buffer's storage is either
/// uniquely-referenced or pinned. NOTE: this does not mean
/// the buffer is mutable; see the comment on isUniquelyReferenced.
@warn_unused_result
public mutating func isUniquelyReferencedOrPinned() -> Bool {
return __bufferPointer.holdsUniqueOrPinnedReference()
}
#if _runtime(_ObjC)
/// Convert to an NSArray.
///
/// - Precondition: `Element` is bridged to Objective-C.
///
/// - Complexity: O(1).
@warn_unused_result
public func _asCocoaArray() -> _NSArrayCore {
_sanityCheck(
_isBridgedToObjectiveC(Element.self),
"Array element type is not bridged to Objective-C")
if count == 0 {
return _SwiftDeferredNSArray(
_nativeStorage: _emptyArrayStorage)
}
return _SwiftDeferredNSArray(_nativeStorage: _storage)
}
#endif
/// An object that keeps the elements stored in this buffer alive.
public var owner: AnyObject {
return _storage
}
/// An object that keeps the elements stored in this buffer alive.
public var nativeOwner: AnyObject {
return _storage
}
/// A value that identifies the storage used by the buffer.
///
/// Two buffers address the same elements when they have the same
/// identity and count.
public var identity: UnsafePointer<Void> {
return withUnsafeBufferPointer { UnsafePointer($0.baseAddress) }
}
/// Returns `true` iff we have storage for elements of the given
/// `proposedElementType`. If not, we'll be treated as immutable.
func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {
return _storage.canStoreElements(ofDynamicType: proposedElementType)
}
/// Returns `true` if the buffer stores only elements of type `U`.
///
/// - Precondition: `U` is a class or `@objc` existential.
///
/// - Complexity: O(N).
@warn_unused_result
func storesOnlyElementsOfType<U>(
_: U.Type
) -> Bool {
_sanityCheck(_isClassOrObjCExistential(U.self))
if _fastPath(_storage.staticElementType is U.Type) {
// Done in O(1)
return true
}
// Check the elements
for x in self {
if !(x is U) {
return false
}
}
return true
}
internal var _storage: _ContiguousArrayStorageBase {
return Builtin.castFromNativeObject(__bufferPointer._nativeBuffer)
}
var __bufferPointer: ManagedBufferPointer<_ArrayBody, Element>
}
/// Append the elements of `rhs` to `lhs`.
public func += <
Element, C : Collection where C.Iterator.Element == Element
> (lhs: inout _ContiguousArrayBuffer<Element>, rhs: C) {
let oldCount = lhs.count
let newCount = oldCount + numericCast(rhs.count)
if _fastPath(newCount <= lhs.capacity) {
lhs.count = newCount
(lhs.firstElementAddress + oldCount).initializeFrom(rhs)
}
else {
var newLHS = _ContiguousArrayBuffer<Element>(
uninitializedCount: newCount,
minimumCapacity: _growArrayCapacity(lhs.capacity))
newLHS.firstElementAddress.moveInitializeFrom(
lhs.firstElementAddress, count: oldCount)
lhs.count = 0
swap(&lhs, &newLHS)
(lhs.firstElementAddress + oldCount).initializeFrom(rhs)
}
}
extension _ContiguousArrayBuffer : Collection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Int {
return count
}
}
extension Sequence {
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Iterator.Element> {
return _copySequenceToNativeArrayBuffer(self)
}
}
@warn_unused_result
internal func _copySequenceToNativeArrayBuffer<
S : Sequence
>(source: S) -> _ContiguousArrayBuffer<S.Iterator.Element> {
let initialCapacity = source.underestimatedCount
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<S.Iterator.Element>(
initialCapacity: initialCapacity)
var iterator = source.makeIterator()
// FIXME(performance): use _copyContents(initializing:).
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(iterator.next()!)
}
// Add remaining elements, if any.
while let element = iterator.next() {
builder.add(element)
}
return builder.finish()
}
extension Collection {
public func _copyToNativeArrayBuffer(
) -> _ContiguousArrayBuffer<Iterator.Element> {
return _copyCollectionToNativeArrayBuffer(self)
}
}
extension _ContiguousArrayBuffer {
public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Element> {
return self
}
}
/// This is a fast implementation of _copyToNativeArrayBuffer() for collections.
///
/// It avoids the extra retain, release overhead from storing the
/// ContiguousArrayBuffer into
/// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support
/// ARC loops, the extra retain, release overhead cannot be eliminated which
/// makes assigning ranges very slow. Once this has been implemented, this code
/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.
@warn_unused_result
internal func _copyCollectionToNativeArrayBuffer<
C : Collection
>(source: C) -> _ContiguousArrayBuffer<C.Iterator.Element>
{
let count: Int = numericCast(source.count)
if count == 0 {
return _ContiguousArrayBuffer()
}
let result = _ContiguousArrayBuffer<C.Iterator.Element>(
uninitializedCount: count,
minimumCapacity: 0)
var p = result.firstElementAddress
var i = source.startIndex
for _ in 0..<count {
// FIXME(performance): use _copyContents(initializing:).
p.initialize(with: source[i])
i._successorInPlace()
p._successorInPlace()
}
_expectEnd(i, source)
return result
}
/// A "builder" interface for initializing array buffers.
///
/// This presents a "builder" interface for initializing an array buffer
/// element-by-element. The type is unsafe because it cannot be deinitialized
/// until the buffer has been finalized by a call to `finish`.
internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
internal var result: _ContiguousArrayBuffer<Element>
internal var p: UnsafeMutablePointer<Element>
internal var remainingCapacity: Int
/// Initialize the buffer with an initial size of `initialCapacity`
/// elements.
@inline(__always) // For performance reasons.
init(initialCapacity: Int) {
if initialCapacity == 0 {
result = _ContiguousArrayBuffer()
} else {
result = _ContiguousArrayBuffer(
uninitializedCount: initialCapacity,
minimumCapacity: 0)
}
p = result.firstElementAddress
remainingCapacity = result.capacity
}
/// Add an element to the buffer, reallocating if necessary.
@inline(__always) // For performance reasons.
mutating func add(element: Element) {
if remainingCapacity == 0 {
// Reallocate.
let newCapacity = max(_growArrayCapacity(result.capacity), 1)
var newResult = _ContiguousArrayBuffer<Element>(
uninitializedCount: newCapacity, minimumCapacity: 0)
p = newResult.firstElementAddress + result.capacity
remainingCapacity = newResult.capacity - result.capacity
newResult.firstElementAddress.moveInitializeFrom(
result.firstElementAddress,
count: result.capacity)
result.count = 0
swap(&result, &newResult)
}
addWithExistingCapacity(element)
}
/// Add an element to the buffer, which must have remaining capacity.
@inline(__always) // For performance reasons.
mutating func addWithExistingCapacity(element: Element) {
_sanityCheck(remainingCapacity > 0,
"_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity")
remainingCapacity -= 1
p.initialize(with: element)
p += 1
}
/// Finish initializing the buffer, adjusting its count to the final
/// number of elements.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inline(__always) // For performance reasons.
@warn_unused_result
mutating func finish() -> _ContiguousArrayBuffer<Element> {
// Adjust the initialized count of the buffer.
result.count = result.capacity - remainingCapacity
return finishWithOriginalCount()
}
/// Finish initializing the buffer, assuming that the number of elements
/// exactly matches the `initialCount` for which the initialization was
/// started.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inline(__always) // For performance reasons.
@warn_unused_result
mutating func finishWithOriginalCount() -> _ContiguousArrayBuffer<Element> {
_sanityCheck(remainingCapacity == result.capacity - result.count,
"_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count")
var finalResult = _ContiguousArrayBuffer<Element>()
swap(&finalResult, &result)
remainingCapacity = 0
return finalResult
}
}
| 459a3f2cfd2c4234105b4eccbbc13f55 | 31.460674 | 84 | 0.698122 | false | false | false | false |
mgallagher/sets-and-reps | refs/heads/master | SetsAndReps/Models.swift | mit | 1 | //
// Workout.swift
// SetsAndReps
//
// Created by Michael Gallagher on 3/24/15.
// Copyright (c) 2015 Michael Gallagher. All rights reserved.
//
import Foundation
import RealmSwift
class User : Object
{
dynamic var currentWorkout = Workout()
dynamic var weightLbs = 0.0
// Use a getter function to get their weight and return lbs or kgs depending
/**
Returns weight in lbs or kg depending on what's set
*/
var weight: Double {
get {
if usesKilograms {
return weightLbs * 0.4535923
} else {
return weightLbs
}
}
set {
if usesKilograms {
weightLbs = newValue * 0.4535923
} else {
weightLbs = newValue
}
}
}
dynamic var usesKilograms = false
let activePlans = List<Plan>()
let pastWorkouts = List<Workout>()
func getUser() -> User? {
return Realm().objects(User).first!
}
}
class Plan : Object
{
dynamic var name = ""
let defaultExerciseList = List<Exercise>()
dynamic var isPreconfigured = false
dynamic var isActive = false
dynamic var dateActivated = NSDate(timeIntervalSince1970: 1)
convenience init(name: String) {
self.init()
self.name = name
}
convenience init(name: String, exercises: Exercise...) {
self.init()
self.name = name
for e in exercises {
self.defaultExerciseList.append(e)
}
self.isPreconfigured = true
}
convenience init(nameAsPreconfigured: String) {
self.init()
self.name = nameAsPreconfigured
self.isPreconfigured = true
}
func getPreconfiguredPlans() -> Results<Plan> {
let realm = Realm()
let preconfiguredWorkouts = realm.objects(Plan).filter("isPreconfigured == true")
return preconfiguredWorkouts
}
func getActivePlans() -> Results<Plan> {
let realm = Realm()
let actives = realm.objects(Plan).filter("isActive == true").sorted("dateActivated", ascending: false)
return actives
}
}
class Exercise : Object
{
dynamic var name : String = ""
dynamic var sets = List<Sets>()
convenience init(name: String, sets: [Sets]) {
self.init()
self.name = name
for set in sets {
self.sets.append(set)
}
}
}
class Sets : Object
{
dynamic var reps : Int = 0
dynamic var weight : Int = 0
convenience init(reps: Int, weight: Int) {
self.init()
self.reps = reps
self.weight = weight
}
}
class Workout : Object
{
dynamic var name: String = ""
let exercises = List<Exercise>()
dynamic var isCompleted = false
dynamic var dateCompleted = NSDate(timeIntervalSince1970: 1)
dynamic var totalReps : Int = 0
dynamic var totalSets : Int = 0
dynamic var totalWeightLifted : Int = 0
convenience init(planToCopyFrom: Plan) {
self.init()
self.name = planToCopyFrom.name
// self.exercises = planToCopyFrom.defaultExerciseList
self.exercises.extend(planToCopyFrom.defaultExerciseList)
}
}
class PreconfiguredWorkouts
{
init() {
println("Adding SS and SL to realm")
// Starting Strength
let setWithFiveReps = Sets(reps: 5, weight: 0)
let threeSets = [Sets](count: 3, repeatedValue: setWithFiveReps)
let startingStrength = Plan(name: "STARTING STRENGTH", exercises:
Exercise(name: "SQUATS", sets: threeSets),
Exercise(name: "OVERHEAD PRESS", sets: threeSets),
Exercise(name: "BENCH PRESS", sets: threeSets))
// StrongLifts 5x5
let fiveSets = [Sets](count: 5, repeatedValue: setWithFiveReps)
let strongLifts = Plan(name: "STRONGLIFTS 5X5", exercises:
Exercise(name: "SQUATS", sets: fiveSets),
Exercise(name: "OVERHEAD PRESS", sets: fiveSets),
Exercise(name: "BENCH PRESS", sets: fiveSets))
// HugeLift
let hugeLift = Plan(name: "HUGELIFT", exercises:
Exercise(name: "SQUATS", sets: threeSets),
Exercise(name: "OVERHEAD PRESS", sets: threeSets),
Exercise(name: "BENCH PRESS", sets: threeSets))
Realm().write
{
Realm().add([startingStrength,strongLifts,hugeLift])
}
}
}
| 6ca02dfe88641734ac645cef172fe729 | 26.420732 | 110 | 0.586836 | false | true | false | false |
HarshilShah/NotchKit | refs/heads/master | Example/Sources/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// NotchKitExample
//
// Created by Harshil Shah on 16/09/17.
// Copyright © 2017 Harshil Shah. All rights reserved.
//
import UIKit
import NotchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = {
if #available(iOS 11, *) {
let notch = NotchKitWindow(frame: UIScreen.main.bounds)
notch.maskedEdges = []
return notch
} else {
return UIWindow()
}
}()
let rootViewController = ViewController()
window?.rootViewController = rootViewController
window?.backgroundColor = .black
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and 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:.
}
}
| 65f6aef7d1c5ddc1a50473d5cac059de | 43.724138 | 285 | 0.709329 | false | false | false | false |
tominated/Quake3BSPParser | refs/heads/master | Tests/Quake3BSPParserTests/Quake3BSPParserTests.swift | mit | 1 | //
// Quake3BSPParserTests.swift
// Quake3BSPParser
//
// Created by Thomas Brunoli on {TODAY}.
// Copyright © 2017 Quake3BSPParser. All rights reserved.
//
import Foundation
import XCTest
import Quake3BSPParser
class Quake3BSPParserTests: XCTestCase {
func testBigBox() {
let bigbox = try! loadMap(name: "test_bigbox");
let parser = try! Quake3BSPParser(bspData: bigbox)
let _ = try! parser.parse();
}
func testQ3dm6() {
let q3dm6 = try! loadMap(name: "q3dm6");
let parser = try! Quake3BSPParser(bspData: q3dm6)
let _ = try! parser.parse();
}
private func loadMap(name: String) throws -> Data {
let bundle = Bundle(for: type(of: self))
let filepath = bundle.url(forResource: name, withExtension: "bsp")!
return try Data(contentsOf: filepath)
}
}
| a1aead3cbca81063d5898072dfe5b889 | 26.451613 | 75 | 0.641598 | false | true | false | false |
stripe/stripe-ios | refs/heads/master | StripePaymentSheet/StripePaymentSheet/Analytics/AnalyticsHelper.swift | mit | 1 | //
// AnalyticsHelper.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 2/22/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
final class AnalyticsHelper {
enum TimeMeasurement {
case checkout
case linkSignup
}
static let shared = AnalyticsHelper()
private(set) var sessionID: String?
private let timeProvider: () -> Date
private var startTimes: [TimeMeasurement: Date] = [:]
init(timeProvider: @escaping () -> Date = Date.init) {
self.timeProvider = timeProvider
}
func generateSessionID() {
let uuid = UUID()
// Convert the UUID to lowercase to comply with RFC 4122 and ITU-T X.667.
sessionID = uuid.uuidString.lowercased()
}
func startTimeMeasurement(_ measurement: TimeMeasurement) {
startTimes[measurement] = timeProvider()
}
func getDuration(for measurement: TimeMeasurement) -> TimeInterval? {
guard let startTime = startTimes[measurement] else {
// Return `nil` if the time measurement hasn't started.
return nil
}
let now = timeProvider()
let duration = now.timeIntervalSince(startTime)
// Round to 2 decimal places
return round(duration * 100) / 100
}
}
| 8303632858e57e46777693313f06f2df | 24.115385 | 81 | 0.63706 | false | false | false | false |
eRGoon/RGPageViewController | refs/heads/master | Example/RGViewPager/Examples/ExampleBottomBarViewController.swift | mit | 1 | //
// ExampleBottomBarViewController.swift
// RGViewPager
//
// Created by Ronny Gerasch on 28.01.17.
// Copyright © 2017 Ronny Gerasch. All rights reserved.
//
import UIKit
import RGPageViewController
class ExampleBottomBarViewController: RGPageViewController {
override var pagerOrientation: UIPageViewControllerNavigationOrientation {
return .horizontal
}
override var tabbarPosition: RGTabbarPosition {
return .bottom
}
override var tabbarStyle: RGTabbarStyle {
return .blurred
}
override var tabIndicatorColor: UIColor {
return UIColor.white
}
override var barTintColor: UIColor? {
return navigationController?.navigationBar.barTintColor
}
override var tabStyle: RGTabStyle {
return .inactiveFaded
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.currentTabIndex = 3
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.currentTabIndex = 3
}
override func viewDidLoad() {
super.viewDidLoad()
datasource = self
delegate = self
}
}
// MARK: - RGPageViewControllerDataSource
extension ExampleBottomBarViewController: RGPageViewControllerDataSource {
func numberOfPages(for pageViewController: RGPageViewController) -> Int {
return movies.count
}
func pageViewController(_ pageViewController: RGPageViewController, tabViewForPageAt index: Int) -> UIView {
let tabView = UILabel()
tabView.font = UIFont.systemFont(ofSize: 17)
tabView.text = movies[index]["title"] as? String
tabView.textColor = UIColor.white
tabView.sizeToFit()
return tabView
}
func pageViewController(_ pageViewController: RGPageViewController, viewControllerForPageAt index: Int) -> UIViewController? {
if (movies.count == 0) || (index >= movies.count) {
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard!.instantiateViewController(withIdentifier: "MovieViewController") as! MovieViewController
dataViewController.movieData = movies[index]
return dataViewController
}
}
// MARK: - RGPageViewController Delegate
extension ExampleBottomBarViewController: RGPageViewControllerDelegate {
// use this to set a custom width for a tab
func pageViewController(_ pageViewController: RGPageViewController, widthForTabAt index: Int) -> CGFloat {
var tabSize = (movies[index]["title"] as! String).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17)])
tabSize.width += 32
return tabSize.width
}
}
| 1c08b380fe4c98c46dd01faf8565981c | 26.414141 | 129 | 0.723287 | false | false | false | false |
Hovo-Infinity/radio | refs/heads/master | Radio/Extentions.swift | gpl-3.0 | 1 | //
// Extentions.swift
// Radio
//
// Created by Hovhannes Stepanyan on 7/26/17.
// Copyright © 2017 Hovhannes Stepanyan. All rights reserved.
//
import UIKit
import AVFoundation
extension FileManager {
func createSubdirectoryOfSongPath(maned name:String) -> Bool {
let url = FileManager.songPath().appendingPathComponent(name)
if FileManager.default.fileExists(atPath: url.absoluteString) {
return true;
} else {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error.localizedDescription)
return false
}
return true
}
}
class func songPath() -> URL {
do {
var url = try FileManager.default.url(for: FileManager.SearchPathDirectory.applicationSupportDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: true);
url.appendPathComponent("music");
if (!FileManager.default.fileExists(atPath: url.absoluteString)) {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil);
} catch {
print(error.localizedDescription);
}
}
return url;
} catch {
return URL(string: "")!;
}
}
func directoryExcist(atPath:String) -> Bool {
var isDictionary:ObjCBool = false
self.fileExists(atPath: atPath, isDirectory: &isDictionary)
return isDictionary.boolValue
}
func contentsOfDirectory(at path:URL) throws -> Array<URL> {
do {
return try FileManager.default.contentsOfDirectory(at: path, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles);
} catch {
throw error;
}
}
}
extension AVPlayer {
static let sharedPlayer = AVPlayer();
open func stop() {
self.pause();
self.seek(to: CMTime(value: 0, timescale: AVPlayer.sharedPlayer.currentTime().timescale));
}
open func addObserver(_ observer:UISlider?, forTimePeriod seconds:Float) {
self.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 1000000000), queue: DispatchQueue.main) { (time) in
let value = Float((self.currentItem?.asset.duration.seconds)!);
observer?.maximumValue = value;
observer?.setValue(Float(time.seconds), animated: true);
}
}
}
let _sharedPlayer:AVAudioPlayer = AVAudioPlayer();
extension AVAudioPlayer {
class func sharedAudioPlayer() -> AVAudioPlayer {
return _sharedPlayer;
}
}
class AVPlayerDelegate : NSObject {
private static let share:AVPlayerDelegate = AVPlayerDelegate();
class func sharedInstance() -> AVPlayerDelegate {
return share;
}
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: Selector(("playerNotifListen")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
private func playerNotifListen(_ note:Notification) {
print(note.userInfo ?? "");
let _ = note.object;
}
}
| 9e1b04502033b810a01763bb522d7358 | 33.071429 | 204 | 0.630428 | false | false | false | false |
mark-randall/Forms | refs/heads/master | Pod/Classes/InputViewModels/FormInputViewModel.swift | mit | 1 | //
// FormInputViewModel.swift
//
// The MIT License (MIT)
//
// Created by mrandall on 10/27/15.
// Copyright © 2015 mrandall. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Bond
//MARK: - FormInputViewModelObservable
public protocol FormInputViewModelObservable {
var identifier: String { get }
var focused: Bool { get set }
//attempts to make the view backed by this FormInputViewModelProtocol the firstResponder when the return key is tapped
//does not affect the value of the returnKey; must be set to next manually
var nextInputsViewModel: FormInputViewModelObservable? { get set }
var focusedObservable: Observable<Bool> { get }
var hiddenObservable: Observable<Bool> { get }
var enabledObservable: Observable<Bool> { get }
var displayValueObservable: Observable<String> { get }
var captionObservable: Observable<NSAttributedString> { get }
var placeholderObservable: Observable<NSAttributedString> { get }
var returnKeyTypeObservable: Observable<UIReturnKeyType> { get }
var secureTextEntryObservable: Observable<Bool> { get }
var keyboardTypeObservable: Observable<UIKeyboardType> { get }
var autocorrectionTypeObservable: Observable<UITextAutocorrectionType> { get }
var validObservable: Observable<Bool> { get }
var errorTextObservable: Observable<NSAttributedString> { get }
var inputViewLayoutObservable: Observable<InputViewLayout> { get }
}
//MARK: - InputViewLayout
final public class InputViewLayout: FormBaseTextInputViewLayout {
public var insets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
public var inputLayoutAxis = UILayoutConstraintAxis.Vertical
public var subviewSpacing = 0.0
public var subviewOrder = [InputSubviews.TextField, InputSubviews.ErrorLabel, InputSubviews.CaptionLabel]
init() { }
}
//Base class for FormInputViewModel
public class FormInputViewModel<T>: FormInputViewModelObservable, Equatable {
//textfield text
public var valueObservable: Observable<T?>
public var value: T? {
didSet {
//only update observable if value is not nil
if let value = value {
valueObservable.next(value)
valid = validateUsingDisplayValidationErrorsOnValueChangeValue()
if let displayValueMap = displayValueMap {
displayValue = displayValueMap(value)
} else {
displayValue = value as? String ?? "ERROR"
}
} else {
valid = validateUsingDisplayValidationErrorsOnValueChangeValue()
displayValue = ""
}
}
}
//map value to displya view
public var displayValueMap: ((T) -> String)? {
didSet {
//set value to mapped display value through value didSet observer
let value = self.value
self.value = value
}
}
//MARK: - FormInputViewModelProtocol
public var identifier: String
public var nextInputsViewModel: FormInputViewModelObservable? {
didSet {
if nextInputsViewModel != nil {
returnKeyType = .Next
}
}
}
public var focusedObservable = Observable<Bool>(false)
public var focused = false {
didSet {
if focused != oldValue {
focusedObservable.next(focused)
}
}
}
public var hiddenObservable = Observable<Bool>(false)
public var hidden = false {
didSet {
if hidden != oldValue {
hiddenObservable.next(hidden)
}
}
}
//is viewModel view enabled
//view is responsible for determining what this means
public var enabledObservable = Observable<Bool>(true)
public var enabled: Bool = true {
didSet {
if enabled != oldValue {
enabledObservable.next(enabled)
}
}
}
//textfield text
public var displayValueObservable = Observable<String>("")
public var displayValue: String = "" {
didSet {
if displayValue != oldValue {
displayValueObservable.next(displayValue)
}
}
}
//caption label text
public var captionObservable = Observable<NSAttributedString>(NSAttributedString(string: ""))
public var caption: String = "" {
didSet {
if caption != oldValue {
captionObservable.next(NSAttributedString(string: caption))
}
}
}
public var captionAttributedText: NSAttributedString? {
didSet {
if captionAttributedText?.string != caption {
captionObservable.next(captionAttributedText!)
}
}
}
//textfield placeholder
public var placeholderObservable = Observable<NSAttributedString>(NSAttributedString(string: ""))
public var placeholder: String = "" {
didSet {
if placeholder != oldValue {
placeholderObservable.next(NSAttributedString(string: placeholder))
}
}
}
public var placeholderAttributedText: NSAttributedString? {
didSet {
if placeholderAttributedText?.string != placeholder {
placeholderObservable.next(placeholderAttributedText!)
}
}
}
//textfield return key
public var returnKeyTypeObservable = Observable<UIReturnKeyType>(.Default )
public var returnKeyType: UIReturnKeyType = .Default {
didSet {
if returnKeyType != oldValue {
returnKeyTypeObservable.next(returnKeyType)
}
}
}
//secure input
public var secureTextEntryObservable = Observable<Bool>(false)
public var secureTextEntry: Bool = false {
didSet {
if secureTextEntry != oldValue {
secureTextEntryObservable.next(secureTextEntry)
}
}
}
//keyboardType
public var keyboardTypeObservable = Observable<UIKeyboardType>(.Default)
public var keyboardType: UIKeyboardType = .Default {
didSet {
if keyboardType != oldValue {
keyboardTypeObservable.next(keyboardType)
}
}
}
//autocorrectionType
public var autocorrectionTypeObservable = Observable<UITextAutocorrectionType>(.Default)
public var autocorrectionType: UITextAutocorrectionType = .Default {
didSet {
if autocorrectionType != oldValue {
autocorrectionTypeObservable.next(autocorrectionType)
}
}
}
//MARK: - FormInputValidatable Variables
//whether input is valid
public var validObservable = Observable<Bool>(true)
public var valid = true {
didSet {
if valid != oldValue {
validObservable.next(valid)
}
}
}
//error text if not value
public var errorTextObservable = Observable<NSAttributedString>(NSAttributedString(string: ""))
public var errorText: String? {
didSet {
if errorText != oldValue {
errorTextObservable.next(NSAttributedString(string: errorText ?? ""))
}
}
}
public var validationRules = [FormInputValidationRule<T>]() {
didSet {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.validate(updateErrorText: self.displayValidationErrorsOnValueChange)
}
}
}
public var inputValueToValidate: T? { return self.value }
public var displayValidationErrorsOnValueChange: Bool = false {
didSet {
if displayValidationErrorsOnValueChange == true {
validateUsingDisplayValidationErrorsOnValueChangeValue()
}
}
}
//MARK: - Layout
//layout of input
public var inputViewLayoutObservable = Observable<InputViewLayout>(InputViewLayout())
public var inputViewLayout: InputViewLayout {
didSet {
inputViewLayoutObservable.next(inputViewLayout)
}
}
//MARK: - Init
// Init
//
// - Parameter value: T
public init(identifier: String, value: T?, inputViewLayout: InputViewLayout = InputViewLayout()) {
self.identifier = identifier
self.value = value
valueObservable = Observable<T?>(value)
displayValue = self.value as? String ?? ""
displayValueObservable.next(displayValue)
self.inputViewLayout = inputViewLayout
inputViewLayoutObservable = Observable(self.inputViewLayout)
}
public func validateUsingDisplayValidationErrorsOnValueChangeValue() -> Bool {
return validate(updateErrorText: displayValidationErrorsOnValueChange)
}
}
//MARK: - Equatable
public func ==<T>(lhs: FormInputViewModel<T>, rhs: FormInputViewModel<T>) -> Bool {
return lhs.identifier == rhs.identifier
}
//MARK: - FormInputValidatable
extension FormInputViewModel: FormInputValidatable {
public func validate() -> Bool {
return validate(updateErrorText: true)
}
} | e28ae5c25c95f9845445234ab2680da0 | 32.0375 | 122 | 0.633999 | false | false | false | false |
joshuamcshane/nessie-ios-sdk-swift2 | refs/heads/test | Nessie-iOS-Wrapper/Bill.swift | mit | 1 | //
// Bill.swift
// Nessie-iOS-Wrapper
//
// Created by Mecklenburg, William on 4/3/15.
// Copyright (c) 2015 Nessie. All rights reserved.
//
import Foundation
public enum BillStatus : String {
case PENDING = "pending"
case RECURRING = "recurring"
case CANCELLED = "cancelled"
case COMPLETED = "completed"
}
public class BillRequestBuilder {
public var requestType: HTTPType?
public var billId: String?
public var status: BillStatus?
public var payee: String?
public var nickname: String?
public var paymentDate: NSDate?
public var recurringDate: Int?
public var paymentAmount: Int?
public var accountId: String!
public var customerId: String!
}
public class BillRequest {
private var request: NSMutableURLRequest?
private var getsArray: Bool = true
private var builder: BillRequestBuilder!
public convenience init?(block: (BillRequestBuilder -> Void)) {
let initializingBuilder = BillRequestBuilder()
block(initializingBuilder)
self.init(builder: initializingBuilder)
}
private init?(builder: BillRequestBuilder)
{
self.builder = builder
if (builder.accountId == nil) {
NSLog("Please provide an account ID for bill request")
}
if (builder.billId == nil && builder.requestType != HTTPType.GET && builder.requestType != HTTPType.POST) {
NSLog("PUT/DELETE require a bill id")
return nil
}
let isValid = validateBuilder(builder)
if (!isValid) {
return nil
}
let requestString = buildRequestUrl();
buildRequest(requestString);
}
private func validateBuilder(builder:BillRequestBuilder) -> Bool {
if builder.status == BillStatus.RECURRING {
if (builder.paymentDate != nil || builder.recurringDate == nil) {
NSLog("Recurring payment must have paymentDate of nil, has \(builder.paymentDate). Must have non-nil recurring date, has \(builder.recurringDate)")
return false
}
}
else if builder.status == BillStatus.PENDING {
if (builder.paymentDate == nil || builder.recurringDate != nil) {
NSLog("Pending payment must have non-nil, has \(builder.paymentDate). Must have nil recurring date, has \(builder.recurringDate)")
return false
}
}
return true
}
//Methods for building the request.
private func buildRequestUrl() -> String {
var requestString = "\(baseString)"
if (builder.customerId != nil) {
requestString += "/customers/\(builder.customerId)/bills"
} else if (builder.billId != nil) {
self.getsArray = false
requestString += "/bills/\(builder.billId!)"
} else if (builder.accountId != nil) {
requestString += "/accounts/\(builder.accountId)/bills"
}
requestString += "?key=\(NSEClient.sharedInstance.getKey())"
return requestString
}
private func buildRequest(url: String) -> NSMutableURLRequest {
self.request = NSMutableURLRequest(URL: NSURL(string: url)!)
self.request!.HTTPMethod = builder.requestType!.rawValue
addParamsToRequest();
self.request!.setValue("application/json", forHTTPHeaderField: "content-type")
return request!
}
private func addParamsToRequest() {
var params:Dictionary<String, AnyObject>= [:]
var err: NSError?
if (builder.requestType == HTTPType.POST) {
params = ["nickname":builder.nickname!, "status":builder.status!.rawValue, "payee":builder.payee!,"payment_amount":builder.paymentAmount!]
if (builder.paymentDate != nil) {
params["payment_date"] = dateFormatter.stringFromDate(builder.paymentDate!)
}
if (builder.recurringDate != nil) {
params["recurring_date"] = builder.recurringDate
}
do {
self.request!.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch let error as NSError {
if err == nil {
err = error
self.request!.HTTPBody = nil
}
}
}
if (builder.requestType == HTTPType.PUT) {
if let nickname = builder.nickname {
params["nickname"] = nickname
}
if (builder.paymentDate != nil) {
params["payment_date"] = dateFormatter.stringFromDate(builder.paymentDate!)
}
if (builder.recurringDate != nil) {
params["recurring_date"] = builder.recurringDate
}
if let status = builder.status {
params["status"] = status.rawValue
}
if let payee = builder.payee {
params["payee"] = payee
}
if let paymentAmount = builder.paymentAmount {
params["payment_amount"] = paymentAmount
}
do {
self.request!.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch let error as NSError {
if err == nil {
err = error
self.request!.HTTPBody = nil
}
}
}
}
//Method for sending the request
public func send(completion completion: ((BillResult) -> Void)?) {
NSURLSession.sharedSession().dataTaskWithRequest(request!, completionHandler:{(data, response, error) -> Void in
if error != nil {
NSLog(error!.description)
return
}
if (completion == nil) {
return
}
let result = BillResult(data: data!)
completion!(result)
}).resume()
}
}
public struct BillResult {
private var dataItem:Bill?
private var dataArray:Array<Bill>?
internal init(data:NSData) {
//var parseError: NSError?
if let parsedObject = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? Array<Dictionary<String,AnyObject>> {
dataArray = []
dataItem = nil
for bill in parsedObject {
dataArray?.append(Bill(data: bill))
}
return
}
if let parsedObject = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? Dictionary<String,AnyObject> {
dataArray = nil
//If there is an error message, the json will parse to a dictionary, not an array
if let message:AnyObject = parsedObject["message"] {
NSLog(message.description!)
if let reason:AnyObject = parsedObject["culprit"] {
NSLog("Reasons:\(reason.description)")
return
} else {
return
}
}
if let results:Array<AnyObject> = parsedObject["results"] as? Array<AnyObject> {
dataArray = []
dataItem = nil
for transfer in results {
dataArray?.append(Bill(data: transfer as! Dictionary<String, AnyObject>))
}
return
}
dataItem = Bill(data: parsedObject)
}
if (dataItem == nil && dataArray == nil) {
let datastring = NSString(data: data, encoding: NSUTF8StringEncoding)
if (data.description == "<>") {
NSLog("Bill delete Successful")
} else {
NSLog("Could not parse data: \(datastring)")
}
}
}
public func getBill() -> Bill? {
if (dataItem == nil) {
NSLog("No single data item found. If you were intending to get multiple items, try getAllBills()");
}
return dataItem
}
public func getAllBills() -> Array<Bill>? {
if (dataArray == nil) {
NSLog("No array of data items found. If you were intending to get one single item, try getBill()");
}
return dataArray
}
}
public class Bill {
public let billId:String
public let status:BillStatus
public var nickname:String? = nil
public var paymentDate:NSDate? = nil
public var recurringDate:Int?
public let paymentAmount: Int
public var creationDate:NSDate?
public var upcomingPaymentDate:NSDate? = nil
internal init(data:Dictionary<String,AnyObject>) {
self.billId = data["_id"] as! String
self.status = BillStatus(rawValue: (data["status"] as! String))!
self.nickname = data["nickname"] as? String
let paymentDateString = data["payment_date"] as? String
if let str = paymentDateString {
self.paymentDate = dateFormatter.dateFromString(str)
}
if let recurring:Int = data["recurring_date"] as? Int {
self.recurringDate = recurring
}
self.paymentAmount = data["payment_amount"] as! Int
self.creationDate = dateFormatter.dateFromString(data["creation_date"] as! String)
let upcomingDateString:String? = data["upcoming_payment_date"] as? String
if let str = upcomingDateString {
self.upcomingPaymentDate = dateFormatter.dateFromString(str)
}
}
}
| dbe221a5de4049586ecca48aa9ef78a9 | 34.195652 | 163 | 0.565575 | false | false | false | false |
egnwd/ic-bill-hack | refs/heads/master | MondoKit/MondoAddress.swift | mit | 2 | //
// MondoAddress.swift
// MondoKit
//
// Created by Mike Pollard on 26/01/2016.
// Copyright © 2016 Mike Pollard. All rights reserved.
//
import Foundation
import SwiftyJSON
import SwiftyJSONDecodable
public struct MondoAddress {
public let address : String
public let city : String
public let country : String
public let latitude : Double
public let longitude : Double
public let postcode : String
public let region : String
}
extension MondoAddress : SwiftyJSONDecodable {
public init(json: JSON) throws {
address = try json.decodeValueForKey("address")
city = try json.decodeValueForKey("city")
country = try json.decodeValueForKey("country")
latitude = try json.decodeValueForKey("latitude")
longitude = try json.decodeValueForKey("longitude")
postcode = try json.decodeValueForKey("postcode")
region = try json.decodeValueForKey("region")
}
} | 8d63225e3ba0bc77bbb561af1febbd91 | 25.888889 | 59 | 0.683557 | false | false | false | false |
NeilNie/Done- | refs/heads/master | Pods/Charts/Source/Charts/Renderers/ScatterChartRenderer.swift | apache-2.0 | 2 | //
// ScatterChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class ScatterChartRenderer: LineScatterCandleRadarRenderer
{
@objc open weak var dataProvider: ScatterChartDataProvider?
@objc public init(dataProvider: ScatterChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let scatterData = dataProvider?.scatterData else { return }
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
if let chart = dataProvider as? ScatterChartView {
// Make the chart header the first element in the accessible elements array
let element = createAccessibleHeader(usingChart: chart,
andData: scatterData,
withDefaultDescription: "Scatter Chart")
accessibleChartElements.append(element)
}
// TODO: Due to the potential complexity of data presented in Scatter charts, a more usable way
// for VO accessibility would be to use axis based traversal rather than by dataset.
// Hence, accessibleChartElements is not populated below. (Individual renderers guard against dataSource being their respective views)
for i in 0 ..< scatterData.dataSetCount
{
guard let set = scatterData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IScatterChartDataSet)
{
fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet")
}
drawDataSet(context: context, dataSet: set as! IScatterChartDataSet)
}
}
}
private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawDataSet(context: CGContext, dataSet: IScatterChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let entryCount = dataSet.entryCount
var point = CGPoint()
let valueToPixelMatrix = trans.valueToPixelMatrix
if let renderer = dataSet.shapeRenderer
{
context.saveGState()
for j in 0 ..< Int(min(ceil(Double(entryCount) * animator.phaseX), Double(entryCount)))
{
guard let e = dataSet.entryForIndex(j) else { continue }
point.x = CGFloat(e.x)
point.y = CGFloat(e.y * phaseY)
point = point.applying(valueToPixelMatrix)
if !viewPortHandler.isInBoundsRight(point.x)
{
break
}
if !viewPortHandler.isInBoundsLeft(point.x) ||
!viewPortHandler.isInBoundsY(point.y)
{
continue
}
renderer.renderShape(context: context, dataSet: dataSet, viewPortHandler: viewPortHandler, point: point, color: dataSet.color(atIndex: j))
}
context.restoreGState()
}
else
{
print("There's no IShapeRenderer specified for ScatterDataSet", terminator: "\n")
}
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return }
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< scatterData.dataSetCount
{
let dataSet = dataSets[i]
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
let shapeSize = dataSet.scatterShapeSize
let lineHeight = valueFont.lineHeight
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the lines don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x)
|| !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
let text = formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler)
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(
x: pt.x,
y: pt.y - shapeSize - lineHeight),
align: .center,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: dataSet.valueTextColorAt(j)]
)
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let scatterData = dataProvider.scatterData
else { return }
context.saveGState()
for high in indices
{
guard
let set = scatterData.getDataSetByIndex(high.dataSetIndex) as? IScatterChartDataSet,
set.isHighlightEnabled
else { continue }
guard let entry = set.entryForXValue(high.x, closestToY: high.y) else { continue }
if !isInBoundsX(entry: entry, dataSet: set) { continue }
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let x = entry.x // get the x-position
let y = entry.y * Double(animator.phaseY)
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
let pt = trans.pixelForValues(x: x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
}
| 3dc2cfeab02274934237d323d3eb730b | 35.2607 | 154 | 0.503917 | false | false | false | false |
developerXiong/CYBleManager | refs/heads/master | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceDelegate.swift | bsd-3-clause | 2 | /*
* Copyright (c) 2016, Nordic Semiconductor
* 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 nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@objc public enum DFUError : Int {
// Legacy DFU errors
case remoteLegacyDFUSuccess = 1
case remoteLegacyDFUInvalidState = 2
case remoteLegacyDFUNotSupported = 3
case remoteLegacyDFUDataExceedsLimit = 4
case remoteLegacyDFUCrcError = 5
case remoteLegacyDFUOperationFailed = 6
// Secure DFU errors (received value + 10 as they overlap legacy errors)
case remoteSecureDFUSuccess = 11 // 10 + 1
case remoteSecureDFUOpCodeNotSupported = 12 // 10 + 2
case remoteSecureDFUInvalidParameter = 13 // 10 + 3
case remoteSecureDFUInsufficientResources = 14 // 10 + 4
case remoteSecureDFUInvalidObject = 15 // 10 + 5
case remoteSecureDFUSignatureMismatch = 16 // 10 + 6
case remoteSecureDFUUnsupportedType = 17 // 10 + 7
case remoteSecureDFUOperationNotpermitted = 18 // 10 + 8
case remoteSecureDFUOperationFailed = 20 // 10 + 10
case remoteSecureDFUExtendedError = 21 // 10 + 11
// Experimental Buttonless DFU errors (received value + 9000 as they overlap legacy and secure DFU errors)
case remoteExperimentalBootlonlessDFUSuccess = 9001 // 9000 + 1
case remoteExperimentalBootlonlessDFUOpCodeNotSupported = 9002 // 9000 + 2
case remoteExperimentalBootlonlessDFUOperationFailed = 9004 // 9000 + 4
// Buttonless DFU errors (received value + 9000 as they overlap legacy and secure DFU errors)
case remoteBootlonlessDFUSuccess = 31 // 30 + 1
case remoteBootlonlessDFUOpCodeNotSupported = 32 // 30 + 2
case remoteBootlonlessDFUOperationFailed = 34 // 30 + 4
/// Providing the DFUFirmware is required.
case fileNotSpecified = 101
/// Given firmware file is not supported.
case fileInvalid = 102
/// Since SDK 7.0.0 the DFU Bootloader requires the extended Init Packet. For more details, see:
/// http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v11.0.0/bledfu_example_init.html?cp=4_0_0_4_2_1_1_3
case extendedInitPacketRequired = 103
/// Before SDK 7.0.0 the init packet could have contained only 2-byte CRC value, and was optional.
/// Providing an extended one instead would cause CRC error during validation (the bootloader assumes that the 2 first bytes
/// of the init packet are the firmware CRC).
case initPacketRequired = 104
case failedToConnect = 201
case deviceDisconnected = 202
case bluetoothDisabled = 203
case serviceDiscoveryFailed = 301
case deviceNotSupported = 302
case readingVersionFailed = 303
case enablingControlPointFailed = 304
case writingCharacteristicFailed = 305
case receivingNotificationFailed = 306
case unsupportedResponse = 307
/// Error raised during upload when the number of bytes sent is not equal to number of bytes confirmed in Packet Receipt Notification.
case bytesLost = 308
/// Error raised when the CRC reported by the remote device does not match. Service has done 3 tries to send the data.
case crcError = 309
}
/**
The state of the DFU Service.
- connecting: Service is connecting to the DFU target
- starting: DFU Service is initializing DFU operation
- enablingDfuMode: Service is switching the device to DFU mode
- uploading: Service is uploading the firmware
- validating: The DFU target is validating the firmware
- disconnecting: The iDevice is disconnecting or waiting for disconnection
- completed: DFU operation is completed and successful
- aborted: DFU Operation was aborted
*/
@objc public enum DFUState : Int {
case connecting
case starting
case enablingDfuMode
case uploading
case validating
case disconnecting
case completed
case aborted
public func description() -> String {
switch self {
case .connecting: return "Connecting"
case .starting: return "Starting"
case .enablingDfuMode: return "Enabling DFU Mode"
case .uploading: return "Uploading"
case .validating: return "Validating" // this state occurs only in Legacy DFU
case .disconnecting: return "Disconnecting"
case .completed: return "Completed"
case .aborted: return "Aborted"
}
}
}
/**
* The progress delegates may be used to notify user about progress updates.
* The only method of the delegate is only called when the service is in the Uploading state.
*/
@objc public protocol DFUProgressDelegate {
/**
Callback called in the `State.Uploading` state. Gives detailed information about the progress
and speed of transmission. This method is always called at least two times (for 0% and 100%)
if upload has started and did not fail.
This method is called in the main thread and is safe to update any UI.
- parameter part: number of part that is currently being transmitted. Parts start from 1
and may have value either 1 or 2. Part 2 is used only when there were Soft Device and/or
Bootloader AND an Application in the Distribution Packet and the DFU target does not
support sending all files in a single connection. First the SD and/or BL will be sent, then
the service will disconnect, reconnect again to the (new) bootloader and send the Application.
- parameter totalParts: total number of parts that are to be send (this is always equal to 1 or 2).
- parameter progress: the current progress of uploading the current part in percentage (values 0-100).
Each value will be called at most once - in case of a large file a value e.g. 3% will be called only once,
despite that it will take more than one packet to reach 4%. In case of a small firmware file
some values may be ommited. For example, if firmware file would be only 20 bytes you would get
a callback 0% (called always) and then 100% when done.
- parameter currentSpeedBytesPerSecond: the current speed in bytes per second
- parameter avgSpeedBytesPerSecond: the average speed in bytes per second
*/
func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int,
currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double)
}
/**
* The service delegate reports about state changes and errors.
*/
@objc public protocol DFUServiceDelegate {
/**
Callback called when state of the DFU Service has changed.
This method is called in the main thread and is safe to update any UI.
- parameter state: the new state fo the service
*/
func dfuStateDidChange(to state: DFUState)
/**
Called after an error occurred.
The device will be disconnected and DFU operation has been aborted.
This method is called in the main thread and is safe to update any UI.
- parameter error: the error code
- parameter message: error description
*/
func dfuError(_ error: DFUError, didOccurWithMessage message: String)
}
| dfef74075d77cbc1e3d262928d90a3ad | 50.37931 | 144 | 0.692282 | false | false | false | false |
CodaFi/Tyro | refs/heads/master | Tyro/Date.swift | bsd-3-clause | 3 | //
// Date.swift
// Tyro
//
// Created by Matthew Purland on 11/17/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import Foundation
import Swiftz
public struct DateTimestampJSONConverter : FromJSON, ToJSON {
public typealias T = NSDate
private init() {}
public static func fromJSON(value : JSONValue) -> Either<JSONError, NSDate> {
switch value {
case .Number(let value):
let date = NSDate(timeIntervalSince1970 : value.doubleValue / 1000.0)
return .Right(date)
default:
return .Left(.TypeMismatch("NSDate timestamp", "\(value.dynamicType.self)"))
}
}
public static func toJSON(date : NSDate) -> Either<JSONError, JSONValue> {
return .Right(.Number(NSNumber(unsignedLongLong : UInt64(date.timeIntervalSince1970 * 1000.0))))
}
}
public struct DateTimestampJSONFormatter : JSONFormatterType {
public typealias T = DateTimestampJSONConverter.T
public private(set) var jsonValue : JSONValue?
public init(_ jsonValue : JSONValue?) {
self.jsonValue = jsonValue
}
public init() {
jsonValue = nil
}
public func decodeEither(value : JSONValue) -> Either<JSONError, T> {
return DateTimestampJSONConverter.fromJSON(value)
}
public func encodeEither(value : T) -> Either<JSONError, JSONValue> {
return DateTimestampJSONConverter.toJSON(value)
}
}
public struct DateFormatJSONFormatter : JSONFormatterType {
public typealias T = NSDate
public let dateFormat : String
public static let DefaultDateFormat = "yyyy'-'MM'-'dd HH':'mm':'ss ZZZ"
public private(set) var jsonValue : JSONValue?
public init(_ jsonValue : JSONValue?, _ dateFormat : String = DateFormatJSONFormatter.DefaultDateFormat) {
self.dateFormat = dateFormat
self.jsonValue = jsonValue
}
public func decodeEither(value : JSONValue) -> Either<JSONError, T> {
switch value {
case .String(let value):
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
let date = formatter.dateFromString(value)
if let date = date {
return .Right(date)
}
else {
return .Left(.Custom("Could not format value (\(value)) to format (\(formatter.dateFormat))"))
}
default:
return .Left(.TypeMismatch("NSDate format", "\(value.dynamicType.self)"))
}
}
public func encodeEither(value : T) -> Either<JSONError, JSONValue> {
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
let string = formatter.stringFromDate(value)
return .Right(.String(string))
}
}
| 3bf3a0f11ab9042945b0ba76e2940d5b | 29.989011 | 110 | 0.625532 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | refs/heads/master | Pod/Classes/Sources.Api/Acceleration.swift | apache-2.0 | 1 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Structure representing the data of a single acceleration reading.
@author Carlos Lozano Diez
@since v2.0
@version 1.0
*/
public class Acceleration : APIBean {
/**
Timestamp of the acceleration reading.
*/
var timestamp : Int64?
/**
X-axis component of the acceleration.
*/
var x : Double?
/**
Y-axis component of the acceleration.
*/
var y : Double?
/**
Z-axis component of the acceleration.
*/
var z : Double?
/**
Default constructor
@since v2.0
*/
public override init() {
super.init()
}
/**
Constructor with fields
@param x X Coordinate
@param y Y Coordinate
@param z Z Coordinate
@param timestamp Timestamp
@since v2.0
*/
public init(x: Double, y: Double, z: Double, timestamp: Int64) {
super.init()
self.x = x
self.y = y
self.z = z
self.timestamp = timestamp
}
/**
Timestamp Getter
@return Timestamp
@since v2.0
*/
public func getTimestamp() -> Int64? {
return self.timestamp
}
/**
Timestamp Setter
@param timestamp Timestamp
@since v2.0
*/
public func setTimestamp(timestamp: Int64) {
self.timestamp = timestamp
}
/**
X Coordinate Getter
@return X-axis component of the acceleration.
@since v2.0
*/
public func getX() -> Double? {
return self.x
}
/**
X Coordinate Setter
@param x X-axis component of the acceleration.
@since v2.0
*/
public func setX(x: Double) {
self.x = x
}
/**
Y Coordinate Getter
@return Y-axis component of the acceleration.
@since v2.0
*/
public func getY() -> Double? {
return self.y
}
/**
Y Coordinate Setter
@param y Y-axis component of the acceleration.
@since v2.0
*/
public func setY(y: Double) {
self.y = y
}
/**
Z Coordinate Getter
@return Z-axis component of the acceleration.
@since v2.0
*/
public func getZ() -> Double? {
return self.z
}
/**
Z Coordinate Setter
@param z Z Coordinate
@since v2.0
*/
public func setZ(z: Double) {
self.z = z
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> Acceleration {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> Acceleration {
let resultObject : Acceleration = Acceleration()
if let value : AnyObject = dict.objectForKey("timestamp") {
if "\(value)" as NSString != "<null>" {
let numValue = value as? NSNumber
resultObject.timestamp = numValue?.longLongValue
}
}
if let value : AnyObject = dict.objectForKey("x") {
if "\(value)" as NSString != "<null>" {
resultObject.x = (value as! Double)
}
}
if let value : AnyObject = dict.objectForKey("y") {
if "\(value)" as NSString != "<null>" {
resultObject.y = (value as! Double)
}
}
if let value : AnyObject = dict.objectForKey("z") {
if "\(value)" as NSString != "<null>" {
resultObject.z = (value as! Double)
}
}
return resultObject
}
public static func toJSON(object: Acceleration) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.timestamp != nil ? jsonString.appendString("\"timestamp\": \(object.timestamp!), ") : jsonString.appendString("\"timestamp\": null, ")
object.x != nil ? jsonString.appendString("\"x\": \(object.x!), ") : jsonString.appendString("\"x\": null, ")
object.y != nil ? jsonString.appendString("\"y\": \(object.y!), ") : jsonString.appendString("\"y\": null, ")
object.z != nil ? jsonString.appendString("\"z\": \(object.z!)") : jsonString.appendString("\"z\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| f0d3ed64d5d41d8ffda59d71ec73a546 | 26.138528 | 153 | 0.538044 | false | false | false | false |
maxkatzmann/graphlibS | refs/heads/master | Sources/graphlibS/SGraph.swift | gpl-3.0 | 1 | //
// SGraph.swift
// graphS
//
// Created by Maximilian Katzmann on 22.08.17.
// Copyright © 2018 Maximilian Katzmann. All rights reserved.
//
import Foundation
public enum SGraphOutputFormat: String {
case edgeList = "edgeList"
case GML = "GML"
case DL = "DL"
}
public class SGraph: Sequence {
// MARK: - Properties
/// The edges of the graph. Array at the ith position contains the indices
/// of the neighbors of the ith node.
public var edges: [[Int]] = []
/// Internally each vertex is identified using an index. This dictionary,
/// maps the nodes label (e.g. the name of the node in a file) to this index.
public internal(set) var vertexLabels: [Int: String] = [:]
/// The number of nodes in the graph.
public var numberOfVertices: Int {
get {
return edges.count
}
}
/// The number of edges in the graph.
public var numberOfEdges: Int {
get {
var edgeSum = 0
for edges in self.edges {
edgeSum += edges.count
}
if !self.directed {
edgeSum /= 2
}
return edgeSum
}
}
/// A Bool indicating whether the graph is directed or not.
public let directed: Bool
// MARK: - Initiazlization
/// Default initializer that creates a graph containing the specified
/// number of isolated vertices.
///
/// - Parameters:
/// - numberOfVertices: The number of vertices that the graph should have.
/// - directed: Bool indicating whether the graph is directed. The default value is 'false'.
public init(numberOfVertices: Int = 0, directed: Bool = false) {
self.directed = directed
for _ in 0..<numberOfVertices {
edges.append([Int]())
}
}
/// Extracts the edge information from a string and adds the corresponding
/// edgeto the graph. This is a helper method that unifies the behavior of
/// reading a graph from a file or an edge list string.
///
/// - Parameters:
/// - str: A string describing the edge that should be added.
/// - indexMap: A map from strings to indices that is used to keep track of which vertices have already been indexed.
/// - Returns: A Bool value indicating whether the edge was added successfully or not.
private func addEdge(from str: String,
withIndexMap indexMap: inout [String: Int]) -> Bool {
/**
* When the string is empty, we simply ignore it. Additionally,
* we ignore string that are actually comments.
*/
if !str.isEmpty
&& str[str.startIndex] != "#"
&& str[str.startIndex] != "%" {
/**
* Each string should contain two components seperated by
* whitespaces or tabs.
*/
let stringComponents = str.components(separatedBy: CharacterSet.whitespaces)
if stringComponents.count != 2 {
SLogging.error(message: "There was a string that did not consist of a vertex pair.")
} else {
/**
* Get the index for the first vertex
*/
let label1 = stringComponents[0]
var index1 = indexMap[label1]
if index1 == nil {
/**
* If the vertex does not have an index yet, it will get
* the next available index.
*/
index1 = self.edges.count
indexMap[label1] = index1!
/**
* Make sure we later know which vertex belongs to which
* index and afterwards reserve the neighbor array for
*/
self.vertexLabels[index1!] = label1
self.edges.append([])
}
/**
* Get the index for the second vertex
*/
let label2 = stringComponents[1]
var index2 = indexMap[label2]
if index2 == nil {
/**
* If the vertex does not have an index yet, it will get
* the next available index.
*/
index2 = self.edges.count
indexMap[label2] = index2!
/**
* Make sure we later know which vertex belongs to which
* index and afterwards reserve the neighbor array for
*/
self.vertexLabels[index2!] = label2
self.edges.append([])
}
self.edges[index1!].append(index2!)
if !directed {
self.edges[index2!].append(index1!)
}
/**
* A new edge was added successfully.
*/
return true
}
}
/**
* We did not add the edge.
*/
return false
}
/// Initializer that generates a graph from an edge list stored in a string.
/// - Note: When reading an edge list from a file, use the init(filePath:directed:) method for increased performance.
///
/// - Parameters:
/// - edgeList: A string containing the edge list representing the graph.
/// - directed: Bool indicating whether the graph is directed. The default value is 'false'.
public init(edgeList: String, directed: Bool = false) {
self.directed = directed
/**
* Auxiliary dictionary to quickly recognize whether a vertex
* was assigned an index already.
*/
var indexMap: [String: Int] = [:]
var numberOfEdges = 0
edgeList.enumerateLines {
(line: String, stop: inout Bool) in
if self.addEdge(from: line, withIndexMap: &indexMap) {
numberOfEdges += 1
}
/**
* We don't stop until we reached the end of the line.
*/
stop = false
}
}
/// Initializer that reads the graph from an adjacency list stored in a file.
///
/// - Parameters:
/// - filePath: The path to the file that the graph should be read from.
/// - directed: Bool indicating whether the graph should is directed. The default value is 'false'.
public init(filePath: String, directed: Bool = false) {
self.directed = directed
if let inputStreamReader = StreamReader(path: filePath) {
defer {
inputStreamReader.close()
}
/**
* Auxiliary dictionary to quickly recognize whether a vertex
* was assigned an index already.
*/
var indexMap: [String: Int] = [:]
var numberOfEdges = 0
/**
* Iterate the lines of the file.
*/
while let line = inputStreamReader.nextLine() {
if self.addEdge(from: line, withIndexMap: &indexMap) {
numberOfEdges += 1
}
}
}
}
// MARK: - Sequence Protocol
/// This allows us to iterate the vertices of the graph as
/// ````
/// for vertex in graph {
/// ...
/// }
/// ````
public func makeIterator() -> CountableRange<Int>.Iterator {
return (0..<self.numberOfVertices).makeIterator()
}
// MARK: - Vertices and Edges
/// Add a vertex to the graph.
///
/// - Complexity: O(1)
/// - Returns: The index of the newly added vertex
@discardableResult
public func addVertex() -> Int {
self.edges.append([Int]())
return self.edges.count - 1
}
/// Removes the vertex from the graph.
///
/// - Complexity: O(numberOfNodes + numberOfEdges).
/// - Parameter v: The index of the vertex to be removed
public func removeVertex(_ v: Int) {
/**
* Removing the vertex and its neighbors.
*/
self.edges.remove(at: v)
self.vertexLabels.removeValue(forKey: v)
/**
* Since removing a vertex decreases all the indices of the vertices
* with a larger index, we have to rename all these vertices, which
* can be neighbors of any vertex. This means, we have to iterate all
* vertices and check whether they have an neighbor with a larger index.
* Since we have to do this anyway, we can remove references to the
* deleted vertex in the meantime.
*/
for u in self {
var vIndex = -1
for (index, w) in self.edges[u].enumerated() {
/**
* If v is a neighbor of u, v is removed after iterating the
* neighbors
*/
if w == v {
vIndex = index
} else {
/**
* Removing v decreases the indices of all vertices with a larger index than v.
*/
if w > v {
self.edges[u][index] -= 1
}
}
}
if vIndex >= 0 {
self.edges[u].remove(at: vIndex)
}
/**
* Since the indices of all vertices with index larger than v changed,
* we need to update the vertexLabels to reflect that change.
*/
if u > v {
self.vertexLabels[u - 1] = self.vertexLabels[u]
}
}
}
/// Adds an edge from source u to target v.
///
/// - Note: If the the graph is undirected both vertices are treated as source and target.
///
/// - Complexity: Same as the adjacency check.
/// - Parameters:
/// - v: The index of the edge's source.
/// - u: The index of the edge's target.
/// - Returns: A Bool indicating whether the addition was successful. The operation may fail if the edge is already present.
@discardableResult
public func addEdge(from v: Int, to u: Int) -> Bool {
guard !self.adjacent(u: u, v: v) else {
return false
}
self.edges[u].append(v)
/**
* If the graph is undirected we also add the edge in the other direction.
*
* Also if we u = v, we just added a self loop.
* We don't want to add it again.
*/
if !self.directed && u != v {
self.edges[v].append(u)
}
return true
}
/// Removes the edge from u to v.
///
/// - Complexity: Same as adjacency check.
/// - Parameters:
/// - u: The source vertex of the edge to be deleted.
/// - v: The target vertex of the edge to be deleted.
/// - Returns: A Boolean value indicating whether the removal was successful. The operation may fail if the edge doesn't exist in the first place.
@discardableResult
public func removeEdge(from u: Int, to v: Int) -> Bool {
guard self.adjacent(u: u, v: v) else {
return false
}
var removedSuccessful = true
/**
* Determine the position of neighbor v in the edges array of u.
*/
if let vIndexInU = self.edges[u].index(of: v) {
/**
* Delete the edge and the corresponding attribute.
*/
self.edges[u].remove(at: vIndexInU)
} else {
SLogging.error(message: "Tried to remove an edge that apparently doesn't exist.")
removedSuccessful = false
}
/**
* If the graph is undirected, we actually have to delete two edges.
*/
if !self.directed {
/**
* Determine the position of u in the edges array of neighbor v.
*/
if let uIndexInV = self.edges[v].index(of: u) {
/**
* Delete the edge and the corresponding attribute.
*/
self.edges[v].remove(at: uIndexInV)
} else {
SLogging.error(message: "Tried to remove an edge that apparently doesn't exist.")
removedSuccessful = false
}
}
return removedSuccessful
}
// MARK: - Adjacency
/// Determines whether to vertices are connected by an edge, or not.
///
/// - Complexity: If the graph is directed: O(deg(u)). If the graph is undirected: O(min(deg(u), deg(v)).
/// - Parameters:
/// - u: The index of the first vertex.
/// - v: The index of the second vertex.
/// - Returns: A Bool indicating whether the two vertices are connected by an edge.
public func adjacent(u: Int, v: Int) -> Bool {
if (self.directed) {
return self.edges[u].contains(v)
} else {
if (self.edges[u].count < self.edges[v].count) {
return self.edges[u].contains(v)
} else {
return self.edges[v].contains(u)
}
}
}
/// The degree of v in the receiver. That is the number of outgoing edges of v.
///
/// - Complexity: O(1)
/// - Parameter v: The degree of v.
public func degree(of v: Int) -> Int {
return self.edges[v].count
}
/// The maximum degree of the receiver.
/// - Complexity: O(|vertices|)
/// - Returns: The maximum degree of the receiver.
public func maximumDegree() -> Int {
var maximumDegree = 0
for vertex in 0..<self.numberOfVertices {
if degree(of: vertex) > maximumDegree {
maximumDegree = degree(of: vertex)
}
}
return maximumDegree
}
/// The average degree of the receiver.
///
/// - Complexity: O(|vertices|)
/// - Returns: The average degree of the receiver.
public func averageDegree() -> Double {
var degreeSum = 0
for vertex in 0..<self.numberOfVertices {
degreeSum += self.degree(of: vertex)
}
return Double(degreeSum) / Double(self.numberOfVertices)
}
/// Returns the neighbors of a vertex. This is just a wrapper for accessing
/// the edges array.
///
/// - Parameter v: The vertex whose neighbors are to be obtained.
/// - Returns: The neighbors of that vertex.
public func neighborsOf(_ v: Int) -> [Int] {
return self.edges[v]
}
// MARK: - Properties
/// Estimated the power-law exponent of the degree distribution of the receiver.
/// If beta is the power-law coefficient of a graph then the fraction P(k)
/// of nodes in the network that have degree k is is approximately k^(-beta).
///
/// - Complexity: O(numberOfNodes)
/// - Returns: A Double representing the estimated power-law exponent of the degree distribution of the receiver.
public func estimatedPowerLawExponent() -> Double {
var exponent = 0.0
var degreeDistribution = [Int]()
var minDegree = Int.max
for vertex in self {
let degree = self.degree(of: vertex)
degreeDistribution.append(degree)
if degree < minDegree {
minDegree = degree
}
}
let degreeThreshold = Swift.max(minDegree, 7)
var nodesWithDegreeAtLeastThreshold = 0
for degree in degreeDistribution {
if degree >= degreeThreshold {
exponent += log(Double(degree) / (Double(degreeThreshold) - 0.5));
nodesWithDegreeAtLeastThreshold += 1
}
}
return 1.0 + Double(nodesWithDegreeAtLeastThreshold) / exponent;
}
/// Determines the diameter of an undirected graph, which is the longest shortest
/// path in the graph.
///
/// - Note: Not yet implemented for directed graphs.
/// - Complexity: O({BFS}) = O(numberOfVertices + numberOfEdges)
/// - Returns: The diameter of the graph, or -1 if the graph is directed, or Int.max if the graph is not connected, or Int.min if the graph is empty.
public func diameter() -> Int {
/**
* The case for a directed graph is not implemented yet.
*/
guard !self.directed else {
return -1
}
/**
* If the graph is empty, the diaemter is -infinity. The diameter is
* the maximum length of all shortest paths. If the graph is empty,
* this is the maximum over an empty set, which is -infinity.
*/
guard self.numberOfVertices > 0 else {
return Int.min
}
/**
* We start at a any vertex v and determine the distance to all other
* vertices, using a breadth first search.
*/
let startVertex = 0
/**
* We later need the vertex that is farthest from the start vertex.
*/
var farthestVertex = startVertex
var farthestDistance = 0
var distanceToVertex = [Int](repeating: -1,
count: self.numberOfVertices)
distanceToVertex[startVertex] = 0
SAlgorithms.breadthFirstSearch(in: self, startingAt: startVertex) {
(vertex, parent) -> (Bool) in
distanceToVertex[vertex] = distanceToVertex[parent] + 1
if distanceToVertex[vertex] > farthestDistance {
farthestVertex = vertex
farthestDistance = distanceToVertex[vertex]
}
return true
}
/**
* If we have not seen all vertices in the graph, it consists of several
* components and the diameter is thus infinite.
*/
if let minimumDistance = distanceToVertex.min(), minimumDistance < 0 {
return Int.max
}
/**
* Find the largest distance to any other vertex, from the
* farthestVertex. This is the diameter.
*/
var distanceToFarthest = [Int](repeating: -1, count: self.numberOfVertices)
distanceToFarthest[farthestVertex] = 0
var maximumDistance = 0
SAlgorithms.breadthFirstSearch(in: self, startingAt: farthestVertex) {
(vertex, parent) -> (Bool) in
distanceToFarthest[vertex] = distanceToFarthest[parent] + 1
if distanceToFarthest[vertex] > maximumDistance {
maximumDistance = distanceToFarthest[vertex]
}
return true
}
/**
* The diameter is the largest distance a vertex is from the farthest
* vertex.
*/
return maximumDistance
}
// MARK: - Subgraph
/// Obtain the subgraph of the receiver induced by the vertices in the passed set.
///
/// - Complexity: O(|vertices| * max_degree)
/// - Parameter vertices: The vertex set that forms the induced subgraph.
/// - Returns: A tuple containing the induced subgraph and a dictionary that maps the vertices in the receiver to their counterparts in the induced subgraph.
public func subgraph(containing vertices: [Int]) -> (SGraph, [Int: Int]) {
/**
* Our subgraph will contain as many vertices as we get passed.
*/
let subgraph = SGraph(numberOfVertices: vertices.count,
directed: self.directed)
/**
* Prepare an indicator array that denotes which vertices are part of
* the subgraph, as that will save time later.
*/
var isInComponent = [Bool](repeating: false,
count: self.numberOfVertices)
for vertex in vertices {
isInComponent[vertex] = true
}
/**
* The vertices in the new graph are indexed from 0 to |vertices| - 1.
* Therefore, we create a map that can later be used to identify the
* vertices in the subgraph.
*/
var vertexMap = [Int: Int]()
for (index, vertex) in vertices.enumerated() {
vertexMap[vertex] = index
}
/**
* Now we have to build the subgraph by adding the edges from the
* original subgraph, where both end points are also in the passed
* vertex set.
*/
for (v_orig, v) in vertexMap {
/**
* Now we map the remaining orignal neighbors to their
* indices in the subgraph.
*/
var neighborsInSubgraph = [Int]()
for neighborInOriginalGraph in self.edges[v_orig] {
/**
* Check whether this neighbor is also in the subgraph
*/
if isInComponent[neighborInOriginalGraph] {
/**
* If the force unwrapping fails here, the vertex map is corrupted
* which cannot happen.
*/
neighborsInSubgraph.append(vertexMap[neighborInOriginalGraph]!)
}
}
/**
* Now, we assign the neighbors of the vertex in the subgraph.
*/
subgraph.edges[v] = neighborsInSubgraph
/**
* Finally we copy the labels of the original graph to the labels
* of the subgraph.
*
* v is the vertex in the current graph. v_orig is its counterpart
* in the original graph. Therefore, the label of v_orig in the
* original graph now becomes the label of v in the subgraph.
*/
if let vertexLabel = self.vertexLabels[v_orig] {
subgraph.vertexLabels[v] = vertexLabel
}
}
return (subgraph, vertexMap)
}
// MARK: - Connected Components
/// Determines the vertex set representing the connected component that
/// contains the passed vertex v.
///
/// - Complexity: O(numberOfVertices + numberOfEdges)
/// - Parameter v: The vertex contained in the component to obtain.
/// - Returns: An array containing the vertices of the connected component that contains v.
public func verticesInConnectedComponent(containing v: Int) -> [Int] {
/**
* We collect the vertices that belong to this component.
* The start vertex belongs to it in any case.
*/
var verticesInComponent = [v]
SAlgorithms.breadthFirstSearch(in: self,
startingAt: v,
performingTaskOnSeenVertex: {
(u: Int, _: Int) -> (Bool) in
/**
* Every vertex we encounter in this BFS
* belongs to our component.
*/
verticesInComponent.append(u)
/**
* We always want to continue exploring
*/
return true
})
return verticesInComponent
}
/// Determines the vertex set representing the connected component that contains v.
///
/// - Complexity: Complexity of 'verticesInConnectedComponent:' + Complexity of 'subgraph:'
/// - Parameter v: The vertex whose connected component is to be optained.
/// - Returns: A tuple containing an SGraph representing the connected component containing v and a dictionary that maps the vertices in the receiver to the vertices in the induced subgraph.
public func connectedComponent(containing v: Int) -> (SGraph, [Int: Int]) {
return self.subgraph(containing: self.verticesInConnectedComponent(containing: v))
}
/// Determines the vertex set representing the largest connected component
/// in the graph.
/// - Note: This method is asymptotically not faster than 'verticesInConnectedComponents', it might be faster in practive if one is only interested in the largest component.
///
/// - Complexity: Complexity of 'verticesInConnectedComponents'
/// - Returns: An array containing the vertices of the largest connected component of the receiver.
public func verticesInLargestConnectedComponent() -> [Int] {
var largestConnectedComponent = [Int]()
/**
* Knowing how many vertices were not seen yet helps in determining
* whether its useful to continue searching for larger components.
*/
var numberOfUnseenVertices = self.numberOfVertices
/**
* We store the seen/unseen/processed state of each vertex in this array.
*/
var vertexStates = [SVertexState](repeating: .unseen,
count: self.numberOfVertices)
/**
* We iterate all the vertices of our graph.
*/
for v in 0..<self.numberOfVertices {
/**
* Only if a vertex was not seen yet, we actually process it.
*/
if vertexStates[v] == .unseen {
/**
* Get the vertices of the component that contains the start vertex v.
*/
// TODO: We can actually save the for-loop after this statement, by using the BFS directly, instead of relying on verticesInConnectedComponent!:
let verticesInCurrentComponent = self.verticesInConnectedComponent(containing: v)
/**
* All the vertices that are in the current component cannot
* be in another larger component and are therefore marked as
* seen such that they are not processed again.
*/
for u in verticesInCurrentComponent {
vertexStates[u] = .seen
numberOfUnseenVertices -= 1
}
/**
* If we found a component that is larger than the largest one that
* we found previously, the new one is the new largest component.
*/
if verticesInCurrentComponent.count > largestConnectedComponent.count {
largestConnectedComponent = verticesInCurrentComponent
}
/**
* If the largest connected component thus far is larger than the
* the number of unseen vertices, we cannot find a larger component
* among them. Therefore, we can return early.
*
* Note that we will always return here eventually, since after
* iterating all components the number of unseen vertices is 0 and
* our largest component will be larger anyway.
*/
if largestConnectedComponent.count > numberOfUnseenVertices {
return largestConnectedComponent
}
}
}
/**
* This statement will usually not be executed since we return earlier
* on anyways. An exception might occur for edge cases, for example the
* graph being empty.
*/
return largestConnectedComponent
}
/// Determines the subgraph of the receiver that represents the largest connected
/// component.
///
/// - Returns: A tuple containing an SGraph representing the largest component of the receiver, and a dictionary that maps the vertices in the original graph to their counterpart in the induced subgraph.
public func largestConnectedComponent() -> (SGraph, [Int: Int]) {
return self.subgraph(containing: self.verticesInLargestConnectedComponent())
}
/// Determines the vertex sets that represent the connected components of
/// the graph.
///
/// - Complexity: O(numberOfVertices + numberOfEdges).
/// - Returns: An array containing arrays, each representing the connected components of the receiver, sorted by the size of the components in descending order.
public func verticesInConnectedComponents() -> [[Int]] {
var verticesInComponents = [[Int]]()
/**
* In order to obtain the connected components of a graph we perform
* multiple breadth first searches each starting at a vertex that was
* not yet visited by a previous breadth first search.
*
* Knowing how many vertices were not seen yet helps in determining
* whether its useful to continue searching for larger components.
*/
var numberOfUnseenVertices = self.numberOfVertices
/**
* We store the seen/unseen/processed state of each vertex in this array.
*/
var vertexStates = [SVertexState](repeating: .unseen,
count: self.numberOfVertices)
/**
* We iterate all the vertices of our graph.
*/
for v in 0..<self.numberOfVertices {
/**
* Only if a vertex was not seen yet, we actually process it.
*/
if vertexStates[v] == .unseen {
/**
* Get the vertices of the component that contains the start vertex v.
*/
let verticesInCurrentComponent = self.verticesInConnectedComponent(containing: v)
for u in verticesInCurrentComponent {
vertexStates[u] = .seen
numberOfUnseenVertices -= 1
}
/**
* Now we simply add the vertices in the current component to
* the array containing the vertex sets of the vertices.
*/
verticesInComponents.append(verticesInCurrentComponent)
}
}
/**
* Finally, we sort the components by size.
*/
verticesInComponents.sort {
(component1: [Int], component2: [Int]) -> Bool in
return component1.count > component2.count
}
return verticesInComponents
}
/// Determines all connected components of the receiver.
///
/// - Complexity: Complexits of 'verticesInConnectedComponents' + Complexity of 'subgraph'. (The latter is amortized in O(numberOfVertices * max_degree))
/// - Returns: An array of tuples, each containing a subgraph representing a connected component of the receiver as well as a dictionary that maps the vertices in the receiver to their counterparts in the induced subgraph. (sorted by component size).
public func connectedComponents() -> [(SGraph, [Int: Int])] {
var components: [(SGraph, [Int: Int])] = []
/**
* At first we obtain all vertex sets that represent a connected component
* of the graph.
*/
let verticesInConnectedComponents = self.verticesInConnectedComponents()
/**
* Now we iterate the vertex sets representing the components and
* form their induced subgraphs.
*/
for componentVertexSet in verticesInConnectedComponents {
/**
* Now we add the subgraph induced by the vertices in the current
* component into our array of components.
*/
components.append(self.subgraph(containing: componentVertexSet))
}
return components
}
// MARK: - Contraction
/// Contracts a graph using the vertex assignments in the passed contractions
/// array. That is, the integers in the contractions array go from 0 to
/// <number of vertices in contracted graph> and the integer at the ith position
/// of the contractions array determines the vertex that the ith vertex is
/// contracted into.
///
/// - Note: If the numbers in the contractions array are not consecutive, the resulting graph will have isolated nodes.
///
/// - Complexity: O(m * <complexity of adding an edge>)
/// - Parameter contractions: An array where the ith entry contains the index of the vertex (in the resulting, contracted graph) that vertex i is contracted into.
/// - Returns: An SGraph representing the contracted graph.
public func graphByApplyingContractions(_ contractions: [Int]) -> SGraph? {
/**
* Determine the number of nodes in the contracted graph.
*/
if let largestContractedVertexID = contractions.max() {
/**
* Construct the graph with the contracted nodes.
*/
let contractedGraph = SGraph(numberOfVertices: largestContractedVertexID + 1,
directed: self.directed)
/**
* Now we iterate the edges of the initial graph and construct the
* edges in the contracted graph.
*/
for (vertex, neighbors) in self.edges.enumerated() {
/**
* The contracted vertex that the current vertex was contracted into.
*/
let contractedVertex = contractions[vertex]
for neighbor in neighbors {
/**
* The contracted vertex that the neighbor was contracted into.
*/
let contractedNeighbor = contractions[neighbor]
/**
* Add the edge.
*/
contractedGraph.addEdge(from: contractedVertex,
to: contractedNeighbor)
}
}
return contractedGraph
} else {
return nil
}
}
// MARK: - Writing
/// Creates a string containing the adjacency list of the graph. Each line represents one edge, vertices are seperated by tabs (\t).
///
/// - Complexity: O(numberOfEdges)
/// - Parameter useLabels: Determines whether the vertex indices or the labels of the vertices should be used when printing the graph. (Default false, printing the indices.)
/// - Returns: A string containing the adjacency list of the graph.
public func toString(useLabels: Bool = false,
withFormat format: SGraphOutputFormat = .edgeList) -> String {
var result = ""
switch format {
case .GML:
result = "graph [\n"
result += "\tdirected \(self.directed ? 1 : 0)\n"
for vertex in self {
result += "\tnode [\n"
result += "\t\tid \(vertex)\n"
if useLabels,
let vertexLabel = self.vertexLabels[vertex] {
result += "\t\tlabel \"\(vertexLabel)\"\n"
}
result += "\t]\n"
}
for vertex in self {
for neighbor in self.edges[vertex] {
result += "\tedge [\n"
result += "\t\tsource \(vertex)\n"
result += "\t\ttarget \(neighbor)\n"
result += "\t]\n"
}
}
result += "]"
return result
case .DL:
result = "DL n=\(self.numberOfVertices)\n"
result += "format = edgelist1\n"
result += "labels embedded:\n"
result += "data:\n"
/**
* From now on the DL format is the same as a simple edge list
* therefore we can simply fall through to creating the normal edge
* list.
*/
fallthrough
default:
if self.directed {
for u in self {
for v in self.edges[u] {
if useLabels,
let u = self.vertexLabels[u],
let v = self.vertexLabels[v] {
result += "\(u)\t\(v)\n"
} else {
result += "\(u)\t\(v)\n"
}
}
}
} else {
for u in self {
for v in self.edges[u] {
if u <= v {
if useLabels,
let u = self.vertexLabels[u],
let v = self.vertexLabels[v] {
result += "\(u)\t\(v)\n"
} else {
result += "\(u)\t\(v)\n"
}
}
}
}
}
return result
}
}
/// Creates a string that represents the vertex labels dictionary, i.e.
/// the map of the indices to the labels of the vertices.
/// By default each line has the form: index\tlabel
/// If the inverted flag is set, each line has the form: label\tindex
///
/// - Parameter inverted: If inverted the map from the labels to the indices will be printed instead. (Default is false.)
/// - Complexity: O(numberOfVertices)
/// - Returns: A string representing the index -> label map.
public func vertexLabelsToString(inverted: Bool = false) -> String {
var vertexLabelString = ""
for (vertex, label) in self.vertexLabels {
if inverted {
vertexLabelString += "\(label)\t\(vertex)\n"
} else {
vertexLabelString += "\(vertex)\t\(label)\n"
}
}
return vertexLabelString
}
}
| df08dbd9a15754ecdc2f2c39c784adba | 36.39491 | 254 | 0.518424 | false | false | false | false |
Swamii/adventofcode2016 | refs/heads/master | Sources/utils.swift | mit | 1 | import Foundation
enum Side: String {
case left = "L"
case right = "R"
}
enum CompassPoint: Int {
case north = 1
case east = 2
case south = 3
case west = 4
static var first = CompassPoint.north
static var last = CompassPoint.west
}
enum Direction: Character {
case up = "U"
case right = "R"
case down = "D"
case left = "L"
}
struct Size {
let width: Int
let height: Int
}
/// Regex wrapper
/// from NSHipster - http://nshipster.com/swift-literal-convertible/
struct Regex {
let pattern: String
let options: NSRegularExpression.Options
let matcher: NSRegularExpression
init(pattern: String, options: NSRegularExpression.Options = NSRegularExpression.Options()) {
self.pattern = pattern
self.options = options
self.matcher = try! NSRegularExpression(pattern: self.pattern, options: self.options)
}
func match(_ string: String, options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> Bool {
let numberOfMatches = matcher.numberOfMatches(
in: string,
options: options,
range: NSRange(location: 0, length: string.utf16.count)
)
return numberOfMatches != 0
}
func search(input: String,
options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> [String] {
let matches = matcher.matches(in: input,
options: options,
range: NSRange(location: 0, length: input.utf16.count))
var groups = [String]()
for match in matches as [NSTextCheckingResult] {
// range at index 0: full match, skip that and add all groups to list
for index in 1..<match.numberOfRanges {
let substring = (input as NSString).substring(with: match.rangeAt(index))
groups.append(substring)
}
}
return groups
}
func firstMatch(input: String,
options: NSRegularExpression.MatchingOptions = NSRegularExpression.MatchingOptions()) -> NSTextCheckingResult? {
let match = matcher.firstMatch(
in: input,
options: options,
range: NSRange(location: 0, length: input.utf16.count)
)
return match
}
}
func *(lhs: String, rhs: Int) -> String {
var strings = [String]()
for _ in 0..<rhs {
strings.append(lhs)
}
return strings.joined()
}
extension String {
mutating func popTo(length: Int) -> String {
let range = self.startIndex..<self.index(self.startIndex, offsetBy: length)
let chars = self[range]
removeSubrange(range)
return chars
}
subscript(i: Int) -> String {
return String(self[self.index(self.startIndex, offsetBy: i)])
}
subscript(range: Range<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: range.upperBound, limitedBy: self.endIndex) ?? self.endIndex
return self[startIndex..<endIndex]
}
}
| 5ca3ad3c68b0b610e023e4f967f68d64 | 28.431193 | 132 | 0.611908 | false | false | false | false |
oursky/Redux | refs/heads/master | Example/Redux/TodoListReducer.swift | mit | 1 | //
// TodoListReducer.swift
// SwiftRedux
//
// Created by Steven Chan on 31/12/15.
// Copyright (c) 2016 Oursky Limited. All rights reserved.
//
import Redux
struct TodoListState: AnyEquatable, Equatable {
var list: [TodoListItem]
}
func == (lhs: TodoListState, rhs: TodoListState) -> Bool {
return lhs.list == rhs.list
}
func todoListReducer(_ previousState: Any, action: ReduxAction) -> Any {
var state = previousState as! TodoListState
print("action: ", action)
switch action.payload {
case TodoListAction.loadSuccess(let list):
state.list = list
break
case TodoListAction.add(let token, let content):
state.list.append(
TodoListItem(
content: content,
token: token as NSString
)
)
break
case TodoListAction.addSuccess(let token, let createdAt):
state.list = state.list.map {
item in
item.token as String == token ?
TodoListItem(content: item.content, createdAt: createdAt) :
item
}
break
case TodoListAction.addFail(let token):
state.list = state.list.filter {
item in item.token as String != token
}
break
default:
break
}
return state
}
| c823a6b495896961b6f01532dbdfbb1d | 22.192982 | 75 | 0.593041 | false | false | false | false |
NUKisZ/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/common/UIButton+Util.swift | mit | 1 | //
// UIButton+Util.swift
// TestKitchen
//
// Created by NUK on 16/8/15.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
extension UIButton{
class func createBtn(title:String?,bgImageName:String?,selectBgImageName:String?,target:AnyObject?,action:Selector?)->UIButton{
let btn = UIButton(type: .Custom)
if let btnTitle = title{
btn.setTitle(btnTitle, forState: .Normal)
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
if let btnBgImageName = bgImageName{
btn.setBackgroundImage(UIImage(named: btnBgImageName), forState: .Normal)
}
if let btnSelectBgImageName = selectBgImageName{
btn.setBackgroundImage(UIImage(named: btnSelectBgImageName), forState: .Selected)
}
if let btnTarget = target {
if let btnAction = action{
btn.addTarget(btnTarget, action: btnAction, forControlEvents: .TouchUpInside)
}
}
return btn
}
}
| c2f45ece5277527baf3c08c18d9c8ee2 | 29.485714 | 131 | 0.611996 | false | false | false | false |
ReactiveKit/ReactiveGitter | refs/heads/master | Carthage/Checkouts/Bond/Carthage/Checkouts/ReactiveKit/Tests/ReactiveKitTests/SignalTests.swift | gpl-3.0 | 4 | //
// OperatorTests.swift
// ReactiveKit
//
// Created by Srdan Rasic on 12/04/16.
// Copyright © 2016 Srdan Rasic. All rights reserved.
//
import XCTest
import ReactiveKit
enum TestError: Swift.Error {
case Error
}
class SignalTests: XCTestCase {
func testPerformance() {
self.measure {
(0..<1000).forEach { _ in
let signal = ReactiveKit.Signal<Int, NoError> { observer in
(0..<100).forEach(observer.next)
observer.completed()
return NonDisposable.instance
}
_ = signal.observe { _ in }
}
}
}
func testProductionAndObservation() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.sequence([1, 2, 3]).executeIn(bob.context)
operation.expectComplete(after: [1, 2, 3])
operation.expectComplete(after: [1, 2, 3])
XCTAssertEqual(bob.numberOfRuns, 2)
}
func testDisposing() {
let disposable = SimpleDisposable()
let operation = Signal<Int, TestError> { _ in
return disposable
}
operation.observe { _ in }.dispose()
XCTAssertTrue(disposable.isDisposed)
}
func testJust() {
let operation = Signal<Int, TestError>.just(1)
operation.expectComplete(after: [1])
}
func testSequence() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
operation.expectComplete(after: [1, 2, 3])
}
func testCompleted() {
let operation = Signal<Int, TestError>.completed()
operation.expectComplete(after: [])
}
func testNever() {
let operation = Signal<Int, TestError>.never()
operation.expectNoEvent()
}
func testFailed() {
let operation = Signal<Int, TestError>.failed(.Error)
operation.expect(events: [.failed(.Error)])
}
func testObserveFailed() {
var observedError: TestError? = nil
let operation = Signal<Int, TestError>.failed(.Error)
_ = operation.observeFailed {
observedError = $0
}
XCTAssert(observedError != nil && observedError! == .Error)
}
func testObserveCompleted() {
var completed = false
let operation = Signal<Int, TestError>.completed()
_ = operation.observeCompleted {
completed = true
}
XCTAssert(completed == true)
}
func testBuffer() {
let operation = Signal<Int, TestError>.sequence([1,2,3,4,5])
let buffered = operation.buffer(size: 2)
buffered.expectComplete(after: [[1, 2], [3, 4]])
}
func testMap() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let mapped = operation.map { $0 * 2 }
mapped.expectComplete(after: [2, 4, 6])
}
func testScan() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let scanned = operation.scan(0, +)
scanned.expectComplete(after: [0, 1, 3, 6])
}
func testToSignal() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let operation2 = operation.toSignal()
operation2.expectComplete(after: [1, 2, 3])
}
func testSuppressError() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let signal = operation.suppressError(logging: false)
signal.expectComplete(after: [1, 2, 3])
}
func testSuppressError2() {
let operation = Signal<Int, TestError>.failed(.Error)
let signal = operation.suppressError(logging: false)
signal.expectComplete(after: [])
}
func testRecover() {
let operation = Signal<Int, TestError>.failed(.Error)
let signal = operation.recover(with: 1)
signal.expectComplete(after: [1])
}
func testWindow() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let window = operation.window(size: 2)
window.merge().expectComplete(after: [1, 2])
}
// func testDebounce() {
// let operation = Signal<Int, TestError>.interval(0.1, queue: Queue.global).take(first: 3)
// let distinct = operation.debounce(interval: 0.3, on: Queue.global)
// let exp = expectation(withDescription: "completed")
// distinct.expectComplete(after: [2], expectation: exp)
// waitForExpectations(withTimeout: 1, handler: nil)
// }
func testDistinct() {
let operation = Signal<Int, TestError>.sequence([1, 2, 2, 3])
let distinct = operation.distinct { a, b in a != b }
distinct.expectComplete(after: [1, 2, 3])
}
func testDistinct2() {
let operation = Signal<Int, TestError>.sequence([1, 2, 2, 3])
let distinct = operation.distinct()
distinct.expectComplete(after: [1, 2, 3])
}
func testElementAt() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let elementAt1 = operation.element(at: 1)
elementAt1.expectComplete(after: [2])
}
func testFilter() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let filtered = operation.filter { $0 % 2 != 0 }
filtered.expectComplete(after: [1, 3])
}
func testFirst() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let first = operation.first()
first.expectComplete(after: [1])
}
func testIgnoreElement() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let ignoreElements = operation.ignoreElements()
ignoreElements.expectComplete(after: [])
}
func testLast() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let first = operation.last()
first.expectComplete(after: [3])
}
// TODO: sample
func testSkip() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let skipped1 = operation.skip(first: 1)
skipped1.expectComplete(after: [2, 3])
}
func testSkipLast() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let skippedLast1 = operation.skip(last: 1)
skippedLast1.expectComplete(after: [1, 2])
}
func testTake() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let taken2 = operation.take(first: 2)
taken2.expectComplete(after: [1, 2])
}
func testTakeLast() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let takenLast2 = operation.take(last: 2)
takenLast2.expectComplete(after: [2, 3])
}
// func testThrottle() {
// let operation = Signal<Int, TestError>.interval(0.4, queue: Queue.global).take(5)
// let distinct = operation.throttle(1)
// let exp = expectation(withDescription: "completed")
// distinct.expectComplete(after: [0, 3], expectation: exp)
// waitForExpectationsWithTimeout(3, handler: nil)
// }
func testIgnoreNil() {
let operation = Signal<Int?, TestError>.sequence(Array<Int?>([1, nil, 3]))
let unwrapped = operation.ignoreNil()
unwrapped.expectComplete(after: [1, 3])
}
func testReplaceNil() {
let operation = Signal<Int?, TestError>.sequence(Array<Int?>([1, nil, 3, nil]))
let unwrapped = operation.replaceNil(with: 7)
unwrapped.expectComplete(after: [1, 7, 3, 7])
}
func testCombineLatestWith() {
let bob = Scheduler()
let eve = Scheduler()
let operationA = Signal<Int, TestError>.sequence([1, 2, 3]).observeIn(bob.context)
let operationB = Signal<String, TestError>.sequence(["A", "B", "C"]).observeIn(eve.context)
let combined = operationA.combineLatest(with: operationB).map { "\($0)\($1)" }
let exp = expectation(description: "completed")
combined.expectAsyncComplete(after: ["1A", "1B", "2B", "3B", "3C"], expectation: exp)
bob.runOne()
eve.runOne()
eve.runOne()
bob.runRemaining()
eve.runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testMergeWith() {
let bob = Scheduler()
let eve = Scheduler()
let operationA = Signal<Int, TestError>.sequence([1, 2, 3]).observeIn(bob.context)
let operationB = Signal<Int, TestError>.sequence([4, 5, 6]).observeIn(eve.context)
let merged = operationA.merge(with: operationB)
let exp = expectation(description: "completed")
merged.expectAsyncComplete(after: [1, 4, 5, 2, 6, 3], expectation: exp)
bob.runOne()
eve.runOne()
eve.runOne()
bob.runOne()
eve.runRemaining()
bob.runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testStartWith() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let startWith4 = operation.start(with: 4)
startWith4.expectComplete(after: [4, 1, 2, 3])
}
func testZipWith() {
let operationA = Signal<Int, TestError>.sequence([1, 2, 3])
let operationB = Signal<String, TestError>.sequence(["A", "B"])
let combined = operationA.zip(with: operationB).map { "\($0)\($1)" }
combined.expectComplete(after: ["1A", "2B"])
}
func testZipWithWhenNotComplete() {
let operationA = Signal<Int, TestError>.sequence([1, 2, 3]).ignoreTerminal()
let operationB = Signal<String, TestError>.sequence(["A", "B"])
let combined = operationA.zip(with: operationB).map { "\($0)\($1)" }
combined.expectComplete(after: ["1A", "2B"])
}
func testZipWithWhenNotComplete2() {
let operationA = Signal<Int, TestError>.sequence([1, 2, 3])
let operationB = Signal<String, TestError>.sequence(["A", "B"]).ignoreTerminal()
let combined = operationA.zip(with: operationB).map { "\($0)\($1)" }
combined.expect(events: [.next("1A"), .next("2B")])
}
func testZipWithAsyncSignal() {
let operationA = Signal<Int, TestError>.interval(0.5).take(first: 4) // Takes just 2 secs to emit 4 nexts.
let operationB = Signal<Int, TestError>.interval(1.0).take(first: 10) // Takes 4 secs to emit 4 nexts.
let combined = operationA.zip(with: operationB).map { $0 + $1 } // Completes after 4 nexts due to operationA and takes 4 secs due to operationB
let exp = expectation(description: "completed")
combined.expectAsyncComplete(after: [0, 2, 4, 6], expectation: exp)
waitForExpectations(timeout: 5.0, handler: nil)
}
func testFlatMapError() {
let operation = Signal<Int, TestError>.failed(.Error)
let recovered = operation.flatMapError { error in Signal<Int, TestError>.just(1) }
recovered.expectComplete(after: [1])
}
func testFlatMapError2() {
let operation = Signal<Int, TestError>.failed(.Error)
let recovered = operation.flatMapError { error in Signal<Int, NoError>.just(1) }
recovered.expectComplete(after: [1])
}
func testRetry() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.failed(.Error).executeIn(bob.context)
let retry = operation.retry(times: 3)
retry.expect(events: [.failed(.Error)])
XCTAssertEqual(bob.numberOfRuns, 4)
}
func testexecuteIn() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.sequence([1, 2, 3]).executeIn(bob.context)
operation.expectComplete(after: [1, 2, 3])
XCTAssertEqual(bob.numberOfRuns, 1)
}
// TODO: delay
func testDoOn() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
var start = 0
var next = 0
var completed = 0
var disposed = 0
let d = operation.doOn(next: { _ in next += 1 }, start: { start += 1}, completed: { completed += 1}, disposed: { disposed += 1}).observe { _ in }
XCTAssert(start == 1)
XCTAssert(next == 3)
XCTAssert(completed == 1)
XCTAssert(disposed == 1)
d.dispose()
XCTAssert(disposed == 1)
}
func testobserveIn() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.sequence([1, 2, 3]).observeIn(bob.context)
operation.expectComplete(after: [1, 2, 3])
XCTAssertEqual(bob.numberOfRuns, 4) // 3 elements + completion
}
func testPausable() {
let operation = PublishSubject<Int, TestError>()
let controller = PublishSubject<Bool, TestError>()
let paused = operation.shareReplay().pausable(by: controller)
let exp = expectation(description: "completed")
paused.expectAsyncComplete(after: [1, 3], expectation: exp)
operation.next(1)
controller.next(false)
operation.next(2)
controller.next(true)
operation.next(3)
operation.completed()
waitForExpectations(timeout: 1, handler: nil)
}
func testTimeoutNoFailure() {
let exp = expectation(description: "completed")
Signal<Int, TestError>.just(1).timeout(after: 0.2, with: .Error, on: DispatchQueue.main).expectAsyncComplete(after: [1], expectation: exp)
waitForExpectations(timeout: 1, handler: nil)
}
func testTimeoutFailure() {
let exp = expectation(description: "completed")
Signal<Int, TestError>.never().timeout(after: 0.5, with: .Error, on: DispatchQueue.main).expectAsync(events: [.failed(.Error)], expectation: exp)
waitForExpectations(timeout: 1, handler: nil)
}
func testAmbWith() {
let bob = Scheduler()
let eve = Scheduler()
let operationA = Signal<Int, TestError>.sequence([1, 2]).observeIn(bob.context)
let operationB = Signal<Int, TestError>.sequence([3, 4]).observeIn(eve.context)
let ambdWith = operationA.amb(with: operationB)
let exp = expectation(description: "completed")
ambdWith.expectAsyncComplete(after: [3, 4], expectation: exp)
eve.runOne()
bob.runRemaining()
eve.runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testCollect() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let collected = operation.collect()
collected.expectComplete(after: [[1, 2, 3]])
}
func testConcatWith() {
let bob = Scheduler()
let eve = Scheduler()
let operationA = Signal<Int, TestError>.sequence([1, 2]).observeIn(bob.context)
let operationB = Signal<Int, TestError>.sequence([3, 4]).observeIn(eve.context)
let merged = operationA.concat(with: operationB)
let exp = expectation(description: "completed")
merged.expectAsyncComplete(after: [1, 2, 3, 4], expectation: exp)
bob.runOne()
eve.runOne()
bob.runRemaining()
eve.runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testDefaultIfEmpty() {
let operation = Signal<Int, TestError>.sequence([])
let defaulted = operation.defaultIfEmpty(1)
defaulted.expectComplete(after: [1])
}
func testReduce() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let reduced = operation.reduce(0, +)
reduced.expectComplete(after: [6])
}
func testZipPrevious() {
let operation = Signal<Int, TestError>.sequence([1, 2, 3])
let zipped = operation.zipPrevious()
zipped.expectComplete(after: [(nil, 1), (1, 2), (2, 3)])
}
func testFlatMapMerge() {
let bob = Scheduler()
let eves = [Scheduler(), Scheduler()]
let operation = Signal<Int, TestError>.sequence([1, 2]).observeIn(bob.context)
let merged = operation.flatMapMerge { num in
return Signal<Int, TestError>.sequence([5, 6].map { $0 * num }).observeIn(eves[num-1].context)
}
let exp = expectation(description: "completed")
merged.expectAsyncComplete(after: [5, 10, 12, 6], expectation: exp)
bob.runOne()
eves[0].runOne()
bob.runRemaining()
eves[1].runRemaining()
eves[0].runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testFlatMapLatest() {
let bob = Scheduler()
let eves = [Scheduler(), Scheduler()]
let operation = Signal<Int, TestError>.sequence([1, 2]).observeIn(bob.context)
let merged = operation.flatMapLatest { num in
return Signal<Int, TestError>.sequence([5, 6].map { $0 * num }).observeIn(eves[num-1].context)
}
let exp = expectation(description: "completed")
merged.expectAsyncComplete(after: [5, 10, 12], expectation: exp)
bob.runOne()
eves[0].runOne()
bob.runRemaining()
eves[1].runRemaining()
eves[0].runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testFlatMapConcat() {
let bob = Scheduler()
let eves = [Scheduler(), Scheduler()]
let operation = Signal<Int, TestError>.sequence([1, 2]).observeIn(bob.context)
let merged = operation.flatMapConcat { num in
return Signal<Int, TestError>.sequence([5, 6].map { $0 * num }).observeIn(eves[num-1].context)
}
let exp = expectation(description: "completed")
merged.expectAsyncComplete(after: [5, 6, 10, 12], expectation: exp)
bob.runRemaining()
eves[1].runOne()
eves[0].runRemaining()
eves[1].runRemaining()
waitForExpectations(timeout: 1, handler: nil)
}
func testReplay() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.sequence([1, 2, 3]).executeIn(bob.context)
let replayed = operation.replay(limit: 2)
operation.expectComplete(after: [1, 2, 3])
let _ = replayed.connect()
replayed.expectComplete(after: [2, 3])
XCTAssertEqual(bob.numberOfRuns, 2)
}
func testPublish() {
let bob = Scheduler()
bob.runRemaining()
let operation = Signal<Int, TestError>.sequence([1, 2, 3]).executeIn(bob.context)
let published = operation.publish()
operation.expectComplete(after: [1, 2, 3])
let _ = published.connect()
published.expectNoEvent()
XCTAssertEqual(bob.numberOfRuns, 2)
}
}
| a8234091a8b7409bfc8810588c225dc8 | 29.528674 | 149 | 0.654946 | false | true | false | false |
farshadtx/Fleet | refs/heads/master | FleetTests/FleetErrorSpec.swift | apache-2.0 | 1 | import XCTest
import Nimble
import Fleet
class FleetErrorSpec: XCTestCase {
func test_canBeUsedToIntializeAString() {
let error = FleetError(message: "turtle error message")
let errorString = String(describing: error)
expect(errorString).to(equal("Fleet error: turtle error message"))
}
func test_isCustomStringConvertible() {
let error = FleetError(message: "turtle error message")
let errorString = error.description
expect(errorString).to(equal("Fleet error: turtle error message"))
}
func test_isDebugStringConvertible() {
let error = FleetError(message: "turtle error message")
let errorString = error.debugDescription
expect(errorString).to(equal("Fleet error: turtle error message"))
}
}
| 18231f28b985ea038b312d2b46c3877b | 33.521739 | 74 | 0.691436 | false | true | false | false |
livefront/bonsai | refs/heads/master | Tests/CommandSpec.swift | mit | 1 | import Quick
import Nimble
@testable import Bonsai
class CommandSpec: QuickSpec {
enum CommandAction: Action {
case someAction
}
enum ParentAction: Action, Equatable {
case child(CommandAction)
static func == (lhs: ParentAction, rhs: ParentAction) -> Bool {
switch (lhs, rhs) {
case let (.child(left), .child(right)):
return left == right
}
}
}
override func spec() {
var subject: Command<CommandAction>!
describe("a command") {
beforeEach {
subject = Command(arguments: 1)
}
it("maps an action to another action") {
let mapped = subject!.map { return ParentAction.child($0) }
let actionCreated: ParentAction = mapped.create(CommandAction.someAction)
expect(actionCreated).to(equal(ParentAction.child(.someAction)))
}
}
}
}
| 7e47c3cba545fbf9a3c1ce4db507e0ad | 24.051282 | 89 | 0.551689 | false | false | false | false |
nicelion/JSON-Test | refs/heads/master | JSON Test/TableViewController.swift | mit | 1 | //
// TableViewController.swift
// JSON Test
//
// Created by Ian Thompson on 12/20/15.
// Copyright © 2015 Ian Thompson. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var JSON_Info = [JSONInfo]()
override func viewDidLoad() {
super.viewDidLoad()
var jsonResults: AnyObject
// let webUrl = NSURL(string: "https://website.com/directory/json.json")
let URL = NSBundle.mainBundle().URLForResource("TutorialJSON", withExtension: "json")
if let JSONData = NSData(contentsOfURL: URL!) {
do {
jsonResults = try NSJSONSerialization.JSONObjectWithData(JSONData, options: [])
if let infoArray = jsonResults["Posts"] as? [NSDictionary] {
for item in infoArray {
JSON_Info.append(JSONInfo(json: item))
}
}
} catch {
print("Fetch Failed: \((error as NSError).localizedDescription)")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return JSON_Info.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
if JSON_Info[indexPath.row].isBlue == true {
cell.titleLabel.textColor = UIColor.blueColor()
} else{
cell.titleLabel.textColor = UIColor.blackColor()
}
cell.titleLabel?.text = JSON_Info[indexPath.row].title
cell.descriptionLabel?.text = JSON_Info[indexPath.row].description
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let imageOfPost = self.JSON_Info[indexPath.row].image!
cell.postImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: imageOfPost)!)!)
})
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let urlOfPost = JSON_Info[indexPath.row].url
let url = NSURL(string: urlOfPost!)
UIApplication.sharedApplication().openURL(url!)
tableView.reloadData()
}
}
| b215dbbc3d46847234850b2ebdd52772 | 22.852713 | 118 | 0.505037 | false | false | false | false |
lucas34/SwiftQueue | refs/heads/master | Sources/SwiftQueue/SwiftQueueManager+BackgroundTask.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2022 Lucas Nelaupe
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS) || os(tvOS)
#if canImport(BackgroundTasks)
import BackgroundTasks
#endif
@available(iOS 13.0, tvOS 13.0, *)
/// Extension of SwiftQueueManager to support BackgroundTask API from iOS 13.
public extension SwiftQueueManager {
/// Register task that can potentially run in Background (Using BackgroundTask API)
/// Registration of all launch handlers must be complete before the end of applicationDidFinishLaunching(_:)
/// https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler/3180427-register
func registerForBackgroundTask(forTaskWithUUID: String) {
BGTaskScheduler.shared.register(forTaskWithIdentifier: forTaskWithUUID, using: nil) { [weak self] task in
if let operation = self?.getOperation(forUUID: task.identifier) {
task.expirationHandler = {
operation.done(.fail(SwiftQueueError.timeout))
}
operation.handler.onRun(callback: TaskJobResult(actual: operation, task: task))
}
}
}
/// Call this method when application is entering background to schedule jobs as background task
func applicationDidEnterBackground() {
for operation in getAllAllowBackgroundOperation() {
operation.scheduleBackgroundTask()
}
}
/// Cancel all possible background Task
func cancelAllBackgroundTask() {
for operation in getAllAllowBackgroundOperation() {
if let uuid = operation.name {
BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: uuid)
}
}
}
}
@available(iOS 13.0, tvOS 13.0, *)
internal extension SqOperation {
func scheduleBackgroundTask() {
guard let name = name else { return }
let request = BGProcessingTaskRequest(identifier: name)
if let _: NetworkConstraint = getConstraint(info) {
request.requiresNetworkConnectivity = true
}
if let _: BatteryChargingConstraint = getConstraint(info) {
request.requiresExternalPower = true
}
request.earliestBeginDate = nextRunSchedule
do {
try BGTaskScheduler.shared.submit(request)
} catch {
logger.log(.verbose, jobId: name, message: "Could not schedule BackgroundTask")
}
}
}
@available(iOS 13.0, tvOS 13.0, *)
private class TaskJobResult: JobResult {
private let task: BGTask
private let actual: JobResult
init(actual: JobResult, task: BGTask) {
self.actual = actual
self.task = task
}
public func done(_ result: JobCompletion) {
actual.done(result)
switch result {
case .success:
task.setTaskCompleted(success: true)
case .fail:
task.setTaskCompleted(success: false)
}
}
}
#endif
| d0a920c009fe14250882918bfb5c5c36 | 34.283186 | 113 | 0.682468 | false | false | false | false |
bm842/Brokers | refs/heads/master | Sources/OandaRestV20Broker.swift | mit | 2 | /*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
import Logger
extension Timestamp
{
var oandaRestV20Value: UInt32 { return seconds }
}
public class OandaRestV20Broker: OandaRestBroker
{
public override func refreshAccounts(_ completion: @escaping (RequestStatus)->())
{
/*restConnection.fetchArray2("accounts")
{
(status, accountProperties: [OandaRestV3AccountProperty]?) in
if let setProperties = accountProperties
{
let wq = DispatchQueue(label: "fetchAccounts")
//.init(label: "fetchAccounts", qos: DispatchQos., attributes: DispatchQueue.Attributes.concurrent, autoreleaseFrequency: <#T##DispatchQueue.AutoreleaseFrequency#>, target: <#T##DispatchQueue?#>)
//(label: "fetchAccounts")
//log.debug("\(wq.)"
//let group = DispatchGroup()
var globalStatus: RequestStatus? = nil
for property in setProperties
{
wq.async
{
let sync = Sync<RequestStatus>()
log.debug("fetching account \(property.id)")
self.restConnection.fetchObject("accounts/\(property.id)/summary", jsonSubField: "account")
{
(status, summary: OandaRestV3AccountSummary?) in
log.debug("status = \(status)")
if let setSummary = summary
{
self.accounts.append(OandaRestV20Account(oanda: self, summary: setSummary) as Account)
}
sync.post(status)
}
let status = sync.take()
if let setGlobalStatus = globalStatus
{
if case OandaStatus.success = setGlobalStatus
{
globalStatus = status
}
}
else
{
globalStatus = status
}
}
}
wq.async
{
log.debug("%f: final report")
completion(globalStatus ?? OandaStatus.success)
}
}
else
{
completion(status)
}
}*/
}
}
public class OandaRestFXTradeV20Broker: OandaRestV20Broker
{
public init(userAuthentication: UserAuthentication)
{
super.init(environment: .fxTrade(version: 3), userAuthentication: userAuthentication)
}
}
public class OandaRestFXPracticeV20Broker: OandaRestV20Broker
{
public init(userAuthentication: UserAuthentication)
{
super.init(environment: .fxPractice(version: 3), userAuthentication: userAuthentication)
}
}
| 0eb1eddf4864409f202574cc51a21663 | 36.617391 | 215 | 0.542302 | false | false | false | false |
luckymore0520/GreenTea | refs/heads/master | Loyalty/Setting/ViewModel/ShopInfoDataSource.swift | mit | 1 | //
// ShopInfoDataSource.swift
// Loyalty
//
// Created by WangKun on 16/4/24.
// Copyright © 2016年 WangKun. All rights reserved.
//
import UIKit
enum ShopInfoRowType:Int,TitlePresentable{
case ShopInfo = 0;
case LocationInfo;
case ShopDetailInfo;
case ShopActivityInfo;
case ContactInfo;
case Review;
static func allTypes(isMyOwnShop:Bool) -> [[ShopInfoRowType]]{
return isMyOwnShop ? [[.ShopInfo,.LocationInfo],[.ShopDetailInfo],[.ShopActivityInfo],[.ContactInfo],[.Review] ] :
[[.ShopInfo,.LocationInfo],[.ShopDetailInfo],[.Review] ]
}
var title:String {
get {
switch self {
case .ShopDetailInfo:
return "店铺详情"
case .ContactInfo:
return "联系方式"
case .Review:
return "网友点评"
case .ShopActivityInfo:
return "我的活动"
default:
return ""
}
}
}
var titleColor: UIColor {
return UIColor.globalSectionHeaderColor()
}
}
class ShopInfoDataSource: NSObject {
weak var tableView:UITableView?
var shopViewModel:ShopInfoViewModel?
var tableRowInfo:[[ShopInfoRowType]] = []
init(shop:Shop, tableView:UITableView) {
super.init()
self.shopViewModel = ShopInfoViewModel(shop: shop)
self.tableView = tableView
self.tableRowInfo = ShopInfoRowType.allTypes(shop.isMine())
tableView.dataSource = self
tableView.registerReusableCell(ShopInfoTableViewCell.self)
tableView.registerReusableCell(LocationInfoTableViewCell.self)
tableView.registerReusableCell(ActivityTimeInfoTableViewCell.self)
tableView.registerReusableCell(ActivityDetailInfoTableViewCell.self)
tableView.registerReusableCell(ActivityDetailSectionHeaderTableViewCell.self)
tableView.registerReusableCell(SimpleActivityTableViewCell.self)
tableView.registerReusableCell(CommentCell.self)
}
func render(imageView:UIImageView) {
self.shopViewModel?.updateImageView(imageView)
}
func viewForHeader(tableView:UITableView,section:Int) -> UIView? {
if section == 0 { return nil }
let cell = tableView.dequeueReusableCell() as ActivityDetailSectionHeaderTableViewCell
cell.backgroundColor = UIColor.globalViewColor()
let sectionType = tableRowInfo[section][0]
if sectionType.title.length > 0 {
cell.render(sectionType)
}
return cell
}
func heightForHeader(section:Int) -> CGFloat {
return section == 0 ? 0 : 35
}
func heightForRowAtIndexPath(indexPath:NSIndexPath) -> CGFloat {
if tableRowInfo[indexPath.section][0] == .ShopActivityInfo {
return 90
}
if tableRowInfo[indexPath.section][0] == .Review {
if let comment = self.shopViewModel?.comments[indexPath.row] {
return 70 - (comment.replyName == nil ? 0 : 15) + comment.content.minHeight(UIScreen.mainScreen().bounds.size.width - 74)
}
return 0
}
switch tableRowInfo[indexPath.section][indexPath.row] {
case .ShopInfo:
return 56
case .LocationInfo:
return 32
case .ContactInfo:
return 45
case .ShopDetailInfo:
return 30 + (self.shopViewModel?.detail.minHeight(UIScreen.mainScreen().bounds.width - 30) ?? 0)
default:
return 0
}
}
func objectForRowAtIndexPath(indexPath:NSIndexPath) -> Any? {
let staticRowArray = tableRowInfo[indexPath.section]
if staticRowArray[0] == .ShopActivityInfo {
return self.shopViewModel?.activityList?[indexPath.row]
}
if tableRowInfo[indexPath.section][0] == .Review {
return self.shopViewModel?.comments[indexPath.row]
}
return tableRowInfo[indexPath.section][indexPath.row]
}
}
extension ShopInfoDataSource:UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tableRowInfo.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section < tableRowInfo.count {
if tableRowInfo[section][0] == .ShopActivityInfo {
return self.shopViewModel?.activityList?.count ?? 0
}
if tableRowInfo[section][0] == .Review {
return self.shopViewModel?.comments.count ?? 0
}
return tableRowInfo[section].count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let staticRowArray = tableRowInfo[indexPath.section]
if staticRowArray[0] == .ShopActivityInfo {
let activityCell = tableView.dequeueReusableCell(indexPath: indexPath) as SimpleActivityTableViewCell
if let activity = self.shopViewModel?.activityList?[indexPath.row] {
activityCell.render(ActivityDetaiViewModel(activity: activity))
}
return activityCell
}
if tableRowInfo[indexPath.section][0] == .Review {
let commentCell = tableView.dequeueReusableCell(indexPath: indexPath) as CommentCell
if let comment = self.shopViewModel?.comments[indexPath.row] {
commentCell.render(CommentViewModel(comment: comment))
}
return commentCell
}
var cell:UITableViewCell?
switch tableRowInfo[indexPath.section][indexPath.row] {
case .ShopInfo:
let shopInfoCell = tableView.dequeueReusableCell(indexPath: indexPath) as ShopInfoTableViewCell
shopInfoCell.render(self.shopViewModel)
cell = shopInfoCell
case .LocationInfo:
let locationInfoCell = tableView.dequeueReusableCell(indexPath: indexPath) as LocationInfoTableViewCell
locationInfoCell.render(self.shopViewModel)
cell = locationInfoCell
case .ContactInfo:
let contactInfoCell = tableView.dequeueReusableCell(indexPath: indexPath) as ActivityTimeInfoTableViewCell
contactInfoCell.render(self.shopViewModel)
cell = contactInfoCell
case .ShopDetailInfo:
let detailCell = tableView.dequeueReusableCell(indexPath: indexPath) as ActivityDetailInfoTableViewCell
detailCell.render(self.shopViewModel)
cell = detailCell
default:
cell = UITableViewCell(style: UITableViewCellStyle.Default,reuseIdentifier: "ShopActivityInfo")
}
return cell!
}
}
| e7bdaba7b90a5426c7d9277c2e40ae1b | 36.214286 | 137 | 0.640927 | false | false | false | false |
ingresse/ios-sdk | refs/heads/dev | IngresseSDK/Services/MyTicketsService.swift | mit | 1 | //
// Copyright © 2017 Gondek. All rights reserved.
//
public class MyTicketsService: BaseService {
/// Get sessions user has tickets to
///
/// - Parameters:
/// - userId: id of logged user
/// - userToken: token of logged user
/// - from: past or future events
/// - page: page of request
/// - pageSize: number of events per page
/// - delegate: callback interface
public func getUserWallet(userId: String,
userToken: String,
from: String = "",
page: Int,
pageSize: Int = 50,
delegate: WalletSyncDelegate) {
var builder = URLBuilder(client: client)
.setPath("user/\(userId)/wallet")
.addParameter(key: "usertoken", value: userToken)
.addParameter(key: "page", value: String(page))
.addParameter(key: "pageSize", value: String(pageSize))
if from == "future" {
builder = builder.addParameter(key: "order", value: "ASC")
builder = builder.addParameter(key: "from", value: "yesterday")
}
if from == "past" {
builder = builder.addParameter(key: "order", value: "DESC")
builder = builder.addParameter(key: "to", value: "yesterday")
}
guard let request = try? builder.build() else {
return delegate.didFailSyncItems(errorData: APIError.getDefaultError())
}
client.restClient.GET(request: request,
onSuccess: { response in
guard
let data = response["data"] as? [[String: Any]],
let paginationObj = response["paginationInfo"] as? [String: Any],
let pagination = JSONDecoder().decodeDict(of: PaginationInfo.self, from: paginationObj),
let items = JSONDecoder().decodeArray(of: [WalletItem].self, from: data)
else {
delegate.didFailSyncItems(errorData: APIError.getDefaultError())
return
}
delegate.didSyncItemsPage(items, from: from, pagination: pagination)
}, onError: { error in
delegate.didFailSyncItems(errorData: error)
})
}
/// Get all tickets user has
///
/// - Parameters:
/// - userId: id of logged user
/// - userToken: token of logged user
/// - eventId: id of requested event
/// - page: page of request
/// - delegate: callback interface
public func getUserTickets(userId: String,
eventId: String,
userToken: String,
page: Int,
delegate: TicketSyncDelegate) {
let builder = URLBuilder(client: client)
.setPath("user/\(userId)/tickets")
.addParameter(key: "eventId", value: eventId)
.addParameter(key: "usertoken", value: userToken)
.addParameter(key: "page", value: String(page))
.addParameter(key: "pageSize", value: "25")
guard let request = try? builder.build() else {
return delegate.didFailSyncTickets(errorData: APIError.getDefaultError())
}
client.restClient.GET(request: request,
onSuccess: { response in
guard
let data = response["data"] as? [[String: Any]],
let paginationObj = response["paginationInfo"] as? [String: Any],
let tickets = JSONDecoder().decodeArray(of: [UserTicket].self, from: data),
let pagination = JSONDecoder().decodeDict(of: PaginationInfo.self, from: paginationObj)
else {
delegate.didFailSyncTickets(errorData: APIError.getDefaultError())
return
}
delegate.didSyncTicketsPage(eventId: eventId, tickets: tickets, pagination: pagination)
}, onError: { error in
delegate.didFailSyncTickets(errorData: error)
})
}
/// Get number of tickets for a given event
///
/// - Parameters:
/// - userId: id of logged user
/// - eventId: id of requested event
/// - userToken: token of logged user
public func getWalletTicketsOf(request: Request.Wallet.NumberOfTickets,
onSuccess: @escaping (_ tickets: Int) -> Void,
onError: @escaping (_ error: APIError) -> Void) {
let builder = URLBuilder(client: client)
.setPath("user/\(request.userId)/tickets")
.addParameter(key: "eventId", value: request.eventId)
.addParameter(key: "usertoken", value: request.userToken)
.addParameter(key: "page", value: 1)
.addParameter(key: "pageSize", value: "1")
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: request, onSuccess: { (response) in
guard
let paginationObj = response["paginationInfo"] as? [String: Any],
let pagination = JSONDecoder().decodeDict(of: PaginationInfo.self, from: paginationObj)
else {
onError(APIError.getDefaultError())
return
}
onSuccess(pagination.totalResults)
}, onError: onError)
}
}
| 39550f474542f0f569e21cab287e2d98 | 39.59854 | 104 | 0.54279 | false | false | false | false |
iWeslie/Ant | refs/heads/master | Ant/Ant/LunTan/HouseNeedRent/Controller/HouseNeedRentVC.swift | apache-2.0 | 1 | //
// HuseNeedRentVC.swift
// Ant
//
// Created by LiuXinQiang on 2017/7/20.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
import MJRefresh
class HouseNeedRentVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
let houseNeedRentCellID = "LunTanListWithAvatarCell"
let topPlistName = ["job_recruit_type","job_recruit_visa","house_rent_create_time","job_recruit_nature"]
var category : CategoryVC?
var categoryDetial : CategoryDetialVC?
//定义顶部列表栏
fileprivate var topView: UIView?
//导航分类箭头image
fileprivate var arrowImag : UIImageView?
fileprivate lazy var nowButton = UIButton()
//定义全局plist名
var plistName : String?
var tableView : UITableView?
//定义当前页数
var page = 1
//定义当前的page总页数
var pages = 1
fileprivate lazy var modelInfo: [LunTanDetialModel] = [LunTanDetialModel]()
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
loadCellData(page: page)
// 定义发布按钮
creatRightBtn()
//加载头部
//loadListView()
//注册cell
tableView?.register(UINib.init(nibName: "LunTanListWithAvatarCell", bundle: nil), forCellReuseIdentifier: houseNeedRentCellID)
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 100
}
func initTableView() -> () {
self.view.backgroundColor = UIColor.white
self.tabBarController?.tabBar.isHidden = true
self.tableView = UITableView.init(frame:CGRect.init(x: 0, y: 40, width: screenWidth, height: screenHeight - 44), style: .plain)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.sectionIndexColor = UIColor.init(red: 252/255.0, green: 74/255.0, blue: 132/255.0, alpha: 1.0)
self.tableView?.showsVerticalScrollIndicator = false
self.view.addSubview(self.tableView!)
//设置回调
//默认下拉刷新
tableView?.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(HouseRentListVC.refresh))
// 马上进入刷新状态
self.tableView?.mj_header.beginRefreshing()
//上拉刷新
tableView?.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(HouseRentListVC.loadMore))
}
//MARK: - refresh
func loadMore() {
self.loadCellData(page: self.page)
}
func refresh() {
weak var weakself = self
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8, execute: {
//结束刷新
weakself?.tableView?.mj_header.endRefreshing()
//重新调用数据接口
weakself?.tableView?.reloadData()
})
}
override func viewWillDisappear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return modelInfo.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: houseNeedRentCellID) as! LunTanListWithAvatarCell
cell.viewModel = modelInfo[indexPath.row]
//头像点击事件
cell.avatarClick = {
self.present(UIStoryboard.init(name: "Others", bundle: nil).instantiateInitialViewController()!, animated: true, completion: nil)
}
return cell
}
// tableView点击触发事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = self.modelInfo[indexPath.row]
let rentNeedVC = RentNeedDVC()
rentNeedVC.rentNeedID = Int(model.id!)
rentNeedVC.modelInfo = model
self.navigationController?.pushViewController(rentNeedVC, animated: true)
}
}
//MARK: -房屋求租发布
extension HouseNeedRentVC{
func creatRightBtn(){
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发布", style: .plain, target: self, action: #selector(showHouseRent))
}
func showHouseRent(){
let giveVC = GiveOutVC()
giveVC.title = "房屋求租"
let listTableview = HouseRentTabView.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight), style: .grouped)
giveVC.listTableView = listTableview
listTableview.pushModifyVCClouse = {[weak self](text , index) in
//获取当前故事版
let storyBoard = UIStoryboard(name: "SelfProfile", bundle: nil)
let dest = storyBoard.instantiateViewController(withIdentifier: "modify") as? SelfDetialViewController
dest?.info = text!
self?.navigationController?.pushViewController(dest!, animated: true)
giveVC.cateDict = listTableview.houseRentDic
dest?.changeClosure = {(changeText) in
listTableview.changeTableData(indexPath: index, text: changeText!)
giveVC.cateDict = listTableview.houseRentDic
listTableview.reloadData()
}
}
listTableview.pushChooseVCClouse = {[weak self](strArr , index) in
let choseVC = ChoseTableView()
//初始化闭包
choseVC.choseBtnClouse = {(name) in
listTableview.changeTableData(indexPath: index, text: name!)
giveVC.cateDict = listTableview.houseRentDic
listTableview.reloadData()
}
choseVC.resourceArr = strArr as! NSMutableArray
self?.navigationController?.pushViewController(choseVC, animated: true)
}
self.navigationController?.pushViewController(giveVC, animated: true)
}
}
//MARK: - TopListChoose
extension HouseNeedRentVC {
fileprivate func loadListView() {
self.topView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
let topListArray = ["区域" ,"类型","排序时间","租金"]
addTopButton(topListArrays: topListArray as NSArray ,topPlistName : topPlistName as NSArray)
self.view.addSubview(self.topView!)
}
// MARK:- add cascade list view
@objc fileprivate func addCascadeList(nowTopListBtn : UIButton ) {
self.nowButton = nowTopListBtn
let btnImageView = self.topView?.viewWithTag( nowTopListBtn.tag - 100)
//执行旋转动画
self.loadRotationImg(sender: btnImageView as! UIImageView)
//取出button展现的plist
if self.nowButton.isSelected == true {
UIView.animate(withDuration: 0.2, animations: {
self.category?.tableView.removeFromSuperview()
self.categoryDetial?.tableView.removeFromSuperview()
self.categoryDetial?.view.removeFromSuperview()
self.category?.view.removeFromSuperview()
self.category?.removeFromParentViewController()
self.categoryDetial?.removeFromParentViewController()
}, completion: { (_) in
})
self.nowButton.isSelected = !self.nowButton.isSelected
} else {
self.category?.tableView.removeFromSuperview()
self.categoryDetial?.tableView.removeFromSuperview()
self.categoryDetial?.view.removeFromSuperview()
self.category?.view.removeFromSuperview()
self.category?.removeFromParentViewController()
self.categoryDetial?.removeFromParentViewController()
let tempcategory = CategoryVC()
tempcategory.plistName = topPlistName[nowTopListBtn.tag - 200]
tempcategory.view.frame.origin = CGPoint.init(x: 0, y: 30)
let tempcategoryDetial = CategoryDetialVC()
tempcategoryDetial.view.frame.origin = CGPoint.init(x: 0, y: 30)
self.category = tempcategory
self.categoryDetial = tempcategoryDetial
category?.categoryDelegate = categoryDetial
//闭包传值
category?.selectClosure = {[weak self](item) in
self?.nowButton.setTitleColor(UIColor.red, for: .normal)
// 马上进入刷新状态
self?.tableView?.mj_header.beginRefreshing()
self?.refresh()
self?.nowButton.setTitle(item, for: .normal)
let btnImageView = self?.topView?.viewWithTag( nowTopListBtn.tag - 100)
self?.loadRotationImg(sender: btnImageView as! UIImageView)
self?.nowButton.isSelected = false
self?.category?.tableView.removeFromSuperview()
self?.categoryDetial?.tableView.removeFromSuperview()
self?.categoryDetial?.view.removeFromSuperview()
self?.category?.view.removeFromSuperview()
self?.category?.removeFromParentViewController()
self?.categoryDetial?.removeFromParentViewController()
}
addChildViewController(category!)
addChildViewController(categoryDetial!)
categoryDetial?.view.frame.origin = CGPoint.init(x: width * 0.4, y: 30)
//闭包传值
categoryDetial?.selectClosure = {[weak self](item) in
self?.nowButton.setTitle(item, for: .normal)
self?.nowButton.setTitleColor(UIColor.red, for: .normal)
// 马上进入刷新状态
self?.tableView?.mj_header.beginRefreshing()
self?.refresh()
let btnImageView = self?.topView?.viewWithTag( nowTopListBtn.tag - 100)
self?.loadRotationImg(sender: btnImageView as! UIImageView)
self?.nowButton.isSelected = false
self?.category?.tableView.removeFromSuperview()
self?.categoryDetial?.tableView.removeFromSuperview()
self?.categoryDetial?.view.removeFromSuperview()
self?.category?.view.removeFromSuperview()
self?.category?.removeFromParentViewController()
self?.categoryDetial?.removeFromParentViewController()
}
self.view.addSubview((category?.view)!)
self.view.addSubview((categoryDetial?.view)!)
if categoryDetial?.subcategories?.count == 0 {
self.categoryDetial?.view.isHidden = true
}else {
self.categoryDetial?.view.isHidden = false
}
self.nowButton.isSelected = !self.nowButton.isSelected
}
}
//添加小三角
fileprivate func addTopButton(topListArrays : NSArray, topPlistName : NSArray) {
for i in 0..<topListArrays.count {
let btn = UIButton.init(frame: CGRect(x: ((screenWidth - 2) / CGFloat(topListArrays.count) ) * CGFloat(i) , y: 0, width: (screenWidth - 2) / CGFloat(topListArrays.count) , height: 40))
btn.setTitleColor(UIColor.black, for: .normal)
btn.setTitle(topListArrays[i] as? String, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.addTarget(self, action: #selector(addCascadeList(nowTopListBtn:)), for: .touchUpInside)
btn.tag = i + 200
//定义尖头image
let arrowImag = UIImageView.init(frame: CGRect.init(x: btn.frame.maxX - 15, y: 15, width: 9, height: 4.5))
arrowImag.image = #imageLiteral(resourceName: "triangle")
self.arrowImag = arrowImag
arrowImag.tag = i + 100
if i != topListArrays.count - 1 {
let lineView1: UIView = UIView(frame: CGRect(x: arrowImag.frame.maxX + 5, y: 8, width: 1, height: 24))
lineView1.backgroundColor = UIColor.lightGray
self.topView?.addSubview(lineView1)
}
self.topView?.addSubview(btn)
self.topView?.addSubview(arrowImag)
}
}
//小三角旋转动画
fileprivate func loadRotationImg(sender: UIImageView) {
// 1.创建动画
let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
// 2.设置动画的属性
if self.nowButton.isSelected == false {
rotationAnim.fromValue = 0
rotationAnim.toValue = Double.pi
} else {
rotationAnim.fromValue = Double.pi
rotationAnim.toValue = 0
}
rotationAnim.duration = 0.2
rotationAnim.isRemovedOnCompletion = false
rotationAnim.fillMode = kCAFillModeForwards
// 3.将动画添加到layer中
sender.layer.add(rotationAnim, forKey: nil)
}
}
// MARK:- Pass the data to the tableView
extension HouseNeedRentVC {
// MARK:- DispatchGroup
fileprivate func loadCellData(page : Int) {
if self.page != self.pages {
self.page += 1
}
let group = DispatchGroup()
//将当前的下载操作添加到组中
group.enter()
NetWorkTool.shareInstance.infoList(VCType: .seek, cate_2 : "", cate_3 : "", cate_4 : "", p: page) { [weak self](result, error) in
//在这里异步加载任务
if error != nil {
print(error ?? "load house info list failed")
return
}
guard let resultDict = result!["result"] else {
return
}
guard let resultList = resultDict["list"] as? NSArray else {
return
}
guard let pages = resultDict["pages"] as? Int else {
return
}
self?.pages = pages
for i in 0..<resultList.count {
let dict = resultList[i]
let basic = LunTanDetialModel.init(dict: dict as! [String : AnyObject])
self?.modelInfo.append(basic)
}
if self?.page == self?.pages {
self?.tableView?.mj_footer.endRefreshingWithNoMoreData()
}else {
self?.tableView?.mj_footer.endRefreshing()
}
//离开当前组
group.leave()
}
group.notify(queue: DispatchQueue.main) {
//在这里告诉调用者,下完完毕,执行下一步操作
self.tableView?.reloadData()
}
}
}
| 4f5c8fd057786ac9f3e3c484d65c5219 | 37.456 | 200 | 0.603148 | false | false | false | false |
marcinkuptel/FitToday | refs/heads/master | FitToday/Source/FitBit client/HTTP responses/GetActivityStatsResponse.swift | mit | 1 | //
// GetActivityStatsResponse.swift
// FitToday
//
// Created by Marcin Kuptel on 17/02/15.
// Copyright (c) 2015 Marcin Kuptel. All rights reserved.
//
import Foundation
class GetActivityStatsResponse: HTTPResponse {
lazy var steps: Int? = {
if let dict = self.dictionary {
var bestObject = dict["best"] as? [String:AnyObject]
if let best = bestObject {
var totalObject = best["total"] as? [String:AnyObject]
if let total = totalObject {
var stepsObject = total["steps"] as? [String:AnyObject]
if let steps = stepsObject {
return steps["value"] as? Int
}
}
}
}
return nil
}()
}
| 62179fee0d19edd467f63d0ce7192d0f | 24.870968 | 75 | 0.516209 | false | false | false | false |
BryanHoke/swift-corelibs-foundation | refs/heads/master | Foundation/NSCFString.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal class _NSCFString : NSMutableString {
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
override var length: Int {
return CFStringGetLength(unsafeBitCast(self, CFStringRef.self))
}
override func characterAtIndex(index: Int) -> unichar {
return CFStringGetCharacterAtIndex(unsafeBitCast(self, CFStringRef.self), index)
}
override func replaceCharactersInRange(range: NSRange, withString aString: String) {
CFStringReplace(unsafeBitCast(self, CFMutableStringRef.self), CFRangeMake(range.location, range.length), aString._cfObject)
}
}
internal final class _NSCFConstantString : _NSCFString {
internal var _ptr : UnsafePointer<UInt8> {
get {
let ptr = unsafeAddressOf(self) + sizeof(COpaquePointer) + sizeof(Int32) + sizeof(Int32) + sizeof(_CFInfo)
return UnsafePointer<UnsafePointer<UInt8>>(ptr).memory
}
}
internal var _length : UInt32 {
get {
let offset = sizeof(COpaquePointer) + sizeof(Int32) + sizeof(Int32) + sizeof(_CFInfo) + sizeof(UnsafePointer<UInt8>)
let ptr = unsafeAddressOf(self) + offset
return UnsafePointer<UInt32>(ptr).memory
}
}
required init(characters: UnsafePointer<unichar>, length: Int) {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(extendedGraphemeClusterLiteral value: StaticString) {
fatalError()
}
required init(stringLiteral value: StaticString) {
fatalError()
}
required init(capacity: Int) {
fatalError()
}
deinit {
fatalError("Constant strings cannot be deallocated")
}
override var length: Int {
return Int(_length)
}
override func characterAtIndex(index: Int) -> unichar {
return unichar(_ptr[index])
}
override func replaceCharactersInRange(range: NSRange, withString aString: String) {
fatalError()
}
}
internal func _CFSwiftStringGetLength(string: AnyObject) -> CFIndex {
return (string as! NSString).length
}
internal func _CFSwiftStringGetCharacterAtIndex(str: AnyObject, index: CFIndex) -> UniChar {
return (str as! NSString).characterAtIndex(index)
}
internal func _CFSwiftStringGetCharacters(str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UniChar>) {
(str as! NSString).getCharacters(buffer, range: NSMakeRange(range.location, range.length))
}
internal func _CFSwiftStringGetBytes(str: AnyObject, range: CFRange, buffer: UnsafeMutablePointer<UInt8>, maxBufLen: CFIndex, usedBufLen: UnsafeMutablePointer<CFIndex>) -> CFIndex {
let s = (str as! NSString)._swiftObject.utf8
let start = s.startIndex
if buffer != nil {
for idx in 0..<range.length {
let c = s[start.advancedBy(idx + range.location)]
buffer.advancedBy(idx).initialize(c)
}
}
if usedBufLen != nil {
usedBufLen.memory = range.length
}
return range.length
}
internal func _CFSwiftStringCreateWithSubstring(str: AnyObject, range: CFRange) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).substringWithRange(NSMakeRange(range.location, range.length))._nsObject)
}
internal func _CFSwiftStringCreateCopy(str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).copyWithZone(nil))
}
internal func _CFSwiftStringCreateMutableCopy(str: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((str as! NSString).mutableCopyWithZone(nil))
}
internal func _CFSwiftStringFastCStringContents(str: AnyObject) -> UnsafePointer<Int8> {
return (str as! NSString)._fastCStringContents
}
internal func _CFSwiftStringFastContents(str: AnyObject) -> UnsafePointer<UniChar> {
return (str as! NSString)._fastContents
}
internal func _CFSwiftStringGetCString(str: AnyObject, buffer: UnsafeMutablePointer<Int8>, maxLength: Int, encoding: CFStringEncoding) -> Bool {
return (str as! NSString).getCString(buffer, maxLength: maxLength, encoding: CFStringConvertEncodingToNSStringEncoding(encoding))
}
internal func _CFSwiftStringInsert(str: AnyObject, index: CFIndex, inserted: AnyObject) {
(str as! NSMutableString).insertString((inserted as! NSString)._swiftObject, atIndex: index)
}
internal func _CFSwiftStringDelete(str: AnyObject, range: CFRange) {
(str as! NSMutableString).deleteCharactersInRange(NSMakeRange(range.location, range.length))
}
internal func _CFSwiftStringReplace(str: AnyObject, range: CFRange, replacement: AnyObject) {
(str as! NSMutableString).replaceCharactersInRange(NSMakeRange(range.location, range.length), withString: (replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringReplaceAll(str: AnyObject, replacement: AnyObject) {
(str as! NSMutableString).setString((replacement as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppend(str: AnyObject, appended: AnyObject) {
(str as! NSMutableString).appendString((appended as! NSString)._swiftObject)
}
internal func _CFSwiftStringAppendCharacters(str: AnyObject, chars: UnsafePointer<UniChar>, length: CFIndex) {
(str as! NSMutableString).appendCharacters(chars, length: length)
}
internal func _CFSwiftStringAppendCString(str: AnyObject, chars: UnsafePointer<Int8>, length: CFIndex) {
(str as! NSMutableString)._cfAppendCString(chars, length: length)
}
| 1ff5bc4c1a19315c44be8ed3affaf09f | 33.666667 | 181 | 0.707282 | false | false | false | false |
tjw/swift | refs/heads/master | test/SILGen/optional.swift | apache-2.0 | 1 |
// RUN: %target-swift-frontend -module-name optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func testCall(_ f: (() -> ())?) {
f?()
}
// CHECK: sil hidden @{{.*}}testCall{{.*}}
// CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> ()>):
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK-NEXT: switch_enum [[T0_COPY]] : $Optional<@callee_guaranteed () -> ()>, case #Optional.some!enumelt.1: [[SOME:bb[0-9]+]], case #Optional.none!enumelt: [[NONE:bb[0-9]+]]
//
// CHECK: [[NONE]]:
// CHECK: br [[NOTHING_BLOCK_EXIT:bb[0-9]+]]
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: [[SOME]]([[FN0:%.*]] :
// .... then call it
// CHECK-NEXT: [[B:%.*]] = begin_borrow [[FN0]]
// CHECK-NEXT: apply [[B]]()
// CHECK: destroy_value [[FN0]]
// CHECK: br [[EXIT:bb[0-9]+]](
// (first nothing block)
// CHECK: [[NOTHING_BLOCK_EXIT]]:
// CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt
// CHECK-NEXT: br [[EXIT]]
// CHECK: } // end sil function '$S8optional8testCallyyyycSgF'
func testAddrOnlyCallResult<T>(_ f: (() -> T)?) {
var f = f
var x = f?()
}
// CHECK-LABEL: sil hidden @{{.*}}testAddrOnlyCallResult{{.*}} : $@convention(thin) <T> (@guaranteed Optional<@callee_guaranteed () -> @out T>) -> ()
// CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> @out T>):
// CHECK: [[F:%.*]] = alloc_box $<τ_0_0> { var Optional<@callee_guaranteed () -> @out τ_0_0> } <T>, var, name "f"
// CHECK-NEXT: [[PBF:%.*]] = project_box [[F]]
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK: store [[T0_COPY]] to [init] [[PBF]]
// CHECK-NEXT: [[X:%.*]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>, var, name "x"
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]]
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBF]]
// Check whether 'f' holds a value.
// CHECK: [[HASVALUE:%.*]] = select_enum_addr [[READ]]
// CHECK-NEXT: cond_br [[HASVALUE]], bb2, bb1
// If so, pull out the value...
// CHECK: bb2:
// CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[READ]]
// CHECK-NEXT: [[T0:%.*]] = load [copy] [[T1]]
// CHECK-NEXT: end_access [[READ]]
// ...evaluate the rest of the suffix...
// CHECK: [[B:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: apply [[B]]([[TEMP]])
// ...and coerce to T?
// CHECK: inject_enum_addr [[PBX]] {{.*}}some
// CHECK: destroy_value [[T0]]
// CHECK-NEXT: br bb3
// Continuation block.
// CHECK: bb3
// CHECK-NEXT: destroy_value [[X]]
// CHECK-NEXT: destroy_value [[F]]
// CHECK-NOT: destroy_value %0
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
// Nothing block.
// CHECK: bb4:
// CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none
// CHECK-NEXT: br bb3
// <rdar://problem/15180622>
func wrap<T>(_ x: T) -> T? { return x }
// CHECK-LABEL: sil hidden @$S8optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F
func wrap_then_unwrap<T>(_ x: T) -> T {
// CHECK: switch_enum_addr {{.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]]
// CHECK: [[FAIL]]:
// CHECK: unreachable
// CHECK: [[OK]]:
// CHECK: unchecked_take_enum_data_addr
return wrap(x)!
}
// CHECK-LABEL: sil hidden @$S8optional10tuple_bind{{[_0-9a-zA-Z]*}}F
func tuple_bind(_ x: (Int, String)?) -> String? {
return x?.1
// CHECK: switch_enum {{%.*}}, case #Optional.some!enumelt.1: [[NONNULL:bb[0-9]+]], case #Optional.none!enumelt: [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]](
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: destroy_value [[STRING]]
}
// rdar://21883752 - We were crashing on this function because the deallocation happened
// out of scope.
// CHECK-LABEL: sil hidden @$S8optional16crash_on_deallocyys10DictionaryVySiSaySiGGFfA_
func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) {
var dict = dict
dict[1]?.append(2)
}
| 3e046bdf247eed4ace5008333c60e2b3 | 37.873786 | 177 | 0.573926 | false | false | false | false |
Norod/Filterpedia | refs/heads/swift-3 | Filterpedia/customFilters/VoronoiNoise.swift | gpl-3.0 | 1 | //
// VoronoiNoise.swift
// Filterpedia
//
// Created by Simon Gladman on 09/04/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
import CoreImage
class VoronoiNoise: CIFilter
{
var inputSeed: CGFloat = 20
var inputSize: CGFloat = 60
var inputDensity: CGFloat = 0.75
var inputWidth: CGFloat = 640
var inputHeight: CGFloat = 640
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Voronoi Noise",
"inputSeed": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Seed",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1000,
kCIAttributeType: kCIAttributeTypeScalar],
"inputSize": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 60,
kCIAttributeDisplayName: "Size",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 200,
kCIAttributeType: kCIAttributeTypeScalar],
"inputDensity": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.75,
kCIAttributeDisplayName: "Density",
kCIAttributeMin: 0.5,
kCIAttributeSliderMin: 0.5,
kCIAttributeSliderMax: 1.5,
kCIAttributeType: kCIAttributeTypeScalar],
"inputWidth": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Width",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1280,
kCIAttributeType: kCIAttributeTypeScalar],
"inputHeight": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Height",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1280,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
let voronoiKernel: CIColorKernel =
{
let shaderPath = Bundle.main.path(forResource: "Voronoi", ofType: "cikernel")
guard let path = shaderPath,
let code = try? String(contentsOfFile: path),
let kernel = CIColorKernel(string: code) else
{
fatalError("Unable to build Voronoi shader")
}
return kernel
}()
override var outputImage: CIImage?
{
return voronoiKernel.apply(
withExtent: CGRect(origin: CGPoint.zero, size: CGSize(width: inputWidth, height: inputHeight)),
arguments: [inputSeed, inputSize, inputDensity])
}
}
| 92207322f1be0aa804c1b9aa9542aee3 | 34.581395 | 107 | 0.575163 | false | false | false | false |
slavapestov/swift | refs/heads/master | test/DebugInfo/test-foundation.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-ir -g %s -o %t.ll
// RUN: FileCheck %s --check-prefix CHECK-HIDDEN < %t.ll
// RUN: FileCheck %s --check-prefix IMPORT-CHECK < %t.ll
// RUN: FileCheck %s --check-prefix LOC-CHECK < %t.ll
// RUN: llc %t.ll -filetype=obj -o %t.o
// RUN: llvm-dwarfdump %t.o | FileCheck %s --check-prefix DWARF-CHECK
// RUN: dwarfdump --verify %t.o
// REQUIRES: OS=macosx
// CHECK-HIDDEN: @[[HIDDEN_GV:_TWVVSC.*]] = linkonce_odr hidden
// CHECK-HIDDEN-NOT: !DIGlobalVariable({{.*}}[[HIDDEN_GV]]
import ObjectiveC
import Foundation
class MyObject : NSObject {
// Ensure we don't emit linetable entries for ObjC thunks.
// LOC-CHECK: define {{.*}} @_TToFC4main8MyObjectg5MyArrCSo7NSArray
// LOC-CHECK: ret {{.*}}, !dbg ![[DBG:.*]]
// LOC-CHECK: ret
var MyArr = NSArray()
// IMPORT-CHECK: filename: "test-foundation.swift"
// IMPORT-CHECK: [[FOUNDATION:[0-9]+]] = !DIModule({{.*}} name: "Foundation",
// IMPORT-CHECK-SAME: {{.*}} includePath:
// IMPORT-CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "NSArray",
// IMPORT-CHECK-SAME: scope: ![[FOUNDATION]]
// IMPORT-CHECK: !DIImportedEntity(tag: DW_TAG_imported_module, {{.*}}entity: ![[FOUNDATION]]
func foo(obj: MyObject) {
return obj.foo(obj)
}
}
// SANITY-DAG: !DISubprogram(name: "blah",{{.*}} line: [[@LINE+2]],{{.*}} isDefinition: true
extension MyObject {
func blah() {
MyObject()
}
}
// SANITY-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "NSObject",{{.*}} identifier: "_TtCSo8NSObject"
// SANITY-DAG: !DIGlobalVariable(name: "NsObj",{{.*}} line: [[@LINE+1]],{{.*}} type: !"_TtCSo8NSObject",{{.*}} isDefinition: true
var NsObj: NSObject
NsObj = MyObject()
var MyObj: MyObject
MyObj = NsObj as! MyObject
MyObj.blah()
public func err() {
// DWARF-CHECK: DW_AT_name{{.*}}NSError
// DWARF-CHECK: DW_AT_linkage_name{{.*}}_TtCSo7NSError
let error = NSError(domain: "myDomain", code: 4,
userInfo: ["a":1,"b":2,"c":3])
}
// LOC-CHECK: define {{.*}}4date
public func date() {
// LOC-CHECK: call {{.*}} @_TFSSCfT21_builtinStringLiteralBp8byteSizeBw7isASCIIBi1__SS{{.*}}, !dbg ![[L1:.*]]
let d1 = NSDateFormatter()
// LOC-CHECK: br{{.*}}, !dbg ![[L2:.*]]
d1.dateFormat = "dd. mm. yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L2]]
// LOC-CHECK: call {{.*}} @_TFSSCfT21_builtinStringLiteralBp8byteSizeBw7isASCIIBi1__SS{{.*}}, !dbg ![[L3:.*]]
let d2 = NSDateFormatter()
// LOC-CHECK: br{{.*}}, !dbg ![[L4:.*]]
d2.dateFormat = "mm dd yyyy" // LOC-CHECK: call{{.*}}objc_msgSend{{.*}}, !dbg ![[L4]]
}
// Make sure we build some witness tables for enums.
func useOptions(opt: NSURLBookmarkCreationOptions)
-> NSURLBookmarkCreationOptions {
return [opt, opt]
}
// LOC-CHECK: ![[THUNK:.*]] = distinct !DISubprogram({{.*}}linkageName: "_TToFC4main8MyObjectg5MyArrCSo7NSArray"
// LOC-CHECK-NOT: line:
// LOC-CHECK-SAME: isDefinition: true
// LOC-CHECK: ![[DBG]] = !DILocation(line: 0, scope: ![[THUNK]])
// These debug locations should all be in ordered by increasing line number.
// LOC-CHECK: ![[L1]] =
// LOC-CHECK: ![[L2]] =
// LOC-CHECK: ![[L3]] =
// LOC-CHECK: ![[L4]] =
| 756fb0d15f5bd699f699b92c4c48b2c0 | 37.642857 | 129 | 0.613678 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/Hero/Sources/Preprocessors/CascadePreprocessor.swift | mit | 1 | //
// CascadeEffect.swift
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public enum CascadeDirection {
case topToBottom
case bottomToTop
case leftToRight
case rightToLeft
case radial(center: CGPoint)
case inverseRadial(center: CGPoint)
var comparator: (UIView, UIView) -> Bool {
switch self {
case .topToBottom:
return topToBottomComperator
case .bottomToTop:
return bottomToTopComperator
case .leftToRight:
return leftToRightComperator
case .rightToLeft:
return rightToLeftComperator
case .radial(let center):
return { (lhs: UIView, rhs: UIView) -> Bool in
return lhs.center.distance(center) < rhs.center.distance(center)
}
case .inverseRadial(let center):
return { (lhs: UIView, rhs: UIView) -> Bool in
return lhs.center.distance(center) > rhs.center.distance(center)
}
}
}
init?(_ string: String) {
switch string {
case "bottomToTop":
self = .bottomToTop
case "leftToRight":
self = .leftToRight
case "rightToLeft":
self = .rightToLeft
case "topToBottom":
self = .topToBottom
case "leadingToTrailing":
self = .leadingToTrailing
case "trailingToLeading":
self = .trailingToLeading
default:
return nil
}
}
public static var leadingToTrailing: CascadeDirection {
return UIApplication.shared.userInterfaceLayoutDirection == .leftToRight ? .leftToRight : .rightToLeft
}
public static var trailingToLeading: CascadeDirection {
return UIApplication.shared.userInterfaceLayoutDirection == .leftToRight ? .rightToLeft : .leftToRight
}
private func topToBottomComperator(lhs: UIView, rhs: UIView) -> Bool {
return lhs.frame.minY < rhs.frame.minY
}
private func bottomToTopComperator(lhs: UIView, rhs: UIView) -> Bool {
return lhs.frame.maxY == rhs.frame.maxY ? lhs.frame.maxX > rhs.frame.maxX : lhs.frame.maxY > rhs.frame.maxY
}
private func leftToRightComperator(lhs: UIView, rhs: UIView) -> Bool {
return lhs.frame.minX < rhs.frame.minX
}
private func rightToLeftComperator(lhs: UIView, rhs: UIView) -> Bool {
return lhs.frame.maxX > rhs.frame.maxX
}
}
class CascadePreprocessor: BasePreprocessor {
override func process(fromViews: [UIView], toViews: [UIView]) {
process(views: fromViews)
process(views: toViews)
}
func process(views: [UIView]) {
for view in views {
guard let (deltaTime, direction, delayMatchedViews) = context[view]?.cascade else { continue }
var parentView = view
if view is UITableView, let wrapperView = view.subviews.get(0) {
parentView = wrapperView
}
let sortedSubviews = parentView.subviews.sorted(by: direction.comparator)
let initialDelay = context[view]!.delay
let finalDelay = TimeInterval(sortedSubviews.count) * deltaTime + initialDelay
for (i, subview) in sortedSubviews.enumerated() {
let delay = TimeInterval(i) * deltaTime + initialDelay
func applyDelay(view: UIView) {
if context.pairedView(for: view) == nil {
context[view]?.delay = delay
} else if delayMatchedViews, let paired = context.pairedView(for: view) {
context[view]?.delay = finalDelay
context[paired]?.delay = finalDelay
}
for subview in view.subviews {
applyDelay(view: subview)
}
}
applyDelay(view: subview)
}
}
}
}
| e8d30b8ae5a1251de9ee58c448dfdcbf | 32.376812 | 111 | 0.688016 | false | false | false | false |
937447974/YJCocoa | refs/heads/master | YJCocoa/Classes/AppFrameworks/UIKit/Extension/UIImageExt.swift | mit | 1 | //
// UIImageExt.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/6/19.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
import CoreImage
public extension UIImage {
/// color 转 image
static func image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
context.setFillColor(color.cgColor)
context.fill(CGRect(origin: CGPoint.zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/// 渐变色转 image
static func image(with gradientColors: [CGColor], opaque: Bool, start startPoint: CGPoint, end endPoint: CGPoint) -> UIImage? {
let size = CGSize(width: max(startPoint.x, endPoint.x), height: max(startPoint.y, endPoint.y))
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors = gradientColors as CFArray
guard let context = UIGraphicsGetCurrentContext(),
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: nil) else {
UIGraphicsEndImageContext()
return nil
}
if opaque {
context.setFillColor(UIColor.white.cgColor)
context.fill(CGRect(origin: CGPoint.zero, size: size))
}
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/// UIView 转 UIImage
static func image(with view: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.frameSize, false, 0)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
view.layer.render(in: context)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// UIView 中指定位置取圆角
/// - parameter view: 视图
/// - parameter rect: 矩形框
/// - parameter corner: 是否圆角
static func image(with view: UIView, rect: CGRect, corner: Bool = false) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.frameSize, true, 0)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
if corner {
context.addEllipse(in: rect)
} else {
let pathRef = CGMutablePath()
pathRef.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
pathRef.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
pathRef.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
pathRef.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
context.addPath(pathRef)
}
context.clip()
view.draw(view.bounds)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// 生成二维码
static func imageQRCode(with url: String, to width: CGFloat) -> UIImage? {
guard let filter = CIFilter(name: "CIQRCodeGenerator"), let data = url.data(using: .utf8) else { return nil }
filter.setDefaults()
filter.setValue(data, forKey: "inputMessage")
guard let ciImage = filter.outputImage else { return nil }
// 生成高清的UIImage
let extent = ciImage.extent.integral
let scale = min(width/extent.width, width/extent.height)
let width = Int(extent.width * scale)
let height = Int(extent.height * scale)
let cs = CGColorSpaceCreateDeviceGray()
guard let bitmapRef = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0) else { return nil }
let context = CIContext(options: nil)
guard let bitmapImage = context.createCGImage(ciImage, from: extent) else { return nil }
bitmapRef.interpolationQuality = CGInterpolationQuality.none
bitmapRef.scaleBy(x: scale, y: scale)
bitmapRef.draw(bitmapImage, in: extent)
guard let cgImage = bitmapRef.makeImage() else { return nil }
return UIImage(cgImage: cgImage)
}
/// 本地图片预解码加载 Downsampling large images for display at smaller size
static func downsample(imageAt imageURL: URL, to pointSize: CGSize) -> UIImage? {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions) else { return nil }
var maxPixelSize = max(pointSize.width, pointSize.height) * UIScreen.main.scale
if maxPixelSize <= 0 { maxPixelSize = UIScreen.main.bounds.height }
let downsampleOptions = [kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize] as CFDictionary
guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
return nil
}
return UIImage(cgImage: downsampledImage).decodedImage
}
/// 生成本地图片预解码
static func image(contentsOf url: URL) -> UIImage? {
if let data = try? Data(contentsOf: url) {
return UIImage(data: data)?.decodedImage
}
return UIImage(contentsOfFile: url.absoluteString)?.decodedImage
}
/// 图片解码
var decodedImage: UIImage {
// Decoding only works for CG-based image.
guard let imageRef = self.cgImage else { return self }
let size = CGSize(width: CGFloat(imageRef.width) / self.scale, height: CGFloat(imageRef.height) / self.scale)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return self }
defer { UIGraphicsEndImageContext() }
// If drawing a CGImage, we need to make context flipped.
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0, y: -size.height)
context.draw(imageRef, in: CGRect(origin: .zero, size: size))
guard let cgImage = context.makeImage() else { return self }
return UIImage(cgImage: cgImage, scale: self.scale, orientation: self.imageOrientation)
}
/// 生成圆角图片
func withCornerRadius(_ cornerRadius: CGFloat, size: CGSize, backgroundColor: UIColor = UIColor.white) -> UIImage? {
guard cornerRadius > 0 else {
return self
}
let rect = CGRect(origin: CGPoint(), size: size)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
backgroundColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius)
path.addClip()
path.stroke()
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// 图片换色
func withTintColor(color: UIColor) -> UIImage? {
if #available(iOS 13.0, *) {
return self.withTintColor(color)
}
UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
color.setFill()
let rect = CGRect(origin: CGPoint(), size: self.size)
UIRectFill(rect)
self.draw(in: rect, blendMode: .destinationIn, alpha: 1)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// Creates and returns a image object that has the same image space and component values as the receiver, but has the specified alpha component.
/// - parameter alpha: The opacity value of the new color object, specified as a value from 0.0 to 1.0. Alpha values below 0.0 are interpreted as 0.0, and values above 1.0 are interpreted as 1.0
func withAlphaComponent(_ alpha: CGFloat) -> UIImage? {
guard alpha < 1 else {
return self
}
UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
guard let context = UIGraphicsGetCurrentContext(), let cgImage = self.cgImage else {
UIGraphicsEndImageContext()
return nil
}
let area = CGRect(origin: CGPoint(), size: self.size)
context.scaleBy(x: 1, y: -1)
context.translateBy(x: 0, y: -area.size.height)
context.setBlendMode(CGBlendMode.multiply)
context.setAlpha(alpha)
context.draw(cgImage, in: area)
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
return newImage
}
/// 图片压缩
func compress(size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
self.draw(in: CGRect(origin: CGPoint(), size: size))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| 1019e700414018827d9fb9eeff71281d | 42.825688 | 198 | 0.649885 | false | false | false | false |
HenvyLuk/BabyGuard | refs/heads/master | BabyGuard/BabyGuard/Helper/DataHelper.swift | apache-2.0 | 1 | //
// DataHelper.swift
// BabyGuard
//
// Created by csh on 16/7/5.
// Copyright © 2016年 csh. All rights reserved.
//
import UIKit
import AssetsLibrary
class DataHelper: NSObject {
class func contentOfServerDataString(dataStr: String) -> NSDictionary? {
do {
if let datas = dataStr.dataUsingEncoding(NSUTF8StringEncoding) {
let content = try NSJSONSerialization.JSONObjectWithData(datas, options: .MutableLeaves)
print("content:\(content)")
return content as? NSDictionary
} else {
return nil
}
} catch {
print("content error")
}
return nil
}
class func analyzeServerData(inString dataStr: String) -> (isSuc: Bool, error: String?, count: Int, datas: AnyObject?, attribute: AnyObject?) {
if let content = contentOfServerDataString(dataStr) {
let suc = content.objectForKey("Success")
let errorInfo = content.objectForKey("ErrorInfo")
let maxCount = content.objectForKey("MaxCount")
let data = content.objectForKey("SerData")
let attribute = content.objectForKey("AttachValue")
if (suc as! String) == "true" {
let count = Int(maxCount as! String)
return (true, nil, count!, data, attribute)
} else {
return (false, errorInfo as? String, 0, nil, nil)
}
}
print("服务器返回不能解析的数据:" + dataStr)
return (false, "数据解析失败", 0, nil, nil)
}
}
| 4c6c68022e96800f02bb281759a8cb20 | 29.90566 | 147 | 0.553724 | false | false | false | false |
gservera/ScheduleKit | refs/heads/master | ScheduleKit/Views/SCKGridView.swift | mit | 1 | /*
* SCKGridView.swift
* ScheduleKit
*
* Created: Guillem Servera on 28/10/2016.
* Copyright: © 2016-2019 Guillem Servera (https://github.com/gservera)
*
* 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 Cocoa
/// An object conforming to the `SCKGridViewDelegate` protocol may implement a
/// method to provide unavailable time ranges to a grid-style schedule view in
/// addition to other methods defined in `SCKViewDelegate`.
@objc public protocol SCKGridViewDelegate: SCKViewDelegate {
/// Implement this method to specify the first displayed hour. Defaults to 0.
/// - Parameter gridView: The grid view asking for a start hour.
/// - Returns: An hour value from 0 to 24.
@objc(dayStartHourForGridView:) func dayStartHour(for gridView: SCKGridView) -> Int
/// Implement this method to specify the last displayed hour. Defaults to 24.
/// - Parameter gridView: The grid view asking for a start hour.
/// - Returns: An hour value from 0 to 24, where 0 is parsed as 24.
@objc(dayEndHourForGridView:) func dayEndHour(for gridView: SCKGridView) -> Int
/// Implemented by a grid-style schedule view's delegate to provide an array
/// of unavailable time ranges that are drawn as so by the view.
/// - Parameter gridView: The schedule view asking for the values.
/// - Returns: The array of unavailable time ranges (may be empty).
@objc(unavailableTimeRangesForGridView:)
optional func unavailableTimeRanges(for gridView: SCKGridView) -> [SCKUnavailableTimeRange]
}
/// An abstract `SCKView` subclass that implements the common functionality of any
/// grid-style schedule view, such as the built in day view and week view. This
/// class provides conflict management, interaction with the displayed days and
/// hours, displaying unavailable time intervals and a zoom feature.
///
/// It also manages a series of day, month, hour and hour fraction labels, which
/// are automatically updated and laid out by this class.
/// - Note: Do not instantiate this class directly.
public class SCKGridView: SCKView {
struct Constants {
static let DayAreaHeight: CGFloat = 40.0
static let DayAreaMarginBottom: CGFloat = 20.0
static let MaxHeightPerHour: CGFloat = 300.0
static let HourAreaWidth: CGFloat = 56.0
static var paddingTop: CGFloat { return DayAreaHeight + DayAreaMarginBottom }
}
override func setUp() {
super.setUp()
updateHourParameters()
}
override public weak var delegate: SCKViewDelegate? {
didSet {
readDefaultsFromDelegate()
}
}
// MARK: - Date handling additions
public override var dateInterval: DateInterval {
didSet { // Set up day count and day labels
let sDate = dateInterval.start
let eDate = dateInterval.end.addingTimeInterval(1)
dayCount = sharedCalendar.dateComponents([.day], from: sDate, to: eDate).day!
dayLabelingView.configure(dayCount: dayCount, startDate: sDate)
_ = self.minuteTimer
}
}
/// The number of days displayed. Updated by changing `dateInterval`.
private(set) var dayCount: Int = 0
/// A value representing the day start hour.
private var dayStartPoint = SCKDayPoint.zero
/// A view representign the day end hour.
private var dayEndPoint = SCKDayPoint(hour: 24, minute: 0, second: 0)
/// Called when the `dayStartPoint` and `dayEndPoint` change during initialisation
/// or when their values are read from the delegate. Sets the `firstHour` and
/// `hourCount` properties and ensures a minimum height per hour to fill the view.
private func updateHourParameters() {
firstHour = dayStartPoint.hour
hourCount = dayEndPoint.hour - dayStartPoint.hour
let minHourHeight = contentRect.height / CGFloat(hourCount)
if hourHeight < minHourHeight {
hourHeight = minHourHeight
}
}
/// The first hour of the day displayed.
internal var firstHour: Int = 0 {
didSet { hourLabelingView.configureHourLabels(firstHour: firstHour, hourCount: hourCount) }
}
/// The total number of hours displayed.
internal var hourCount: Int = 1 {
didSet { hourLabelingView.configureHourLabels(firstHour: firstHour, hourCount: hourCount) }
}
/// The height for each hour row. Setting this value updates the saved one in
/// UserDefaults and updates hour labels visibility.
internal var hourHeight: CGFloat = 0.0 {
didSet {
if hourHeight != oldValue && superview != nil {
let key = SCKGridView.defaultsZoomKeyPrefix + ".\(type(of: self))"
UserDefaults.standard.set(hourHeight, forKey: key)
invalidateIntrinsicContentSize()
}
hourLabelingView.updateHourLabelsVisibility(hourHeight: hourHeight,
eventViewBeingDragged: eventViewBeingDragged)
}
}
// MARK: Day and month labels
/// A container view for day labels. Pinned at the top of the scroll view.
private let dayLabelingView = SCKDayLabelingView(frame: CGRect(x: 0, y: 0, width: 0, height: Constants.DayAreaHeight))
/// A container view for hour labels. Pinned left in the scroll view.
private let hourLabelingView = SCKHourLabelingView(frame: .zero)
// MARK: - Date transform additions
override func relativeTimeLocation(for point: CGPoint) -> Double {
if contentRect.contains(point) {
let dayWidth: CGFloat = contentRect.width / CGFloat(dayCount)
let offsetPerDay = 1.0 / Double(dayCount)
let day = Int(trunc((point.x-contentRect.minX)/dayWidth))
let dayOffset = offsetPerDay * Double(day)
let offsetPerMin = calculateRelativeTimeLocation(for: dateInterval.start.addingTimeInterval(60))
let offsetPerHour = 60.0 * offsetPerMin
let totalMinutes = 60.0 * CGFloat(hourCount)
let minute = totalMinutes * (point.y - contentRect.minY) / contentRect.height
let minuteOffset = offsetPerMin * Double(minute)
return dayOffset + offsetPerHour * Double(firstHour) + minuteOffset
}
return SCKRelativeTimeLocationInvalid
}
/// Returns the Y-axis position in the view's coordinate system that represents a particular hour and
/// minute combination.
/// - Parameters:
/// - hour: The hour.
/// - minute: The minute.
/// - Returns: The calculated Y position.
internal func yFor(hour: Int, minute: Int) -> CGFloat {
let canvas = contentRect
let hours = CGFloat(hourCount)
let hourIndex = CGFloat(hour - firstHour)
return canvas.minY + canvas.height * (hourIndex + CGFloat(minute)/60.0) / hours
}
// MARK: - Event Layout overrides
override public var contentRect: CGRect {
// Exclude day and hour labeling areas.
return CGRect(x: Constants.HourAreaWidth, y: Constants.paddingTop,
width: frame.width - Constants.HourAreaWidth,
height: CGFloat(hourCount) * hourHeight)
}
override func invalidateLayout(for eventView: SCKEventView) {
// Overriden to manage event conflicts. No need to call super in this case.
let conflicts = controller.resolvedConflicts(for: eventView.eventHolder)
if !conflicts.isEmpty {
eventView.eventHolder.conflictCount = conflicts.count
} else {
eventView.eventHolder.conflictCount = 1 //FIXME: Should not get here.
NSLog("Unexpected behavior")
}
eventView.eventHolder.conflictIndex = conflicts.firstIndex(where: { $0 === eventView.eventHolder }) ?? 0
}
override func prepareForDragging() {
hourLabelingView.updateHourLabelsVisibility(hourHeight: hourHeight,
eventViewBeingDragged: eventViewBeingDragged)
super.prepareForDragging()
}
override func restoreAfterDragging() {
hourLabelingView.updateHourLabelsVisibility(hourHeight: hourHeight,
eventViewBeingDragged: eventViewBeingDragged)
super.restoreAfterDragging()
}
// MARK: - NSView overrides
public override var intrinsicContentSize: NSSize {
return CGSize(width: NSView.noIntrinsicMetric, height: CGFloat(hourCount) * hourHeight + Constants.paddingTop)
}
public override func removeFromSuperview() {
dayLabelingView.removeFromSuperview()
super.removeFromSuperview()
}
public override func updateConstraints() {
let marginLeft = Constants.HourAreaWidth
let dayLabelsRect = CGRect(x: marginLeft, y: 0, width: frame.width-marginLeft, height: Constants.DayAreaHeight)
let dayWidth = dayLabelsRect.width / CGFloat(dayCount)
// Layout events
let offsetPerDay = 1.0/Double(dayCount)
for eventView in subviews.compactMap({ $0 as? SCKEventView }) where eventView.eventHolder.isReady {
let holder = eventView.eventHolder!
let day = Int(trunc(holder.relativeStart/offsetPerDay))
let sPoint = SCKDayPoint(date: holder.cachedScheduledDate)
let eMinute = sPoint.minute + holder.cachedDuration
let ePoint = SCKDayPoint(hour: sPoint.hour, minute: eMinute, second: sPoint.second)
let top = yFor(hour: sPoint.hour, minute: sPoint.minute)
eventView.topConstraint.constant = top
eventView.heightConstraint.constant = yFor(hour: ePoint.hour, minute: ePoint.minute)-top
let width = dayWidth / CGFloat(eventView.eventHolder.conflictCount)
eventView.widthConstraint.constant = width
eventView.leadingConstraint.constant = Constants.HourAreaWidth + CGFloat(day) * dayWidth + width * CGFloat(holder.conflictIndex)
NSLayoutConstraint.activate([
eventView.topConstraint, eventView.leadingConstraint,
eventView.widthConstraint, eventView.heightConstraint
])
}
super.updateConstraints()
}
public override func resize(withOldSuperviewSize oldSize: NSSize) {
super.resize(withOldSuperviewSize: oldSize) // Triggers layout. Try to acommodate hour height.
let visibleHeight = superview!.frame.height - Constants.paddingTop
let contentHeight = CGFloat(hourCount) * hourHeight
if contentHeight < visibleHeight && hourCount > 0 {
hourHeight = visibleHeight / CGFloat(hourCount)
}
dayLabelingView.needsUpdateConstraints = true
hourLabelingView.needsUpdateConstraints = true
needsUpdateConstraints = true
}
public override func viewWillMove(toSuperview newSuperview: NSView?) {
// Insert day labeling view
guard let superview = newSuperview else { return }
let height = Constants.DayAreaHeight
if let parent = superview.superview?.superview {
dayLabelingView.translatesAutoresizingMaskIntoConstraints = false
parent.addSubview(dayLabelingView, positioned: .above, relativeTo: nil)
NSLayoutConstraint.activate([
dayLabelingView.leftAnchor.constraint(equalTo: parent.leftAnchor, constant: Constants.HourAreaWidth),
dayLabelingView.rightAnchor.constraint(equalTo: parent.rightAnchor),
dayLabelingView.topAnchor.constraint(equalTo: parent.topAnchor),
dayLabelingView.heightAnchor.constraint(equalToConstant: height)
])
hourLabelingView.translatesAutoresizingMaskIntoConstraints = false
hourLabelingView.paddingTop = Constants.DayAreaMarginBottom
addSubview(hourLabelingView, positioned: .above, relativeTo: nil)
NSLayoutConstraint.activate([
hourLabelingView.leftAnchor.constraint(equalTo: leftAnchor),
hourLabelingView.widthAnchor.constraint(equalToConstant: Constants.HourAreaWidth),
hourLabelingView.topAnchor.constraint(equalTo: topAnchor, constant: Constants.DayAreaHeight)
])
}
DispatchQueue.main.asyncAfter(deadline: .now()) { [weak self] in
self?.dayLabelingView.needsUpdateConstraints = true
}
}
public override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
guard superview != nil else { return } // Called when removed
// Restore zoom if possible
let zoomKey = SCKGridView.defaultsZoomKeyPrefix + ".\(String(describing: type(of: self)))"
let hHeight = CGFloat(UserDefaults.standard.double(forKey: zoomKey))
processNewHourHeight(hHeight)
}
// MARK: - Delegate defaults
/// Calls some of the delegate methods to reflect user preferences. The default implementation asks for
/// unavailable time ranges and day start/end hours. Subclasses may override this method to set up additional
/// parameters by importing settings from their delegate objects. This method is called when the view is set
/// up and when the `invalidateUserDefaults()` method is called. You should not call this method directly.
internal func readDefaultsFromDelegate() {
guard let delegate = delegate as? SCKGridViewDelegate else { return }
if let unavailableRanges = delegate.unavailableTimeRanges?(for: self) {
unavailableTimeRanges = unavailableRanges
needsDisplay = true
}
let start = delegate.dayStartHour(for: self)
var end = delegate.dayEndHour(for: self)
if end == 0 { end = 24 }
dayStartPoint = SCKDayPoint(hour: start, minute: 0, second: 0)
dayEndPoint = SCKDayPoint(hour: end, minute: 0, second: 0)
updateHourParameters()
invalidateIntrinsicContentSize()
invalidateLayoutForAllEventViews()
}
/// Makes the view update some of its parameters, such as the unavailable time
/// ranges by reflecting the values supplied by the delegate.
@objc public final func invalidateUserDefaults() {
readDefaultsFromDelegate()
}
// MARK: - Unavailable time ranges
/// The time ranges that should be drawn as unavailable in this view.
private var unavailableTimeRanges: [SCKUnavailableTimeRange] = []
/// Calculates the rect to be drawn as unavailable from a given unavailable time range.
/// - Parameter rng: The unavailable time range.
/// - Returns: The calcualted rect.
func rectForUnavailableTimeRange(_ rng: SCKUnavailableTimeRange) -> CGRect {
let canvas = contentRect
let dayWidth: CGFloat = canvas.width / CGFloat(dayCount)
let sDate = sharedCalendar.date(bySettingHour: rng.startHour, minute: rng.startMinute, second: 0,
of: dateInterval.start)!
let sOffset = calculateRelativeTimeLocation(for: sDate)
if sOffset != SCKRelativeTimeLocationInvalid {
let endSeconds = rng.endMinute * 60 + rng.endHour * 3600
let startSeconds = rng.startMinute * 60 + rng.startHour * 3600
let eDate = sDate.addingTimeInterval(Double(endSeconds - startSeconds))
let yOrigin = yFor(hour: rng.startHour, minute: rng.startMinute)
var yLength: CGFloat = frame.maxY - yOrigin // Assuming SCKRelativeTimeLocationInvalid for eDate
if calculateRelativeTimeLocation(for: eDate) != SCKRelativeTimeLocationInvalid {
yLength = yFor(hour: rng.endHour, minute: rng.endMinute) - yOrigin
}
let weekday = (rng.weekday == -1) ? 0.0 : CGFloat(rng.weekday)
return CGRect(x: canvas.minX + weekday * dayWidth, y: yOrigin, width: dayWidth, height: yLength)
}
return .zero
}
// MARK: - Minute timer
/// A timer that fires every minute to mark the view as needing display in order to update the "now" line.
private lazy var minuteTimer: Timer = {
let sel = #selector(SCKGridView.minuteTimerFired(timer:))
let tmr = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: sel, userInfo: nil, repeats: true)
tmr.tolerance = 50.0
return tmr
}()
@objc dynamic func minuteTimerFired(timer: Timer) {
needsDisplay = true
}
// MARK: - Drawing
public override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
guard hourCount > 0 else { return }
drawUnavailableTimeRanges()
drawDayDelimiters()
drawHourDelimiters()
drawCurrentTimeLine()
drawDraggingGuidesIfNeeded()
}
private func drawUnavailableTimeRanges() {
NSColor.windowBackgroundColor.set()
unavailableTimeRanges.forEach { rectForUnavailableTimeRange($0).fill() }
}
private func drawDayDelimiters() {
let canvas = CGRect(x: Constants.HourAreaWidth, y: Constants.DayAreaHeight,
width: frame.width-Constants.HourAreaWidth, height: frame.height-Constants.DayAreaHeight)
let dayWidth = canvas.width / CGFloat(dayCount)
NSColor.gridColor.set()
for day in 0..<dayCount {
CGRect(x: canvas.minX + CGFloat(day) * dayWidth, y: canvas.minY, width: 1.0, height: canvas.height).fill()
}
}
private func drawHourDelimiters() {
NSColor.gridColor.set()
for hour in 0..<hourCount {
CGRect(x: contentRect.minX-8.0, y: contentRect.minY + CGFloat(hour) * hourHeight - 0.4,
width: contentRect.width + 8.0, height: 1.0).fill()
}
}
private func drawCurrentTimeLine() {
let canvas = contentRect
let components = sharedCalendar.dateComponents([.hour, .minute], from: Date())
let minuteCount = Double(hourCount) * 60.0
let elapsedMinutes = Double(components.hour!-firstHour) * 60.0 + Double(components.minute!)
let yOrigin = canvas.minY + canvas.height * CGFloat(elapsedMinutes / minuteCount)
NSColor.systemRed.setFill()
CGRect(x: canvas.minX, y: yOrigin-0.5, width: canvas.width, height: 1.0).fill()
NSBezierPath(ovalIn: CGRect(x: canvas.minX-2.0, y: yOrigin-2.0, width: 4.0, height: 4.0)).fill()
}
private func drawDraggingGuidesIfNeeded() {
guard let dView = eventViewBeingDragged else { return }
(dView.backgroundColor ?? NSColor.darkGray).setFill()
let canvas = contentRect
let dragFrame = dView.frame
// Left, right, top and bottom guides
CGRect.fill(canvas.minX, dragFrame.midY-1.0, dragFrame.minX-canvas.minX, 2.0)
CGRect.fill(dragFrame.maxX, dragFrame.midY-1.0, frame.width-dragFrame.maxX, 2.0)
CGRect.fill(dragFrame.midX-1.0, canvas.minY, 2.0, dragFrame.minY-canvas.minY)
CGRect.fill(dragFrame.midX-1.0, dragFrame.maxY, 2.0, frame.height-dragFrame.maxY)
let dayWidth = canvas.width / CGFloat(dayCount)
let offsetPerDay = 1.0/Double(dayCount)
let startOffset = relativeTimeLocation(for: CGPoint(x: dragFrame.midX, y: dragFrame.minY))
if startOffset != SCKRelativeTimeLocationInvalid {
CGRect.fill(canvas.minX + dayWidth * CGFloat(trunc(startOffset/offsetPerDay)), canvas.minY, dayWidth, 2.0)
let startDate = calculateDate(for: startOffset)!
let sPoint = SCKDayPoint(date: startDate)
let ePoint = SCKDayPoint(date: startDate.addingTimeInterval(Double(dView.eventHolder.cachedDuration)*60.0))
let sLabelText = NSString(format: "%ld:%02ld", sPoint.hour, sPoint.minute)
let eLabelText = NSString(format: "%ld:%02ld", ePoint.hour, ePoint.minute)
let attrs: [NSAttributedString.Key: Any] = [
.foregroundColor: NSColor.darkGray,
.font: NSFont.systemFont(ofSize: 12.0)
]
let sLabelSize = sLabelText.size(withAttributes: attrs)
let eLabelSize = eLabelText.size(withAttributes: attrs)
let sLabelRect = CGRect(x: Constants.HourAreaWidth/2.0-sLabelSize.width/2.0,
y: dragFrame.minY-sLabelSize.height/2.0,
width: sLabelSize.width, height: sLabelSize.height)
let eLabelRect = CGRect(x: Constants.HourAreaWidth/2.0-eLabelSize.width/2.0,
y: dragFrame.maxY-eLabelSize.height/2.0,
width: eLabelSize.width, height: eLabelSize.height)
sLabelText.draw(in: sLabelRect, withAttributes: attrs)
eLabelText.draw(in: eLabelRect, withAttributes: attrs)
let durationText = "\(dView.eventHolder.cachedDuration) min"
let dLabelSize = durationText.size(withAttributes: attrs)
let durationRect = CGRect(x: Constants.HourAreaWidth/2.0-dLabelSize.width/2.0,
y: dragFrame.midY-dLabelSize.height/2.0,
width: dLabelSize.width, height: dLabelSize.height)
durationText.draw(in: durationRect, withAttributes: attrs)
}
}
}
// MARK: - Hour height and zoom
extension SCKGridView {
/// A prefix appended to the class name to work as a key to store last zoom level for each subclass in user defaults
private static let defaultsZoomKeyPrefix = "MEKZoom"
/// Increases the hour height property if less than the maximum value. Marks the view as needing display.
func increaseZoomFactor() {
processNewHourHeight(hourHeight + 8.0)
}
/// Decreases the hour height property if greater than the minimum value. Marks the view as needing display.
func decreaseZoomFactor() {
processNewHourHeight(hourHeight - 8.0)
}
public override func magnify(with event: NSEvent) {
processNewHourHeight(hourHeight + 16.0 * event.magnification)
}
/// Increases or decreases the hour height property if greater than the minimum value and less than the maximum
/// hour height. Marks the view as needing display.
/// - Parameter targetHeight: The calculated new hour height.
private func processNewHourHeight(_ targetHeight: CGFloat) {
defer {
needsDisplay = true
needsUpdateConstraints = true
}
guard targetHeight < Constants.MaxHeightPerHour else {
hourHeight = Constants.MaxHeightPerHour
return
}
let minimumContentHeight = superview!.frame.height - Constants.paddingTop
if targetHeight * CGFloat(hourCount) >= minimumContentHeight {
hourHeight = targetHeight
} else {
hourHeight = minimumContentHeight / CGFloat(hourCount)
}
}
}
| b59dca37016e4d487bcaff306c1dd707 | 46.838 | 140 | 0.667252 | false | false | false | false |
didinozka/Projekt_Bakalarka | refs/heads/master | bp_v1/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// bp_v1
//
// Created by Dusan Drabik on 11/03/16.
// Copyright © 2016 Dusan Drabik. 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 "sk.ardstudio.swift.bp_v1" 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("bp_v1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bca90c7f61387e2b897b319d7ad06f07 | 53.873874 | 291 | 0.718765 | false | false | false | false |
yulingtianxia/pbxprojHelper | refs/heads/master | pbxprojHelper/Utils.swift | gpl-3.0 | 1 | //
// Utils.swift
// pbxprojHelper
//
// Created by 杨萧玉 on 2016/11/12.
// Copyright © 2016年 杨萧玉. All rights reserved.
//
import Cocoa
typealias Item = (key: String, value: Any, parent: Any?)
func isItem(_ item: Any, containsKeyWord word: String) -> Bool {
func checkAny(value: Any, containsString string: String) -> Bool {
return ((value is String) && (value as! String).lowercased().contains(string.lowercased()))
}
if let tupleItem = item as? Item {
if checkAny(value: tupleItem.key, containsString: word) || checkAny(value: tupleItem.value, containsString: word) {
return true
}
func dfs(propertyList list: Any) -> Bool {
if let dictionary = list as? [String: Any] {
for (key, value) in dictionary {
if checkAny(value: key, containsString: word) || checkAny(value: value, containsString: word) {
return true
}
else if dfs(propertyList: value) {
return true
}
}
}
if let array = list as? [Any] {
for value in array {
if checkAny(value: value, containsString: word) {
return true
}
else if dfs(propertyList: value) {
return true
}
}
}
return false
}
return dfs(propertyList: tupleItem.value)
}
return false
}
func elementsOfDictionary(_ dictionary: [String: Any], containsKeyWord word: String) -> [String: Any] {
var filtResult = [String: Any]()
for (key, value) in dictionary {
if isItem(Item(key: key, value: value, parent: nil), containsKeyWord: word) {
filtResult[key] = value
}
}
return filtResult
}
func elementsOfArray(_ array: [Any], containsKeyWord word: String) -> [Any] {
return array.filter { isItem(Item(key: "", value: $0, parent: nil), containsKeyWord: word) }
}
func keyPath(forItem item: Any?) -> String {
let key: String
let parent: Any?
if let tupleItem = item as? Item {
key = tupleItem.key
parent = tupleItem.parent
}
else {
key = ""
parent = nil
}
if let parentItem = parent {
return "\(keyPath(forItem: parentItem)).\(key)"
}
return "\(key)"
}
var recentUsePaths = LRUCache <String, String>()
var projectConfigurationPathPairs = [String : URL]()
class CacheGenerator<T: Hashable> : IteratorProtocol {
typealias Element = T
var counter: Int
let array: [T]
init(keys: [T]) {
counter = 0
array = keys
}
func next() -> Element? {
let result:Element? = counter < array.count ? array[counter] : nil
counter += 1
return result
}
}
class LRUCache <K: Hashable, V> : NSObject, NSCoding, Sequence {
fileprivate var _cache = [K : V]()
fileprivate var _keys = [K]()
var countLimit: Int = 0
var count: Int {
get {
return _keys.count
}
}
override init() {
}
subscript(index: Int) -> K {
get {
return _keys[index]
}
}
subscript(key: K) -> V? {
get {
return _cache[key]
}
set(obj) {
if obj == nil {
_cache.removeValue(forKey: key)
}
else {
useKey(key)
_cache[key] = obj
}
}
}
fileprivate func useKey(_ key: K) {
if let index = _keys.firstIndex(of: key) {// key 已存在数组中,只需要将其挪至 index 0
_keys.insert(_keys.remove(at: index), at: 0)
}
else {// key 不存在数组中,需要将其插入 index 0,并在超出缓存大小阈值时移走最后面的元素
if _keys.count >= countLimit {
_cache.removeValue(forKey: _keys.last!)
_keys.removeLast()
}
_keys.insert(key, at: 0)
}
}
typealias Iterator = CacheGenerator<K>
func makeIterator() -> Iterator {
return CacheGenerator(keys: _keys)
}
func cleanCache() {
_cache.removeAll()
_keys.removeAll()
}
// NSCoding
@objc required init?(coder aDecoder: NSCoder) {
_keys = aDecoder.decodeObject(forKey: "keys") as! [K]
_cache = aDecoder.decodeObject(forKey: "cache") as! [K:V]
}
@objc func encode(with aCoder: NSCoder) {
aCoder.encode(_keys, forKey: "keys")
aCoder.encode(_cache, forKey: "cache")
}
}
func writePasteboard(_ location: String) {
NSPasteboard.general.declareTypes([.string], owner: nil)
NSPasteboard.general.setString(location, forType: .string)
}
| 0540e12f5390e3d58225826336554c32 | 25.883978 | 123 | 0.524044 | false | false | false | false |
jlyu/swift-demo | refs/heads/master | Homepwner/Homepwner/DetailViewController.swift | mit | 1 | //
// DetailViewController.swift
// Homepwner
//
// Created by chain on 14-6-30.
// Copyright (c) 2014 chain. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController,
UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate {
@IBOutlet var nameField : UITextField
@IBOutlet var serialNumberField : UITextField
@IBOutlet var valueField : UITextField
@IBOutlet var dateLabel : UILabel
@IBOutlet var imageView : UIImageView
var item: BNRItem? = nil {
willSet(newValue) {
self.navigationItem.title = newValue!.itemName
}
}
var tableViewDataReloadHandler: ()-> Void = { }
func save() {
self.presentingViewController.dismissViewControllerAnimated(true, completion: tableViewDataReloadHandler)
}
func cancle() {
BNRItemStore.instance.removeItem(self.item!)
self.presentingViewController.dismissViewControllerAnimated(true, completion: tableViewDataReloadHandler)
}
init(forNewItem isNew: Bool) {
super.init(nibName: "DetailView", bundle: nil)
if self != nil {
if isNew {
var doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self,
action: Selector("save"))
self.navigationItem.rightBarButtonItem = doneButton
var cancleButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel,
target: self,
action: Selector("cancle"))
self.navigationItem.leftBarButtonItem = cancleButton
}
}
}
@IBAction func takePicture(sender : AnyObject) {
var imagePickerController: UIImagePickerController = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
imagePickerController.sourceType = UIImagePickerControllerSourceType.Camera
} else {
imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
imagePickerController.delegate = self
//set modal view
self.presentViewController(imagePickerController, animated: true, completion: nil)
}
@IBAction func dropPicture(sender : AnyObject) {
if let currentKey = item!.imageKey {
BNRImageStore.instance.deleteImageForKey(currentKey)
BNRItemStore.instance.deleteThumbnailImageForKey(currentKey)
}
self.imageView.image = nil
}
@IBAction func backgroundTapped(sender : AnyObject) {
self.view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.groupTableViewBackgroundColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nameField.text = item!.itemName
serialNumberField.text = item!.serialNumber
valueField.text = String(item!.valueInDollars)
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateLabel.text = dateFormatter.stringFromDate(item!.dateCreated)
if let imageKey: String = item!.imageKey {
imageView.image = BNRImageStore.instance.imageForKey(imageKey)
} else {
imageView.image = nil
}
}
override func viewWillDisappear(animated: Bool) {
self.editing = true
item!.itemName = nameField.text
item!.serialNumber = serialNumberField.text
item!.valueInDollars = valueField.text.toInt()!
}
// conform UIImagePickerControllerDelegation
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
if let oldKey = item!.imageKey {
BNRImageStore.instance.deleteImageForKey(oldKey)
}
var image: UIImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage
// since that has "Create" in the name, code is responsible for releasing the object. (no any more in Swift)
var newUniqueID: CFUUIDRef = CFUUIDCreate(kCFAllocatorDefault)
var newUniqueIDString: CFStringRef = CFUUIDCreateString(kCFAllocatorDefault, newUniqueID)
var key: String = String(newUniqueIDString as String)
item!.imageKey = key
BNRImageStore.instance.setImage(image, forKey: key)
item!.setThumbnailDataFromImage(image)
//CFRelease(newUniqueIDString) // Swift don't need manually call CFRelease anymore
//CFRelease(newUniqueID)
imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 40271271040f94dce2f28d4c3e2db478 | 35.548611 | 118 | 0.65666 | false | false | false | false |
cxy921126/Advanced | refs/heads/master | Advanced/Advanced/ViewController.swift | mit | 1 | //
// ViewController.swift
// Advanced
//
// Created by cxy on 16/4/23.
// Copyright © 2016年 cxy. All rights reserved.
//
import UIKit
import MBProgressHUD
class ViewController: UIViewController {
@IBOutlet weak var usernameTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var loginViewCons: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
showLoginView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
UIApplication.sharedApplication().statusBarStyle = .LightContent
}
@IBAction func loginClick(sender: AnyObject) {
// let userDic : [String:AnyObject] = ["username" : usernameTF.text ?? "", "password" : passwordTF.text ?? "", "id" : 1]
// let userAcc = UserAccount(dic: userDic)
// userAcc.saveAccount()
view.endEditing(true)
guard let userAccount = UserAccount.readAccount() else{
showErrorMessage()
return
}
if usernameTF.text == userAccount.username && passwordTF.text == userAccount.password {
let containerVC = storyboard?.instantiateViewControllerWithIdentifier("container") as! ContainerViewController
presentViewController(containerVC, animated: true, completion: nil)
}
else{
showErrorMessage()
}
}
func showErrorMessage(){
let hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud.mode = .Text
hud.labelText = "用户名或密码错误!"
hud.hide(true, afterDelay: 2)
}
func showProcessing(){
let hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud.mode = .DeterminateHorizontalBar
hud.labelText = "test for MBP"
hud.hide(true, afterDelay: 5)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
func showLoginView(){
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.init(rawValue: 0), animations: {
self.loginViewCons.constant = 100
self.view.layoutIfNeeded()
}, completion: nil)
}
}
| a20b1045aea572a586c898feff17b31e | 30.133333 | 127 | 0.629979 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.