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
lemonkey/iOS
refs/heads/master
WatchKit/_Apple/ListerforAppleWatchiOSandOSX/Swift/Lister WatchKit Extension/ListInterfaceController.swift
mit
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `ListInterfaceController` interface controller that presents a single list managed by a `ListPresenterType` object. */ import WatchKit import ListerKit /** The interface controller that presents a list. The interface controller listens for changes to how the list should be presented by the list presenter. */ class ListInterfaceController: WKInterfaceController, ListPresenterDelegate { // MARK: Types struct Storyboard { static let interfaceControllerName = "ListInterfaceController" struct RowTypes { static let item = "ListControllerItemRowType" static let noItems = "ListControllerNoItemsRowType" } } // MARK: Properties @IBOutlet weak var interfaceTable: WKInterfaceTable! var listDocument: ListDocument! var listPresenter: IncompleteListItemsPresenter! { return listDocument?.listPresenter as? IncompleteListItemsPresenter } // MARK: Interface Table Selection override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { let listItem = listPresenter.presentedListItems[rowIndex] listPresenter.toggleListItem(listItem) } // MARK: Actions @IBAction func markAllListItemsAsComplete() { listPresenter.updatePresentedListItemsToCompletionState(true) } @IBAction func markAllListItemsAsIncomplete() { listPresenter.updatePresentedListItemsToCompletionState(false) } func refreshAllData() { let listItemCount = listPresenter.count if listItemCount > 0 { interfaceTable.setNumberOfRows(listItemCount, withRowType: Storyboard.RowTypes.item) for idx in 0..<listItemCount { configureRowControllerAtIndex(idx) } } else { let indexSet = NSIndexSet(index: 0) interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems) } } // MARK: ListPresenterDelegate func listPresenterDidRefreshCompleteLayout(_: ListPresenterType) { refreshAllData() } func listPresenterWillChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { // `WKInterfaceTable` objects do not need to be notified of changes to the table, so this is a no op. } func listPresenter(_: ListPresenterType, didInsertListItem listItem: ListItem, atIndex index: Int) { let indexSet = NSIndexSet(index: index) // The list presenter was previously empty. Remove the "no items" row. if index == 0 && listPresenter!.count == 1 { interfaceTable.removeRowsAtIndexes(indexSet) } interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.item) } func listPresenter(_: ListPresenterType, didRemoveListItem listItem: ListItem, atIndex index: Int) { let indexSet = NSIndexSet(index: index) interfaceTable.removeRowsAtIndexes(indexSet) // The list presenter is now empty. Add the "no items" row. if index == 0 && listPresenter!.isEmpty { interfaceTable.insertRowsAtIndexes(indexSet, withRowType: Storyboard.RowTypes.noItems) } } func listPresenter(_: ListPresenterType, didUpdateListItem listItem: ListItem, atIndex index: Int) { configureRowControllerAtIndex(index) } func listPresenter(_: ListPresenterType, didMoveListItem listItem: ListItem, fromIndex: Int, toIndex: Int) { // Remove the item from the fromIndex straight away. let fromIndexSet = NSIndexSet(index: fromIndex) interfaceTable.removeRowsAtIndexes(fromIndexSet) /* Determine where to insert the moved item. If the `toIndex` was beyond the `fromIndex`, normalize its value. */ var toIndexSet: NSIndexSet if toIndex > fromIndex { toIndexSet = NSIndexSet(index: toIndex - 1) } else { toIndexSet = NSIndexSet(index: toIndex) } interfaceTable.insertRowsAtIndexes(toIndexSet, withRowType: Storyboard.RowTypes.item) } func listPresenter(_: ListPresenterType, didUpdateListColorWithColor color: List.Color) { for idx in 0..<listPresenter.count { configureRowControllerAtIndex(idx) } } func listPresenterDidChangeListLayout(_: ListPresenterType, isInitialLayout: Bool) { if isInitialLayout { // Display all of the list items on the first layout. refreshAllData() } else { /* The underlying document changed because of user interaction (this event only occurs if the list presenter's underlying list presentation changes based on user interaction). */ listDocument.updateChangeCount(.Done) } } // MARK: Convenience func setupInterfaceTable() { listDocument.listPresenter = IncompleteListItemsPresenter() listPresenter.delegate = self listDocument.openWithCompletionHandler { success in if !success { println("Couldn't open document: \(self.listDocument?.fileURL).") return } /* Once the document for the list has been found and opened, update the user activity with its URL path to enable the container iOS app to start directly in this list document. A URL path is passed instead of a URL because the `userInfo` dictionary of a WatchKit app's user activity does not allow NSURL values. */ let userInfo: [NSObject: AnyObject] = [ AppConfiguration.UserActivity.listURLPathUserInfoKey: self.listDocument.fileURL.path!, AppConfiguration.UserActivity.listColorUserInfoKey: self.listDocument.listPresenter!.color.rawValue ] /* Lister uses a specific user activity name registered in the Info.plist and defined as a constant to separate this action from the built-in UIDocument handoff support. */ self.updateUserActivity(AppConfiguration.UserActivity.watch, userInfo: userInfo, webpageURL: nil) } } func configureRowControllerAtIndex(index: Int) { let listItemRowController = interfaceTable.rowControllerAtIndex(index) as! ListItemRowController let listItem = listPresenter.presentedListItems[index] listItemRowController.setText(listItem.text) let textColor = listItem.isComplete ? UIColor.grayColor() : UIColor.whiteColor() listItemRowController.setTextColor(textColor) // Update the checkbox image. let state = listItem.isComplete ? "checked" : "unchecked" let imageName = "checkbox-\(listPresenter.color.name.lowercaseString)-\(state)" listItemRowController.setCheckBoxImageNamed(imageName) } // MARK: Interface Life Cycle override func awakeWithContext(context: AnyObject?) { precondition(context is ListInfo, "Expected class of `context` to be ListInfo.") let listInfo = context as! ListInfo listDocument = ListDocument(fileURL: listInfo.URL) // Set the title of the interface controller based on the list's name. setTitle(listInfo.name) // Fill the interface table with the current list items. setupInterfaceTable() } override func didDeactivate() { listDocument.closeWithCompletionHandler(nil) } }
c37b05e93ea6d37a802d1893e9b78d94
36.299065
123
0.648584
false
false
false
false
fqhuy/minimind
refs/heads/master
miniminds/GraphView.swift
mit
1
// // GraphView.swift // minimind // // Created by Phan Quoc Huy on 6/4/17. // Copyright © 2017 Phan Quoc Huy. All rights reserved. // import UIKit import minimind @IBDesignable class GraphView: Artist { override var x: [CGFloat] { get{ var xx: [CGFloat] = [] for item in items { xx.append(contentsOf: item.x) } return xx } set(val) { } } override var y: [CGFloat] { get{ var yy: [CGFloat] = [] for item in items { yy.append(contentsOf: item.y) } return yy } set(val) { } } private var items: [Artist] = [] { willSet(newItems) { for item in items { item.removeFromSuperview() } } didSet { addItems(items) } } public func addItems(_ artists: [Artist]) { for item in artists { item.center = self.convert(self.center, from: item) addSubview(item) } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { super.init(coder: coder) } public func plot(x: [CGFloat], y: [CGFloat], c: UIColor, s: CGFloat) -> Line2D { let line = Line2D(x: x, y: y, frame: self.bounds) line.edgeColor = c line.lineWidth = s self.items.append(line) return line } public func plotAnimation(x: [[CGFloat]], y: [[CGFloat]], c: UIColor, s: CGFloat) -> Line2D { let line = Line2D(x: x[0], y: y[0], frame: self.bounds) line.edgeColor = c line.lineWidth = s self.items.append(line) var i = 0 // line.transform = CGAffineTransform(scaleX: 0, y: 0) // UIView.animate(withDuration: 2.0, animations: { // line.transform = CGAffineTransform(scaleX: 1, y: 1) // } // ) UIView.animateKeyframes(withDuration: 5.0, delay: 0.5, animations: { // line.edgeColor = UIColor.white for i in [0, 1, 2] { UIView.addKeyframe(withRelativeStartTime: Double(i) * 0.3, relativeDuration: 0.3, animations: { line.x = x[i] line.y = y[i] } ) } }, completion: nil) return line } public func scatter(x: [CGFloat], y: [CGFloat], c: UIColor, s: CGFloat ) -> PathCollection { let coll = PathCollection(x: x, y: y, frame: self.bounds) //self.frame coll.edgeColor = c coll.markerSize = s self.items.append(coll) return coll } public func imshow(_ x: Matrix<Float>, _ interpolation: String = "nearest", _ cmap: String = "blues") -> Image2D { let im = Image2D(x, interpolation, cmap, self.bounds) self.items.append(im) return im } override func drawInternal(_ rect: CGRect) { let path = UIBezierPath() path.lineWidth = lineWidth path.move(to: CGPoint(x: 0.0, y: 0.0)) path.addLine(to: CGPoint(x: 0.0, y: frame.height)) path.move(to: CGPoint(x: 0.0, y: 0.0)) path.addLine(to: CGPoint(x: frame.width, y: 0.0)) path.stroke() } func autoScaleAll(_ keepRatio: Bool = true) { self.autoScale(keepRatio) for item in self.items { item.scale(xScale, yScale) } } }
ad8354f862e1737a616f3edf3ea2921e
26.052632
118
0.500278
false
false
false
false
chanhx/Octogit
refs/heads/master
iGithub/Views/Cell/CommitCell.swift
gpl-3.0
2
// // CommitCell.swift // iGithub // // Created by Chan Hocheung on 10/3/16. // Copyright © 2016 Hocheung. All rights reserved. // import Foundation class CommitCell: UITableViewCell { fileprivate let avatarView = UIImageView() fileprivate let titleLabel = UILabel() fileprivate let infoLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.configureSubviews() self.layout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureSubviews() { titleLabel.numberOfLines = 3 titleLabel.lineBreakMode = .byTruncatingTail titleLabel.font = .systemFont(ofSize: 16) titleLabel.textColor = UIColor(netHex: 0x333333) titleLabel.layer.masksToBounds = true titleLabel.layer.isOpaque = true titleLabel.backgroundColor = .white infoLabel.font = .systemFont(ofSize: 14) infoLabel.textColor = UIColor(netHex: 0x767676) infoLabel.numberOfLines = 0 infoLabel.lineBreakMode = .byWordWrapping infoLabel.layer.isOpaque = true infoLabel.backgroundColor = .white contentView.addSubviews([avatarView, titleLabel, infoLabel]) } func layout() { let margins = contentView.layoutMarginsGuide NSLayoutConstraint.activate([ avatarView.topAnchor.constraint(equalTo: margins.topAnchor), avatarView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 11), avatarView.heightAnchor.constraint(equalToConstant: 36), avatarView.widthAnchor.constraint(equalToConstant: 36), titleLabel.topAnchor.constraint(equalTo: avatarView.topAnchor), titleLabel.leadingAnchor.constraint(equalTo: avatarView.trailingAnchor, constant: 8), titleLabel.trailingAnchor.constraint(equalTo: margins.trailingAnchor), infoLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5), infoLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor), infoLabel.trailingAnchor.constraint(equalTo: titleLabel.trailingAnchor), infoLabel.bottomAnchor.constraint(equalTo: margins.bottomAnchor) ]) } var entity: Commit! { didSet { avatarView.setAvatar(with: entity.author?.avatarURL) titleLabel.text = entity.message?.replacingOccurrences(of: "\n\n", with: "\n") let author = entity.author?.login ?? entity.authorName infoLabel.text = "\(entity.shortSHA) by \(author!) \(entity.commitDate!.naturalString(withPreposition: true))" } } }
6b4c50e080fec127aca73c2ab153df60
37.171053
122
0.65736
false
false
false
false
CocOAuth/CocOAuth
refs/heads/master
CocOAuth/CwlMutex.swift
apache-2.0
1
// // CwlMutex.swift // CwlUtils // // Created by Matt Gallagher on 2015/02/03. // Copyright © 2015 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import Foundation /// A basic mutex protocol that requires nothing more than "performing work inside the mutex". public protocol ScopedMutex { /// Perform work inside the mutex func sync<R>(execute work: () throws -> R) rethrows -> R func trySync<R>(execute work: () throws -> R) rethrows -> R? } /// A more specific kind of mutex that assume an underlying primitive and unbalanced lock/trylock/unlock operators public protocol RawMutex: ScopedMutex { associatedtype MutexPrimitive /// The raw primitive is exposed as an "unsafe" public property for faster access in some cases var unsafeMutex: MutexPrimitive { get set } func unbalancedLock() func unbalancedTryLock() -> Bool func unbalancedUnlock() } extension RawMutex { public func sync<R>(execute work: () throws -> R) rethrows -> R { unbalancedLock() defer { unbalancedUnlock() } return try work() } public func trySync<R>(execute work: () throws -> R) rethrows -> R? { guard unbalancedTryLock() else { return nil } defer { unbalancedUnlock() } return try work() } } /// A basic wrapper around the "NORMAL" and "RECURSIVE" `pthread_mutex_t` (a safe, general purpose FIFO mutex). This type is a "class" type to take advantage of the "deinit" method and prevent accidental copying of the `pthread_mutex_t`. public final class PThreadMutex: RawMutex { public typealias MutexPrimitive = pthread_mutex_t // Non-recursive "PTHREAD_MUTEX_NORMAL" and recursive "PTHREAD_MUTEX_RECURSIVE" mutex types. public enum PThreadMutexType { case normal case recursive } public var unsafeMutex = pthread_mutex_t() /// Default constructs as ".Normal" or ".Recursive" on request. public init(type: PThreadMutexType = .normal) { var attr = pthread_mutexattr_t() guard pthread_mutexattr_init(&attr) == 0 else { preconditionFailure() } switch type { case .normal: pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL) case .recursive: pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) } guard pthread_mutex_init(&unsafeMutex, &attr) == 0 else { preconditionFailure() } } deinit { pthread_mutex_destroy(&unsafeMutex) } public func unbalancedLock() { pthread_mutex_lock(&unsafeMutex) } public func unbalancedTryLock() -> Bool { return pthread_mutex_trylock(&unsafeMutex) == 0 } public func unbalancedUnlock() { pthread_mutex_unlock(&unsafeMutex) } }
43d707e852ed06048ee25f210a262923
35.262626
237
0.671588
false
false
false
false
blinksh/blink
refs/heads/raw
Blink/Subscriptions/EntitlementsManager.swift
gpl-3.0
1
//////////////////////////////////////////////////////////////////////////////// // // B L I N K // // Copyright (C) 2016-2019 Blink Mobile Shell Project // // This file is part of Blink. // // Blink is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Blink is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Blink. If not, see <http://www.gnu.org/licenses/>. // // In addition, Blink is also subject to certain additional terms under // GNU GPL version 3 section 7. // // You should have received a copy of these additional terms immediately // following the terms and conditions of the GNU General Public License // which accompanied the Blink Source Code. If not, see // <http://www.github.com/blinksh/blink>. // //////////////////////////////////////////////////////////////////////////////// import Combine import Foundation import UIKit let UnlimitedScreenTimeEntitlementID = "unlimited_screen_time" let ProductBlinkShellPlusID = "blink_shell_plus_1y_1999" let ProductBlinkShellClassicID = "blink_shell_classic_unlimited_0" // Decoupled from RevCat Entitlement public struct Entitlement: Identifiable, Equatable, Hashable { public let id: String public var active: Bool public var unlockProductID: String? public static var inactiveUnlimitedScreenTime = Self(id: UnlimitedScreenTimeEntitlementID, active: false, unlockProductID: nil) } public protocol EntitlementsSourceDelegate: AnyObject { func didUpdateEntitlements( source: EntitlementsSource, entitlements :Dictionary<String, Entitlement>, activeSubscriptions: Set<String>, nonSubscriptionTransactions: Set<String> ) } public protocol EntitlementsSource: AnyObject { var delegate: EntitlementsSourceDelegate? { get set } func startUpdates() } public class EntitlementsManager: ObservableObject, EntitlementsSourceDelegate { public static let shared = EntitlementsManager([AppStoreEntitlementsSource()]) @Published var unlimitedTimeAccess: Entitlement = .inactiveUnlimitedScreenTime @Published var activeSubscriptions: Set<String> = .init() @Published var nonSubscriptionTransactions: Set<String> = .init() @Published var isUnknownState: Bool = true private let _sources: [EntitlementsSource] private init(_ sources: [EntitlementsSource]) { _sources = sources for s in sources { s.delegate = self } } public func startUpdates() { for s in _sources { s.startUpdates() } } public func didUpdateEntitlements( source: EntitlementsSource, entitlements: Dictionary<String, Entitlement>, activeSubscriptions: Set<String>, nonSubscriptionTransactions: Set<String> ) { defer { self.isUnknownState = false } // TODO: merge stategy from multiple sources self.activeSubscriptions = activeSubscriptions self.nonSubscriptionTransactions = nonSubscriptionTransactions let oldValue = self.unlimitedTimeAccess; if let newValue = entitlements[UnlimitedScreenTimeEntitlementID] { self.unlimitedTimeAccess = newValue } if isUnknownState { _updateSubscriptionNag() } else { if oldValue.active != self.unlimitedTimeAccess.active { _updateSubscriptionNag() } } } private func _updateSubscriptionNag() { if ProcessInfo().isMacCatalystApp || FeatureFlags.noSubscriptionNag { SubscriptionNag.shared.terminate() return } if self.unlimitedTimeAccess.active { SubscriptionNag.shared.terminate() } else { SubscriptionNag.shared.start() } } public func currentPlanName() -> String { if activeSubscriptions.contains(ProductBlinkShellPlusID) { return "Blink+ Plan" } if nonSubscriptionTransactions.contains(ProductBlinkShellClassicID) { return "Blink Classic Plan" } return "Free Plan" } }
2af27d2aa53cc928923a7d143421fe68
29.475177
129
0.701652
false
false
false
false
lukhnos/LuceneSearchDemo-iOS
refs/heads/master
LuceneSearchDemo/DetailsViewController.swift
mit
1
// // DetailsViewController.swift // LuceneSearchDemo // // Copyright (c) 2015 Lukhnos Liu. // // 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 class DetailsViewController : UIViewController { var document: Document! @IBOutlet var reviewTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() if document == nil { return } let text = NSMutableAttributedString() text.append(GetAttrString(document.highlightedTitle, 18)) text.append(NSAttributedString(string: "\n\n")) text.append(GetAttrString(document.info, 12)) text.append(NSAttributedString(string: "\n\n")) text.append(GetAttrString(document.highlightedReview, 14)) reviewTextView.attributedText = text reviewTextView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) // reviewTextView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: false) // reviewTextView.setContentOffset(CGPointZero, animated: false) reviewTextView.isScrollEnabled = false if let _ = document.source { let sourceButton = UIBarButtonItem(title: "Source", style: UIBarButtonItem.Style.plain, target: self, action: #selector(sourceAction)) navigationItem.rightBarButtonItem = sourceButton } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) reviewTextView.isScrollEnabled = true } @objc func sourceAction() { if let source = document.source { UIApplication.shared.open(source, options: [:], completionHandler: nil) } } }
0bb40d4bd72c980353dcc31d8e794eb1
38.695652
146
0.702081
false
false
false
false
aranasaurus/TKAnimatedCheckButton
refs/heads/master
TKAnimatedCheckButton/Classes/TKAnimatedCheckButton.swift
mit
2
// // TKAnimatedCheckButton.swift // TKAnimatedCheckButton // // Created by Takuya Okamoto on 2015/08/06. // Copyright (c) 2015年 Uniface. All rights reserved. // Inspired by //http://robb.is/working-on/a-hamburger-button-transition/ //https://dribbble.com/shots/1631598-On-Off import Foundation import CoreGraphics import QuartzCore import UIKit public class TKAnimatedCheckButton : UIButton { public var color = UIColor.whiteColor().CGColor { didSet { self.shape.strokeColor = color } } public var skeletonColor = UIColor.whiteColor().colorWithAlphaComponent(0.25).CGColor { didSet { circle.strokeColor = skeletonColor check.strokeColor = skeletonColor } } let path: CGPath = { let p = CGPathCreateMutable() CGPathMoveToPoint(p, nil, 5.07473346,20.2956615) CGPathAddCurveToPoint(p, nil, 3.1031115,24.4497281, 2,29.0960413, 2,34) CGPathAddCurveToPoint(p, nil, 2,51.673112, 16.326888,66, 34,66) CGPathAddCurveToPoint(p, nil, 51.673112,66, 66,51.673112, 66,34) CGPathAddCurveToPoint(p, nil, 66,16.326888, 51.673112,2, 34,2) CGPathAddCurveToPoint(p, nil, 21.3077047,2, 10.3412842,9.38934836, 5.16807419,20.1007094) CGPathAddLineToPoint(p, nil, 29.9939289,43.1625671) CGPathAddLineToPoint(p, nil, 56.7161293,17.3530369) return p }() let pathSize:CGFloat = 70 let circleStrokeStart: CGFloat = 0.0 let circleStrokeEnd: CGFloat = 0.738 let checkStrokeStart: CGFloat = 0.8 let checkStrokeEnd: CGFloat = 0.97 var shape: CAShapeLayer! = CAShapeLayer() var circle: CAShapeLayer! = CAShapeLayer() var check: CAShapeLayer! = CAShapeLayer() let lineWidth:CGFloat = 4 let lineWidthBold:CGFloat = 5 public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) let defaultPoint = self.frame.origin var size = frame.width if frame.width < frame.height { size = frame.height } let scale:CGFloat = size / pathSize self.frame.size = CGSize(width: pathSize, height: pathSize) self.shape.path = path self.circle.path = path self.check.path = path self.shape.strokeColor = color self.circle.strokeColor = skeletonColor self.check.strokeColor = skeletonColor self.shape.position = CGPointMake(pathSize/2, pathSize/2) self.circle.position = self.shape.position self.check.position = self.shape.position self.shape.strokeStart = circleStrokeStart self.shape.strokeEnd = circleStrokeEnd self.circle.strokeStart = circleStrokeStart self.circle.strokeEnd = circleStrokeEnd self.check.strokeStart = checkStrokeStart self.check.strokeEnd = checkStrokeEnd shape.lineWidth = lineWidth circle.lineWidth = lineWidth check.lineWidth = lineWidthBold for layer in [ circle, check, self.shape ] { layer.fillColor = nil layer.miterLimit = 4 layer.lineCap = kCALineCapRound layer.masksToBounds = true let strokingPath:CGPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 4, kCGLineCapRound, kCGLineJoinMiter, 4) layer.bounds = CGPathGetPathBoundingBox(strokingPath) layer.actions = [ "strokeStart": NSNull(), "strokeEnd": NSNull(), "transform": NSNull() ] self.layer.transform = CATransform3DMakeScale(scale, scale, 1); self.layer.addSublayer(layer) } self.frame.origin = defaultPoint } let timingFunc = CAMediaTimingFunction(controlPoints: 0.44,-0.04,0.64,1.4)//0.69,0.12,0.23,1.27) let backFunc = CAMediaTimingFunction(controlPoints: 0.45,-0.36,0.44,0.92) public var checked: Bool = false { didSet { let strokeStart = CABasicAnimation(keyPath: "strokeStart") let strokeEnd = CABasicAnimation(keyPath: "strokeEnd") let lineWidthAnim = CABasicAnimation(keyPath: "lineWidth") if self.checked { strokeStart.toValue = checkStrokeStart strokeStart.duration = 0.3//0.5 strokeStart.timingFunction = timingFunc strokeEnd.toValue = checkStrokeEnd strokeEnd.duration = 0.3//0.6 strokeEnd.timingFunction = timingFunc lineWidthAnim.toValue = lineWidthBold lineWidthAnim.beginTime = 0.2 lineWidthAnim.duration = 0.1 lineWidthAnim.timingFunction = timingFunc } else { strokeStart.toValue = circleStrokeStart strokeStart.duration = 0.2//0.5 strokeStart.timingFunction = backFunc//CAMediaTimingFunction(controlPoints: 0.25, 0, 0.5, 1.2) // strokeStart.beginTime = CACurrentMediaTime() + 0.1 strokeStart.fillMode = kCAFillModeBackwards strokeEnd.toValue = circleStrokeEnd strokeEnd.duration = 0.3//0.6 strokeEnd.timingFunction = backFunc//CAMediaTimingFunction(controlPoints: 0.25, 0.3, 0.5, 0.9) lineWidthAnim.toValue = lineWidth lineWidthAnim.duration = 0.1 lineWidthAnim.timingFunction = backFunc } self.shape.ocb_applyAnimation(strokeStart) self.shape.ocb_applyAnimation(strokeEnd) self.shape.ocb_applyAnimation(lineWidthAnim) } } } extension CALayer { func ocb_applyAnimation(animation: CABasicAnimation) { let copy = animation.copy() as! CABasicAnimation if copy.fromValue == nil { copy.fromValue = self.presentationLayer().valueForKeyPath(copy.keyPath) } self.addAnimation(copy, forKey: copy.keyPath) self.setValue(copy.toValue, forKeyPath:copy.keyPath) } }
7987238a64093f4b0ff75d870b926c6c
34.872832
126
0.62069
false
false
false
false
mathcamp/Carlos
refs/heads/master
Sample/ComplexCacheSampleViewController.swift
mit
1
import Foundation import UIKit import Carlos import PiedPiper struct ModelDomain { let name: String let identifier: Int let URL: NSURL } enum IgnoreError: ErrorType { case Ignore } class CustomCacheLevel: Fetcher { typealias KeyType = Int typealias OutputType = String func get(key: KeyType) -> Future<OutputType> { let request = Promise<OutputType>() if key > 0 { Logger.log("Fetched \(key) on the custom cache", .Info) request.succeed("\(key)") } else { Logger.log("Failed fetching \(key) on the custom cache", .Info) request.fail(IgnoreError.Ignore) } return request.future } } class ComplexCacheSampleViewController: BaseCacheViewController { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var identifierField: UITextField! @IBOutlet weak var urlField: UITextField! private var cache: BasicCache<ModelDomain, NSData>! override func titleForScreen() -> String { return "Complex cache" } override func setupCache() { super.setupCache() let modelDomainToString = OneWayTransformationBox<ModelDomain, String>(transform: { Future($0.name) }) let modelDomainToInt = OneWayTransformationBox<ModelDomain, Int>(transform: { Future($0.identifier) }) let stringToData = StringTransformer().invert() let uppercaseTransformer = OneWayTransformationBox<String, String>(transform: { Future($0.uppercaseString) }) cache = ((modelDomainToString =>> (MemoryCacheLevel() >>> DiskCacheLevel())) >>> (modelDomainToInt =>> (CustomCacheLevel() ~>> uppercaseTransformer) =>> stringToData) >>> BasicFetcher(getClosure: { (key: ModelDomain) in let request = Promise<NSData>() Logger.log("Fetched \(key.name) on the fetcher closure", .Info) request.succeed("Last level was hit!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) return request.future })).dispatch(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) } override func fetchRequested() { super.fetchRequested() let key = ModelDomain(name: nameField.text ?? "", identifier: Int(identifierField.text ?? "") ?? 0, URL: NSURL(string: urlField.text ?? "")!) cache.get(key) for field in [nameField, identifierField, urlField] { field.resignFirstResponder() } } }
f67a0dfe41f22885639e8ff8e918e507
28
223
0.67872
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKitUI/Views/Settings Editors/InsulinModelChartView.swift
mit
1
// // InsulinModelChartView.swift // LoopKitUI // // Created by Michael Pangburn on 7/15/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI import HealthKit import LoopKit struct InsulinModelChartView: UIViewRepresentable { let chartManager: ChartsManager var glucoseUnit: HKUnit var selectedInsulinModelValues: [GlucoseValue] var unselectedInsulinModelValues: [[GlucoseValue]] var glucoseDisplayRange: ClosedRange<HKQuantity> func makeUIView(context: Context) -> ChartContainerView { let view = ChartContainerView() view.chartGenerator = { [chartManager] frame in chartManager.chart(atIndex: 0, frame: frame)?.view } return view } func updateUIView(_ chartContainerView: ChartContainerView, context: Context) { chartManager.invalidateChart(atIndex: 0) insulinModelChart.glucoseUnit = glucoseUnit insulinModelChart.setSelectedInsulinModelValues(selectedInsulinModelValues) insulinModelChart.setUnselectedInsulinModelValues(unselectedInsulinModelValues) insulinModelChart.glucoseDisplayRange = glucoseDisplayRange chartManager.prerender() chartContainerView.reloadChart() } private var insulinModelChart: InsulinModelChart { guard chartManager.charts.count == 1, let insulinModelChart = chartManager.charts.first as? InsulinModelChart else { fatalError("Expected exactly one insulin model chart in ChartsManager") } return insulinModelChart } }
0371fb03f84de55a6b15332a0a5f53f9
33
124
0.731458
false
false
false
false
wordpress-mobile/WordPress-iOS
refs/heads/trunk
WordPress/WordPressTest/GravatarServiceTests.swift
gpl-2.0
1
import Foundation import XCTest import WordPressKit @testable import WordPress /// GravatarService Unit Tests /// class GravatarServiceTests: CoreDataTestCase { class GravatarServiceRemoteMock: GravatarServiceRemote { var capturedAccountToken: String = "" var capturedAccountEmail: String = "" override func uploadImage(_ image: UIImage, accountEmail: String, accountToken: String, completion: ((NSError?) -> ())?) { capturedAccountEmail = accountEmail capturedAccountToken = accountToken if let completion = completion { completion(nil) } } } class GravatarServiceTester: GravatarService { var gravatarServiceRemoteMock: GravatarServiceRemoteMock? override func gravatarServiceRemote() -> GravatarServiceRemote { gravatarServiceRemoteMock = GravatarServiceRemoteMock() return gravatarServiceRemoteMock! } } func testServiceSanitizesEmailAddressCapitals() { let account = createTestAccount(username: "some", token: "1234", emailAddress: "[email protected]") let gravatarService = GravatarServiceTester() gravatarService.uploadImage(UIImage(), forAccount: account) XCTAssertEqual("[email protected]", gravatarService.gravatarServiceRemoteMock!.capturedAccountEmail) } func testServiceSanitizesEmailAddressTrimsSpaces() { let account = createTestAccount(username: "some", token: "1234", emailAddress: " [email protected] ") let gravatarService = GravatarServiceTester() gravatarService.uploadImage(UIImage(), forAccount: account) XCTAssertEqual("[email protected]", gravatarService.gravatarServiceRemoteMock!.capturedAccountEmail) } private func createTestAccount(username: String, token: String, emailAddress: String) -> WPAccount { let mainContext = contextManager.mainContext let accountService = AccountService(managedObjectContext: mainContext) let defaultAccount = accountService.createOrUpdateAccount(withUsername: username, authToken: token) defaultAccount.email = emailAddress contextManager.saveContextAndWait(mainContext) accountService.setDefaultWordPressComAccount(defaultAccount) XCTAssertNotNil(try WPAccount.lookupDefaultWordPressComAccount(in: mainContext)) return defaultAccount } }
6938a3ae0581bfff9432ebc97c45cc95
36.476923
130
0.721264
false
true
false
false
crepashok/The-Complete-Watch-OS2-Developer-Course
refs/heads/master
Section-3/Flip a coin/Flip a coin WatchKit Extension/InterfaceController.swift
gpl-3.0
1
// // InterfaceController.swift // Flip a coin WatchKit Extension // // Created by Pavlo Cretsu on 4/15/16. // Copyright © 2016 Pasha Cretsu. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var btnFlip: WKInterfaceButton! var coinFlipHeads : Bool = true let coinHead : String = "1.png" let coinTail : String = "2.png" override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } @IBAction func btnFlipAction() { flipTheCoin() } func flipTheCoin() { btnFlip.setBackgroundImageNamed(coinFlipHeads == false ? coinHead : coinTail) coinFlipHeads = !coinFlipHeads } }
b993459f175ba12cf71efc622b5ea72d
17.388889
85
0.595166
false
false
false
false
aiwalle/LiveProject
refs/heads/master
LiveProject/CommonViews/LJPageView/LJPageStyle.swift
mit
1
// // LJPageStyle.swift // LiveProject // // Created by liang on 2017/7/25. // Copyright © 2017年 liang. All rights reserved. // import UIKit struct LJPageStyle { var titleHeight : CGFloat = 44 var normalColor : UIColor = .black var selectColor : UIColor = .red var titleFont : UIFont = UIFont.systemFont(ofSize: 14.0) var isScrollEnable: Bool = false var titleMargin : CGFloat = 20.0 var isShowBottomLine: Bool = false var bottomLineColor : UIColor = .red var bottomLineHeight : CGFloat = 2.0 var isNeedScale : Bool = false var maxScale : CGFloat = 1.2 var titleBgColor : UIColor = .clear var coverViewColor : UIColor = .black var coverViewAlpha : CGFloat = 0.3 var isShowCoverView : Bool = false var coverViewHeight : CGFloat = 25 var coverViewRadius : CGFloat = 12 var coverViewMargin : CGFloat = 8 // 这里应该添加一个功能是根据传入titles的整体长度来判断是否滚动,而不是让用户来设置 }
a68cc6fae30f2cb5ef08964b7904f72f
26.852941
60
0.673706
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
Example/Pods/RxSwift/RxSwift/Observables/Sample.swift
apache-2.0
6
// // Sample.swift // RxSwift // // Created by Krunoslav Zaher on 5/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Samples the source observable sequence using a sampler observable sequence producing sampling ticks. Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. **In case there were no new elements between sampler ticks, no element is sent to the resulting sequence.** - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) - parameter sampler: Sampling tick sequence. - returns: Sampled observable sequence. */ public func sample<Source: ObservableType>(_ sampler: Source) -> Observable<Element> { return Sample(source: self.asObservable(), sampler: sampler.asObservable()) } } final private class SamplerSink<Observer: ObserverType, SampleType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = SampleType typealias Parent = SampleSequenceSink<Observer, SampleType> private let _parent: Parent var _lock: RecursiveLock { return self._parent._lock } init(parent: Parent) { self._parent = parent } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next, .completed: if let element = _parent._element { self._parent._element = nil self._parent.forwardOn(.next(element)) } if self._parent._atEnd { self._parent.forwardOn(.completed) self._parent.dispose() } case .error(let e): self._parent.forwardOn(.error(e)) self._parent.dispose() } } } final private class SampleSequenceSink<Observer: ObserverType, SampleType> : Sink<Observer> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = Observer.Element typealias Parent = Sample<Element, SampleType> private let _parent: Parent let _lock = RecursiveLock() // state fileprivate var _element = nil as Element? fileprivate var _atEnd = false private let _sourceSubscription = SingleAssignmentDisposable() init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { self._sourceSubscription.setDisposable(self._parent._source.subscribe(self)) let samplerSubscription = self._parent._sampler.subscribe(SamplerSink(parent: self)) return Disposables.create(_sourceSubscription, samplerSubscription) } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func _synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): self._element = element case .error: self.forwardOn(event) self.dispose() case .completed: self._atEnd = true self._sourceSubscription.dispose() } } } final private class Sample<Element, SampleType>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _sampler: Observable<SampleType> init(source: Observable<Element>, sampler: Observable<SampleType>) { self._source = source self._sampler = sampler } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
3b322a961e031dac50efee6a30ee70c7
29.676692
171
0.63799
false
false
false
false
thewisecity/declarehome-ios
refs/heads/master
CookedApp/TableViewControllers/AlertCategoriesTableViewController.swift
gpl-3.0
1
// // AlertCategoriesTableViewController.swift // CookedApp // // Created by Dexter Lohnes on 10/20/15. // Copyright © 2015 The Wise City. All rights reserved. // import UIKit class AlertCategoriesTableViewController: PFQueryTableViewController { var delegate: AlertCategoriesTableViewDelegate? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.paginationEnabled = true self.objectsPerPage = 25 } init() { super.init(style: .Plain, className: AlertCategory.className) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func queryForTable() -> PFQuery { let query = PFQuery(className: self.parseClassName!) // query.orderByDescending("createdAt") return query } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? { let cellIdentifier = "CategoryCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? AlertCategoryCell if cell == nil { cell = AlertCategoryCell(style: .Default, reuseIdentifier: cellIdentifier) } return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let category = objectAtIndexPath(indexPath) as? AlertCategory { // cell?.textLabel?.text = category.description if let theCell = cell as? AlertCategoryCell { theCell.category = category } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedCategory = objectAtIndexPath(indexPath) as? AlertCategory delegate?.chooseAlertCategory(selectedCategory) } // 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?) { super.prepareForSegue(segue, sender: sender) // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. // if let selectedGroup = sender as? Group{ // if let destinationController = segue.destinationViewController as? GroupDetailsViewController { // destinationController.group = selectedGroup // } // } } }
a85717ee2bee9b3c4d17868d14c513ee
33.047619
138
0.646853
false
false
false
false
motoom/ios-apps
refs/heads/master
TeVoet/TeVoet/Persistence.swift
mit
1
// Persistence.swift import UIKit import CoreLocation func filenametimestamp(locations: [CLLocation]) -> String { let yyyymmddhhmm = NSDateFormatter() yyyymmddhhmm.dateFormat = "yyyyMMddHHmm" return yyyymmddhhmm.stringFromDate(locations[0].timestamp) } func saveWaypoints(locations: [CLLocation]) { // Filename voor save bepalen let tijdstamp = filenametimestamp(locations) let filenaam = "\(tijdstamp).v1.locations" // v1 = versie file format let fullfilenaam = docdirfilenaam(filenaam) // Saven. TODO: Saven als dict met keys "meta" met pedometerdata, afgelegde afstand, en "locations", en opname kwaliteit (nearest10m, best, bestfornavigation en reporting distance). Meta ook exporteren naar CSV. NSKeyedArchiver.archivedDataWithRootObject(locations).writeToFile(fullfilenaam, atomically: true) } func loadWaypoints(filename: String) -> [CLLocation]? { return NSKeyedUnarchiver.unarchiveObjectWithFile(docdirfilenaam(filename)) as? [CLLocation] } func saveWaypointsCSV(locations: [CLLocation]) { let tijdstamp = filenametimestamp(locations) let filenaam = "\(tijdstamp).csv" let fullfilenaam = docdirfilenaam(filenaam) // CSV header var csv = "\"unix timestamp\", \"datetime\", \"latitude\", \"longitude\", \"horizontal accuracy\", \"altitude\", \"vertical accuracy\", \"distance\", \"cumulative distance\"\n" var cumulDistance: Double = 0, delta: Double = 0 var prevLocation: CLLocation? for location in locations { // Calculate distance and cumulative distance if prevLocation == nil { prevLocation = location } else { delta = location.distanceFromLocation(prevLocation!) cumulDistance += delta prevLocation = location } // Format for output. let regel = "\(location.timestamp.timeIntervalSince1970), \"\(location.timestamp)\", \(location.coordinate.latitude), \(location.coordinate.longitude), \(location.horizontalAccuracy), \(location.altitude), \(location.verticalAccuracy), \(delta), \(cumulDistance)\n" csv += regel } do { try csv.writeToFile(fullfilenaam, atomically: true, encoding: NSUTF8StringEncoding) } catch { let err = error as NSError print(err.localizedDescription) } }
6c42aa6f1a1c3d4f67970b3c21ad3e04
37.852459
273
0.681857
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
MinimedKit/PumpEvents/ChangeTimeFormatPumpEvent.swift
mit
1
// // ChangeTimeFormatPumpEvent.swift // RileyLink // // Created by Pete Schwamb on 3/8/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct ChangeTimeFormatPumpEvent: TimestampedPumpEvent { public let length: Int public let rawData: Data public let timestamp: DateComponents public let timeFormat: String public init?(availableData: Data, pumpModel: PumpModel) { length = 7 guard length <= availableData.count else { return nil } rawData = availableData.subdata(in: 0..<length) timestamp = DateComponents(pumpEventData: availableData, offset: 2) func d(_ idx: Int) -> Int { return Int(availableData[idx]) } timeFormat = d(1) == 1 ? "24hr" : "am_pm" } public var dictionaryRepresentation: [String: Any] { return [ "_type": "ChangeTimeFormat", "timeFormat": timeFormat, ] } }
e987a71764acbf11bfc25f17ec8a6b33
23.804878
75
0.597837
false
false
false
false
jakubknejzlik/ChipmunkSwiftWrapper
refs/heads/master
Pod/Classes/ChipmunkConstraint.swift
mit
1
// // ChipmunkConstraint.swift // chipmunk-swift-wrapper // // Created by Jakub Knejzlik on 16/11/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Foundation public class ChipmunkConstraint: ChipmunkSpaceObject { public let bodyA: ChipmunkBody public let bodyB: ChipmunkBody public let constraint: UnsafeMutablePointer<cpConstraint> override var space: ChipmunkSpace? { willSet { if let space = self.space { cpSpaceRemoveConstraint(space.space, self.constraint) } } didSet { if let space = self.space { cpSpaceAddConstraint(space.space, self.constraint) } } } public init(bodyA: ChipmunkBody, bodyB: ChipmunkBody, constraint: UnsafeMutablePointer<cpConstraint>) { self.bodyA = bodyA self.bodyB = bodyB self.constraint = constraint super.init() } }
4e2255d5623ad31ffdd2b6d7314ad3b8
25.027027
107
0.620582
false
false
false
false
yogeshbh/SimpleLogger
refs/heads/master
SimpleLogger/Logger/YBLogger.swift
apache-2.0
1
// // YBLogger.swift // SimpleLogger // // Created by Yogesh Bhople on 10/07/17. // Copyright © 2017 Yogesh Bhople. All rights reserved. // import Foundation protocol YBLoggerConfiguration { func allowToPrint() -> Bool func allowToLogWrite() -> Bool func addTimeStamp() -> Bool func addFileName() -> Bool func addFunctionName() -> Bool func addLineNumber() -> Bool } extension YBLoggerConfiguration { func addTimeStamp() -> Bool {return false} func addFileName() -> Bool {return false} func addFunctionName() -> Bool {return true} func addLineNumber() -> Bool {return true} } public enum YBLogger : YBLoggerConfiguration { case DEBUG,INFO,ERROR,EXCEPTION,WARNING fileprivate func symbolString() -> String { var messgeString = "" switch self { case .DEBUG: messgeString = "\u{0001F539} " case .INFO: messgeString = "\u{0001F538} " case .ERROR: messgeString = "\u{0001F6AB} " case .EXCEPTION: messgeString = "\u{2757}\u{FE0F} " case .WARNING: messgeString = "\u{26A0}\u{FE0F} " } var logLevelString = "\(self)" for _ in 0 ..< (10 - logLevelString.count) { logLevelString.append(" ") } messgeString = messgeString + logLevelString + "➯ " return messgeString } } public func print(_ message: Any...,logLevel:YBLogger,_ callingFunctionName: String = #function,_ lineNumber: UInt = #line,_ fileName:String = #file) { let messageString = message.map({"\($0)"}).joined(separator: " ") var fullMessageString = logLevel.symbolString() if logLevel.addTimeStamp() { fullMessageString = fullMessageString + Date().formattedISO8601 + " ⇨ " } if logLevel.addFileName() { let fileName = URL(fileURLWithPath: fileName).deletingPathExtension().lastPathComponent fullMessageString = fullMessageString + fileName + " ⇨ " } if logLevel.addFunctionName() { fullMessageString = fullMessageString + callingFunctionName if logLevel.addLineNumber() { fullMessageString = fullMessageString + " : \(lineNumber)" + " ⇨ " } else { fullMessageString = fullMessageString + " ⇨ " } } fullMessageString = fullMessageString + messageString if logLevel.allowToPrint() { print(fullMessageString) } if logLevel.allowToLogWrite() { var a = YBFileLogger.default print(fullMessageString,to:&a) } } extension Foundation.Date { /* Reference : http://stackoverflow.com/questions/28016578/ //swift-how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-tim */ struct Date { static let formatterISO8601: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX" return formatter }() static let formatteryyyyMMdd: DateFormatter = { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyyMMdd" return formatter }() } var formattedISO8601: String { return Date.formatterISO8601.string(from: self) } var currentDate: String { return Date.formatteryyyyMMdd.string(from: self) } }
c90c0fcf8daef722faa4db54813c73c3
33.072072
151
0.622686
false
false
false
false
JarlRyan/IOSNote
refs/heads/master
Swift/Hello/Hello/ViewController.swift
apache-2.0
1
// // ViewController.swift // Hello // // Created by bingoogol on 14-6-4. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet var qqTextField : UITextField @IBOutlet var pwdTextField : UITextField @IBOutlet var number1 : UITextField @IBOutlet var number2 : UITextField @IBOutlet var result : UILabel override func viewDidLoad() { super.viewDidLoad() addButton() } func addButton() { let button:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton button.frame = CGRect(origin:CGPoint(x:150,y:450), size:CGSize(width: 100,height: 40)) button.setTitle("别摸我", forState: UIControlState.Normal) button.setTitleColor(UIColor.greenColor(), forState: UIControlState.Normal) // 如果有参数,则在后面加一个冒号 button.addTarget(self, action: Selector("tabButton:"), forControlEvents : UIControlEvents.TouchUpInside) view.addSubview(button) } func tabButton(button:UIButton) { println("我被摸了\(button.titleForState(UIControlState.Normal))") } func textFieldShouldReturn(textField: UITextField!) -> Bool { // 要执行此代理方法,需要在Storybord中,将文本框的代理设置给controller if textField == qqTextField { // 当用户在qq号输入框获取焦点时按下回车按钮,光标切换到密码框 pwdTextField.becomeFirstResponder() } else if textField == pwdTextField { // 当用户在密码框获取焦点时按下回车按钮,执行登陆操作 login() } return true; } @IBAction func login() { let qq = qqTextField.text let pwd = pwdTextField.text view.endEditing(true) println("点击了登陆按钮,qq=\(qq),密码=\(pwd)") } @IBAction func calculator() { if let num1 = number1.text.toInt() { if let num2 = number2.text.toInt() { result.text = "\(num1 + num2)" // number2.resignFirstResponder() view.endEditing(true) } else { println("number2 Couldn't convert to a number") } } else { println("number1 Couldn't convert to a number") } } @IBAction func indexChange(sender : UISegmentedControl) { println(sender.selectedSegmentIndex) } }
6781309d54ce242289eb4b1bff5dbb5a
27.493976
112
0.607611
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Core/PaymentMethods/Link Bank Flow/Yodlee Screen/YodleeScreenViewController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import RIBs import RxCocoa import RxSwift import UIKit import WebKit final class YodleeScreenViewController: BaseScreenViewController, YodleeScreenPresentable, YodleeScreenViewControllable { private let disposeBag = DisposeBag() private let closeTriggerred = PublishSubject<Bool>() private let backTriggerred = PublishSubject<Void>() private let webview: WKWebView private let pendingView: YodleePendingView init(webConfiguration: WKWebViewConfiguration) { webview = WKWebView(frame: .zero, configuration: webConfiguration) pendingView = YodleePendingView() super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // so that we'll be able to listen for system dismissal methods navigationController?.presentationController?.delegate = self setupUI() } override func navigationBarTrailingButtonPressed() { closeTriggerred.onNext(false) } override func navigationBarLeadingButtonPressed() { backTriggerred.onNext(()) } // MARK: - YodleeScreenPresentable func connect(action: Driver<YodleeScreen.Action>) -> Driver<YodleeScreen.Effect> { let requestAction = action .compactMap(\.request) let contentAction = action .compactMap(\.content) .distinctUntilChanged() requestAction .drive(weak: self) { (self, request) in self.webview.load(request) } .disposed(by: disposeBag) contentAction .drive(pendingView.rx.content) .disposed(by: disposeBag) contentAction .drive(weak: self) { (self, _) in self.toggle(visibility: true, of: self.pendingView) self.toggle(visibility: false, of: self.webview) } .disposed(by: disposeBag) webview.rx.observeWeakly(Bool.self, "loading", options: [.new]) .compactMap { $0 } .observe(on: MainScheduler.asyncInstance) .subscribe(onNext: { [weak self] loading in guard let self = self else { return } self.toggle(visibility: loading, of: self.pendingView) self.toggle(visibility: !loading, of: self.webview) }) .disposed(by: disposeBag) let closeTapped = closeTriggerred .map { isInteractive in YodleeScreen.Effect.closeFlow(isInteractive) } .asDriverCatchError() let backTapped = backTriggerred .map { _ in YodleeScreen.Effect.back } .asDriverCatchError() let linkTapped = contentAction .flatMap { content -> Driver<TitledLink> in content.subtitleLinkTap .asDriver(onErrorDriveWith: .empty()) } .map { link -> YodleeScreen.Effect in .link(url: link.url) } return .merge(closeTapped, backTapped, linkTapped) } // MARK: - Private private func setupUI() { titleViewStyle = .text(value: LocalizationConstants.SimpleBuy.YodleeWebScreen.title) set( barStyle: .darkContent(), leadingButtonStyle: .back, trailingButtonStyle: .close ) view.addSubview(webview) view.addSubview(pendingView) webview.layoutToSuperview(axis: .vertical) webview.layoutToSuperview(axis: .horizontal) pendingView.layoutToSuperview(.top) pendingView.layoutToSuperview(.leading) pendingView.layoutToSuperview(.trailing) pendingView.layoutToSuperview(.bottom) } private func toggle(visibility: Bool, of view: UIView) { let alpha: CGFloat = visibility ? 1.0 : 0.0 let hidden = !visibility UIView.animate( withDuration: 0.2, animations: { view.alpha = alpha }, completion: { _ in view.isHidden = hidden } ) } } extension YodleeScreenViewController: UIAdaptivePresentationControllerDelegate { /// Called when a pull-down dismissal happens func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { closeTriggerred.onNext(true) } }
d0dd7d4dc9cc35e985f6af4756938d2d
30.162162
95
0.620121
false
false
false
false
soniccat/GAPageViewController
refs/heads/master
GAPagerViewController/PagerController/GAPagerCell.swift
mit
1
// // PagerCell.swift // CollectionPager // // Created by Alexey Glushkov on 19.02.17. // Copyright © 2017 Alexey Glushkov. All rights reserved. // import UIKit open class GAPagerCell: UICollectionViewCell { open var controller: UIViewController? private var isDisappearing = false override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func prepareForReuse() { super.prepareForReuse() if let ctrl = self.controller { gaLog("prepareForReuse %p", ctrl) } } open func startAddingController(ct: UIViewController, animated: Bool) { controller = ct prepareController(controller: ct) if needPassAppearEvents() { ct.beginAppearanceTransition(true, animated: animated) isDisappearing = false } addSubview(ct.view) } private func prepareController(controller: UIViewController) { controller.view.frame = self.bounds controller.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] controller.view.translatesAutoresizingMaskIntoConstraints = true } open func finishAddingController() { if needPassAppearEvents() { self.controller!.endAppearanceTransition() } } open func startRemovingController(animated: Bool) { // We use isDisappearing flag to handle a situation when we swipe long in a one direction // and then swipe long in another direction while the scrollView is decelerating // If we start with page 0 after the first swipe we will get willDisappear for the page 1 to start showing page 2 // and after the the second swipe we will get willDisappear again for the page 1 to start showing page 2 // When we call more than one beginAppearanceTransition with false isAppearing in a row we have to call // the same amount of endAppearanceTransition to trigger viewDidDisappear // Here we avoid that possible double call of beginAppearanceTransition with false isAppearing if needPassAppearEvents() && !isDisappearing { self.controller!.beginAppearanceTransition(false, animated: animated) isDisappearing = true } } open func finishRemovingController() { self.controller!.view.removeFromSuperview() let v: Int = needPassAppearEvents() ? 1 : 0 gaLog("finishRemovingController %d", v) if needPassAppearEvents() { self.controller!.endAppearanceTransition() isDisappearing = false } self.controller?.removeFromParentViewController() self.controller = nil } private func needPassAppearEvents() -> Bool { return self.window != nil && self.superview != nil } }
e8243a97253ffd326f6e76e3a20ab16f
33.298851
121
0.649799
false
false
false
false
reactive-swift/Future
refs/heads/master
Sources/Future/Error.swift
apache-2.0
2
//===--- Error.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Boilerplate public enum FutureError : Error { case AlreadyCompleted case MappedNil case FilteredOut } internal func anyError(_ e:Error) -> AnyError { switch e { case let error as AnyError: return error default: return AnyError(e) } }
9d5b0da9c68bbcbbf28273bf128de09b
30.176471
80
0.625472
false
false
false
false
dnfodjo/DJI_TensaFlow_Swift
refs/heads/master
ARAJOY/FPVViewController.swift
apache-2.0
1
// // FPVViewController.swift // ARAJOY // // Created by Daniel Nfodjo on 6/30/17. // Copyright © 2017 Daniel Nfodjo. All rights reserved. // import UIKit import DJISDK import VideoPreviewer class FPVViewController: UIViewController, DJIVideoFeedListener, DJISDKManagerDelegate, DJICameraDelegate { var isRecording : Bool! @IBOutlet var recordTimeLabel: UILabel! @IBOutlet var captureButton: UIButton! @IBOutlet var recordButton: UIButton! @IBOutlet var workModeSegmentControl: UISegmentedControl! @IBOutlet var fpvView: UIView! override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let camera = self.fetchCamera() if((camera != nil) && (camera?.delegate?.isEqual(self))!){ camera?.delegate = nil } self.resetVideoPreview() } override func viewDidLoad() { super.viewDidLoad() DJISDKManager.registerApp(with: self) recordTimeLabel.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setupVideoPreviewer() { VideoPreviewer.instance().setView(self.fpvView) let product = DJISDKManager.product(); //Use "SecondaryVideoFeed" if the DJI Product is A3, N3, Matrice 600, or Matrice 600 Pro, otherwise, use "primaryVideoFeed". if ((product?.model == DJIAircraftModelNameA3) || (product?.model == DJIAircraftModelNameN3) || (product?.model == DJIAircraftModelNameMatrice600) || (product?.model == DJIAircraftModelNameMatrice600Pro)){ DJISDKManager.videoFeeder()?.secondaryVideoFeed.add(self, with: nil) }else{ DJISDKManager.videoFeeder()?.primaryVideoFeed.add(self, with: nil) } VideoPreviewer.instance().start() } func resetVideoPreview() { VideoPreviewer.instance().unSetView() let product = DJISDKManager.product(); //Use "SecondaryVideoFeed" if the DJI Product is A3, N3, Matrice 600, or Matrice 600 Pro, otherwise, use "primaryVideoFeed". if ((product?.model == DJIAircraftModelNameA3) || (product?.model == DJIAircraftModelNameN3) || (product?.model == DJIAircraftModelNameMatrice600) || (product?.model == DJIAircraftModelNameMatrice600Pro)){ DJISDKManager.videoFeeder()?.secondaryVideoFeed.remove(self) }else{ DJISDKManager.videoFeeder()?.primaryVideoFeed.remove(self) } } func fetchCamera() -> DJICamera? { let product = DJISDKManager.product() if (product == nil) { return nil } if (product!.isKind(of: DJIAircraft.self)) { return (product as! DJIAircraft).camera } else if (product!.isKind(of: DJIHandheld.self)) { return (product as! DJIHandheld).camera } return nil } func formatSeconds(seconds: UInt) -> String { let date = Date(timeIntervalSince1970: TimeInterval(seconds)) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "mm:ss" return(dateFormatter.string(from: date)) } func showAlertViewWithTitle(title: String, withMessage message: String) { let alert = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction.init(title:"OK", style: UIAlertActionStyle.default, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } // DJISDKManagerDelegate Methods func productConnected(_ product: DJIBaseProduct?) { NSLog("Product Connected") if (product != nil) { let camera = self.fetchCamera() if (camera != nil) { camera!.delegate = self } self.setupVideoPreviewer() } } func productDisconnected() { NSLog("Product Disconnected") let camera = self.fetchCamera() if((camera != nil) && (camera?.delegate?.isEqual(self))!){ camera?.delegate = nil } self.resetVideoPreview() } func appRegisteredWithError(_ error: Error?) { var message = "Register App Successed!" if (error != nil) { message = "Register app failed! Please enter your app key and check the network." } else { DJISDKManager.startConnectionToProduct() } self.showAlertViewWithTitle(title:"Register App", withMessage: message) } // DJICameraDelegate Method func camera(_ camera: DJICamera, didUpdate cameraState: DJICameraSystemState) { self.isRecording = cameraState.isRecording self.recordTimeLabel.isHidden = !self.isRecording self.recordTimeLabel.text = formatSeconds(seconds: cameraState.currentVideoRecordingTimeInSeconds) if (self.isRecording == true) { self.recordButton.setTitle("Stop Record", for: UIControlState.normal) } else { self.recordButton.setTitle("Start Record", for: UIControlState.normal) } //Update UISegmented Control's State if (cameraState.mode == DJICameraMode.shootPhoto) { self.workModeSegmentControl.selectedSegmentIndex = 0 } else { self.workModeSegmentControl.selectedSegmentIndex = 1 } } // DJIVideoFeedListener Method func videoFeed(_ videoFeed: DJIVideoFeed, didUpdateVideoData rawData: Data) { let videoData = rawData as NSData let videoBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: videoData.length) videoData.getBytes(videoBuffer, length: videoData.length) VideoPreviewer.instance().push(videoBuffer, length: Int32(videoData.length)) } // IBAction Methods @IBAction func captureAction(_ sender: UIButton) { let camera = self.fetchCamera() if (camera != nil) { camera?.setMode(DJICameraMode.shootPhoto, withCompletion: {(error) in DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){ camera?.startShootPhoto(completion: { (error) in if (error != nil) { NSLog("Shoot Photo Error: " + String(describing: error)) } }) } }) } } @IBAction func recordAction(_ sender: UIButton) { let camera = self.fetchCamera() if (camera != nil) { if (self.isRecording) { camera?.stopRecordVideo(completion: { (error) in if (error != nil) { NSLog("Stop Record Video Error: " + String(describing: error)) } }) } else { camera?.startRecordVideo(completion: { (error) in if (error != nil) { NSLog("Start Record Video Error: " + String(describing: error)) } }) } } } @IBAction func workModeSegmentChange(_ sender: UISegmentedControl) { let camera = self.fetchCamera() if (camera != nil) { if (sender.selectedSegmentIndex == 0) { camera?.setMode(DJICameraMode.shootPhoto, withCompletion: { (error) in if (error != nil) { NSLog("Set ShootPhoto Mode Error: " + String(describing: error)) } }) } else if (sender.selectedSegmentIndex == 1) { camera?.setMode(DJICameraMode.recordVideo, withCompletion: { (error) in if (error != nil) { NSLog("Set RecordVideo Mode Error: " + String(describing: error)) } }) } } } }
e722292a0a0323fdcdd02fe0fc36b78e
33.468619
132
0.575989
false
false
false
false
ludoded/ReceiptBot
refs/heads/master
ReceiptBot/Helper/Extension/TextField+Rebotise.swift
lgpl-3.0
1
// // TextField+Rebotise.swift // ReceiptBot // // Created by Haik Ampardjian on 4/8/17. // Copyright © 2017 receiptbot. All rights reserved. // import Material extension TextField { func rebotize() { self.placeholderNormalColor = .lightText self.placeholderActiveColor = RebotColor.Text.green self.textColor = .lightText self.dividerNormalColor = .lightText self.dividerActiveColor = RebotColor.Text.green self.dividerActiveHeight = 1.0 self.dividerNormalHeight = 2.0 } }
58c9a34f727c150adecb61a3e82e7129
24.090909
59
0.668478
false
false
false
false
buyiyang/iosstar
refs/heads/master
iOSStar/Scenes/User/Controller/AccountInfoVC.swift
gpl-3.0
4
// // AccountInfoVC.swift // iOSStar // // Created by sum on 2017/4/26. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit class AccountInfoVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
4bf66741a5c5a3fd004d12968cd38c7e
28.25
136
0.653171
false
false
false
false
Spacerat/HexKeyboard
refs/heads/master
HexKeyboard/SemitonesPickerViewController.swift
gpl-2.0
1
// // File.swift // HexKeyboard // // Created by Joseph Atkins-Turkish on 14/09/2014. // Copyright (c) 2014 Joseph Atkins-Turkish. All rights reserved. // import Foundation import UIKit class SemitonesPickerViewController: UITableViewController { let minTranspose = -12 let maxTranspose = 24 var selectedCell : UITableViewCell? var selectedTranspose = Interval(semitones: 0) override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) selectedTranspose = Interval.transposeInterval() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("semitoneCell")! as UITableViewCell let interval = intervalForRowAtIndexPath(indexPath) cell.textLabel?.text = interval.transposeName cell.accessoryType = interval == selectedTranspose ? .Checkmark : .None if interval == selectedTranspose { selectedCell = cell } return cell } func intervalForRowAtIndexPath(indexPath:NSIndexPath) -> Interval { return Interval(semitones: indexPath.row + minTranspose) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return maxTranspose - minTranspose + 1 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let newCell = tableView.cellForRowAtIndexPath(indexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let newTranspose = intervalForRowAtIndexPath(indexPath) if newTranspose != selectedTranspose { newCell.accessoryType = .Checkmark selectedCell?.accessoryType = .None selectedCell = newCell selectedTranspose = newTranspose let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(selectedTranspose.semitones, forKey: "transpose") defaults.synchronize() } } } }
1020292f905b7fc7fd7c9c652d5a278a
34.548387
118
0.667423
false
false
false
false
haawa799/WaniKani-Kanji-Strokes
refs/heads/master
Advance Code/AdvancedNSOperations/Earthquakes/Operations/DelayOperation.swift
apache-2.0
12
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows how to make an operation that efficiently waits. */ import Foundation /** `DelayOperation` is an `Operation` that will simply wait for a given time interval, or until a specific `NSDate`. It is important to note that this operation does **not** use the `sleep()` function, since that is inefficient and blocks the thread on which it is called. Instead, this operation uses `dispatch_after` to know when the appropriate amount of time has passed. If the interval is negative, or the `NSDate` is in the past, then this operation immediately finishes. */ class DelayOperation: Operation { // MARK: Types private enum Delay { case Interval(NSTimeInterval) case Date(NSDate) } // MARK: Properties private let delay: Delay // MARK: Initialization init(interval: NSTimeInterval) { delay = .Interval(interval) super.init() } init(until date: NSDate) { delay = .Date(date) super.init() } override func execute() { let interval: NSTimeInterval // Figure out how long we should wait for. switch delay { case .Interval(let theInterval): interval = theInterval case .Date(let date): interval = date.timeIntervalSinceNow } guard interval > 0 else { finish() return } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { // If we were cancelled, then finish() has already been called. if !self.cancelled { self.finish() } } } override func cancel() { super.cancel() // Cancelling the operation means we don't want to wait anymore. self.finish() } }
d078ea0db01223235ccdfcba79f4d0ca
25.897436
91
0.601525
false
false
false
false
coach-plus/ios
refs/heads/master
Floral/Pods/Hero/Sources/Transition/HeroProgressRunner.swift
mit
3
// 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 protocol HeroProgressRunnerDelegate: class { func updateProgress(progress: Double) func complete(finished: Bool) } class HeroProgressRunner { weak var delegate: HeroProgressRunnerDelegate? var isRunning: Bool { return displayLink != nil } internal var timePassed: TimeInterval = 0.0 internal var duration: TimeInterval = 0.0 internal var displayLink: CADisplayLink? internal var isReversed: Bool = false @objc func displayUpdate(_ link: CADisplayLink) { timePassed += isReversed ? -link.duration : link.duration if isReversed, timePassed <= 1.0 / 120 { delegate?.complete(finished: false) stop() return } if !isReversed, timePassed > duration - 1.0 / 120 { delegate?.complete(finished: true) stop() return } delegate?.updateProgress(progress: timePassed / duration) } func start(timePassed: TimeInterval, totalTime: TimeInterval, reverse: Bool) { stop() self.timePassed = timePassed self.isReversed = reverse self.duration = totalTime displayLink = CADisplayLink(target: self, selector: #selector(displayUpdate(_:))) displayLink!.add(to: .main, forMode: RunLoop.Mode.common) } func stop() { displayLink?.isPaused = true displayLink?.remove(from: RunLoop.main, forMode: RunLoop.Mode.common) displayLink = nil } }
0ff24c194b985eda890a8a51d83c4d86
33.930556
85
0.725249
false
false
false
false
gtranchedone/AlgorithmsSwift
refs/heads/master
Algorithms.playground/Pages/Problem - Binary Tree Balance.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) func isBinaryTreeBalanced<T>(root: BinaryNode<T>) -> Bool { var height = 0 // inout parameters in Swift cannot be optional return isBinaryTreeBalanced(root, height: &height) } func isBinaryTreeBalanced<T>(root: BinaryNode<T>?, inout height: Int) -> Bool { guard root != nil else { height = 0 return true } var hLeft = 0, hRight = 0 let balancedLeft = isBinaryTreeBalanced(root!.left, height: &hLeft) let balancedRight = isBinaryTreeBalanced(root!.right, height: &hRight) height = 1 + max(hLeft, hRight) let isBalanced = !(hLeft > hRight + 1 || hRight > hLeft + 1) return isBalanced && balancedLeft && balancedRight } class BinaryNode<T> { let value: T var left: BinaryNode<T>? var right: BinaryNode<T>? init(value: T) { self.value = value } } let n1 = BinaryNode(value: 1) isBinaryTreeBalanced(n1) let n2 = BinaryNode(value: 2) n1.left = n2 isBinaryTreeBalanced(n1) let n3 = BinaryNode(value: 3) n1.right = n3 isBinaryTreeBalanced(n1) let n4 = BinaryNode(value: 4) n2.left = n4 isBinaryTreeBalanced(n1) let n5 = BinaryNode(value: 5) n4.left = n5 isBinaryTreeBalanced(n1) //: [Next](@next)
cd64e6d6d332f579b7c929806bb9d8cc
24.446809
79
0.676421
false
false
false
false
xeo-it/poggy
refs/heads/master
Pods/OAuthSwift/OAuthSwift/OAuthWebViewController.swift
apache-2.0
1
// // OAuthWebViewController.swift // OAuthSwift // // Created by Dongri Jin on 2/11/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias OAuthViewController = UIViewController #elseif os(watchOS) import WatchKit public typealias OAuthViewController = WKInterfaceController #elseif os(OSX) import AppKit public typealias OAuthViewController = NSViewController #endif // Delegate for OAuthWebViewController public protocol OAuthWebViewControllerDelegate { #if os(iOS) || os(tvOS) // Did web view presented (work only without navigation controller) func oauthWebViewControllerDidPresent() // Did web view dismiss (work only without navigation controller) func oauthWebViewControllerDidDismiss() #endif func oauthWebViewControllerWillAppear() func oauthWebViewControllerDidAppear() func oauthWebViewControllerWillDisappear() func oauthWebViewControllerDidDisappear() } // A web view controller, which handler OAuthSwift authentification. public class OAuthWebViewController: OAuthViewController, OAuthSwiftURLHandlerType { #if os(iOS) || os(tvOS) || os(OSX) // Delegate for this view public var delegate: OAuthWebViewControllerDelegate? #endif #if os(iOS) || os(tvOS) // If controller have an navigation controller, application top view controller could be used if true public var useTopViewControlerInsteadOfNavigation = false public var topViewController: UIViewController? { #if !OAUTH_APP_EXTENSIONS return UIApplication.topViewController #else return nil #endif } #elseif os(OSX) // How to present this view controller if parent view controller set public enum Present { case AsModalWindow case AsSheet case AsPopover(relativeToRect: NSRect, ofView : NSView, preferredEdge: NSRectEdge, behavior: NSPopoverBehavior) case TransitionFrom(fromViewController: NSViewController, options: NSViewControllerTransitionOptions) case Animator(animator: NSViewControllerPresentationAnimator) case Segue(segueIdentifier: String) } public var present: Present = .AsModalWindow #endif public func handle(url: NSURL) { // do UI in main thread OAuthSwift.main { [unowned self] in self.doHandle(url) } } #if os(watchOS) public static var userActivityType: String = "org.github.dongri.oauthswift.connect" #endif public func doHandle(url: NSURL) { #if os(iOS) || os(tvOS) let completion: () -> Void = { [unowned self] in self.delegate?.oauthWebViewControllerDidPresent() } let animated = true if let navigationController = self.navigationController where (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil) { navigationController.pushViewController(self, animated: animated) } else if let p = self.parentViewController { p.presentViewController(self, animated: animated, completion: completion) } else if let topViewController = topViewController { topViewController.presentViewController(self, animated: animated, completion: completion) } else { // assert no presentation } #elseif os(watchOS) if (url.scheme == "http" || url.scheme == "https") { self.updateUserActivity(OAuthWebViewController.userActivityType, userInfo: nil, webpageURL: url) } #elseif os(OSX) if let p = self.parentViewController { // default behaviour if this controller affected as child controller switch self.present { case .AsSheet: p.presentViewControllerAsSheet(self) break case .AsModalWindow: p.presentViewControllerAsModalWindow(self) // FIXME: if we present as window, window close must detected and oauthswift.cancel() must be called... break case .AsPopover(let positioningRect, let positioningView, let preferredEdge, let behavior): p.presentViewController(self, asPopoverRelativeToRect: positioningRect, ofView : positioningView, preferredEdge: preferredEdge, behavior: behavior) break case .TransitionFrom(let fromViewController, let options): let completion: () -> Void = { /*[unowned self] in*/ //self.delegate?.oauthWebViewControllerDidPresent() } p.transitionFromViewController(fromViewController, toViewController: self, options: options, completionHandler: completion) break case .Animator(let animator): p.presentViewController(self, animator: animator) case .Segue(let segueIdentifier): p.performSegueWithIdentifier(segueIdentifier, sender: self) // The segue must display self.view break } } else if let window = self.view.window { window.makeKeyAndOrderFront(nil) } // or create an NSWindow or NSWindowController (/!\ keep a strong reference on it) #endif } public func dismissWebViewController() { #if os(iOS) || os(tvOS) let completion: () -> Void = { [unowned self] in self.delegate?.oauthWebViewControllerDidDismiss() } let animated = true if let navigationController = self.navigationController where (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil){ navigationController.popViewControllerAnimated(animated) } else if let parentViewController = self.parentViewController { // The presenting view controller is responsible for dismissing the view controller it presented parentViewController.dismissViewControllerAnimated(animated, completion: completion) } else if let topViewController = topViewController { topViewController.dismissViewControllerAnimated(animated, completion: completion) } else { // keep old code... self.dismissViewControllerAnimated(animated, completion: completion) } #elseif os(watchOS) self.dismissController() #elseif os(OSX) if self.presentingViewController != nil { self.dismissController(nil) if self.parentViewController != nil { self.removeFromParentViewController() } } else if let window = self.view.window { window.performClose(nil) } #endif } // MARK: overrides #if os(iOS) || os(tvOS) public override func viewWillAppear(animated: Bool) { self.delegate?.oauthWebViewControllerWillAppear() } public override func viewDidAppear(animated: Bool) { self.delegate?.oauthWebViewControllerDidAppear() } public override func viewWillDisappear(animated: Bool) { self.delegate?.oauthWebViewControllerWillDisappear() } public override func viewDidDisappear(animated: Bool) { self.delegate?.oauthWebViewControllerDidDisappear() } #elseif os(OSX) public override func viewWillAppear() { self.delegate?.oauthWebViewControllerWillAppear() } public override func viewDidAppear() { self.delegate?.oauthWebViewControllerDidAppear() } public override func viewWillDisappear() { self.delegate?.oauthWebViewControllerWillDisappear() } public override func viewDidDisappear() { self.delegate?.oauthWebViewControllerDidDisappear() } #endif }
b285acfe6ab6789a78e91b5e93167dc0
39.606965
167
0.638892
false
false
false
false
apple/swift
refs/heads/main
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_generic-fileprivate-2nd_ancestor_nongeneric.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir -I %t -L %t %s > %t/out.ir // RUN: %FileCheck --input-file=%t/out.ir %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z_0-9]+]]LLCySiGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: )*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type* // CHECK-SAME: )*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]] // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]] // CHECK-SAME:}> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCySiGMM // CHECK-unknown-SAME: [[INT]] 0, // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* // : )*, // : i8**, // : [[INT]], // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void ( // : %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* // : )*, // : [[INT]], // : %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* ( // : [[INT]], // : %swift.type* // : )*, // : %swift.type*, // : [[INT]], // : %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* ( // : %swift.opaque*, // : %swift.type* // : )* // : }>* @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ), // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // : i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @"_DATA_$s4main5Value[[UNIQUE_ID_1]]LLCySiGMf" to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(40|20)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(152|88)}}, // CHECK-unknown-SAME: i32 128, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : %swift.method_override_descriptor // CHECK-SAME: $s4main5Value[[UNIQUE_ID_2:[A-Za-z_0-9]+]]LLCMn // CHECK-SAME: ), // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfE // CHECK-SAME: [[INT]] {{16|8}}, // CHECK-SAME: %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main9Ancestor2[[UNIQUE_ID_1]]LLCyADyxGSicfC // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{24|12}} // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: [[INT]] {{32|16}} // CHECK-SAME:}>, // CHECK-SAME:align [[ALIGNMENT]] fileprivate class Ancestor1 { let first_Ancestor1: Int init(_ int: Int) { self.first_Ancestor1 = int } } fileprivate class Ancestor2<First> : Ancestor1 { let first_Ancestor2: First init(first: First) { self.first_Ancestor2 = first super.init(7573672) } } fileprivate class Value<First> : Ancestor2<First> { let first_Value: First override init(first: First) { self.first_Value = first super.init(first: first) } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } func doit() { consume( Value(first: 13) ) } doit() // CHECK-LABEL: define hidden swiftcc void @"$s4main4doityyF"() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb" // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK-NEXT: entry: // CHECK: [[SUPERCLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) // CHECK-unknown: ret // CHECK-apple: [[THIS_CLASS_METADATA:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value[[UNIQUE_ID_1]]LLC* // : )*, // : i8**, // : i64, // : %swift.type*, // : %swift.opaque*, // : %swift.opaque*, // : i64, // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : void ( // : %T4main5Value[[UNIQUE_ID_1]]LLC* // : )*, // : i64, // : %T4main9Ancestor2[[UNIQUE_ID_1]]LLC* ( // : i64, // : %swift.type* // : )*, // : %swift.type*, // : i64, // : %T4main5Value[[UNIQUE_ID_1]]LLC* ( // : %swift.opaque*, // : %swift.type* // : )*, // : %swift.type*, // : i64 // CHECK-SAME: }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMf" to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[THIS_TYPE_METADATA:%[0-9]+]] = bitcast %objc_class* [[THIS_CLASS_METADATA]] to %swift.type* // CHECK-apple: [[RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[THIS_TYPE_METADATA]], 0 // CHECK-apple: [[COMPLETE_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]] // CHECK: }
e80eec13b1e305168a6b856807b2ef2b
39.570397
158
0.388592
false
false
false
false
raptorxcz/Rubicon
refs/heads/main
Generator/Syntactic analysis/Parser/ArgumentParser.swift
mit
1
// // ArgumentParser.swift // Rubicon // // Created by Kryštof Matěj on 27/04/2017. // Copyright © 2017 Kryštof Matěj. All rights reserved. // public enum ArgumentParserError: Error { case invalidName case invalidColon case invalidType } public class ArgumentParser { public init() {} public func parse(storage: Storage) throws -> ArgumentType { guard case let .identifier(label) = storage.current else { throw ArgumentParserError.invalidName } guard let secondToken = try? storage.next() else { throw ArgumentParserError.invalidColon } let argumentType: ArgumentType if case let .identifier(name) = secondToken { _ = try? storage.next() argumentType = try parseColon(in: storage, label: label, name: name) } else { argumentType = try parseColon(in: storage, label: nil, name: label) } return argumentType } private func parseColon(in storage: Storage, label: String?, name: String) throws -> ArgumentType { guard storage.current == .colon else { throw ArgumentParserError.invalidColon } _ = try? storage.next() let typeParser = TypeParser(storage: storage) guard let type = try? typeParser.parse() else { throw ArgumentParserError.invalidType } return ArgumentType(label: label, name: name, type: type) } }
c9c5b13c8bbd2fc5676fa73ae29338f7
26.185185
103
0.625341
false
false
false
false
lanserxt/teamwork-ios-sdk
refs/heads/master
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Comments.swift
mit
1
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func getRecentComments(resource: String, resourceId: String, page: Int = 1, pageSize: Int = 20, _ responseBlock: @escaping (Bool, Int, [Comment]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getRecentComments.path, resource, resourceId, page, pageSize), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<Comment>.init(rootObjectName: TWApiClientConstants.APIPath.getRecentComments.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getComment(commentId: String, _ responseBlock: @escaping (Bool, Int, Comment?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getComment.path, commentId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Comment>.init(rootObjectName: TWApiClientConstants.APIPath.getComment.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func createComment(resource: String, resourceId: String, comment: Comment, _ responseBlock: @escaping (Bool, Int, Comment?, Error?) -> Void){ let parameters: [String : Any] = ["comment" : comment.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createComment.path, resource, resourceId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Comment>.init(rootObjectName: TWApiClientConstants.APIPath.createComment.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func updateComment(comment: Comment, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["comment" : comment.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateComment.path, comment.id!), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.updateComment.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteComment(comment: Comment, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteComment.path, comment.id!), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.deleteComment.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func markCommentAsRead(comment: Comment, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.markCommentAsRead.path, comment.id!), method: HTTPMethod.put, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.markCommentAsRead.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } }
70f3013c500553291fc26c4bb21705da
52.441026
234
0.533346
false
false
false
false
himadrisj/SiriPay
refs/heads/dev
Client/SiriPay/SiriPay/SPSignupViewController.swift
mit
1
// // SPSignupViewController.swift // SiriPay // // Created by Jatin Arora on 10/09/16. // Copyright // import Foundation class SPSignupViewController : UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var numberTextField: UITextField! @IBOutlet weak var nextButton: UIBarButtonItem! var emailID : String? var number : String? override func viewDidLoad() { let tapGestureRecogniser = UITapGestureRecognizer(target: self, action: #selector(viewTapped)) view.addGestureRecognizer(tapGestureRecogniser) } func viewTapped() { emailTextField.resignFirstResponder() numberTextField.resignFirstResponder() emailID = emailTextField.text number = numberTextField.text if let emailID = emailID , emailID.characters.count > 0 { if let number = number , number.characters.count > 0 { nextButton.isEnabled = true } } } @IBAction func nextButtonTapped(_ sender: AnyObject) { UserDefaults.standard.set(emailTextField.text, forKey: kDefaults_UserName) UserDefaults.standard.set(numberTextField.text, forKey: kDefaults_MobileNumber) UserDefaults.standard.synchronize() SPPaymentController.sharedInstance.requestOTPForSignIn(email: emailTextField.text!, mobileNo: numberTextField.text!) { (result, error) in if let _ = error { print("Error while signing in = \(error)") let alert = UIAlertController(title: "Wrong username or password", message:"Please try again", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } else { self.performSegue(withIdentifier: "OTPSegueIdentifier", sender: self) } } } } extension SPSignupViewController : UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField.text?.characters.count == 9 { nextButton.isEnabled = true } return true } }
d415b0eb8241d9e4dbbd2652b18543ca
38.388889
208
0.437518
false
false
false
false
scottfinkelstein/MixedRealityKit
refs/heads/master
MixedRealityKit/Source/MixedRealityKit.swift
mit
1
// // MixedRealityView.swift // MRKit // // Created by Scott Finkelstein on 9/1/17. // Copyright © 2017 Scott Finkelstein. All rights reserved. // import UIKit import SceneKit import ARKit public protocol MixedRealityDelegate: class { func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) func session(_ session: ARSession, didUpdate frame: ARFrame) func session(_ session: ARSession, didFailWithError error: Error) func sessionWasInterrupted(_ session: ARSession) func sessionInterruptionEnded(_ session: ARSession) } extension MixedRealityDelegate { func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { } func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) { } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { } func session(_ session: ARSession, didUpdate frame: ARFrame) { } func session(_ session: ARSession, didFailWithError error: Error) { } func sessionWasInterrupted(_ session: ARSession) { } func sessionInterruptionEnded(_ session: ARSession) { } } public class MixedRealityKit: ARSCNView, ARSessionDelegate, ARSCNViewDelegate { private var cameraTransform:matrix_float4x4? private var cameraNode:SCNNode? public weak var mixedRealityDelegate:MixedRealityDelegate? public var disableSleepMode:Bool = true { willSet(newValue) { print("value will change to \(newValue)") } didSet { if disableSleepMode == true { UIApplication.shared.isIdleTimerDisabled = true }else { UIApplication.shared.isIdleTimerDisabled = false } } } override public var scene: SCNScene { didSet { setupMainCamera() stereoSplit() } } public override init(frame: CGRect, options: [String: Any]? = nil) { super.init(frame: frame, options: options) delegate = self session.delegate = self showsStatistics = true } public func runSession(detectPlanes: Bool) { // Create a session configuration let configuration = ARWorldTrackingConfiguration() if detectPlanes == true { configuration.planeDetection = .horizontal } // Run the view's session session.run(configuration) } public func runSession() { runSession(detectPlanes: false) } public func pauseSession() { session.pause() } public func addNode(node:SCNNode) { scene.rootNode.addChildNode(node) } private func setupMainCamera() { cameraNode=SCNNode() cameraNode?.camera=SCNCamera() cameraNode?.position=SCNVector3(0, 0, 0) scene.rootNode.addChildNode(cameraNode!) } private func stereoSplit() { // Set up left & Right SCNCameraNodes & SCNSceneView's which mirror the main (single-view) instances. let cameraNodeLeft=SCNNode() cameraNodeLeft.camera=SCNCamera() cameraNodeLeft.camera?.zNear = 0.001 cameraNodeLeft.position=SCNVector3(-0.05, 0, 0) cameraNode?.addChildNode(cameraNodeLeft) let cameraNodeRight=SCNNode() cameraNodeRight.camera=SCNCamera() cameraNodeRight.camera?.zNear = 0.001 cameraNodeRight.position=SCNVector3(0.05, 0, 0) cameraNode?.addChildNode(cameraNodeRight) let sceneViewLeft=SCNView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width * 0.5, height: self.frame.size.height)) sceneViewLeft.pointOfView=cameraNodeLeft sceneViewLeft.scene=scene self.addSubview(sceneViewLeft) let sceneViewRight=SCNView(frame: CGRect(x: self.frame.size.width * 0.5, y: 0, width: self.frame.size.width * 0.5, height: self.frame.size.height)) sceneViewRight.pointOfView=cameraNodeRight sceneViewRight.scene=scene self.addSubview(sceneViewRight) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Session Delegate public func session(_ session: ARSession, didUpdate frame: ARFrame) { cameraTransform=frame.camera.transform cameraNode?.transform=SCNMatrix4(cameraTransform!) guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.session(session, didUpdate: frame) } public func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.session(session, didFailWithError: error) } public func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.sessionWasInterrupted(session) } public func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.sessionInterruptionEnded(session) } public func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.renderer(renderer, updateAtTime: time) } public func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.renderer(renderer, didAdd: node, for: anchor) } public func renderer(_ renderer: SCNSceneRenderer, willUpdate node: SCNNode, for anchor: ARAnchor) { guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.renderer(renderer, willUpdate: node, for: anchor) } public func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { guard let mixedRealityDelegate = mixedRealityDelegate else { return } mixedRealityDelegate.renderer(renderer, didRemove: node, for: anchor) } }
9f361bc5514d686f92dac635ae0256be
35.551546
155
0.667748
false
false
false
false
BlueBiteLLC/Eddystone
refs/heads/master
Pod/Classes/Beacon.swift
mit
2
import CoreBluetooth open class Beacon { //MARK: Enumerations public enum SignalStrength: Int { case excellent case veryGood case good case low case veryLow case noSignal case unknown } //MARK: Frames var frames: ( url: UrlFrame?, uid: UidFrame?, tlm: TlmFrame? ) = (nil,nil,nil) //MARK: Properties var txPower: Int var identifier: String var rssi: Double { get { var totalRssi: Double = 0 for rssi in self.rssiBuffer { totalRssi += rssi } let average: Double = totalRssi / Double(self.rssiBuffer.count) return average } } var signalStrength: SignalStrength = .unknown var rssiBuffer = [Double]() var distance: Double { get { return Beacon.calculateAccuracy(txPower: self.txPower, rssi: self.rssi) } } //MARK: Initializations init(rssi: Double, txPower: Int, identifier: String) { self.txPower = txPower self.identifier = identifier self.updateRssi(rssi) } //MARK: Delegate var delegate: BeaconDelegate? func notifyChange() { self.delegate?.beaconDidChange() } //MARK: Functions func updateRssi(_ newRssi: Double) -> Bool { self.rssiBuffer.insert(newRssi, at: 0) if self.rssiBuffer.count >= 20 { self.rssiBuffer.removeLast() } let signalStrength = Beacon.calculateSignalStrength(self.distance) if signalStrength != self.signalStrength { self.signalStrength = signalStrength self.notifyChange() } return false } //MARK: Calculations class func calculateAccuracy(txPower: Int, rssi: Double) -> Double { if rssi == 0 { return 0 } let ratio: Double = rssi / Double(txPower) if ratio < 1 { return pow(ratio, 10) } else { return 0.89976 * pow(ratio, 7.7095) + 0.111 } } class func calculateSignalStrength(_ distance: Double) -> SignalStrength { switch distance { case 0...24999: return .excellent case 25000...49999: return .veryGood case 50000...74999: return .good case 75000...99999: return .low default: return .veryLow } } //MARK: Advertisement Data func parseAdvertisementData(_ advertisementData: [AnyHashable: Any], rssi: Double) { self.updateRssi(rssi) if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) { if let type = Beacon.frameTypeFromBytes(bytes) { switch type { case .url: if let frame = UrlFrame.frameWithBytes(bytes) { if frame.url != self.frames.url?.url { self.frames.url = frame log("Parsed URL Frame with url: \(frame.url)") self.notifyChange() } } case .uid: if let frame = UidFrame.frameWithBytes(bytes) { if frame.uid != self.frames.uid?.uid { self.frames.uid = frame log("Parsed UID Frame with uid: \(frame.uid)") self.notifyChange() } } case .tlm: if let frame = TlmFrame.frameWithBytes(bytes) { self.frames.tlm = frame log("Parsed TLM Frame with battery: \(frame.batteryVolts) temperature: \(frame.temperature) advertisement count: \(frame.advertisementCount) on time: \(frame.onTime)") self.notifyChange() } } } } } //MARK: Bytes class func beaconWithAdvertisementData(_ advertisementData: [AnyHashable: Any], rssi: Double, identifier: String) -> Beacon? { var txPower: Int? var type: FrameType? if let bytes = Beacon.bytesFromAdvertisementData(advertisementData) { type = Beacon.frameTypeFromBytes(bytes) txPower = Beacon.txPowerFromBytes(bytes) if let txPower = txPower, type != nil { let beacon = Beacon(rssi: rssi, txPower: txPower, identifier: identifier) beacon.parseAdvertisementData(advertisementData, rssi: rssi) return beacon } } return nil } class func bytesFromAdvertisementData(_ advertisementData: [AnyHashable: Any]) -> [Byte]? { if let serviceData = advertisementData[CBAdvertisementDataServiceDataKey] as? [AnyHashable: Any] { if let urlData = serviceData[Scanner.eddystoneServiceUUID] as? Data { let count = urlData.count / MemoryLayout<UInt8>.size var bytes = [UInt8](repeating: 0, count: count) (urlData as NSData).getBytes(&bytes, length:count * MemoryLayout<UInt8>.size) return bytes.map { byte in return Byte(byte) } } } return nil } class func frameTypeFromBytes(_ bytes: [Byte]) -> FrameType? { if bytes.count >= 1 { switch bytes[0] { case 0: return .uid case 16: return .url case 32: return .tlm default: break } } return nil } class func txPowerFromBytes(_ bytes: [Byte]) -> Int? { if bytes.count >= 2 { if let type = Beacon.frameTypeFromBytes(bytes) { if type == .uid || type == .url { return Int(bytes[1]) } } } return nil } } protocol BeaconDelegate { func beaconDidChange() }
34ce161ea4907bf3205460a7e03e0a8f
29.407767
191
0.505268
false
false
false
false
JGiola/swift
refs/heads/main
test/stdlib/StringAPICString.swift
apache-2.0
6
// RUN: %target-run-simple-swift // REQUIRES: executable_test // // Tests for the non-Foundation CString-oriented API of String // import StdlibUnittest var CStringTests = TestSuite("CStringTests") func getNullUTF8() -> UnsafeMutablePointer<UInt8>? { return nil } func getASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x61 up[1] = 0x62 up[2] = 0 return (up, { up.deallocate() }) } func getNonASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0xd0 up[1] = 0xb0 up[2] = 0xd0 up[3] = 0xb1 up[4] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func getIllFormedUTF8String1( ) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x41 up[1] = 0xed up[2] = 0xa0 up[3] = 0x80 up[4] = 0x41 up[5] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func getIllFormedUTF8String2( ) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) { let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100) up[0] = 0x41 up[0] = 0x41 up[1] = 0xed up[2] = 0xa0 up[3] = 0x81 up[4] = 0x41 up[5] = 0 return (UnsafeMutablePointer(up), { up.deallocate() }) } func asCCharArray(_ a: [UInt8]) -> [CChar] { return a.map { CChar(bitPattern: $0) } } func getUTF8Length(_ cString: UnsafePointer<UInt8>) -> Int { var length = 0 while cString[length] != 0 { length += 1 } return length } func bindAsCChar(_ utf8: UnsafePointer<UInt8>) -> UnsafePointer<CChar> { return UnsafeRawPointer(utf8).bindMemory(to: CChar.self, capacity: getUTF8Length(utf8)) } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: UnsafePointer<UInt8>) { var index = 0 while lhs[index] != 0 { expectEqual(lhs[index], rhs[index]) index += 1 } expectEqual(0, rhs[index]) } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: ContiguousArray<UInt8>) { rhs.withUnsafeBufferPointer { expectEqualCString(lhs, $0.baseAddress!) } } func expectEqualCString(_ lhs: UnsafePointer<UInt8>, _ rhs: ContiguousArray<CChar>) { rhs.withUnsafeBufferPointer { $0.baseAddress!.withMemoryRebound( to: UInt8.self, capacity: rhs.count) { expectEqualCString(lhs, $0) } } } CStringTests.test("String.init(validatingUTF8:)") { do { let (s, dealloc) = getASCIIUTF8() expectEqual("ab", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getNonASCIIUTF8() expectEqual("аб", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() expectNil(String(validatingUTF8: bindAsCChar(s))) dealloc() } } CStringTests.test("String(cString:)") { do { let (s, dealloc) = getASCIIUTF8() let result = String(cString: s) expectEqual("ab", result) let su = bindAsCChar(s) expectEqual("ab", String(cString: su)) dealloc() } do { let (s, dealloc) = getNonASCIIUTF8() let result = String(cString: s) expectEqual("аб", result) let su = bindAsCChar(s) expectEqual("аб", String(cString: su)) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() let result = String(cString: s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) let su = bindAsCChar(s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", String(cString: su)) dealloc() } } CStringTests.test("String.decodeCString") { do { let s = getNullUTF8() let result = String.decodeCString(s, as: UTF8.self) expectNil(result) } do { // repairing let (s, dealloc) = getIllFormedUTF8String1() if let (result, repairsMade) = String.decodeCString( s, as: UTF8.self, repairingInvalidCodeUnits: true) { expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) expectTrue(repairsMade) } else { expectUnreachable("Expected .some()") } dealloc() } do { // non repairing let (s, dealloc) = getIllFormedUTF8String1() let result = String.decodeCString( s, as: UTF8.self, repairingInvalidCodeUnits: false) expectNil(result) dealloc() } } CStringTests.test("String.utf8CString") { do { let (cstr, dealloc) = getASCIIUTF8() defer { dealloc() } let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) } do { let (cstr, dealloc) = getNonASCIIUTF8() defer { dealloc() } let str = String(cString: cstr) expectEqualCString(cstr, str.utf8CString) } } CStringTests.test("String.withCString") { do { let (cstr, dealloc) = getASCIIUTF8() defer { dealloc() } let str = String(cString: cstr) str.withCString { expectEqual(str, String(cString: $0)) } } do { let (cstr, dealloc) = getASCIIUTF8() defer { dealloc() } let str = String(cString: cstr) str.withCString { expectEqual(str, String(cString: $0)) } } } CStringTests.test("Substring.withCString") { do { let (cstr, dealloc) = getASCIIUTF8() defer { dealloc() } let str = String(cString: cstr).dropFirst() str.withCString { expectEqual(str, String(cString: $0)) } } do { let (cstr, dealloc) = getASCIIUTF8() defer { dealloc() } let str = String(cString: cstr).dropFirst() str.withCString { expectEqual(str, String(cString: $0)) } } } CStringTests.test("String.cString.with.Array.UInt8.input") { guard #available(SwiftStdlib 5.7, *) else { return } do { let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } let cstr = UnsafePointer(u8p) let buffer = UnsafeBufferPointer(start: cstr, count: getUTF8Length(u8p)+1) let str = String(cString: Array(buffer)) str.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: buffer.count) { expectEqualCString(u8p, $0) } } } // no need to test every case; that is covered in other tests expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(cString:) must be null-terminated" ) _ = String(cString: [] as [UInt8]) expectUnreachable() } CStringTests.test("String.cString.with.Array.CChar.input") { guard #available(SwiftStdlib 5.7, *) else { return } do { let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } let buffer = UnsafeBufferPointer(start: u8p, count: getUTF8Length(u8p)+1) let str = buffer.withMemoryRebound(to: CChar.self) { String(cString: Array($0)) } str.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: buffer.count) { expectEqualCString(u8p, $0) } } } // no need to test every case; that is covered in other tests expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(cString:) must be null-terminated" ) _ = String(cString: [] as [CChar]) expectUnreachable() } CStringTests.test("String.cString.with.String.input") { guard #available(SwiftStdlib 5.7, *) else { return } let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } var str = String(cString: "ab") str.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: getUTF8Length(u8p)+1) { expectEqualCString(u8p, $0) } } str = String(cString: "") expectTrue(str.isEmpty) } CStringTests.test("String.cString.with.inout.UInt8.conversion") { guard #available(SwiftStdlib 5.7, *) else { return } var c = UInt8.zero var str = String(cString: &c) expectTrue(str.isEmpty) c = 100 expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(cString:) must be null-terminated" ) str = String(cString: &c) expectUnreachable() } CStringTests.test("String.cString.with.inout.CChar.conversion") { guard #available(SwiftStdlib 5.7, *) else { return } var c = CChar.zero var str = String(cString: &c) expectTrue(str.isEmpty) c = 100 expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(cString:) must be null-terminated" ) str = String(cString: &c) expectUnreachable() } CStringTests.test("String.validatingUTF8.with.Array.input") { guard #available(SwiftStdlib 5.7, *) else { return } do { let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } let buffer = UnsafeBufferPointer(start: u8p, count: getUTF8Length(u8p)+1) let str = buffer.withMemoryRebound(to: CChar.self) { String(validatingUTF8: Array($0)) } expectNotNil(str) str?.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: buffer.count) { expectEqualCString(u8p, $0) } } } // no need to test every case; that is covered in other tests expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(validatingUTF8:) must be null-terminated" ) _ = String(validatingUTF8: []) expectUnreachable() } CStringTests.test("String.validatingUTF8.with.String.input") { guard #available(SwiftStdlib 5.7, *) else { return } let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } var str = String(validatingUTF8: "ab") expectNotNil(str) str?.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: getUTF8Length(u8p)+1) { expectEqualCString(u8p, $0) } } str = String(validatingUTF8: "") expectNotNil(str) expectEqual(str?.isEmpty, true) } CStringTests.test("String.validatingUTF8.with.inout.conversion") { guard #available(SwiftStdlib 5.7, *) else { return } var c = CChar.zero var str = String(validatingUTF8: &c) expectNotNil(str) expectEqual(str?.isEmpty, true) c = 100 expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(validatingUTF8:) must be null-terminated" ) str = String(validatingUTF8: &c) expectUnreachable() } CStringTests.test("String.decodeCString.with.Array.input") { guard #available(SwiftStdlib 5.7, *) else { return } do { let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } let buffer = UnsafeBufferPointer(start: u8p, count: getUTF8Length(u8p)+1) let result = buffer.withMemoryRebound(to: Unicode.UTF8.CodeUnit.self) { String.decodeCString(Array($0), as: Unicode.UTF8.self) } expectNotNil(result) expectEqual(result?.repairsMade, false) result?.result.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: buffer.count) { expectEqualCString(u8p, $0) } } } // no need to test every case; that is covered in other tests expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of decodeCString(_:as:repairingInvalidCodeUnits:) must be null-terminated" ) _ = String.decodeCString([], as: Unicode.UTF8.self) expectUnreachable() } CStringTests.test("String.decodeCString.with.String.input") { guard #available(SwiftStdlib 5.7, *) else { return } let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } var result = String.decodeCString( "ab", as: Unicode.UTF8.self, repairingInvalidCodeUnits: true ) expectNotNil(result) expectEqual(result?.repairsMade, false) result?.result.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: getUTF8Length(u8p)+1) { expectEqualCString(u8p, $0) } } result = String.decodeCString("", as: Unicode.UTF8.self) expectNotNil(result) expectEqual(result?.repairsMade, false) expectEqual(result?.result.isEmpty, true) } CStringTests.test("String.decodeCString.with.inout.conversion") { guard #available(SwiftStdlib 5.7, *) else { return } var c = Unicode.UTF8.CodeUnit.zero var result = String.decodeCString( &c, as: Unicode.UTF8.self, repairingInvalidCodeUnits: true ) expectNotNil(result) expectEqual(result?.result.isEmpty, true) expectEqual(result?.repairsMade, false) c = 100 expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of decodeCString(_:as:repairingInvalidCodeUnits:) must be null-terminated" ) result = String.decodeCString(&c, as: Unicode.UTF8.self) expectUnreachable() } CStringTests.test("String.init.decodingCString.with.Array.input") { guard #available(SwiftStdlib 5.7, *) else { return } do { let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } let buffer = UnsafeBufferPointer(start: u8p, count: getUTF8Length(u8p)+1) let str = buffer.withMemoryRebound(to: Unicode.UTF8.CodeUnit.self) { String(decodingCString: Array($0), as: Unicode.UTF8.self) } str.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: buffer.count) { expectEqualCString(u8p, $0) } } } // no need to test every case; that is covered in other tests expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of decodeCString(_:as:repairingInvalidCodeUnits:) must be null-terminated" ) _ = String(decodingCString: [], as: Unicode.UTF8.self) expectUnreachable() } CStringTests.test("String.init.decodingCString.with.String.input") { guard #available(SwiftStdlib 5.7, *) else { return } let (u8p, dealloc) = getASCIIUTF8() defer { dealloc() } var str = String(decodingCString: "ab", as: Unicode.UTF8.self) str.withCString { $0.withMemoryRebound(to: UInt8.self, capacity: getUTF8Length(u8p)+1) { expectEqualCString(u8p, $0) } } str = String(decodingCString: "", as: Unicode.UTF8.self) expectTrue(str.isEmpty) } CStringTests.test("String.init.decodingCString.with.inout.conversion") { guard #available(SwiftStdlib 5.7, *) else { return } var c = Unicode.UTF8.CodeUnit.zero var str = String(decodingCString: &c, as: Unicode.UTF8.self) expectEqual(str.isEmpty, true) c = 100 expectCrashLater( // Workaround for https://bugs.swift.org/browse/SR-16103 (rdar://91365967) // withMessage: "input of String.init(decodingCString:as:) must be null-terminated" ) str = String(decodingCString: &c, as: Unicode.UTF8.self) expectUnreachable() } runAllTests()
8e7bd2be30e261bf0fa5ee1177610fa1
28.595918
101
0.668735
false
true
false
false
buscarini/pairofwings
refs/heads/master
pairofwings/pairofwings/Validators.swift
mit
1
// // Validation.swift // pairofwings // // Created by Jose Manuel Sánchez Peñarroja on 24/10/14. // Copyright (c) 2014 José Manuel Sánchez. All rights reserved. // import Foundation public protocol ValidatorProtocol { typealias T func validate(value : T) -> Bool } public class Validator<T> : ValidatorProtocol { public func validate(value : T) -> Bool { return true } } public class ClosureValidator<T> : Validator<T> { public var closure : (T) -> Bool public init(closure: (T) -> Bool) { self.closure = closure } public override func validate(value: T) -> Bool { return closure(value) } } public class RangeValueValidator<T : Comparable> : Validator <T> { public var min : T public var max : T public init(_ min: T,_ max: T) { self.min = min self.max = max } public override func validate(value: T) -> Bool { return (value>=self.min && value<=self.max) } }
f10992dc2a1bdbc41626d159661d036b
16.576923
66
0.663746
false
false
false
false
Bouke/Swift-Security
refs/heads/master
Swift-Security/Certificate.swift
mit
1
// // Certificate.swift // Security // // Created by Bouke Haarsma on 06-04-15. // Copyright (c) 2015 Bouke Haarsma. All rights reserved. // import Foundation import Security let SUBJECT_NAME = kSecOIDX509V1SubjectName.takeRetainedValue() as! String let SEC_KEY_LABEL = kSecPropertyKeyLabel.takeUnretainedValue() as! String let SEC_KEY_VALUE = kSecPropertyKeyValue.takeUnretainedValue() as! String public func root_certs() -> [Certificate] { var result: Unmanaged<CFArray>? switch sec(SecTrustCopyAnchorCertificates(&result)) { case .Success: let certificates = map(result?.takeUnretainedValue() as! [SecCertificate]) { Certificate(ref: $0) } result?.release() return certificates default: abort() } } func cert_data(ref: SecCertificateRef, keys: [String]) -> [String: [String: String]] { var data = [String: [String: String]]() let contents = SecCertificateCopyValues(ref, keys, nil) as Unmanaged<CFDictionary>? if let contents = contents?.takeUnretainedValue() as? [String: NSDictionary] { for (key, value) in contents { data[key] = [:] if let contents2 = value[SEC_KEY_VALUE] as? [[String: String]] { for contents3 in contents2 { if let key2 = contents3[SEC_KEY_LABEL] { data[key]?[key2] = contents3[SEC_KEY_VALUE] } } } } } contents?.release() return data } public class Certificate { let ref: SecCertificateRef init(ref: SecCertificateRef) { self.ref = ref } lazy public var commonName: String? = { var cfName: Unmanaged<CFString>? SecCertificateCopyCommonName(self.ref, &cfName) var name = cfName?.takeUnretainedValue() as? String cfName?.release() if name == nil { let desc = SecCertificateCopyLongDescription(nil, self.ref, nil) name = desc.takeUnretainedValue() as? String desc.release() } return name }() var subjectName: [String: String]? { return cert_data(self.ref, [SUBJECT_NAME])[SUBJECT_NAME] } lazy public var subjectCountry: String? = { return self.subjectName?["2.5.4.6"] }() public func trustSettings(domain: TrustSettingsDomain) -> TrustSettings? { return TrustSettings(ref: ref, domain: domain) } } extension Certificate: Printable { public var description: String { return "Certificate(ref=\(ref))" } }
4daf1d1cdf224cee95fa94bb0efbddbd
28.917647
107
0.621951
false
false
false
false
TellMeAMovieTeam/TellMeAMovie_iOSApp
refs/heads/master
TellMeAMovie/Pods/TMDBSwift/Sources/Models/MovieMDBModel.swift
apache-2.0
1
// // MovieMDBModel.swift // MDBSwiftWrapper // // Created by George Kye on 2016-03-08. // Copyright © 2016 George KyeKye. All rights reserved. // import Foundation open class MovieMDB: DiscoverMovieMDB{ open var title: String? open var video: Bool? open var release_date: String? open var original_title: String? open var genres = [genresType]() public typealias genresType = (id: Int?, name: String?) public required init(results: JSON) { super.init(results: results) title = results["title"].string video = results["video"].bool adult = results["adult"].bool release_date = results["release_date"].string original_title = results["original_title"].string results["genres"].forEach(){ genres.append(($0.1["id"].int, $0.1["name"].string)) } } }
84341855beba38374b4d5c3771dd316d
24.40625
58
0.665437
false
false
false
false
overtake/TelegramSwift
refs/heads/master
packages/InAppSettings/Sources/InAppSettings/DownloadedFilesPaths.swift
gpl-2.0
1
// // DownloadedFilesPaths.swift // Telegram // // Created by Mikhail Filimonov on 13/03/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import Postbox import SwiftSignalKit import TelegramCore public struct DownloadedPath : Codable, Equatable { public let id: MediaId public let downloadedPath: String public let size: Int64 public let lastModified: Int32 public init(id: MediaId, downloadedPath: String, size: Int64, lastModified: Int32) { self.id = id self.downloadedPath = downloadedPath self.size = size self.lastModified = lastModified } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) self.id = try container.decode(MediaId.self, forKey: "id") self.downloadedPath = try container.decode(String.self, forKey: "dp") self.size = try container.decode(Int64.self, forKey: "s") self.lastModified = try container.decode(Int32.self, forKey: "lm") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(self.id, forKey: "id") try container.encode(self.downloadedPath, forKey: "dp") try container.encode(self.size, forKey: "s") try container.encode(self.lastModified, forKey: "lm") } } public struct DownloadedFilesPaths: Codable, Equatable { private let paths: [DownloadedPath] public static var defaultValue: DownloadedFilesPaths { return DownloadedFilesPaths(paths: []) } public init(paths: [DownloadedPath]) { self.paths = paths } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) self.paths = try container.decode([DownloadedPath].self, forKey: "p") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(self.paths, forKey: "p") } public func path(for mediaId: MediaId) -> DownloadedPath? { for path in paths { if path.id == mediaId { return path } } return nil } public func withAddedPath(_ path: DownloadedPath) -> DownloadedFilesPaths { var paths = self.paths if let index = paths.firstIndex(where: {$0.id == path.id}) { paths[index] = path } else { paths.append(path) } return DownloadedFilesPaths(paths: paths) } } public func downloadedFilePaths(_ postbox: Postbox) -> Signal<DownloadedFilesPaths, NoError> { return postbox.transaction { transaction in return transaction.getPreferencesEntry(key: ApplicationSpecificPreferencesKeys.downloadedPaths)?.get(DownloadedFilesPaths.self) ?? DownloadedFilesPaths.defaultValue } } public func updateDownloadedFilePaths(_ postbox: Postbox, _ f: @escaping(DownloadedFilesPaths) -> DownloadedFilesPaths) -> Signal<Never, NoError> { return postbox.transaction { transaction in transaction.updatePreferencesEntry(key: ApplicationSpecificPreferencesKeys.downloadedPaths, { entry in let current = entry?.get(DownloadedFilesPaths.self) ?? DownloadedFilesPaths.defaultValue return PreferencesEntry(f(current)) }) } |> ignoreValues }
3b1f9eb12fdd726fa02b092ffb47dc99
33.165049
172
0.664109
false
false
false
false
JohnBehnke/RPI_Tours_iOS
refs/heads/master
RPI Tours/RPI Tours/Classes.swift
mit
2
// // Classes.swift // RPI Tours // // Created by John Behnke on 4/2/17. // Copyright © 2017 RPI Web Tech. All rights reserved. // import Foundation import CoreLocation class TourCat { var name: String var desc: String var tours: [Tour] //INITIALIZERS init(name: String, desc: String, tours: [Tour]) { self.name = name self.desc = desc self.tours = tours } //empty Init init() { self.name = "" self.desc = "" self.tours = [] } } class Landmark { //INITIALIZERS init(name: String, desc: String, lat: Double, long: Double, urls: [String]) { self.name = name self.desc = desc self.urls = urls self.point = CLLocationCoordinate2D(latitude: lat, longitude: long) } //VARIABLES var name: String var desc: String var urls: [String] var point: CLLocationCoordinate2D } class Tour { var name: String var desc: String var waypoints: [CLLocationCoordinate2D] var landmarks: [Landmark] //INITIALIZERS init(name: String, desc: String, waypoints: [CLLocationCoordinate2D], landmarks: [Landmark]) { self.name = name self.desc = desc self.waypoints = waypoints self.landmarks = landmarks } init() { self.name = "" self.desc = "" self.waypoints = [] self.landmarks = [] } }
dab0c625640b3fec65889372f09f555c
17.532468
98
0.577435
false
false
false
false
sviatoslav/EndpointProcedure
refs/heads/master
Examples/Basic usage.playground/Sources/PendingEvent.swift
mit
2
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import Dispatch /// `PendingEvent` encapsulates a reference to a future `Procedure` event, and can be used /// to ensure that asynchronous tasks are executed to completion *before* the future event. /// /// While a reference to the `PendingEvent` exists, the event will not occur. /// /// You cannot instantiate your own `PendingEvent` instances - only the framework /// itself creates and provides (in certain circumstances) PendingEvents. /// /// A common use-case is when handling a WillExecute or WillFinish observer callback. /// ProcedureKit will provide your observer with a `PendingExecuteEvent` or a `PendingFinishEvent`. /// /// If you must dispatch an asynchronous task from within your observer, but want to /// ensure that the observed `Procedure` does not execute / finish until your asynchronous task /// completes, you can use the Pending(Execute/Finish)Event like so: /// /// ```swift /// procedure.addWillFinishObserver { procedure, errors, pendingFinish in /// DispatchQueue.global().async { /// pendingFinish.doBeforeEvent { /// // do something asynchronous /// // this block is guaranteed to complete before the procedure finishes /// } // } /// } /// ``` /// /// Some of the built-in `Procedure` functions take an optional "before:" parameter, /// to which a `PendingEvent` can be directly passed. For example: /// /// ```swift /// procedure.addWillFinishObserver { procedure, errors, pendingFinish in /// // produce a new operation before the procedure finishes /// procedure.produce(BlockOperation { /* do something */ }, before: pendingFinish) /// } /// ``` /// final public class PendingEvent: CustomStringConvertible { public enum Kind: CustomStringConvertible { case postDidAttach case addOperation case postDidAddOperation case execute case postDidExecute case postDidCancel case finish case postDidFinish public var description: String { switch self { case .addOperation: return "AddOperation" case .postDidAddOperation: return "PostAddOperation" case .execute: return "Execute" case .postDidExecute: return "PostExecute" case .postDidCancel: return "PostDidCancel" case .finish: return "Finish" case .postDidFinish: return "PostFinish" case .postDidAttach: return "PostDidAttach" } } } internal let event: Kind internal let group: DispatchGroup fileprivate let procedure: ProcedureProtocol private let isDerivedEvent: Bool internal init(forProcedure procedure: ProcedureProtocol, withGroup group: DispatchGroup = DispatchGroup(), withEvent event: Kind) { self.group = group self.procedure = procedure self.event = event self.isDerivedEvent = false group.enter() } // Ensures that a block is executed prior to the event described by the `PendingEvent` public func doBeforeEvent(block: () -> Void) { group.enter() block() group.leave() } // Ensures that the call to this function will occur prior to the event described by the `PendingEvent` public func doThisBeforeEvent() { group.enter() group.leave() } deinit { debugProceed() group.leave() } private func debugProceed() { procedure.log.verbose(message: "(\(self)) is ready to proceed") } public var description: String { return "Pending\(event.description) for: \(procedure.procedureName)" } } internal extension PendingEvent { static let execute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .execute) } static let postDidExecute: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidExecute) } static let finish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .finish) } static let postFinish: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidFinish) } static let addOperation: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .addOperation) } static let postDidAdd: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAddOperation) } static let postDidAttach: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidAttach) } static let postDidCancel: (Procedure) -> PendingEvent = { PendingEvent(forProcedure: $0, withEvent: .postDidCancel) } } public typealias PendingExecuteEvent = PendingEvent public typealias PendingFinishEvent = PendingEvent public typealias PendingAddOperationEvent = PendingEvent
4367dfd6b953008bc2bd717ca8339f15
38.699187
135
0.685439
false
false
false
false
sekouperry/news-pro
refs/heads/master
codecanyon-11884937-wp-news-pro/Code_Documentation/Code/WPNews2/WPNews2/ISAlertView.swift
apache-2.0
1
// // ISAlertView.swift // import Foundation import UIKit public enum ISAlertViewStyle { case OpenSafari } public enum ISActionType { case None, Selector, Closure } public class ISButton: UIButton { var actionType = ISActionType.None var target:AnyObject! var selector:Selector! var action:(()->Void)! public init() { super.init(frame: CGRectZero) } required public init(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } override public init(frame:CGRect) { super.init(frame:frame) } } public class ISAlertViewResponder { let alertview: ISAlertView public init(alertview: ISAlertView) { self.alertview = alertview } public func setTitle(title: String) { self.alertview.labelTitle.text = title } public func setSubTitle(subTitle: String) { self.alertview.viewText.text = subTitle } public func close() { self.alertview.hideView() } } let kCircleHeightBackground: CGFloat = 62.0 public class ISAlertView: UIViewController { let kDefaultShadowOpacity: CGFloat = 0.7 let kCircleTopPosition: CGFloat = -12.0 let kCircleBackgroundTopPosition: CGFloat = -15.0 let kCircleHeight: CGFloat = 56.0 let kCircleIconHeight: CGFloat = 56.0 let kTitleTop:CGFloat = 24.0 let kTitleHeight:CGFloat = 40.0 let kWindowWidth: CGFloat = 240.0 var kWindowHeight: CGFloat = 178.0 var kTextHeight: CGFloat = 90.0 let kDefaultFont = "HelveticaNeue" let kButtonFont = "HelveticaNeue-Bold" var viewColor = UIColor() var pressBrightnessFactor = 0.85 var baseView = UIView() var labelTitle = UILabel() var viewText = UITextView() var contentView = UIView() var circleBG = UIView(frame:CGRect(x:0, y:0, width:kCircleHeightBackground, height:kCircleHeightBackground)) var circleView = UIView() var circleIconImageView = UIImageView() var durationTimer: NSTimer! private var inputs = [UITextField]() private var buttons = [ISButton]() required public init(coder aDecoder: NSCoder) { fatalError("Error") } required public init() { super.init(nibName:nil, bundle:nil) view.frame = UIScreen.mainScreen().bounds view.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kDefaultShadowOpacity) view.addSubview(baseView) baseView.frame = view.frame baseView.addSubview(contentView) contentView.backgroundColor = UIColor(white:1, alpha:1) contentView.layer.cornerRadius = 5 contentView.layer.masksToBounds = true contentView.layer.borderWidth = 0.5 contentView.addSubview(labelTitle) contentView.addSubview(viewText) circleBG.backgroundColor = UIColor.whiteColor() circleBG.layer.cornerRadius = circleBG.frame.size.height / 2 baseView.addSubview(circleBG) circleBG.addSubview(circleView) circleView.addSubview(circleIconImageView) var x = (kCircleHeightBackground - kCircleHeight) / 2 circleView.frame = CGRect(x:x, y:x, width:kCircleHeight, height:kCircleHeight) circleView.layer.cornerRadius = circleView.frame.size.height / 2 x = (kCircleHeight - kCircleIconHeight) / 2 circleIconImageView.frame = CGRect(x:x, y:x, width:kCircleIconHeight, height:kCircleIconHeight) labelTitle.numberOfLines = 1 labelTitle.textAlignment = .Center labelTitle.font = UIFont(name: kDefaultFont, size:20) labelTitle.frame = CGRect(x:12, y:kTitleTop, width: kWindowWidth - 24, height:kTitleHeight) viewText.editable = false viewText.textAlignment = .Center viewText.textContainerInset = UIEdgeInsetsZero viewText.textContainer.lineFragmentPadding = 0; viewText.font = UIFont(name: kDefaultFont, size:14) contentView.backgroundColor = UIColor(white:1, alpha:1) labelTitle.textColor = UIColor.blackColor() viewText.textColor = UIColor.blackColor() contentView.layer.borderColor = UIColor.lightGrayColor().CGColor } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var sz = UIScreen.mainScreen().bounds.size let sver = UIDevice.currentDevice().systemVersion as NSString let ver = sver.floatValue if ver < 8.0 { if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { let ssz = sz sz = CGSize(width:ssz.height, height:ssz.width) } } // Set background frame view.frame.size = sz // Set frames var x = (sz.width - kWindowWidth) / 2 var y = (sz.height - kWindowHeight - (kCircleHeight / 8)) / 2 contentView.frame = CGRect(x:x, y:y, width:kWindowWidth, height:kWindowHeight) y -= kCircleHeightBackground * 0.6 x = (sz.width - kCircleHeightBackground) / 2 circleBG.frame = CGRect(x:x, y:y+6, width:kCircleHeightBackground, height:kCircleHeightBackground) // Subtitle y = kTitleTop + kTitleHeight viewText.frame = CGRect(x:12, y:y, width: kWindowWidth - 24, height:kTextHeight) // Text fields y += kTextHeight + 14.0 for txt in inputs { txt.frame = CGRect(x:12, y:y, width:kWindowWidth - 24, height:30) txt.layer.cornerRadius = 3 y += 40 } // Buttons for btn in buttons { btn.frame = CGRect(x:12, y:y, width:kWindowWidth - 24, height:35) btn.layer.cornerRadius = 3 y += 45.0 } } override public func touchesEnded(touches:Set<NSObject>, withEvent event:UIEvent) { if event.touchesForView(view)?.count > 0 { view.endEditing(true) } } public func addTextField(title:String?=nil)->UITextField { // Update view height kWindowHeight += 40.0 // Add text field let txt = UITextField() txt.borderStyle = UITextBorderStyle.RoundedRect txt.font = UIFont(name:kDefaultFont, size: 14) txt.autocapitalizationType = UITextAutocapitalizationType.Words txt.clearButtonMode = UITextFieldViewMode.WhileEditing txt.layer.masksToBounds = true txt.layer.borderWidth = 1.0 if title != nil { txt.placeholder = title! } contentView.addSubview(txt) inputs.append(txt) return txt } public func addButton(title:String, action:()->Void)->ISButton { let btn = addButton(title) btn.actionType = ISActionType.Closure btn.action = action btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside) btn.addTarget(self, action:Selector("buttonTapDown:"), forControlEvents:.TouchDown | .TouchDragEnter) btn.addTarget(self, action:Selector("buttonRelease:"), forControlEvents:.TouchUpInside | .TouchUpOutside | .TouchCancel | .TouchDragOutside ) return btn } public func addButton(title:String, target:AnyObject, selector:Selector)->ISButton { let btn = addButton(title) btn.actionType = ISActionType.Selector btn.target = target btn.selector = selector btn.addTarget(self, action:Selector("buttonTapped:"), forControlEvents:.TouchUpInside) btn.addTarget(self, action:Selector("buttonTapDown:"), forControlEvents:.TouchDown | .TouchDragEnter) btn.addTarget(self, action:Selector("buttonRelease:"), forControlEvents:.TouchUpInside | .TouchUpOutside | .TouchCancel | .TouchDragOutside ) return btn } private func addButton(title:String)->ISButton { kWindowHeight += 45.0 let btn = ISButton() btn.layer.masksToBounds = true btn.setTitle(title, forState: .Normal) btn.titleLabel?.font = UIFont(name:kButtonFont, size: 14) contentView.addSubview(btn) buttons.append(btn) return btn } func buttonTapped(btn:ISButton) { if btn.actionType == ISActionType.Closure { btn.action() } else if btn.actionType == ISActionType.Selector { let ctrl = UIControl() ctrl.sendAction(btn.selector, to:btn.target, forEvent:nil) } else { println("Unknow action type for button") } hideView() } func buttonTapDown(btn:ISButton) { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 btn.backgroundColor?.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) btn.backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } func buttonRelease(btn:ISButton) { btn.backgroundColor = viewColor } public func showOpenSafari(title: String, subTitle: String, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0) -> ISAlertViewResponder { return showTitle(title, subTitle: subTitle, duration: duration, completeText:closeButtonTitle, style: .OpenSafari) } public func showTitle(title: String, subTitle: String, style: ISAlertViewStyle, closeButtonTitle:String?=nil, duration:NSTimeInterval=0.0) -> ISAlertViewResponder { return showTitle(title, subTitle: subTitle, duration:duration, completeText:closeButtonTitle, style: style) } public func showTitle(title: String, subTitle: String, duration: NSTimeInterval?, completeText: String?, style: ISAlertViewStyle) -> ISAlertViewResponder { view.alpha = 0 let rv = UIApplication.sharedApplication().keyWindow! as UIWindow rv.addSubview(view) view.frame = rv.bounds baseView.frame = rv.bounds // Alert colour/icon viewColor = UIColor() var iconImage: UIImage // Icon style switch style { case .OpenSafari: viewColor = UIColor(white:1, alpha:1) iconImage = UIImage(named:"Safari")! } // Title if !title.isEmpty { self.labelTitle.text = title } // Subtitle if !subTitle.isEmpty { viewText.text = subTitle // Adjust text view size, if necessary let str = subTitle as NSString let attr = [NSFontAttributeName:viewText.font] let sz = CGSize(width: kWindowWidth - 24, height:90) let r = str.boundingRectWithSize(sz, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes:attr, context:nil) let ht = ceil(r.size.height) if ht < kTextHeight { kWindowHeight -= (kTextHeight - ht) kTextHeight = ht } } let txt = completeText != nil ? completeText! : "Cancel" addButton(txt, target:self, selector:Selector("hideView")) self.circleView.backgroundColor = viewColor self.circleIconImageView.image = iconImage for txt in inputs { txt.layer.borderColor = viewColor.CGColor } for btn in buttons { btn.backgroundColor = viewColor if style == ISAlertViewStyle.OpenSafari { btn.setTitleColor(UIColor.blackColor(), forState:UIControlState.Normal) } } if duration > 0 { durationTimer?.invalidate() durationTimer = NSTimer.scheduledTimerWithTimeInterval(duration!, target: self, selector: Selector("hideView"), userInfo: nil, repeats: false) } self.baseView.frame.origin.y = -400 UIView.animateWithDuration(0.2, animations: { self.baseView.center.y = rv.center.y + 15 self.view.alpha = 1 }, completion: { finished in UIView.animateWithDuration(0.2, animations: { self.baseView.center = rv.center }) }) return ISAlertViewResponder(alertview: self) } public func hideView() { UIView.animateWithDuration(0.2, animations: { self.view.alpha = 0 }, completion: { finished in self.view.removeFromSuperview() }) } }
d2d024d4cd914c0ff54b5f98fbcb5856
34.221918
168
0.629278
false
false
false
false
dsxNiubility/SXSwiftWeibo
refs/heads/master
103 - swiftWeibo/103 - swiftWeibo/Classes/Tools/String+Regex.swift
mit
1
// // String+Regex.swift // 103 - swiftWeibo // // Created by 董 尚先 on 15/3/13. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import Foundation extension String { /// 删除字符串中 href 的引用 func removeHref() -> String? { // 0. pattern 匹配方案 - 要过滤字符串最重要的依据 // <a href="http://www.xxx.com/abc">XXX软件</a> // () 是要提取的匹配内容,不使用括号,就是要忽略的内容 let pattern = "<a.*?>(.*?)</a>" // 定义正则表达式 // DotMatchesLineSeparators 使用 . 可以匹配换行符 // CaseInsensitive 忽略大小写 let regex = try! NSRegularExpression(pattern: pattern, options: [NSRegularExpressionOptions.CaseInsensitive, NSRegularExpressionOptions.DotMatchesLineSeparators]) // 匹配文字 // firstMatchInString 在字符串中查找第一个匹配的内容 // rangeAtIndex 函数是使用正则最重要的函数 -> 从 result 中获取到匹配文字的 range // index == 0,取出与 pattern 刚好匹配的内容 // index == 1,取出第一个(.*?)中要匹配的内容 // index 可以依次递增,对于复杂字符串过滤,可以使用多几个 () let text = self as NSString let length = text.length // 不能直接使用 String.length,包含UNICODE的编码长度,会出现数组越界 // let length = self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) if let result = regex.firstMatchInString(self, options: NSMatchingOptions(), range: NSMakeRange(0, length)) { // 匹配到内容 return text.substringWithRange(result.rangeAtIndex(1)) } return nil } /// 过滤表情字符串,生成属性字符串 /** 1. 匹配所有的 [xxx] 的内容 2. 准备结果属性字符串 3. 倒着遍历查询到的匹配结果 3.1 用查找到的字符串,去表情数组中查找对应的表情对象 3.2 用表情对象生成属性文本(使用 图片 attachment 替换结果字符串中 range 对应的 文本) 4. 返回结果 */ func emoticonString() -> NSAttributedString? { // 1. pattern - [] 是正则表达式的特殊字符 let pattern = "\\[(.*?)\\]" // 2. regex let regex = try! NSRegularExpression(pattern: pattern, options: [NSRegularExpressionOptions.CaseInsensitive, NSRegularExpressionOptions.DotMatchesLineSeparators]) let text = self as NSString // 3. 多个匹配,[NSTextCheckingResult] let checkingResults = regex.matchesInString(self, options: NSMatchingOptions(), range: NSMakeRange(0, text.length)) // !!! 结果字符串 let attributeString = NSMutableAttributedString(string: self) // 4. 倒着遍历匹配结果 for var i = checkingResults.count - 1; i >= 0; i-- { let result = checkingResults[i] // 表情符号的文字 let str = text.substringWithRange(result.rangeAtIndex(0)) let e = emoticon(str) // 替换图像 if e?.png != nil { // 生成图片附件,替换属性文本 let attString = SXEmoteTextAttachment.attributeString(e!, height: 18) // 替换属性文本 attributeString.replaceCharactersInRange(result.rangeAtIndex(0), withAttributedString: attString) } } // for result in checkingResults { // println(text.substringWithRange(result.rangeAtIndex(0))) // // // 表情符号的文字 // let str = text.substringWithRange(result.rangeAtIndex(0)) // let e = emoticon(str) // // println(e?.png) // } return attributeString } /// 在表情列表中查找表情符号对象 private func emoticon(str: String) -> Emoticon? { let emoticons = EmoticonList.sharedEmoticonList.allEmoticons // 遍历数组 var emoticon: Emoticon? for e in emoticons { if e.chs == str { emoticon = e break } } return emoticon } }
f3bc4343df2f927f3742bff115ac291b
30.466667
170
0.550199
false
false
false
false
wjc2118/TagView
refs/heads/master
TagView_Swift/TagView_Swift/ViewController.swift
mit
1
// // ViewController.swift // TagView_Swift // // Created by Mac-os on 16/12/26. // Copyright © 2016年 risen. All rights reserved. // import UIKit class ViewController: UIViewController { weak var tagView: TagView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white let tag = TagView(/*frame: CGRect(x: 0, y: 100, width: view.frame.width, height: 300)*/) // tag.backgroundColor = UIColor.gray view.addSubview(tag) tag.dataSource = self // tag.titlePlace = .right tag.showIndicatorAt(.bottom) tagView = tag } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tagView.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 300) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { tagView.titlePlace = .right tagView.showIndicatorAt(.right) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if size.width > size.height { tagView.titlePlace = .left tagView.showIndicatorAt(.right) } else { tagView.titlePlace = .top tagView.showIndicatorAt(.bottom) } } let titles: [String] = ["A", "BB", "CCC", "DDDD", "EEEEE", ] } extension ViewController: TagViewDataSource { func numberOfTags(in tagView: TagView) -> Int { return titles.count } func tagView(_ tagView: TagView, sizeForTagAt index: Int) -> CGSize { return CGSize(width: 100, height: 50) } func tagView(_ tagView: TagView, configureTagButton tagButton: UIButton, At index: Int) { tagButton.setTitle(titles[index], for: .normal) // tagButton.setTitle("XXX", for: .selected) tagButton.backgroundColor = UIColor.wjc.randomColor } func tagView(_ tagView: TagView, configureTableView tableView: UITableView, At index: Int) { tableView.backgroundColor = UIColor.wjc.randomColor } }
c9f790c0714f9ecd78a49fdabe2a309d
25.313953
112
0.609368
false
false
false
false
jmgc/swift
refs/heads/master
test/decl/protocol/conforms/inherited.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift // Inheritable: method with 'Self' in its signature protocol P1 { func f1(_ x: Self?) -> Bool } // Inheritable: property with 'Self' in its signature. protocol P2 { var prop2: Self { get set } } protocol P2a { var prop2a: Self { get set } } // Inheritable: subscript with 'Self' in its result type. protocol P3 { subscript (i: Int) -> Self { get } } // Inheritable: subscript with 'Self' in its index type. protocol P4 { subscript (s: Self) -> Int { get } } // Potentially inheritable: method returning Self protocol P5 { func f5() -> Self } protocol P5a { func f5a() -> Self } // Inheritable: method returning Self protocol P6 { func f6() -> Self } // Inheritable: method involving associated type. protocol P7 { associatedtype Assoc func f7() -> Assoc } // Inheritable: initializer requirement. protocol P8 { init(int: Int) } // Inheritable: operator requirement. protocol P9 { static func ==(x: Self, y: Self) -> Bool } // Never inheritable: method with 'Self' in a non-contravariant position. protocol P10 { func f10(_ arr: [Self]) } protocol P10a { func f10a(_ arr: [Self]) } // Never inheritable: method with 'Self' in curried position. protocol P11 { func f11() -> (_ x: Self) -> Int } // Inheritable: parameter is a function returning 'Self'. protocol P12 { func f12(_ s: () -> (Self, Self)) } // Never inheritable: parameter is a function accepting 'Self'. protocol P13 { func f13(_ s: (Self) -> ()) } // Inheritable: parameter is a function accepting a function // accepting 'Self'. protocol P14 { func f14(_ s: ((Self) -> ()) -> ()) } // Never inheritable: parameter is a function accepting a function // returning 'Self'. protocol P15 { func f15(_ s: (() -> Self) -> ()) } // Class A conforms to everything that can be conformed to by a // non-final class. class A : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 { // P1 func f1(_ x: A?) -> Bool { return true } // P2 var prop2: A { // expected-error{{property 'prop2' in non-final class 'A' must specify type 'Self' to conform to protocol 'P2'}} get { return self } set {} } // P2a var prop2a: A { // expected-note {{'prop2a' declared here}} get { return self } set {} } // P3 subscript (i: Int) -> A { // expected-error{{subscript 'subscript(_:)' in non-final class 'A' must return 'Self' to conform to protocol 'P3'}} get { return self } } // P4 subscript (a: A) -> Int { get { return 5 } } // P5 func f5() -> A { return self } // expected-error{{method 'f5()' in non-final class 'A' must return 'Self' to conform to protocol 'P5'}} // P5a func f5a() -> A { return self } // expected-note {{'f5a()' declared here}} // P6 func f6() -> Self { return self } // P7 func f7() -> Int { return 5 } // P8 required init(int: Int) { } // P10 func f10(_ arr: [A]) { } // expected-error{{protocol 'P10' requirement 'f10' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}} // P10a func f10a(_ arr: [A]) { } // expected-note {{'f10a' declared here}} // P11 func f11() -> (_ x: A) -> Int { return { x in 5 } } } extension A: P2a, P5a, P10a {} // expected-error@-1 {{property 'prop2a' in non-final class 'A' must specify type 'Self' to conform to protocol 'P2a'}} // expected-error@-2 {{method 'f5a()' in non-final class 'A' must return 'Self' to conform to protocol 'P5a'}} // expected-error@-3 {{protocol 'P10a' requirement 'f10a' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}} // P9 func ==(x: A, y: A) -> Bool { return true } // Class B inherits A; gets all of its conformances. class B : A { required init(int: Int) { } } func testB(_ b: B) { var _: P1 = b // expected-error{{has Self or associated type requirements}} var _: P4 = b // expected-error{{has Self or associated type requirements}} var _: P5 = b var _: P6 = b var _: P7 = b // expected-error{{has Self or associated type requirements}} var _: P8 = b // okay var _: P9 = b // expected-error{{has Self or associated type requirements}} } // Class A5 conforms to P5 in an inheritable manner. class A5 : P5 { // P5 func f5() -> Self { return self } } // Class B5 inherits A5; gets all of its conformances. class B5 : A5 { } func testB5(_ b5: B5) { var _: P5 = b5 // okay } // Class A8 conforms to P8 in an inheritable manner. class A8 : P8 { required init(int: Int) { } } class B8 : A8 { required init(int: Int) { } } func testB8(_ b8: B8) { var _: P8 = b8 // okay } // Class A9 conforms to everything. final class A9 : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 { // P1 func f1(_ x: A9?) -> Bool { return true } // P2 var prop2: A9 { get { return self } set {} } // P3 subscript (i: Int) -> A9 { get { return self } } // P4 subscript (a: A9) -> Int { get { return 5 } } // P5 func f5() -> A9 { return self } // P6 func f6() -> Self { return self } // P7 func f7() -> Int { return 5 } // P8 required init(int: Int) { } // P10 func f10(_ arr: [A9]) { } // P11 func f11() -> (_ x: A9) -> Int { return { x in 5 } } } // P9 func ==(x: A9, y: A9) -> Bool { return true } class A12 : P12 { func f12(_ s: () -> (A12, A12)) {} } class A13 : P13 { func f13(_ s: (A13) -> ()) {} // expected-error{{protocol 'P13' requirement 'f13' cannot be satisfied by a non-final class ('A13') because it uses 'Self' in a non-parameter, non-result type position}} } class A14 : P14 { func f14(_ s: ((A14) -> ()) -> ()) {} } class A15 : P15 { func f15(_ s: (() -> A15) -> ()) {} // expected-error{{protocol 'P15' requirement 'f15' cannot be satisfied by a non-final class ('A15') because it uses 'Self' in a non-parameter, non-result type position}} }
03d70d77820c466af3d925e343e58cd4
21.957364
208
0.601722
false
false
false
false
Moriquendi/WWDC15-Portfolio
refs/heads/master
WWDC15/WWDC15/Code/Controllers/AGHacksViewController.swift
mit
1
// // AGHacksViewController.swift // WWDC15 // // Created by Michal Smialko on 25/04/15. // Copyright (c) 2015 Michal Smialko. All rights reserved. // import UIKit import MediaPlayer class AGHacksViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var logoView: UIImageView! let kImageCell = "kImageCell" @IBOutlet weak var movieContentView: UIView! var images = [] let moviePlayer: MPMoviePlayerController! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { let movieURL = NSBundle.mainBundle().URLForResource("aghacksPromo", withExtension: "mp4") self.moviePlayer = MPMoviePlayerController(contentURL: movieURL!) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { let movieURL = NSBundle.mainBundle().URLForResource("aghacksPromo", withExtension: "mp4") self.moviePlayer = MPMoviePlayerController(contentURL: movieURL!) super.init(coder: aDecoder) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.moviePlayer.pause() } override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.opaque = false self.logoView.layer.cornerRadius = self.logoView.bounds.size.width/2 let imagesNames = ["aghacksteam", "aghacks1", "aghacks2", "aghacks3", "aghacks4","aghacks5","aghacks6","aghacks7","aghacks8"] for name in imagesNames { self.images = self.images.arrayByAddingObject(UIImage(named: name)!) } self.navigationItem.leftBarButtonItem?.target = self self.navigationItem.leftBarButtonItem?.action = Selector("dismiss") self.movieContentView.addSubview(self.moviePlayer.view) self.moviePlayer.view.frame = self.movieContentView.bounds self.moviePlayer.view.autoresizingMask = .FlexibleWidth | .FlexibleHeight self.moviePlayer.play() } func dismiss() { self.dismissViewControllerAnimated(true, completion: nil) } // MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kImageCell, forIndexPath: indexPath) as! ImageCollectionViewCell cell.imageView.image = self.images[indexPath.item] as? UIImage return cell } }
57ed765c7efa7600ee67cf0c1d8b4748
34.666667
137
0.691935
false
false
false
false
GalinaCode/Nutriction-Cal
refs/heads/master
NutritionCal/Nutrition Cal/FullItemDetailsViewController.swift
apache-2.0
1
// // FullItemDetailsViewController.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // import UIKit import CoreData import HealthKit import MaterialDesignColor import RKDropdownAlert class FullItemDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating { var ndbItem: NDBItem! let healthStore = HealthStore.sharedInstance() var nutritionsArray: [NDBNutrient] = [] var filtredNutritionsArray: [NDBNutrient] = [] @IBOutlet weak var tableView: UITableView! var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() nutritionsArray = ndbItem.nutrients! tableView.delegate = self tableView.dataSource = self // UI customizations tabBarController?.tabBar.tintColor = MaterialDesignColor.green500 navigationController?.navigationBar.tintColor = MaterialDesignColor.green500 navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MaterialDesignColor.green500] // set the search controller searchController = UISearchController(searchResultsController: nil) searchController.delegate = self searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.sizeToFit() // UI customizations searchController.searchBar.tintColor = MaterialDesignColor.green500 let textFieldInsideSearchBar = searchController.searchBar.valueForKey("searchField") as? UITextField textFieldInsideSearchBar?.textColor = MaterialDesignColor.green500 searchController.searchBar.barTintColor = MaterialDesignColor.grey200 tableView.tableHeaderView = self.searchController.searchBar self.definesPresentationContext = true } // MARK: - Core Data Convenience // Shared Context from CoreDataStackManager var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext } func updateSearchResultsForSearchController(searchController: UISearchController) { let searchString = self.searchController.searchBar.text if searchString?.characters.count > 0 { filterContentForSearch(searchString!) } else { filtredNutritionsArray = nutritionsArray } tableView.reloadData() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FullItemDetailsViewControllerTableViewCell")! if searchController.active { cell.textLabel?.text = filtredNutritionsArray[indexPath.row].name let value = filtredNutritionsArray[indexPath.row].value! as Double let roundedValue = Double(round(1000*value)/1000) let valueText = "\(roundedValue) " + filtredNutritionsArray[indexPath.row].unit! cell.detailTextLabel?.text = valueText } else { cell.textLabel?.text = nutritionsArray[indexPath.row].name let value = nutritionsArray[indexPath.row].value! as Double let roundedValue = Double(round(1000*value)/1000) let valueText = "\(roundedValue) " + nutritionsArray[indexPath.row].unit! cell.detailTextLabel?.text = valueText } return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active { return filtredNutritionsArray.count } else { return nutritionsArray.count } } @IBAction func eatItBarButtonItemTapped(sender: UIBarButtonItem) { let alert = UIAlertController(title: "Select Size:", message: "\(ndbItem.name) has many sizes, Please choose one to eat/drink:", preferredStyle: .ActionSheet) let nutrients = ndbItem.nutrients for nutrient in nutrients! { if nutrient.id == 208 { for measure in nutrient.measures! { let action = UIAlertAction(title: measure.label!, style: .Default, handler: { (action) -> Void in let qtyAlert = UIAlertController(title: "Enter Quanitity", message: "How many \(measure.label!) did you eat/drink ?", preferredStyle: UIAlertControllerStyle.Alert) qtyAlert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.placeholder = "Enter quanitity" textField.keyboardType = UIKeyboardType.NumberPad textField.addTarget(self, action: "qtyTextChanged:", forControlEvents: .EditingChanged) }) qtyAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) let eatAction = UIAlertAction(title: "Eat!", style: .Default, handler: { (action) -> Void in let textField = qtyAlert.textFields?.first! if textField != nil { if let qty = Int(textField!.text!) { // create a DayEntry for the item eated dispatch_async(dispatch_get_main_queue()) { _ = DayEntry(item: self.ndbItem!, measure: measure, qty: qty, context: self.sharedContext) self.saveContext() // show eated dropdown alert dispatch_async(dispatch_get_main_queue()) { _ = RKDropdownAlert.title("Added", message: "", backgroundColor: MaterialDesignColor.green500, textColor: UIColor.whiteColor(), time: 2) } } if let healthStoreSync = NSUserDefaults.standardUserDefaults().valueForKey("healthStoreSync") as? Bool { if healthStoreSync { self.healthStore.addNDBItemToHealthStore(self.ndbItem, selectedMeasure: measure, qty: qty, completionHandler: { (success, errorString) -> Void in if success { dispatch_async(dispatch_get_main_queue()) { print("\(self.ndbItem.name) added to helth app") } } else { print(errorString!) self.presentMessage("Oops!", message: errorString!, action: "OK") } }) } } } } }) eatAction.enabled = false qtyAlert.addAction(eatAction) qtyAlert.view.tintColor = MaterialDesignColor.green500 dispatch_async(dispatch_get_main_queue()) { self.presentViewController(qtyAlert, animated: true, completion: nil) qtyAlert.view.tintColor = MaterialDesignColor.green500 } }) alert.addAction(action) } } } alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in })) alert.view.tintColor = MaterialDesignColor.green500 presentViewController(alert, animated: true, completion: nil) alert.view.tintColor = MaterialDesignColor.green500 } //MARK: - Helpers func filterContentForSearch (searchString: String) { filtredNutritionsArray = nutritionsArray.filter({ (nutrient) -> Bool in let nutrientMatch = nutrient.name!.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) return nutrientMatch != nil ? true : false }) } func qtyTextChanged(sender:AnyObject) { let tf = sender as! UITextField var resp : UIResponder = tf while !(resp is UIAlertController) { resp = resp.nextResponder()! } let alert = resp as! UIAlertController (alert.actions[1] as UIAlertAction).enabled = (tf.text != "") } func saveContext() { dispatch_async(dispatch_get_main_queue()) { CoreDataStackManager.sharedInstance().saveContext() } } }
7e73a461d3469b527e14444d19a7faae
30.441296
173
0.694952
false
false
false
false
yannickl/DynamicButton
refs/heads/master
Sources/DynamicButtonPathVector.swift
mit
1
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /** A path vector is a structure compound of 4 paths (p1, p2, p3, p4). It defines the geometric shape used to draw a `DynamicButton`. */ public struct DynamicButtonPathVector { /// The path p1. public let p1: CGPath /// The path p2. public let p2: CGPath /// The path p3. public let p3: CGPath /// The path p4. public let p4: CGPath /// Default constructor. public init(p1 : CGPath, p2 : CGPath, p3 : CGPath, p4 : CGPath) { self.p1 = p1 self.p2 = p2 self.p3 = p3 self.p4 = p4 } /// The path vectore whose each path are equals to zero. public static let zero: DynamicButtonPathVector = DynamicButtonPathVector(p1: CGMutablePath(), p2: CGMutablePath(), p3: CGMutablePath(), p4: CGMutablePath()) }
6a0c82e752b858dee37448d3f69eb6bb
34.2
159
0.722107
false
false
false
false
chenzhe555/core-ios-swift
refs/heads/master
core-ios-swift/Source/BaseHttpEncryption_s.swift
mit
1
// // BaseHttpEncryption_s.swift // core-ios-swift // // Created by 陈哲#[email protected] on 16/2/25. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit /** * 加密存放字典 */ let encryDictionary: NSMutableDictionary = [:]; /*加密的间隔符*/ let KEY_SEPARATOR = "="; let VALUE_SEPARATOR = "&"; let FINAL_SEPARATOR = "-"; class BaseHttpEncryption_s: NSObject { //MARK: 对外方法 /** 网络请求私钥数组 - returns: 私钥数组 */ class func setParametersArray() throws -> NSArray { throw BaseHttpErrorType_s.NotOverrideMethod_setParamater; } //MARK: 第一种加密方式 /** 类似微信支付后台接口的加密规则(目前不支持结构复杂的请求参数),如果要使用,请与后台协商公私钥。 - parameter parameters: 请求参数 - parameter keyArray: 加密的私钥 */ class func encrytionParameterMethod1(parameters: NSMutableDictionary,keyArray: NSArray) -> NSMutableDictionary { //添加盐和时间戳 srandom(UInt32(time(nil))); let index = random()%keyArray.count; parameters.setObject(String(index), forKey: "salt_index"); let timeStr = String(self.getTimeStamp()); parameters.setObject(timeStr, forKey: "time_stamp"); //加密 self.encryption(parameters) //拼接请求参数提取出的字符串 let mutaString: NSMutableString = self.appendItem(encryDictionary); mutaString.appendString(keyArray.objectAtIndex(index) as! String); let encrStr = MCEncryptionTool.MD5EncryptionToString(String(mutaString)); //拼接sign字符串 let signStr:NSMutableString = ""; signStr.appendString(encrStr); signStr.appendString(",\(index)"); signStr.appendString(",\(timeStr)"); parameters.setObject(signStr, forKey: "sign"); parameters.removeObjectForKey("salt_index"); parameters.removeObjectForKey("time_stamp"); return parameters; } /** 对参数进行加密(会额外添加sign参数) - parameter parameters: 待加密的参数 - returns: */ /** 对参数进行加密(会额外添加sign参数) :获取时间戳 - returns: */ private class func getTimeStamp() -> UInt64 { return UInt64((NSDate().timeIntervalSince1970)*1000); } /** 对参数进行加密(会额外添加sign参数) :拼接参数 - parameter encryptionDic: */ private class func encryption(encryptionDic: AnyObject) -> Void { let arr = encryptionDic.allKeys; for key in arr { let value = encryptionDic.objectForKey(key); if (value is NSArray) { self.encryptionArray(value as! NSArray, key: key as! String); } else if(value is NSDictionary) { self.encryption(value!); } else { if ((encryDictionary.objectForKey(key)) != nil) { let haveArray = encryDictionary.objectForKey(key) as! NSMutableArray; haveArray.addObject((value?.lowercaseString)!); encryDictionary.setObject(haveArray, forKey: key.lowercaseString); } else { let noArray:NSMutableArray = []; noArray.addObject((value?.lowercaseString)!); encryDictionary.setObject(noArray, forKey: key.lowercaseString); } } } } /** 对参数进行加密(会额外添加sign参数) :拼接参数 - parameter encryptionArray: value为数组的时候 - parameter key: key值 */ private class func encryptionArray(encryptionArray: NSArray,key:String) -> Void { for value in encryptionArray { if (value is NSArray) { self.encryptionArray(value as! NSArray, key: key); } else if (value is NSDictionary) { self.encryption(value); } else { if ((encryDictionary.objectForKey(key)) != nil) { let haveArray = encryDictionary.objectForKey(key) as! NSMutableArray; haveArray.addObject((value.lowercaseString)!); encryDictionary.setObject(haveArray, forKey: key.lowercaseString); } else { let noArray = NSMutableArray(); noArray.addObject((value.lowercaseString)!); encryDictionary.setObject(noArray, forKey: key.lowercaseString); } } } } /** 对参数进行加密(会额外添加sign参数) :附加拼接额外字段 - parameter totalDic: 待拼接字典 - returns: */ private class func appendItem(totalDic: NSMutableDictionary) -> NSMutableString { let arr = (totalDic.allKeys as NSArray).sortedArrayUsingSelector(Selector("compare:")); let mutaStr: NSMutableString = ""; for key in arr { mutaStr.appendString(key as! String); mutaStr.appendString(KEY_SEPARATOR); let valueArray = (totalDic.objectForKey(key) as! NSArray).sortedArrayUsingSelector(Selector("compare:")); let count = valueArray.count; for(var i = 0;i < count;++i) { mutaStr.appendString(valueArray[i] as! String); if (i != count - 1) { mutaStr.appendString(FINAL_SEPARATOR); } } mutaStr.appendString(VALUE_SEPARATOR); } mutaStr.deleteCharactersInRange(NSRange(location: mutaStr.length-1,length: 1)); return mutaStr; } //MARK: 第二种加密方式 }
79182f1c361bd64a0d1ea3f8b779481e
26.587678
117
0.535475
false
false
false
false
JGiola/swift
refs/heads/main
test/ClangImporter/objc_parse.swift
apache-2.0
3
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify -disable-experimental-clang-importer-diagnostics // REQUIRES: objc_interop import AppKit import AVFoundation import Newtype import NewtypeSystem import objc_ext import TestProtocols import TypeAndValue import ObjCParseExtras import ObjCParseExtrasToo import ObjCParseExtrasSystem func markUsed<T>(_ t: T) {} func testAnyObject(_ obj: AnyObject) { _ = obj.nsstringProperty } // Construction func construction() { _ = B() } // Subtyping func treatBAsA(_ b: B) -> A { return b } // Instance method invocation func instanceMethods(_ b: B) { var i = b.method(1, with: 2.5 as Float) i = i + b.method(1, with: 2.5 as Double) // BOOL b.setEnabled(true) // SEL b.perform(#selector(NSObject.isEqual(_:)), with: b) if let result = b.perform(#selector(B.getAsProto), with: nil) { _ = result.takeUnretainedValue() } // Renaming of redundant parameters. b.performAdd(1, withValue:2, withValue2:3, withValue:4) // expected-error{{argument 'withValue' must precede argument 'withValue2'}} {{32-32=withValue:4, }} {{44-57=}} b.performAdd(1, withValue:2, withValue:4, withValue2: 3) b.performAdd(1, 2, 3, 4) // expected-error{{missing argument labels 'withValue:withValue:withValue2:' in call}} {{19-19=withValue: }} {{22-22=withValue: }} {{25-25=withValue2: }} // Both class and instance methods exist. _ = b.description b.instanceTakesObjectClassTakesFloat(b) b.instanceTakesObjectClassTakesFloat(2.0) // Instance methods with keyword components var obj = NSObject() var prot = NSObjectProtocol.self b.`protocol`(prot, hasThing:obj) b.doThing(obj, protocol: prot) } // Class method invocation func classMethods(_ b: B, other: NSObject) { var i = B.classMethod() i += B.classMethod(1) i += B.classMethod(1, with: 2) i += b.classMethod() // expected-error{{static member 'classMethod' cannot be used on instance of type 'B'}} // Both class and instance methods exist. B.description() B.instanceTakesObjectClassTakesFloat(2.0) // TODO(diagnostics): Once argument/parameter conversion diagnostics are implemented we should be able to // diagnose this as failed conversion from NSObject to Float, but right now the problem is that there // exists another overload `instanceTakesObjectClassTakesFloat: (Any?) -> Void` which makes this invocation // type-check iff base is an instance of `B`. B.instanceTakesObjectClassTakesFloat(other) // expected-error@-1 {{instance member 'instanceTakesObjectClassTakesFloat' cannot be used on type 'B'; did you mean to use a value of this type instead?}} // Call an instance method of NSObject. var c: AnyClass = B.myClass() // no-warning c = b.myClass() // no-warning } // Instance method invocation on extensions func instanceMethodsInExtensions(_ b: B) { b.method(1, onCat1:2.5) b.method(1, onExtA:2.5) b.method(1, onExtB:2.5) b.method(1, separateExtMethod:3.5) let m1 = b.method(_:onCat1:) _ = m1(1, 2.5) let m2 = b.method(_:onExtA:) _ = m2(1, 2.5) let m3 = b.method(_:onExtB:) _ = m3(1, 2.5) let m4 = b.method(_:separateExtMethod:) _ = m4(1, 2.5) } func dynamicLookupMethod(_ b: AnyObject) { if let m5 = b.method(_:separateExtMethod:) { _ = m5(1, 2.5) } } // Properties func properties(_ b: B) { var i = b.counter b.counter = i + 1 i = i + b.readCounter b.readCounter = i + 1 // expected-error{{cannot assign to property: 'readCounter' is a get-only property}} b.setCounter(5) // expected-error{{value of type 'B' has no member 'setCounter'}} // Informal properties in Objective-C map to methods, not variables. b.informalProp() // An informal property cannot be made formal in a subclass. The // formal property is simply ignored. b.informalMadeFormal() b.informalMadeFormal = i // expected-error{{cannot assign to value: 'informalMadeFormal' is a method}} b.setInformalMadeFormal(5) b.overriddenProp = 17 // Dynamic properties. var obj : AnyObject = b var optStr = obj.nsstringProperty // optStr has type String?? if optStr != nil { var s : String = optStr! // expected-error{{value of optional type 'String?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} var t : String = optStr!! } // Properties that are Swift keywords var prot = b.`protocol` // Properties whose accessors run afoul of selector splitting. _ = SelectorSplittingAccessors() } // Construction. func newConstruction(_ a: A, aproxy: AProxy) { var b : B = B() b = B(int: 17) b = B(int:17) b = B(double:17.5, 3.14159) b = B(bbb:b) b = B(forWorldDomination:()) b = B(int: 17, andDouble : 3.14159) b = B.new(with: a) B.alloc()._initFoo() b.notAnInit() // init methods are not imported by themselves. b.initWithInt(17) // expected-error{{value of type 'B' has no member 'initWithInt'}} // init methods on non-NSObject-rooted classes AProxy(int: 5) // expected-warning{{unused}} } // Indexed subscripting func indexedSubscripting(_ b: B, idx: Int, a: A) { b[idx] = a _ = b[idx] as! A } // Keyed subscripting func keyedSubscripting(_ b: B, idx: A, a: A) { b[a] = a var a2 = b[a] as! A let dict = NSMutableDictionary() dict[NSString()] = a let value = dict[NSString()] // notes attached to the partially matching declarations for both following subscripts: // - override subscript(_: Any) -> Any? -> 'nil' is not compatible with expected argument type 'Any' at position #1 // - open subscript(key: NSCopying) -> Any? { get set } -> 'nil' is not compatible with expected argument type 'NSCopying' at position #1 dict[nil] = a // expected-error {{no exact matches in call to subscript}} let q = dict[nil] // expected-error {{no exact matches in call to subscript}} _ = q } // Typed indexed subscripting func checkHive(_ hive: Hive, b: Bee) { let b2 = hive.bees[5] as Bee b2.buzz() } // Protocols func testProtocols(_ b: B, bp: BProto) { var bp2 : BProto = b var b2 : B = bp // expected-error{{cannot convert value of type 'any BProto' to specified type 'B'}} bp.method(1, with: 2.5 as Float) bp.method(1, withFoo: 2.5) // expected-error{{incorrect argument label in call (have '_:withFoo:', expected '_:with:')}} bp2 = b.getAsProto() var c1 : Cat1Proto = b var bcat1 = b.getAsProtoWithCat()! c1 = bcat1 bcat1 = c1 // expected-error{{value of type 'any Cat1Proto' does not conform to 'BProto' in assignment}} } // Methods only defined in a protocol func testProtocolMethods(_ b: B, p2m: P2.Type) { b.otherMethod(1, with: 3.14159) b.p2Method() b.initViaP2(3.14159, second: 3.14159) // expected-error{{value of type 'B' has no member 'initViaP2'}} // Imported constructor. var b2 = B(viaP2: 3.14159, second: 3.14159) _ = p2m.init(viaP2:3.14159, second: 3.14159) } func testId(_ x: AnyObject) { x.perform!("foo:", with: x) // expected-warning{{no method declared with Objective-C selector 'foo:'}} // expected-warning @-1 {{result of call to function returning 'Unmanaged<AnyObject>?' is unused}} _ = x.performAdd(1, withValue: 2, withValue: 3, withValue2: 4) _ = x.performAdd!(1, withValue: 2, withValue: 3, withValue2: 4) _ = x.performAdd?(1, withValue: 2, withValue: 3, withValue2: 4) } class MySubclass : B { // Override a regular method. override func anotherMethodOnB() {} // Override a category method override func anotherCategoryMethod() {} } func getDescription(_ array: NSArray) { _ = array.description } // Method overriding with unfortunate ordering. func overridingTest(_ srs: SuperRefsSub) { let rs : RefedSub rs.overridden() } func almostSubscriptableValueMismatch(_ as1: AlmostSubscriptable, a: A) { as1[a] // expected-error{{value of type 'AlmostSubscriptable' has no subscripts}} } func almostSubscriptableKeyMismatch(_ bc: BadCollection, key: NSString) { // FIXME: We end up importing this as read-only due to the mismatch between // getter/setter element types. var _ : Any = bc[key] } func almostSubscriptableKeyMismatchInherited(_ bc: BadCollectionChild, key: String) { var value : Any = bc[key] bc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } func almostSubscriptableKeyMismatchInherited(_ roc: ReadOnlyCollectionChild, key: String) { var value : Any = roc[key] roc[key] = value // expected-error{{cannot assign through subscript: subscript is get-only}} } // Use of 'Class' via dynamic lookup. func classAnyObject(_ obj: NSObject) { _ = obj.myClass().description!() } // Protocol conformances class Wobbler : NSWobbling { @objc func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler : NSMaybeInitWobble { // expected-error{{type 'Wobbler' does not conform to protocol 'NSMaybeInitWobble'}} } @objc class Wobbler2 : NSObject, NSWobbling { func wobble() { } func returnMyself() -> Self { return self } } extension Wobbler2 : NSMaybeInitWobble { // expected-error{{type 'Wobbler2' does not conform to protocol 'NSMaybeInitWobble'}} } func optionalMemberAccess(_ w: NSWobbling) { w.wobble() w.wibble() // expected-error{{value of optional type '(() -> Void)?' must be unwrapped to a value of type '() -> Void'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let x = w[5]!! _ = x } func protocolInheritance(_ s: NSString) { var _: NSCoding = s } func ivars(_ hive: Hive) { var d = hive.bees.description hive.queen.description() // expected-error{{value of type 'Hive' has no member 'queen'}} } class NSObjectable : NSObjectProtocol { // expected-error {{cannot declare conformance to 'NSObjectProtocol' in Swift; 'NSObjectable' should inherit 'NSObject' instead}} @objc var description : String { return "" } @objc(conformsToProtocol:) func conforms(to _: Protocol) -> Bool { return false } @objc(isKindOfClass:) func isKind(of aClass: AnyClass) -> Bool { return false } } // Properties with custom accessors func customAccessors(_ hive: Hive, bee: Bee) { markUsed(hive.isMakingHoney) markUsed(hive.makingHoney()) // expected-error{{cannot call value of non-function type 'Bool'}}{{28-30=}} hive.setMakingHoney(true) // expected-error{{value of type 'Hive' has no member 'setMakingHoney'}} _ = (hive.`guard` as AnyObject).description // okay _ = (hive.`guard` as AnyObject).description! // no-warning hive.`guard` = bee // no-warning } // instancetype/Dynamic Self invocation. func testDynamicSelf(_ queen: Bee, wobbler: NSWobbling) { var hive = Hive() // Factory method with instancetype result. var hive1 = Hive(queen: queen) hive1 = hive hive = hive1 // Instance method with instancetype result. var hive2 = hive!.visit() hive2 = hive hive = hive2 // Instance method on a protocol with instancetype result. var wobbler2 = wobbler.returnMyself()! var wobbler: NSWobbling = wobbler2 wobbler2 = wobbler // Instance method on a base class with instancetype result, called on the // class itself. // FIXME: This should be accepted. let baseClass: ObjCParseExtras.Base.Type = ObjCParseExtras.Base.returnMyself() // expected-error@-1 {{instance member 'returnMyself' cannot be used on type 'Base'; did you mean to use a value of this type instead?}} // expected-error@-2 {{cannot convert value of type 'Base?' to specified type 'Base.Type'}} } func testRepeatedProtocolAdoption(_ w: NSWindow) { _ = w.description } class ProtocolAdopter1 : FooProto { @objc var bar: CInt // no-warning init() { bar = 5 } } class ProtocolAdopter2 : FooProto { @objc var bar: CInt { get { return 42 } set { /* do nothing! */ } } } class ProtocolAdopterBad1 : FooProto { // expected-error {{type 'ProtocolAdopterBad1' does not conform to protocol 'FooProto'}} @objc var bar: Int = 0 // expected-note {{candidate has non-matching type 'Int'}} } class ProtocolAdopterBad2 : FooProto { // expected-error {{type 'ProtocolAdopterBad2' does not conform to protocol 'FooProto'}} let bar: CInt = 0 // expected-note {{candidate is not settable, but protocol requires it}} } class ProtocolAdopterBad3 : FooProto { // expected-error {{type 'ProtocolAdopterBad3' does not conform to protocol 'FooProto'}} var bar: CInt { // expected-note {{candidate is not settable, but protocol requires it}} return 42 } } @objc protocol RefinedFooProtocol : FooProto {} func testPreferClassMethodToCurriedInstanceMethod(_ obj: NSObject) { // FIXME: We shouldn't need the ": Bool" type annotation here. // <rdar://problem/18006008> let _: Bool = NSObject.isEqual(obj) _ = NSObject.isEqual(obj) as (NSObject?) -> Bool // no-warning } func testPropertyAndMethodCollision(_ obj: PropertyAndMethodCollision, rev: PropertyAndMethodReverseCollision) { obj.object = nil obj.object(obj, doSomething:#selector(getter: NSMenuItem.action)) type(of: obj).classRef = nil type(of: obj).classRef(obj, doSomething:#selector(getter: NSMenuItem.action)) rev.object = nil rev.object(rev, doSomething:#selector(getter: NSMenuItem.action)) type(of: rev).classRef = nil type(of: rev).classRef(rev, doSomething:#selector(getter: NSMenuItem.action)) var value: Any value = obj.protoProp() value = obj.protoPropRO() value = type(of: obj).protoClassProp() value = type(of: obj).protoClassPropRO() _ = value } func testPropertyAndMethodCollisionInOneClass( obj: PropertyAndMethodCollisionInOneClass, rev: PropertyAndMethodReverseCollisionInOneClass ) { obj.object = nil obj.object() type(of: obj).classRef = nil type(of: obj).classRef() rev.object = nil rev.object() type(of: rev).classRef = nil type(of: rev).classRef() } func testSubscriptAndPropertyRedeclaration(_ obj: SubscriptAndProperty) { _ = obj.x obj.x = 5 _ = obj.objectAtIndexedSubscript(5) // expected-error{{'objectAtIndexedSubscript' is unavailable: use subscripting}} obj.setX(5) // expected-error{{value of type 'SubscriptAndProperty' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testSubscriptAndPropertyWithProtocols(_ obj: SubscriptAndPropertyWithProto) { _ = obj.x obj.x = 5 obj.setX(5) // expected-error{{value of type 'SubscriptAndPropertyWithProto' has no member 'setX'}} _ = obj[0] obj[1] = obj obj.setObject(obj, atIndexedSubscript: 2) // expected-error{{'setObject(_:atIndexedSubscript:)' is unavailable: use subscripting}} } func testProtocolMappingSameModule(_ obj: AVVideoCompositionInstruction, p: AVVideoCompositionInstructionProtocol) { markUsed(p.enablePostProcessing) markUsed(obj.enablePostProcessing) _ = obj.backgroundColor } func testProtocolMappingDifferentModules(_ obj: ObjCParseExtrasToo.ProtoOrClass, p: ObjCParseExtras.ProtoOrClass) { markUsed(p.thisIsTheProto) markUsed(obj.thisClassHasAnAwfulName) let _: ProtoOrClass? // expected-error{{'ProtoOrClass' is ambiguous for type lookup in this context}} _ = ObjCParseExtrasToo.ClassInHelper() // expected-error{{'any ClassInHelper' cannot be constructed because it has no accessible initializers}} _ = ObjCParseExtrasToo.ProtoInHelper() _ = ObjCParseExtrasTooHelper.ClassInHelper() _ = ObjCParseExtrasTooHelper.ProtoInHelper() // expected-error{{'any ProtoInHelper' cannot be constructed because it has no accessible initializers}} } func testProtocolClassShadowing(_ obj: ClassInHelper, p: ProtoInHelper) { let _: ObjCParseExtrasToo.ClassInHelper = obj let _: ObjCParseExtrasToo.ProtoInHelper = p } func testDealloc(_ obj: NSObject) { // dealloc is subsumed by deinit. obj.dealloc() // expected-error{{'dealloc()' is unavailable in Swift: use 'deinit' to define a de-initializer}} } func testConstantGlobals() { markUsed(MAX) markUsed(SomeImageName) markUsed(SomeNumber.description) MAX = 5 // expected-error{{cannot assign to value: 'MAX' is a 'let' constant}} SomeImageName = "abc" // expected-error{{cannot assign to value: 'SomeImageName' is a 'let' constant}} SomeNumber = nil // expected-error{{cannot assign to value: 'SomeNumber' is a 'let' constant}} } func testWeakVariable() { let _: AnyObject = globalWeakVar } class IncompleteProtocolAdopter : Incomplete, IncompleteOptional { // expected-error {{type 'IncompleteProtocolAdopter' cannot conform to protocol 'Incomplete' because it has requirements that cannot be satisfied}} @objc func getObject() -> AnyObject { return self } } func testNullarySelectorPieces(_ obj: AnyObject) { obj.foo(1, bar: 2, 3) // no-warning obj.foo(1, 2, bar: 3) // expected-error{{argument 'bar' must precede unnamed argument #2}} } func testFactoryMethodAvailability() { _ = DeprecatedFactoryMethod() // expected-warning{{'init()' is deprecated: use something newer}} } func testRepeatedMembers(_ obj: RepeatedMembers) { obj.repeatedMethod() } // rdar://problem/19726164 class FooDelegateImpl : NSObject, FooDelegate { var _started = false var isStarted: Bool { get { return _started } @objc(setStarted:) set { _started = newValue } } } class ProtoAdopter : NSObject, ExplicitSetterProto, OptionalSetterProto { var foo: Any? // no errors about conformance var bar: Any? // no errors about conformance } func testUnusedResults(_ ur: UnusedResults) { _ = ur.producesResult() ur.producesResult() // expected-warning{{result of call to 'producesResult()' is unused}} } func testStrangeSelectors(obj: StrangeSelectors) { StrangeSelectors.cStyle(0, 1, 2) // expected-error{{type 'StrangeSelectors' has no member 'cStyle'}} _ = StrangeSelectors(a: 0, b: 0) // okay obj.empty(1, 2) // okay } func testProtocolQualified(_ obj: CopyableNSObject, cell: CopyableSomeCell, plainObj: NSObject, plainCell: SomeCell) { _ = obj as NSObject // expected-error {{'CopyableNSObject' (aka 'any NSCopying & NSObjectProtocol') is not convertible to 'NSObject'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = obj as NSObjectProtocol _ = obj as NSCopying _ = obj as SomeCell // expected-error {{'CopyableNSObject' (aka 'any NSCopying & NSObjectProtocol') is not convertible to 'SomeCell'}} // expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{11-13=as!}} _ = cell as NSObject _ = cell as NSObjectProtocol _ = cell as NSCopying _ = cell as SomeCell _ = plainObj as CopyableNSObject // expected-error {{cannot convert value of type 'NSObject' to type 'CopyableNSObject' (aka 'any NSCopying & NSObjectProtocol') in coercion}} _ = plainCell as CopyableSomeCell // expected-error {{cannot convert value of type 'SomeCell' to type 'CopyableSomeCell' (aka 'any SomeCell & NSCopying') in coercion}} } extension Printing { func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to instance method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } static func testImplicitWarnUnqualifiedAccess() { print() // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self) // expected-warning {{use of 'print' treated as a reference to class method in class 'Printing'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Swift.' to reference the global function}} {{5-5=Swift.}} print(self, options: self) // no-warning } } // <rdar://problem/21979968> The "with array" initializers for NSCountedSet and NSMutable set should be properly disambiguated. func testSetInitializers() { let a: [AnyObject] = [NSObject()] let _ = NSCountedSet(array: a) let _ = NSMutableSet(array: a) } func testNSUInteger(_ obj: NSUIntegerTests, uint: UInt, int: Int) { obj.consumeUnsigned(uint) // okay obj.consumeUnsigned(int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(0, withTheNSUIntegerHere: int) // okay obj.consumeUnsigned(uint, andAnother: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.consumeUnsigned(uint, andAnother: int) // okay do { let x = obj.unsignedProducer() let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.unsignedProducer(uint, fromCount: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.unsignedProducer(int, fromCount: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.unsignedProducer(uint, fromCount: int) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } do { obj.normalProducer(uint, fromUnsigned: uint) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}} obj.normalProducer(int, fromUnsigned: int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = obj.normalProducer(int, fromUnsigned: uint) let _: String = x // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} } let _: String = obj.normalProp // expected-error {{cannot convert value of type 'Int' to specified type 'String'}} let _: String = obj.unsignedProp // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} do { testUnsigned(int, uint) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} testUnsigned(uint, int) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} let x = testUnsigned(uint, uint) // okay let _: String = x // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } // NSNumber let num = NSNumber(value: uint) let _: String = num.uintValue // expected-error {{cannot convert value of type 'UInt' to specified type 'String'}} } class NewtypeUser { @objc func stringNewtype(a: SNTErrorDomain) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{31-45=ErrorDomain}} @objc func stringNewtypeOptional(a: SNTErrorDomain?) {} // expected-error {{'SNTErrorDomain' has been renamed to 'ErrorDomain'}}{{39-53=ErrorDomain}} @objc func intNewtype(a: MyInt) {} @objc func intNewtypeOptional(a: MyInt?) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func intNewtypeArray(a: [MyInt]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func intNewtypeDictionary(a: [MyInt: NSObject]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc func cfNewtype(a: CFNewType) {} @objc func cfNewtypeArray(a: [CFNewType]) {} // expected-error {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} typealias MyTuple = (Int, AnyObject?) typealias MyNamedTuple = (a: Int, b: AnyObject?) @objc func blockWithTypealias(_ input: @escaping (MyTuple) -> MyInt) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{function types cannot be represented in Objective-C}} @objc func blockWithTypealiasWithNames(_ input: (MyNamedTuple) -> MyInt) {} // expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{function types cannot be represented in Objective-C}} } func testTypeAndValue() { _ = testStruct() _ = testStruct(value: 0) let _: (testStruct) -> Void = testStruct let _: () -> testStruct = testStruct.init let _: (CInt) -> testStruct = testStruct.init } // rdar://problem/34913507 func testBridgedTypedef(bt: BridgedTypedefs) { let _: Int = bt.arrayOfArrayOfStrings // expected-error{{'[[String]]'}} } func testBridgeFunctionPointerTypedefs(fptrTypedef: FPTypedef) { // See also print_clang_bool_bridging.swift. let _: Int = fptrTypedef // expected-error{{'@convention(c) (String) -> String'}} let _: Int = getFP() // expected-error{{'@convention(c) (String) -> String'}} } func testNonTrivialStructs() { _ = NonTrivialToCopy() // expected-error {{cannot find 'NonTrivialToCopy' in scope}} _ = NonTrivialToCopyWrapper() // expected-error {{cannot find 'NonTrivialToCopyWrapper' in scope}} _ = TrivialToCopy() // okay } func testErrorNewtype() { _ = ErrorNewType(3) // expected-error {{argument type 'Int' does not conform to expected type 'Error'}} // Since we import NSError as Error, and Error is not Hashable...we end up // losing the types for these functions, even though the above assignment // works. testErrorDictionary(3) // expected-error {{cannot convert value of type 'Int' to expected argument type '[AnyHashable : String]'}} testErrorDictionaryNewtype(3) // expected-error {{cannot convert value of type 'Int' to expected argument type '[AnyHashable : String]'}} } func testNSUIntegerNewtype() { let _: NSUIntegerNewType = NSUIntegerNewType(4) let _: UInt = NSUIntegerNewType(4).rawValue let _: NSUIntegerNewType = NSUIntegerNewType.constant let _: NSUIntegerSystemNewType = NSUIntegerSystemNewType(4) let _: Int = NSUIntegerSystemNewType(4).rawValue let _: NSUIntegerSystemNewType = NSUIntegerSystemNewType.constant }
7199b0d86b1bdf6d7fc1fb8a629130b0
36.701556
214
0.701332
false
true
false
false
puyanLiu/LPYFramework
refs/heads/master
第三方框架改造/pull-to-refresh-master/ESPullToRefreshExample/ESPullToRefreshExample/Custom/Meituan/QQMRefreshFooterAnimator.swift
apache-2.0
1
// // QQMRefreshFooterAnimator.swift // ESPullToRefreshExample // // Created by liupuyan on 2017/6/8. // Copyright © 2017年 egg swift. All rights reserved. // import UIKit class QQMRefreshFooterAnimator: UIView, ESRefreshProtocol, ESRefreshAnimatorProtocol { open var loadingMoreDescription: String = NSLocalizedString("上拉加载更多数据", comment: "") open var noMoreDataDescription: String = NSLocalizedString("No more data", comment: "") open var loadingDescription: String = NSLocalizedString("正在加载更多数据...", comment: "") open var view: UIView { return self } open var duration: TimeInterval = 0.3 open var insets: UIEdgeInsets = UIEdgeInsets.zero open var trigger: CGFloat = 42.0 open var executeIncremental: CGFloat = 42.0 open var state: ESRefreshViewState = .pullToRefresh fileprivate let titleLabel: UILabel = { let label = UILabel.init(frame: CGRect.zero) label.font = UIFont.systemFont(ofSize: 14.0) label.textColor = UIColor.init(white: 160.0 / 255.0, alpha: 1.0) label.textAlignment = .center return label }() fileprivate let indicatorView: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray) indicatorView.isHidden = true return indicatorView }() public override init(frame: CGRect) { super.init(frame: frame) titleLabel.text = loadingMoreDescription addSubview(titleLabel) addSubview(indicatorView) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func refreshAnimationBegin(view: ESRefreshComponent) { indicatorView.startAnimating() titleLabel.text = loadingDescription indicatorView.isHidden = false } open func refreshAnimationEnd(view: ESRefreshComponent) { indicatorView.stopAnimating() titleLabel.text = loadingMoreDescription indicatorView.isHidden = true } open func refresh(view: ESRefreshComponent, progressDidChange progress: CGFloat) { // do nothing } open func refresh(view: ESRefreshComponent, stateDidChange state: ESRefreshViewState) { guard self.state != state else { return } self.state = state switch state { case .refreshing, .autoRefreshing : titleLabel.text = loadingDescription break case .noMoreData: titleLabel.text = noMoreDataDescription break case .pullToRefresh: titleLabel.text = loadingMoreDescription break default: break } self.setNeedsLayout() } open override func layoutSubviews() { super.layoutSubviews() let s = self.bounds.size let w = s.width let h = s.height titleLabel.sizeToFit() titleLabel.center = CGPoint.init(x: w / 2.0, y: h / 2.0 - 5.0) indicatorView.center = CGPoint.init(x: titleLabel.frame.origin.x - 18.0, y: titleLabel.center.y) } }
94063c7f44853115de7954e42b7cecd9
31.520408
104
0.643238
false
false
false
false
hardikdevios/HKKit
refs/heads/master
Pod/Classes/HKExtensions/UIKit+Extensions/UIButton+Extension.swift
mit
1
// // UIButton+Extension.swift // HKCustomization // // Created by Hardik on 10/18/15. // Copyright © 2015 . All rights reserved. // import UIKit extension UIButton{ public func hk_toggleOnOff()->Void{ self.isSelected = !self.isSelected; } public func hk_setDisableWithAlpha(_ isDisable:Bool){ if isDisable { self.isEnabled = false self.alpha = 0.5 }else{ self.isEnabled = true self.alpha = 1.0 } } public func hk_appleBootStrapTheme(_ color:UIColor = HKConstant.sharedInstance.main_color){ self.layer.borderWidth = 1 self.layer.cornerRadius = 2 self.layer.borderColor = color.cgColor self.setTitleColor(color, for: UIControl.State()) } public func hk_setAttributeString(_ mainString:String,attributeString:String,attributes:[NSAttributedString.Key:Any]){ let result = hk_getAttributeString(mainString, attributeString: attributeString, attributes: attributes) self.setAttributedTitle(result, for: .normal) } public func hk_setAttributesString(_ mainString:String,attributeStrings:[String],total_attributes:[[NSAttributedString.Key:Any]]) { let result = hk_getMultipleAttributesString(mainString, attributeStrings: attributeStrings, total_attributes: total_attributes) self.setAttributedTitle(result, for: .normal) } }
38bb6d055589e65c21e0119d1b413bf3
29.326531
135
0.646703
false
true
false
false
insidegui/WWDC
refs/heads/master
WWDC/WWDCImageView.swift
bsd-2-clause
1
// // WWDCImageView.swift // WWDC // // Created by Guilherme Rambo on 14/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa // See: // https://forums.developer.apple.com/thread/79144 // https://stackoverflow.com/q/44537356/3927536 #if swift(>=4.0) let NSURLPboardType = NSPasteboard.PasteboardType(kUTTypeURL as String) let NSFilenamesPboardType = NSPasteboard.PasteboardType("NSFilenamesPboardType") #endif protocol WWDCImageViewDelegate: AnyObject { func wwdcImageView(_ imageView: WWDCImageView, didReceiveNewImageWithFileURL url: URL) } class WWDCImageView: NSView { weak var delegate: WWDCImageViewDelegate? var cornerRadius: CGFloat = 4 { didSet { guard cornerRadius != oldValue else { return } updateCorners() } } var drawsBackground = true { didSet { backgroundLayer.isHidden = !drawsBackground } } override var isOpaque: Bool { drawsBackground && cornerRadius.isZero } var backgroundColor: NSColor = .clear { didSet { backgroundLayer.backgroundColor = backgroundColor.cgColor } } @objc var isEditable: Bool = false { didSet { if isEditable { registerForDraggedTypes([NSURLPboardType, NSFilenamesPboardType]) } else { unregisterDraggedTypes() } } } var image: NSImage? = nil { didSet { imageLayer.contents = image } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) buildUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var backgroundLayer: WWDCLayer = { let l = WWDCLayer() l.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] return l }() private(set) lazy var imageLayer: WWDCLayer = { let l = WWDCLayer() l.contentsGravity = .resizeAspect l.autoresizingMask = [.layerWidthSizable, .layerHeightSizable] l.zPosition = 1 return l }() private func buildUI() { wantsLayer = true layer?.masksToBounds = true layer?.cornerCurve = .continuous backgroundLayer.frame = bounds imageLayer.frame = bounds layer?.addSublayer(backgroundLayer) layer?.addSublayer(imageLayer) updateCorners() } override func makeBackingLayer() -> CALayer { return WWDCLayer() } // MARK: - Editing override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { return .copy } override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { guard let file = (sender.draggingPasteboard.propertyList(forType: NSFilenamesPboardType) as? [String])?.first else { return false } let fileURL = URL(fileURLWithPath: file) guard let image = NSImage.thumbnailImage(with: fileURL, maxWidth: 400) else { return false } self.image = image delegate?.wwdcImageView(self, didReceiveNewImageWithFileURL: fileURL) return true } private func updateCorners() { layer?.cornerRadius = cornerRadius } }
cd3ded6deba75d70bc4550a53f9c6326
23.057971
139
0.62741
false
false
false
false
QuStudio/Vocabulaire
refs/heads/master
Sources/Vocabulaire/User.swift
mit
1
// // User.swift // Vocabulaire // // Created by Oleg Dreyman on 23.03.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // /// Basic entity which represents a user of Qubular. public struct User { /// User identifier. public let id: Int /// Username. public let username: String /// Determines user privileges and access level. public let status: Status public init(id: Int, username: String, status: Status) { self.id = id self.username = username self.status = status } #if swift(>=3.0) public enum Status { case regular case boardMember } #else public enum Status { case Regular case BoardMember } #endif } extension User: Equatable { } public func == (left: User, right: User) -> Bool { return left.id == right.id && left.username == right.username && left.status == right.status }
0b96a0c332d4ee5dc5bc4f9183a420dc
20.930233
96
0.602972
false
false
false
false
BMWB/RRArt-Swift-Test
refs/heads/master
Example/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallBeat.swift
apache-2.0
5
// // NVActivityIndicatorAnimationBallBeat.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallBeat: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - circleSize) / 2 let duration: CFTimeInterval = 0.7 let beginTime = CACurrentMediaTime() let beginTimes = [0.35, 0, 0.35] // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [1, 0.75, 1] scaleAnimation.duration = duration // Opacity animation let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.5, 1] opacityAnimation.values = [1, 0.2, 1] opacityAnimation.duration = duration // Aniamtion let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false // Draw circles for i in 0 ..< 3 { let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize) animation.beginTime = beginTime + beginTimes[i] circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } } }
9a293a821a05dbbd4fdc088ce6d9fcb4
36.305085
139
0.622444
false
false
false
false
customerly/Customerly-iOS-SDK
refs/heads/master
CustomerlySDK/Library/CyMapping.swift
apache-2.0
1
// // CyMapping.swift // Customerly // // Created by Paolo Musolino on 14/10/16. // // import Foundation //MARK: - CyMapping Utils //Parse Dictionary from JSON Data func JSONParseDictionary(data: Data?) -> [String:Any]{ if data != nil{ do{ if let dictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]{ return dictionary } } catch{ cyPrint("Error! Could not create Dictionary from JSON Data.") } } return [String: Any]() } //Parse Array from JSON Data func JSONParseArray(data: Data?) -> [AnyObject]{ if data != nil{ do{ if let array = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [AnyObject] { return array } }catch{ cyPrint("Error! Could not create Array from JSON Data.") } } return [AnyObject]() } //From dictionary to json string func DictionaryToJSONString(dictionary: [String: Any]) -> String?{ let jsonData: Data? = try? JSONSerialization.data(withJSONObject: dictionary, options: JSONSerialization.WritingOptions.prettyPrinted) if let data = jsonData{ return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? } return nil }
38166ec73d1101c4f223c101dab8ae48
25.454545
157
0.62268
false
false
false
false
oisdk/Boolean
refs/heads/master
Bool/Bool/Factorise.swift
mit
2
extension Expr { var factorised: Expr { switch self { case let .OR(x): let (a,b) = x.partition { e -> Either<Set<Expr>,Expr> in if case let .AND(y) = e { return .Left(y) } else { return .Right(e) } } guard let c = a.lazy.flatten().mostFrequent else { return .OR(Set(b)) } let (d,e) = a.partition { (var s) -> Either<Set<Expr>,Set<Expr>> in if let _ = s.remove(c) { return .Left(s) } else { return .Right(s) } } return e.reduce(false) { (a,b) in a || b.reduce(true, combine: &&) } || (c && d.reduce(false) { (a,b) in a || b.reduce(true, combine: &&) }.factorised) default: return self } } }
2f3af3deaedefdcc956c92ad172f5f73
31.454545
87
0.504909
false
false
false
false
Jvaeyhcd/NavTabBarController
refs/heads/master
NavTabBarController/SlippedSegmentItem.swift
mit
1
// // SlippedSegmentItem.swift // govlan // // Created by polesapp-hcd on 2016/11/2. // Copyright © 2016年 Polesapp. All rights reserved. // import UIKit class SlippedSegmentItem: UIButton { var index: Int = 0 private var title: String? private var titleColor: UIColor? private var titleSelectedColor: UIColor? private var titleFont: UIFont? // MARK: - Set private property func setTitle(title: String) { self.title = title self.setTitle(self.title, for: .normal) } func setTitleColor(titleColor: UIColor) { self.titleColor = titleColor self.setTitleColor(self.titleColor, for: .normal) } func setTitleSelectedColor(titleSelectedColor: UIColor) { self.titleSelectedColor = titleSelectedColor self.setTitleColor(self.titleSelectedColor, for: .selected) } func setTitleFont(titleFont: UIFont) { self.titleFont = titleFont self.titleLabel?.font = self.titleFont } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
ed176efa1670462103fd337f62b47500
24.068966
79
0.636176
false
false
false
false
v-andr/LakestoneCore
refs/heads/master
Source/Threading.swift
apache-2.0
1
// // Threading.swift // geoBingAnCore // // Created by Taras Vozniuk on 6/7/16. // Copyright © 2016 GeoThings. 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. // // // Threading-related set of abstractions // The abstractions is alligned to correspond to PerfectThread API naming // // PerfectThread.Threading.Lock has been coppied here to provide the corresponding // iOS Lock implementation for a sake of not having PerfectThread as iOS dependency // #if COOPER import android.os import java.util.concurrent #else import Foundation import PerfectThread #if !os(Linux) import Dispatch #endif #endif #if COOPER public typealias ThreadQueue = ExecutorService #elseif os(iOS) || os(watchOS) || os(tvOS) public typealias ThreadQueue = DispatchQueue #else // for OSX and Linux PerfectThread.ThreadQueue corresponding type is used #endif /// Executes the closure synchronized on given reentrant mutual exlusion lock public func synchronized(on lock: Threading.Lock, closure: () -> Void){ lock.lock() closure() lock.unlock() } #if COOPER public class Threading { internal class _Runnable: Runnable { let callback: () -> Void init(callback: () -> Void){ self.callback = callback } public func run() { callback() } } public class func dispatchOnMainQueue(_ closure: @escaping () -> Void){ Handler(Looper.getMainLooper()).post(_Runnable(callback: closure)) } } extension ThreadQueue { public func dispatch(_ closure: @escaping () -> Void){ self.execute(Threading._Runnable(callback: closure)) } } #elseif os(iOS) || os(watchOS) || os(tvOS) public class Threading {} extension ThreadQueue { public func dispatch(_ closure: @escaping () -> Void){ self.async(execute: closure) } } #endif #if !COOPER && !os(Linux) extension Threading { public static func dispatchOnMainQueue(_ closure: @escaping () -> Void){ DispatchQueue.main.async(execute: closure) } } #endif public extension Threading { #if COOPER // ReentrantLock provides the corresponding functionaly with matching lock()/tryLock()/unlock() naming public typealias Lock = java.util.concurrent.locks.ReentrantLock #elseif os(iOS) || os(watchOS) || os(tvOS) public typealias Lock = PerfectThread.Threading.Lock #endif } extension Threading { /// creates a new serial queue, exception is Linux/OSX, /// where if queue with a given label exists already, existing queue will be returned public static func serialQueue(withLabel label: String) -> ThreadQueue { #if COOPER return Executors.newSingleThreadExecutor() #elseif os(Linux) || os(OSX) return Threading.getQueue(name: label, type: .serial) #else return DispatchQueue(label: label, qos: DispatchQoS.default) #endif } }
56ee55697095b96019226d0019bbff15
23.583942
103
0.704572
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 2 - Robot Maze 2/Branching with If Statements/Bouncer_complete.playground/Contents.swift
mit
1
//:If Statements Exercise: The Bouncer! // Here's the struct the represents the people who want to come in to the club struct Clubgoer { var name: String var age: Int var onGuestList: Bool init(name: String, age:Int, onGuestList: Bool){ self.name = name self.age = age self.onGuestList = onGuestList } } // Here are the people who want to come in. var ayush = Clubgoer(name: "Ayush", age: 19, onGuestList: true) var gabrielle = Clubgoer(name: "Gabrielle", age: 29, onGuestList: true) var chris = Clubgoer(name: "Chris", age: 32, onGuestList: false) func admit(person: Clubgoer) { print("\(person.name), come and party with us!") } func deny(person: Clubgoer) { print("Sorry, \(person.name), maybe you can go play Bingo with the Android team.") } func screen(person: Clubgoer) { if person.onGuestList { admit(person: person) } if !person.onGuestList { deny(person: person) } } func screenUnder21(person: Clubgoer) { if person.onGuestList && person.age >= 21 { admit(person: person) } else { deny(person: person) } } screen(person: ayush) screen(person: gabrielle) screen(person: chris) screenUnder21(person: ayush) screenUnder21(person: gabrielle) screenUnder21(person: chris)
c6340c108815ffaa37cb3307121cb467
24.019231
86
0.664105
false
false
false
false
tid-kijyun/Kanna
refs/heads/master
Sources/Kanna/libxmlHTMLDocument.swift
mit
2
/**@file libxmlHTMLDocument.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 CoreFoundation import libxml2 extension String.Encoding { var IANACharSetName: String? { #if os(Linux) && swift(>=4) switch self { case .ascii: return "us-ascii" case .iso2022JP: return "iso-2022-jp" case .isoLatin1: return "iso-8859-1" case .isoLatin2: return "iso-8859-2" case .japaneseEUC: return "euc-jp" case .macOSRoman: return "macintosh" case .nextstep: return "x-nextstep" case .nonLossyASCII: return nil case .shiftJIS: return "cp932" case .symbol: return "x-mac-symbol" case .unicode: return "utf-16" case .utf16: return "utf-16" case .utf16BigEndian: return "utf-16be" case .utf32: return "utf-32" case .utf32BigEndian: return "utf-32be" case .utf32LittleEndian: return "utf-32le" case .utf8: return "utf-8" case .windowsCP1250: return "windows-1250" case .windowsCP1251: return "windows-1251" case .windowsCP1252: return "windows-1252" case .windowsCP1253: return "windows-1253" case .windowsCP1254: return "windows-1254" default: return nil } #elseif os(Linux) && swift(>=3) switch self { case String.Encoding.ascii: return "us-ascii" case String.Encoding.iso2022JP: return "iso-2022-jp" case String.Encoding.isoLatin1: return "iso-8859-1" case String.Encoding.isoLatin2: return "iso-8859-2" case String.Encoding.japaneseEUC: return "euc-jp" case String.Encoding.macOSRoman: return "macintosh" case String.Encoding.nextstep: return "x-nextstep" case String.Encoding.nonLossyASCII: return nil case String.Encoding.shiftJIS: return "cp932" case String.Encoding.symbol: return "x-mac-symbol" case String.Encoding.unicode: return "utf-16" case String.Encoding.utf16: return "utf-16" case String.Encoding.utf16BigEndian: return "utf-16be" case String.Encoding.utf32: return "utf-32" case String.Encoding.utf32BigEndian: return "utf-32be" case String.Encoding.utf32LittleEndian: return "utf-32le" case String.Encoding.utf8: return "utf-8" case String.Encoding.windowsCP1250: return "windows-1250" case String.Encoding.windowsCP1251: return "windows-1251" case String.Encoding.windowsCP1252: return "windows-1252" case String.Encoding.windowsCP1253: return "windows-1253" case String.Encoding.windowsCP1254: return "windows-1254" default: return nil } #else let cfenc = CFStringConvertNSStringEncodingToEncoding(rawValue) guard let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) else { return nil } return cfencstr as String #endif } } /* libxmlHTMLDocument */ final class libxmlHTMLDocument: HTMLDocument { private var docPtr: htmlDocPtr? private var rootNode: XMLElement? private var html: String private var url: String? private var encoding: String.Encoding var text: String? { rootNode?.text } var toHTML: String? { let buf = xmlBufferCreate() let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) defer { xmlOutputBufferClose(outputBuf) xmlBufferFree(buf) } htmlDocContentDumpOutput(outputBuf, docPtr, nil) let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) return html } var toXML: String? { var buf: UnsafeMutablePointer<xmlChar>? let size: UnsafeMutablePointer<Int32>? = nil defer { xmlFree(buf) } xmlDocDumpMemory(docPtr, &buf, size) let html = String(cString: UnsafePointer<UInt8>(buf!)) return html } var innerHTML: String? { rootNode?.innerHTML } var className: String? { nil } var tagName: String? { get { nil } set {} } var content: String? { get { text } set { rootNode?.content = newValue } } var namespaces: [Namespace] { getNamespaces(docPtr: docPtr) } init(html: String, url: String?, encoding: String.Encoding, option: UInt) throws { self.html = html self.url = url self.encoding = encoding guard html.lengthOfBytes(using: encoding) > 0 else { throw ParseError.Empty } guard let charsetName = encoding.IANACharSetName, let cur = html.cString(using: encoding) else { throw ParseError.EncodingMismatch } let url: String = "" docPtr = cur.withUnsafeBytes { htmlReadDoc($0.bindMemory(to: xmlChar.self).baseAddress!, url, charsetName, CInt(option)) } guard let docPtr = docPtr else { throw ParseError.EncodingMismatch } rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr) } deinit { xmlFreeDoc(docPtr) } var title: String? { at_xpath("//title")?.text } var head: XMLElement? { at_xpath("//head") } var body: XMLElement? { at_xpath("//body") } func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject { guard let docPtr = docPtr else { return .none } return XPath(doc: self, docPtr: docPtr).xpath(xpath, namespaces: namespaces) } func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject { guard let docPtr = docPtr else { return .none } return XPath(doc: self, docPtr: docPtr).css(selector, namespaces: namespaces) } } /* libxmlXMLDocument */ final class libxmlXMLDocument: XMLDocument { private var docPtr: xmlDocPtr? private var rootNode: XMLElement? private var xml: String private var url: String? private var encoding: String.Encoding var text: String? { rootNode?.text } var toHTML: String? { let buf = xmlBufferCreate() let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) defer { xmlOutputBufferClose(outputBuf) xmlBufferFree(buf) } htmlDocContentDumpOutput(outputBuf, docPtr, nil) let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) return html } var toXML: String? { var buf: UnsafeMutablePointer<xmlChar>? let size: UnsafeMutablePointer<Int32>? = nil defer { xmlFree(buf) } xmlDocDumpMemory(docPtr, &buf, size) let html = String(cString: UnsafePointer<UInt8>(buf!)) return html } var innerHTML: String? { rootNode?.innerHTML } var className: String? { nil } var tagName: String? { get { nil } set {} } var content: String? { get { text } set { rootNode?.content = newValue } } var namespaces: [Namespace] { getNamespaces(docPtr: docPtr) } init(xml: String, url: String?, encoding: String.Encoding, option: UInt) throws { self.xml = xml self.url = url self.encoding = encoding if xml.isEmpty { throw ParseError.Empty } guard let charsetName = encoding.IANACharSetName, let cur = xml.cString(using: encoding) else { throw ParseError.EncodingMismatch } let url: String = "" docPtr = cur.withUnsafeBytes { xmlReadDoc($0.bindMemory(to: xmlChar.self).baseAddress!, url, charsetName, CInt(option)) } rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr!) } deinit { xmlFreeDoc(docPtr) } func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject { guard let docPtr = docPtr else { return .none } return XPath(doc: self, docPtr: docPtr).xpath(xpath, namespaces: namespaces) } func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject { guard let docPtr = docPtr else { return .none } return XPath(doc: self, docPtr: docPtr).css(selector, namespaces: namespaces) } } struct XPath { private let doc: XMLDocument private var docPtr: xmlDocPtr private var nodePtr: xmlNodePtr? private var isRoot: Bool { guard let nodePtr = nodePtr else { return true } return xmlDocGetRootElement(docPtr) == nodePtr } init(doc: XMLDocument, docPtr: xmlDocPtr, nodePtr: xmlNodePtr? = nil) { self.doc = doc self.docPtr = docPtr self.nodePtr = nodePtr } func xpath(_ xpath: String, namespaces: [String: String]? = nil) -> XPathObject { guard let ctxt = xmlXPathNewContext(docPtr) else { return .none } defer { xmlXPathFreeContext(ctxt) } if let nsDictionary = namespaces { for (ns, name) in nsDictionary { xmlXPathRegisterNs(ctxt, ns, name) } } if let node = nodePtr { ctxt.pointee.node = node } guard let result = xmlXPathEvalExpression(adoptXpath(xpath), ctxt) else { return .none } defer { xmlXPathFreeObject(result) } return XPathObject(document: doc, docPtr: docPtr, object: result.pointee) } func css(_ selector: String, namespaces: [String: String]? = nil) -> XPathObject { if let xpath = try? CSS.toXPath(selector, isRoot: isRoot) { return self.xpath(xpath, namespaces: namespaces) } return .none } private func adoptXpath(_ xpath: String) -> String { guard !isRoot else { return xpath } if xpath.hasPrefix("/") { return "." + xpath } else { return xpath } } } private func getNamespaces(docPtr: xmlDocPtr?) -> [Namespace] { let rootNode = xmlDocGetRootElement(docPtr) guard let ns = xmlGetNsList(docPtr, rootNode) else { return [] } var result: [Namespace] = [] var next = ns.pointee while next != nil { if let namePtr = next?.pointee.href { let prefixPtr = next?.pointee.prefix let prefix = prefixPtr == nil ? "" : String(cString: UnsafePointer<UInt8>(prefixPtr!)) let name = String(cString: UnsafePointer<UInt8>(namePtr)) result.append(Namespace(prefix: prefix, name: name)) } next = next?.pointee.next } return result }
1ed86fb1f303198ed0f9b1bde990f63e
30.035897
131
0.605502
false
false
false
false
Ivacker/swift
refs/heads/master
test/decl/var/static_var.swift
apache-2.0
10
// RUN: %target-parse-verify-swift -parse-as-library // See also rdar://15626843. static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}} return 42 } class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}} return 42 } static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} func inGlobalFunc() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } struct InMemberFunc { func member() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } } struct S { // expected-note 3{{extended type declared here}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension S { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } enum E { // expected-note 3{{extended type declared here}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension E { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } class C { static var v1: Int = 0 class final var v3: Int = 0 // expected-error {{class stored properties not yet supported}} class var v4: Int = 0 // expected-error {{class stored properties not yet supported}} static var v5: Int { return 0 } class var v6: Int { return 0 } static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}} class final let l3: Int = 0 // expected-error {{class stored properties not yet supported}} static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}} } extension C { static var ev1: Int = 0 class final var ev2: Int = 0 // expected-error {{class stored properties not yet supported}} class var ev3: Int = 0 // expected-error {{class stored properties not yet supported}} static var ev4: Int { return 0 } class var ev5: Int { return 0 } static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}} class final let el3: Int = 0 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}} static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} } protocol P { // Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298 static var v1: Int { get } class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int // expected-error {{static stored properties not yet supported in generic types}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} expected-error {{class stored properties not yet supported in generic types}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} } struct S1 { // rdar://15626843 static var x: Int // expected-error {{'static var' declaration requires an initializer expression or getter/setter specifier}} var y = 1 static var z = 5 } extension S1 { static var zz = 42 static var xy: Int { return 5 } } enum E1 { static var y: Int { get {} } } class C1 { class var x: Int // expected-error {{class stored properties not yet supported}} expected-error {{'class var' declaration requires an initializer expression or getter/setter specifier}} } class C2 { var x: Int = 19 class var x: Int = 17 // expected-error{{class stored properties not yet supported}} func xx() -> Int { return self.x + C2.x } } class ClassHasVars { static var computedStatic: Int { return 0 } // expected-note {{overridden declaration is here}} class var computedClass: Int { return 0 } var computedInstance: Int { return 0 } } class ClassOverridesVars : ClassHasVars { override static var computedStatic: Int { return 1 } // expected-error {{class var overrides a 'final' class var}} override class var computedClass: Int { return 1 } override var computedInstance: Int { return 1 } } struct S2 { var x: Int = 19 static var x: Int = 17 func xx() -> Int { return self.x + C2.x } } // rdar://problem/19887250 protocol Proto { static var name: String {get set} } struct ProtoAdopter : Proto { static var name: String = "name" // no error, even though static setters aren't mutating } // rdar://18990358 public struct Foo { public static let S { a // expected-error{{computed property must have an explicit type}} // expected-error@-1{{type annotation missing in pattern}} // expected-error@-2{{'let' declarations cannot be computed properties}} // expected-error@-3{{use of unresolved identifier 'a'}} } // expected-error@+1 {{expected declaration}}
92aca081dda3ed56273aac36e94c677f
53.616
329
0.695474
false
false
false
false
ontouchstart/swift3-playground
refs/heads/playgroundbook
Learn to Code 1.playgroundbook/Contents/Sources/AnimationComponent.swift
mit
2
// // AnimationComponent.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // import SceneKit class AnimationComponent: NSObject, CAAnimationDelegate, ActorComponent { static let defaultAnimationKey = "DefaultAnimation-Key" // MARK: Properties unowned let actor: Actor lazy var actionAnimations: ActorAnimation = ActorAnimation(type: self.actor.type) private var animationNode: SCNNode? { // The base `scnNode` holds the node animation should be // applied to as it's first child. return actor.scnNode.childNodes.first } private var animationStepIndex = 0 var currentAnimationDuration = 0.0 private var isRunningContinousIdle = false // Runs a random idle animation, followed by the first default animation, continuously. var shouldRunContinousIdle: Bool = false { didSet { animationNode?.removeAllAnimations() animationNode?.removeAllActions() if !shouldRunContinousIdle { isRunningContinousIdle = false actor.scnNode.removeAllActions() actor.scnNode.removeAllAnimations() return } else { isRunningContinousIdle = true // Ensure the animations we require are all loaded. ActorAnimation.loadAnimations(for: actor.type, actions: [.idle, .default]) let actorAnimations = ActorAnimation(type: actor.type) guard let idleAnimation = actorAnimations[.idle].randomElement else { return } guard let defaultAnimation = actorAnimations[.default].first else { return } //defaultAnimation.repeatCount = Float(arc4random_uniform(5)) // default animation to repeat up to 5 times. let idleAction = SCNAction.animate(with: idleAnimation, forKey: "Idle") let defaultAction = SCNAction.animate(with: defaultAnimation, forKey: "Default") let repeatAction = SCNAction.run { _ in if self.isRunningContinousIdle { self.shouldRunContinousIdle = true // Kind of trippy to use property to trigger animation. Should refactor. } } actor.scnNode.run(.sequence([defaultAction, idleAction, repeatAction]), forKey: "continousIdle") } } } var runsDefaultAnimationIndefinitely: Bool = false { didSet { guard oldValue != runsDefaultAnimationIndefinitely else { return } // Clear any lingering animations in either case. animationNode?.removeAllAnimations() actor.scnNode.removeAllAnimations() guard runsDefaultAnimationIndefinitely else { return } guard let defaultAnimation = actionAnimations[.default].first else { return } defaultAnimation.repeatCount = Float.infinity defaultAnimation.fadeInDuration = 0.3 defaultAnimation.fadeOutDuration = 0.3 animationNode?.add(defaultAnimation, forKey: AnimationComponent.defaultAnimationKey) } } // MARK: Initializers required init(actor: Actor) { self.actor = actor super.init() } deinit { runsDefaultAnimationIndefinitely = false } func setInitialState(for action: Action) { switch action { case .move(let startingPosition, _): actor.position = startingPosition case .jump(let startingPosition, _): actor.position = startingPosition case .turn(let startingRotation, _, _): actor.rotation = startingRotation case .teleport(let startingPosition, _): actor.position = startingPosition default: break } } // MARK: Performer func applyStateChange(for action: Action) { switch action { case .move(_, let destination): actor.position = destination case .jump(_, let destination): actor.position = destination case .turn(_, let rotation, _): actor.rotation = rotation case .teleport(_, let destination): actor.position = destination default: break } } func cancel(_: Action) { removeCommandAnimations() } // MARK: ActorComponent func play(animation animationType: AnimationType, variation index: Int, speed: Float) { // Ensure the initial state is correct. if let action = actor.currentAction { setInitialState(for: action) } let animation: CAAnimation? // Look for a faster variation of the requested action to play at speeds above `WorldConfiguration.Actor.walkRunSpeed`. if speed >= WorldConfiguration.Actor.walkRunSpeed, let fastVariation = animationType.fastVariation, let fastAnimation = actionAnimations.animation(for: fastVariation, index: animationStepIndex) { animation = fastAnimation animation?.speed = max(speed - WorldConfiguration.Actor.walkRunSpeed, 1) animationStepIndex = animationStepIndex == 0 ? 1 : 0 } else { animation = actionAnimations.animation(for: animationType, index: index) animation?.speed = speed //AnimationType.walkingAnimations.contains(action) ? speed : 1.0 } guard let readyAnimation = animation else { return } readyAnimation.delegate = self // Remove any lingering animations that may still be attached to the node. removeCommandAnimations() animationNode?.add(readyAnimation, forKey: animationType.rawValue) // Set the current animation duration. currentAnimationDuration = readyAnimation.duration / Double(readyAnimation.speed) } // MARK: Remove func removeCommandAnimations() { guard let animationNode = animationNode else { return } func removeAnimations(from node: SCNNode) { // Remove all animations, but the default. for key in node.animationKeys where key != AnimationComponent.defaultAnimationKey { node.removeAnimation(forKey: key) } } removeAnimations(from: animationNode) removeAnimations(from: actor.scnNode) } // MARK: CAAnimation Delegate func animationDidStop(_: CAAnimation, finished isFinished: Bool) { // Move the character after the animation completes. if isFinished { completeCurrentCommand() } } /// Translates the character based on the type of action. private func completeCurrentCommand() { // Cleanup current state. currentAnimationDuration = 0.0 SCNTransaction.begin() SCNTransaction.animationDuration = 0.0 if let action = actor.currentAction { // Update the node's position. applyStateChange(for: action) } removeCommandAnimations() #if DEBUG let existingKeys = animationNode?.animationKeys.count ?? 0 assert(existingKeys < 3, "There should never be more than the default and current action animations on the actor.") #endif SCNTransaction.commit() // Fire off the next animation. DispatchQueue.main.async { [unowned self] in self.actor.performerFinished(self) } } }
2ccc0daa889b71faeb7a6c71a21ef106
36.014493
131
0.614983
false
false
false
false
serkansokmen/ESCoverFlowLayout
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import ESCoverFlowLayout class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
3f2c314174d22cee8c04e55237de6f20
22.22
60
0.361757
false
false
false
false
bitjammer/swift
refs/heads/master
test/decl/inherit/inherit.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift class A { } protocol P { } // Duplicate inheritance class B : A, A { } // expected-error{{duplicate inheritance from 'A'}}{{12-15=}} // Duplicate inheritance from protocol class B2 : P, P { } // expected-error{{duplicate inheritance from 'P'}}{{13-16=}} // Multiple inheritance class C : B, A { } // expected-error{{multiple inheritance from classes 'B' and 'A'}} // Superclass in the wrong position class D : P, A { } // expected-error{{superclass 'A' must appear first in the inheritance clause}}{{12-15=}}{{11-11=A, }} // Struct inheriting a class struct S : A { } // expected-error{{non-class type 'S' cannot inherit from class 'A'}} // Protocol inheriting a class protocol Q : A { } // expected-error{{non-class type 'Q' cannot inherit from class 'A'}} // Extension inheriting a class extension C : A { } // expected-error{{extension of type 'C' cannot inherit from class 'A'}} // Keywords in inheritance clauses struct S2 : struct { } // expected-error{{expected identifier for type name}} // Protocol composition in inheritance clauses struct S3 : P, P & Q { } // expected-error {{duplicate inheritance from 'P'}} // expected-error @-1 {{protocol composition is neither allowed nor needed here}} // expected-error @-2 {{'Q' requires that 'S3' inherit from 'A'}} // expected-note @-3 {{requirement specified as 'Self' : 'A' [with Self = S3]}} struct S4 : P, P { } // expected-error {{duplicate inheritance from 'P'}} struct S6 : P & { } // expected-error {{expected identifier for type name}} // expected-error @-1 {{protocol composition is neither allowed nor needed here}} struct S7 : protocol<P, Q> { } // expected-warning {{'protocol<...>' composition syntax is deprecated; join the protocols using '&'}} // expected-error @-1 {{protocol composition is neither allowed nor needed here}}{{13-22=}} {{26-27=}} // expected-error @-2 {{'Q' requires that 'S7' inherit from 'A'}} // expected-note @-3 {{requirement specified as 'Self' : 'A' [with Self = S7]}} class GenericBase<T> {} class GenericSub<T> : GenericBase<T> {} // okay class InheritGenericParam<T> : T {} // expected-error {{inheritance from non-protocol, non-class type 'T'}} class InheritBody : T { // expected-error {{use of undeclared type 'T'}} typealias T = A } class InheritBodyBad : fn { // expected-error {{use of undeclared type 'fn'}} func fn() {} }
ec8df20ac66d14fc35c8d15047a63b05
47.867925
134
0.623552
false
false
false
false
alessiobrozzi/firefox-ios
refs/heads/master
Sync/KeyBundle.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import FxA import Account import SwiftyJSON private let KeyLength = 32 open class KeyBundle: Hashable { let encKey: Data let hmacKey: Data open class func fromKB(_ kB: Data) -> KeyBundle { let salt = Data() let contextInfo = FxAClient10.KW("oldsync") let len: UInt = 64 // KeyLength + KeyLength, without type nonsense. let derived = (kB as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: len)! return KeyBundle(encKey: derived.subdata(in: 0..<KeyLength), hmacKey: derived.subdata(in: KeyLength..<(2 * KeyLength))) } open class func random() -> KeyBundle { // Bytes.generateRandomBytes uses SecRandomCopyBytes, which hits /dev/random, which // on iOS is populated by the OS from kernel-level sources of entropy. // That should mean that we don't need to seed or initialize anything before calling // this. That is probably not true on (some versions of) OS X. return KeyBundle(encKey: Bytes.generateRandomBytes(32), hmacKey: Bytes.generateRandomBytes(32)) } open class var invalid: KeyBundle { return KeyBundle(encKeyB64: "deadbeef", hmacKeyB64: "deadbeef")! } public init?(encKeyB64: String, hmacKeyB64: String) { guard let e = Bytes.decodeBase64(encKeyB64), let h = Bytes.decodeBase64(hmacKeyB64) else { return nil } self.encKey = e self.hmacKey = h } public init(encKey: Data, hmacKey: Data) { self.encKey = encKey self.hmacKey = hmacKey } fileprivate func _hmac(_ ciphertext: Data) -> (data: UnsafeMutablePointer<CUnsignedChar>, len: Int) { let hmacAlgorithm = CCHmacAlgorithm(kCCHmacAlgSHA256) let digestLen: Int = Int(CC_SHA256_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen) CCHmac(hmacAlgorithm, hmacKey.getBytes(), hmacKey.count, ciphertext.getBytes(), ciphertext.count, result) return (result, digestLen) } open func hmac(_ ciphertext: Data) -> Data { let (result, digestLen) = _hmac(ciphertext) let data = NSMutableData(bytes: result, length: digestLen) result.deinitialize() return data as Data } /** * Returns a hex string for the HMAC. */ open func hmacString(_ ciphertext: Data) -> String { let (result, digestLen) = _hmac(ciphertext) let hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize() return String(hash) } open func encrypt(_ cleartext: Data, iv: Data?=nil) -> (ciphertext: Data, iv: Data)? { let iv = iv ?? Bytes.generateRandomBytes(16) let (success, b, copied) = self.crypt(cleartext, iv: iv, op: CCOperation(kCCEncrypt)) let byteCount = cleartext.count + kCCBlockSizeAES128 if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return (d, iv) } b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return nil } // You *must* verify HMAC before calling this. open func decrypt(_ ciphertext: Data, iv: Data) -> String? { let (success, b, copied) = self.crypt(ciphertext, iv: iv, op: CCOperation(kCCDecrypt)) let byteCount = ciphertext.count + kCCBlockSizeAES128 if success == CCCryptorStatus(kCCSuccess) { // Hooray! let d = Data(bytes: b, count: Int(copied)) let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue) b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return s as String? } b.deallocate(bytes: byteCount, alignedTo: MemoryLayout<Void>.size) return nil } fileprivate func crypt(_ input: Data, iv: Data, op: CCOperation) -> (status: CCCryptorStatus, buffer: UnsafeMutableRawPointer, count: Int) { let resultSize = input.count + kCCBlockSizeAES128 var copied: Int = 0 let result = UnsafeMutableRawPointer.allocate(bytes: resultSize, alignedTo: MemoryLayout<Void>.size) let success: CCCryptorStatus = CCCrypt(op, CCHmacAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), encKey.getBytes(), kCCKeySizeAES256, iv.getBytes(), input.getBytes(), input.count, result, resultSize, &copied ) return (success, result, copied) } open func verify(hmac: Data, ciphertextB64: Data) -> Bool { let expectedHMAC = hmac let computedHMAC = self.hmac(ciphertextB64) return (expectedHMAC == computedHMAC) } /** * Swift can't do functional factories. I would like to have one of the following * approaches be viable: * * 1. Derive the constructor from the consumer of the factory. * 2. Accept a type as input. * * Neither of these are viable, so we instead pass an explicit constructor closure. * * Most of these approaches produce either odd compiler errors, or -- worse -- * compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159). * * For this reason, be careful trying to simplify or improve this code. */ open func factory<T: CleartextPayloadJSON>(_ f: @escaping (JSON) -> T) -> (String) -> T? { return { (payload: String) -> T? in let potential = EncryptedJSON(json: payload, keyBundle: self) if !potential.isValid() { return nil } let cleartext = potential.cleartext if cleartext == nil { return nil } return f(cleartext!) } } // TODO: how much do we want to move this into EncryptedJSON? open func serializer<T: CleartextPayloadJSON>(_ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? { return { (record: Record<T>) -> JSON? in let json = f(record.payload) let data = (json.rawString([writtingOptionsKeys.castNilToNSNull: true]) ?? "").utf8EncodedData // We pass a null IV, which means "generate me a new one". // We then include the generated IV in the resulting record. if let (ciphertext, iv) = self.encrypt(data, iv: nil) { // So we have the encrypted payload. Now let's build the envelope around it. let ciphertext = ciphertext.base64EncodedString // The HMAC is computed over the base64 string. As bytes. Yes, I know. if let encodedCiphertextBytes = ciphertext.data(using: String.Encoding.ascii, allowLossyConversion: false) { let hmac = self.hmacString(encodedCiphertextBytes) let iv = iv.base64EncodedString // The payload is stringified JSON. Yes, I know. let payload: Any = JSON(object: ["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringValue()! as Any let obj = ["id": record.id, "sortindex": record.sortindex, "ttl": record.ttl as Any, "payload": payload] return JSON(object: obj) } } return nil } } open func asPair() -> [String] { return [self.encKey.base64EncodedString, self.hmacKey.base64EncodedString] } open var hashValue: Int { return "\(self.encKey.base64EncodedString) \(self.hmacKey.base64EncodedString)".hashValue } } public func == (lhs: KeyBundle, rhs: KeyBundle) -> Bool { return (lhs.encKey == rhs.encKey) && (lhs.hmacKey == rhs.hmacKey) } open class Keys: Equatable { let valid: Bool let defaultBundle: KeyBundle var collectionKeys: [String: KeyBundle] = [String: KeyBundle]() public init(defaultBundle: KeyBundle) { self.defaultBundle = defaultBundle self.valid = true } public init(payload: KeysPayload?) { if let payload = payload, payload.isValid() { if let keys = payload.defaultKeys { self.defaultBundle = keys self.collectionKeys = payload.collectionKeys self.valid = true return } } self.defaultBundle = KeyBundle.invalid self.valid = false } public convenience init(downloaded: EnvelopeJSON, master: KeyBundle) { let f: (JSON) -> KeysPayload = { KeysPayload($0) } let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: master.factory(f)) self.init(payload: keysRecord?.payload) } open class func random() -> Keys { return Keys(defaultBundle: KeyBundle.random()) } open func forCollection(_ collection: String) -> KeyBundle { if let bundle = collectionKeys[collection] { return bundle } return defaultBundle } open func encrypter<T: CleartextPayloadJSON>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> { return RecordEncrypter(bundle: forCollection(collection), encoder: encoder) } open func asPayload() -> KeysPayload { let json: JSON = JSON([ "id": "keys", "collection": "crypto", "default": self.defaultBundle.asPair(), "collections": mapValues(self.collectionKeys, f: { $0.asPair() }) ]) return KeysPayload(json) } } /** * Yup, these are basically typed tuples. */ public struct RecordEncoder<T: CleartextPayloadJSON> { let decode: (JSON) -> T let encode: (T) -> JSON } public struct RecordEncrypter<T: CleartextPayloadJSON> { let serializer: (Record<T>) -> JSON? let factory: (String) -> T? init(bundle: KeyBundle, encoder: RecordEncoder<T>) { self.serializer = bundle.serializer(encoder.encode) self.factory = bundle.factory(encoder.decode) } init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) { self.serializer = serializer self.factory = factory } } public func ==(lhs: Keys, rhs: Keys) -> Bool { return lhs.valid == rhs.valid && lhs.defaultBundle == rhs.defaultBundle && lhs.collectionKeys == rhs.collectionKeys }
153089ca305431a0e834e4f990e64440
36.006803
144
0.609559
false
false
false
false
Finb/V2ex-Swift
refs/heads/master
View/TopicDetailCommentCell.swift
mit
1
// // TopicDetailCommentCell.swift // V2ex-Swift // // Created by huangfeng on 1/20/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import YYText import SnapKit class TopicDetailCommentCell: UITableViewCell{ /// 头像 var avatarImageView: UIImageView = { let avatarImageView = UIImageView() avatarImageView.contentMode=UIView.ContentMode.scaleAspectFit avatarImageView.layer.cornerRadius = 3 avatarImageView.layer.masksToBounds = true return avatarImageView }() /// 用户名 var userNameLabel: UILabel = { let userNameLabel = UILabel() userNameLabel.font=v2Font(14) return userNameLabel }() var authorLabel: UILabel = { let authorLabel = UILabel() authorLabel.font=v2Font(12) return authorLabel }() /// 日期 和 最后发送人 var dateLabel: UILabel = { let dateLabel = UILabel() dateLabel.font=v2Font(12) return dateLabel }() /// 回复正文 var commentLabel: YYLabel = { let commentLabel = YYLabel(); commentLabel.font = v2Font(14); commentLabel.numberOfLines = 0; commentLabel.displaysAsynchronously = true return commentLabel }() /// 装上面定义的那些元素的容器 var contentPanel: UIView = { let view = UIView() return view }() //评论喜欢数 var favoriteIconView:UIImageView = { let favoriteIconView = UIImageView(image: UIImage.imageUsedTemplateMode("ic_favorite_18pt")!) favoriteIconView.contentMode = .scaleAspectFit favoriteIconView.isHidden = true return favoriteIconView }() var favoriteLabel:UILabel = { let favoriteLabel = UILabel() favoriteLabel.font = v2Font(10) return favoriteLabel }() var itemModel:TopicCommentModel? var isAuthor:Bool = false { didSet { self.authorLabel.text = isAuthor ? "• 楼主" : "" } } //文本高度约束 //因YYLabel自适应高度不完善,最好还是在在绑定数据时,手动更新 //如果换成UILabel或其他自适应高度Label控件,则不需要这一步 var textLabelHeight: Constraint? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setup()->Void{ let selectedBackgroundView = UIView() self.selectedBackgroundView = selectedBackgroundView self.contentView.addSubview(self.contentPanel); self.contentPanel.addSubview(self.avatarImageView); self.contentPanel.addSubview(self.userNameLabel); self.contentPanel.addSubview(self.authorLabel); self.contentPanel.addSubview(self.favoriteIconView) self.contentPanel.addSubview(self.favoriteLabel) self.contentPanel.addSubview(self.dateLabel); self.contentPanel.addSubview(self.commentLabel); self.setupLayout() //点击用户头像,跳转到用户主页 self.avatarImageView.isUserInteractionEnabled = true self.userNameLabel.isUserInteractionEnabled = true var userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.userNameTap(_:))) self.avatarImageView.addGestureRecognizer(userNameTap) userNameTap = UITapGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.userNameTap(_:))) self.userNameLabel.addGestureRecognizer(userNameTap) //长按手势 self.contentView .addGestureRecognizer( UILongPressGestureRecognizer(target: self, action: #selector(TopicDetailCommentCell.longPressHandle(_:)) ) ) self.themeChangedHandler = {[weak self] _ in self?.userNameLabel.textColor = V2EXColor.colors.v2_TopicListUserNameColor self?.authorLabel.textColor = V2EXColor.colors.v2_TopicListUserNameColor self?.dateLabel.textColor=V2EXColor.colors.v2_TopicListDateColor self?.commentLabel.textColor=V2EXColor.colors.v2_TopicListTitleColor; self?.contentPanel.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor self?.favoriteIconView.tintColor = V2EXColor.colors.v2_TopicListDateColor; self?.favoriteLabel.textColor = V2EXColor.colors.v2_TopicListDateColor; self?.backgroundColor = V2EXColor.colors.v2_backgroundColor; self?.selectedBackgroundView?.backgroundColor = V2EXColor.colors.v2_backgroundColor self?.avatarImageView.backgroundColor = self?.contentPanel.backgroundColor self?.userNameLabel.backgroundColor = self?.contentPanel.backgroundColor self?.authorLabel.backgroundColor = self?.contentPanel.backgroundColor self?.dateLabel.backgroundColor = self?.contentPanel.backgroundColor self?.commentLabel.backgroundColor = self?.contentPanel.backgroundColor self?.favoriteIconView.backgroundColor = self?.contentPanel.backgroundColor self?.favoriteLabel.backgroundColor = self?.contentPanel.backgroundColor } } func setupLayout(){ self.contentPanel.snp.makeConstraints{ (make) -> Void in make.top.left.right.equalTo(self.contentView); } self.avatarImageView.snp.makeConstraints{ (make) -> Void in make.left.top.equalToSuperview().offset(12); make.width.height.equalTo(35); } self.userNameLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.avatarImageView.snp.right).offset(10); make.top.equalTo(self.avatarImageView); } self.authorLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.userNameLabel.snp.right).offset(5); make.centerY.equalTo(self.userNameLabel); } self.favoriteIconView.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.authorLabel); make.left.equalTo(self.authorLabel.snp.right).offset(5) make.width.height.equalTo(10) } self.favoriteLabel.snp.makeConstraints{ (make) -> Void in make.left.equalTo(self.favoriteIconView.snp.right).offset(3) make.centerY.equalTo(self.favoriteIconView) } self.dateLabel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.avatarImageView); make.left.equalTo(self.userNameLabel); } self.commentLabel.snp.makeConstraints{ (make) -> Void in make.top.equalTo(self.avatarImageView.snp.bottom).offset(12); make.left.equalTo(self.avatarImageView); make.right.equalTo(self.contentPanel).offset(-12); self.textLabelHeight = make.height.equalTo(0).constraint make.bottom.equalTo(self.contentPanel.snp.bottom).offset(-12) } self.contentPanel.snp.makeConstraints{ (make) -> Void in make.bottom.equalTo(self.contentView).offset(-SEPARATOR_HEIGHT); } } @objc func userNameTap(_ sender:UITapGestureRecognizer) { if let _ = self.itemModel , let username = itemModel?.userName { let memberViewController = MemberViewController() memberViewController.username = username V2Client.sharedInstance.topNavigationController.pushViewController(memberViewController, animated: true) } } func bind(_ model:TopicCommentModel){ if let avata = model.avata?.avatarString { self.avatarImageView.fin_setImageWithUrl(URL(string: avata)!, placeholderImage: nil, imageModificationClosure: fin_defaultImageModification()) } if self.itemModel?.number == model.number && self.itemModel?.userName == model.userName { return; } self.userNameLabel.text = model.userName; self.dateLabel.text = String(format: "%i楼 %@", model.number, model.date ?? "") if let layout = model.textLayout { self.commentLabel.textLayout = layout if layout.attachments != nil { for attachment in layout.attachments! { if let image = attachment.content as? V2CommentAttachmentImage{ image.attachmentDelegate = self } } } self.textLabelHeight?.update(offset: layout.textBoundingSize.height) } self.favoriteIconView.isHidden = model.favorites <= 0 self.favoriteLabel.text = model.favorites <= 0 ? "" : "\(model.favorites)" self.itemModel = model } } //MARK: - 点击图片 extension TopicDetailCommentCell : V2CommentAttachmentImageTapDelegate ,V2PhotoBrowserDelegate { func V2CommentAttachmentImageSingleTap(_ imageView: V2CommentAttachmentImage) { let photoBrowser = V2PhotoBrowser(delegate: self) photoBrowser.currentPageIndex = imageView.index V2Client.sharedInstance.topNavigationController.present(photoBrowser, animated: true, completion: nil) } //V2PhotoBrowser Delegate func numberOfPhotosInPhotoBrowser(_ photoBrowser: V2PhotoBrowser) -> Int { return self.itemModel!.images.count } func photoAtIndexInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> V2Photo { let photo = V2Photo(url: URL(string: self.itemModel!.images[index] as! String)!) return photo } func guideContentModeInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> UIView.ContentMode { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image.contentMode } return .center } func guideFrameInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> CGRect { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image .convert(image.bounds, to: UIApplication.shared.keyWindow!) } return CGRect.zero } func guideImageInPhotoBrowser(_ photoBrowser: V2PhotoBrowser, index: Int) -> UIImage? { if let attachment = self.itemModel!.textLayout!.attachments?[index] , let image = attachment.content as? V2CommentAttachmentImage{ return image.image } return nil } } //MARK: - 长按复制功能 extension TopicDetailCommentCell { @objc func longPressHandle(_ longPress:UILongPressGestureRecognizer) -> Void { if (longPress.state == .began) { self.becomeFirstResponder() let item = UIMenuItem(title: "复制", action: #selector(TopicDetailCommentCell.copyText)) let menuController = UIMenuController.shared menuController.menuItems = [item] menuController.arrowDirection = .down menuController.setTargetRect(self.frame, in: self.superview!) menuController.setMenuVisible(true, animated: true); } } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if (action == #selector(TopicDetailCommentCell.copyText)){ return true } return super.canPerformAction(action, withSender: sender); } override var canBecomeFirstResponder : Bool { return true } @objc func copyText() -> Void { UIPasteboard.general.string = self.itemModel?.textLayout?.text.string } }
f44fe746e69adbc6d138b79b27312730
39.867133
154
0.654175
false
false
false
false
dmitryelj/SDR-Frequency-Plotter-OSX
refs/heads/master
FrequencyPlotter/ViewControllerSettings.swift
gpl-3.0
1
// // ViewControllerSettings.swift // SpectrumGraph // // Created by Dmitrii Eliuseev on 21/03/16. // Copyright © 2016 Dmitrii Eliuseev. All rights reserved. // [email protected] import Cocoa class ViewControllerSettings: NSViewController { @IBOutlet weak var labelGain1: NSTextField! @IBOutlet weak var sliderGain1: NSSlider! @IBOutlet weak var labelGain2: NSTextField! @IBOutlet weak var sliderGain2: NSSlider! var titleGain1:String = "" var valueGain1:CGFloat = 0 var valueGain1Low:CGFloat = 0 var valueGain1High:CGFloat = 100 var titleGain2:String = "" var valueGain2:CGFloat = 0 var valueGain2Low:CGFloat = 0 var valueGain2High:CGFloat = 100 var onDidChangedGain1: ((CGFloat) -> Void)? var onDidChangedGain2: ((CGFloat) -> Void)? override func viewDidLoad() { super.viewDidLoad() labelGain1.stringValue = titleGain1 sliderGain1.minValue = Double(valueGain1Low) sliderGain1.maxValue = Double(valueGain1High) sliderGain1.floatValue = Float(valueGain1) labelGain2.stringValue = titleGain2 sliderGain2.minValue = Double(valueGain2Low) sliderGain2.maxValue = Double(valueGain2High) sliderGain2.floatValue = Float(valueGain2) } @IBAction func onSliderGain1ValueChanged(sender: AnyObject) { let val = CGFloat(sliderGain1.floatValue) if let ch = onDidChangedGain1 { ch(val) } } @IBAction func onSliderGain2ValueChanged(sender: AnyObject) { let val = CGFloat(sliderGain2.floatValue) if let ch = onDidChangedGain2 { ch(val) } } }
ca0dcc03f924bcb234e87af5ec7da5c8
27.944444
63
0.722329
false
false
false
false
MakeSchool/TripPlanner
refs/heads/master
Argo Playground.playground/Pages/iTunes Example.xcplaygroundpage/Contents.swift
agpl-3.0
21
/*: **Note:** For **Argo** to be imported into the Playground, ensure that the **Argo-Mac** *scheme* is selected from the list of schemes. * * * */ import Foundation import Argo import Curry /*: **Helper function** – load JSON from a file */ func JSONFromFile(file: String) -> AnyObject? { return NSBundle.mainBundle().pathForResource(file, ofType: "json") .flatMap { NSData(contentsOfFile: $0) } .flatMap(JSONObjectWithData) } func JSONObjectWithData(data: NSData) -> AnyObject? { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) } catch { return .None } } /*: During JSON decoding, a **String** representation of a date needs to be converted to a **NSDate**. To achieve this, a **NSDateFormatter** and a helper function will be used. */ let jsonDateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssz" return dateFormatter }() let toNSDate: String -> Decoded<NSDate> = { .fromOptional(jsonDateFormatter.dateFromString($0)) } /*: ## Decoding selected entries from the iTunes store JSON format An example JSON file (**tropos.json**) can be found in the **resources** folder. */ struct App { let name: String let formattedPrice: String let averageUserRating: Float? let releaseDate: NSDate } extension App: CustomStringConvertible { var description: String { return "name: \(name)\nprice: \(formattedPrice), rating: \(averageUserRating), released: \(releaseDate)" } } extension App: Decodable { static func decode(j: JSON) -> Decoded<App> { return curry(self.init) <^> j <| "trackName" <*> j <| "formattedPrice" <*> j <|? "averageUserRating" <*> (j <| "releaseDate" >>- toNSDate) } } /*: * * * */ let app: App? = (JSONFromFile("tropos")?["results"].flatMap(decode))?.first print(app!)
5047c48aa067b32472caf89849354a06
26.686567
134
0.685175
false
false
false
false
alblue/swift
refs/heads/master
test/Constraints/subscript.swift
apache-2.0
4
// RUN: %target-typecheck-verify-swift // Simple subscript of arrays: func simpleSubscript(_ array: [Float], x: Int) -> Float { _ = array[x] return array[x] } // Subscript of archetype. protocol IntToStringSubscript { subscript (i : Int) -> String { get } } class LameDictionary { subscript (i : Int) -> String { get { return String(i) } } } func archetypeSubscript<T : IntToStringSubscript, U : LameDictionary>(_ t: T, u: U) -> String { // Subscript an archetype. if false { return t[17] } // Subscript an archetype for which the subscript operator is in a base class. return u[17] } // Subscript of existential type. func existentialSubscript(_ a: IntToStringSubscript) -> String { return a[17] } class MyDictionary<Key, Value> { subscript (key : Key) -> Value { get {} } } class MyStringToInt<T> : MyDictionary<String, Int> { } // Subscript of generic type. func genericSubscript<T>(_ t: T, array: Array<Int>, i2i: MyDictionary<Int, Int>, t2i: MyDictionary<T, Int>, s2i: MyStringToInt<()>) -> Int { if true { return array[5] } if true { return i2i[5] } if true { return t2i[t] } return s2i["hello"] } // <rdar://problem/21364448> QoI: Poor error message for ambiguous subscript call extension String { func number() -> Int { } // expected-note {{found this candidate}} func number() -> Double { } // expected-note {{found this candidate}} } let _ = "a".number // expected-error {{ambiguous use of 'number()'}} extension Int { subscript(key: String) -> Int { get {} } // expected-note {{found this candidate}} subscript(key: String) -> Double { get {} } // expected-note {{found this candidate}} } let _ = 1["1"] // expected-error {{ambiguous use of 'subscript(_:)'}} let squares = [ 1, 2, 3 ].reduce([:]) { (dict, n) in var dict = dict dict[n] = n * n return dict } // <rdar://problem/23670252> QoI: Misleading error message when assigning a value from [String : AnyObject] func r23670252(_ dictionary: [String : AnyObject], someObject: AnyObject) { let color : String? color = dictionary["color"] // expected-error {{cannot assign value of type 'AnyObject?' to type 'String?'}} _ = color } // SR-718 - Type mismatch reported as extraneous parameter struct SR718 { subscript(b : Int) -> Int { return 0 } subscript(a a : UInt) -> Int { return 0 } } SR718()[a: Int()] // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}} // rdar://problem/25601561 - Qol: Bad diagnostic for failed assignment from Any to more specific type struct S_r25601561 { func value() -> Any? { return "hi" } } class C_r25601561 { var a: [S_r25601561?] = [] func test(i: Int) -> String { let s: String = a[i]!.value()! // expected-error {{cannot convert value of type 'Any' to specified type 'String'}} return s } } // rdar://problem/31977679 - Misleading diagnostics when using subscript with incorrect argument func r31977679_1(_ properties: [String: String]) -> Any? { return properties[0] // expected-error {{cannot subscript a value of type '[String : String]' with an index of type 'Int'}} } func r31977679_2(_ properties: [String: String]) -> Any? { return properties["foo"] // Ok } // rdar://problem/45819956 - inout-to-pointer in a subscript arg could use a better diagnostic func rdar_45819956() { struct S { subscript(takesPtr ptr: UnsafeMutablePointer<Int>) -> Int { get { return 0 } } } let s = S() var i = 0 // TODO: It should be possible to suggest `withUnsafe[Mutable]Pointer` as a fix-it _ = s[takesPtr: &i] // expected-error@-1 {{cannot pass an inout argument to a subscript; use 'withUnsafeMutablePointer' to explicitly convert argument to a pointer}} } // rdar://problem/45825806 - [SR-7190] Array-to-pointer in subscript arg crashes compiler func rdar_45825806() { struct S { subscript(takesPtr ptr: UnsafePointer<Int>) -> Int { get { return 0 } } } let s = S() _ = s[takesPtr: [1, 2, 3]] // Ok }
3af51f4405fea02eb94fce33c6a4b46b
27.30137
147
0.636012
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
refs/heads/master
AviasalesSDKTemplate/Source/HotelsSource/Objects/HDKRoom+Hotellook.swift
mit
1
import Foundation import HotellookSDK @objcMembers class RoomOptionConsts: NSObject { static let kBreakfastOptionKey = "breakfast" static let kAllInclusiveOptionKey = "allInclusive" static let kRefundableOptionKey = "refundable" static let kAvailableRoomsOptionKey = "available" static let kSmokingOptionKey = "smoking" static let kPayNowOptionKey = "deposit" static let kPayLaterOptionKey = "!deposit" static let kPrivatePriceOptionKey = "privatePrice" static let kCardRequiredOptionKey = "cardRequired" static let kViewSentenceOptionKey = "viewSentence" static let kNiceViewOptionKey = "view" static let kFanOptionKey = "fan" static let kRoomAirConditioningOptionKey = "airConditioner" static let kRoomWifiOptionKey = "freeWifi" static let kRoomDormitoryOptionKey = "dormitory" static let kRoomPrivateBathroomKey = "privateBathroom" static let kHotelSharedBathroomKey = "shared bathroom" static let kHotelAirConditioningOptionKey = "air conditioning" static let kHotelWifiInRoomOptionKey = "wi-fi in room" } @objc extension HDKRoom { static let kDiscountLowCutoff = -3 static let kDiscountHighCutoff = -75 func hasDiscountHighlight() -> Bool { return highlightType() == .discount } private func discountInAllowedRange() -> Bool { return (discount <= HDKRoom.kDiscountLowCutoff) && (discount >= HDKRoom.kDiscountHighCutoff) } func hasPrivatePriceHighlight() -> Bool { let highlight = highlightType() return highlight == .mobile || highlight == .private } func highlightType() -> HDKHighlightType { let result = HDKRoom.highlightType(by: highlightTypeString) if result == .discount && !discountInAllowedRange() { assertionFailure() return .none } if (result == .mobile || result == .private) && !hasMobileOrPrivatePriceOption { assertionFailure() return .none } return result } func hasOption(_ option: String, withValue expectedValue: Bool) -> Bool { if option == RoomOptionConsts.kBreakfastOptionKey { return options.breakfast == expectedValue } if option == RoomOptionConsts.kRefundableOptionKey { return options.refundable == expectedValue } if option == RoomOptionConsts.kPayNowOptionKey { return options.deposit == expectedValue } if option == RoomOptionConsts.kAllInclusiveOptionKey { return options.allInclusive == expectedValue } if option == RoomOptionConsts.kRoomWifiOptionKey { return options.freeWifi == expectedValue } if option == RoomOptionConsts.kNiceViewOptionKey { return (options.view != nil) && expectedValue } if option == RoomOptionConsts.kSmokingOptionKey { return options.smoking == expectedValue } if option == RoomOptionConsts.kRoomDormitoryOptionKey { return options.dormitory == expectedValue } assertionFailure() return false } private static func highlightType(by highlightString: String?) -> HDKHighlightType { let map: [String: HDKHighlightType] = [ "mobile": .mobile, "private": .private, "discount": .discount ] guard let highlightString = highlightString else { return .none } return map[highlightString] ?? .none } }
ecc980a82d264eb505fe6bbe3e5b4e58
32.885714
100
0.657392
false
false
false
false
luowei/Swift-Samples
refs/heads/master
Swift-Samples/Swift-Learn/TypeCastViewController.swift
apache-2.0
1
// // TypeCastViewController.swift // Swift-Samples // // Created by luowei on 15/12/1. // Copyright © 2015年 wodedata. All rights reserved. // import UIKit class TypeCastViewController: UIViewController { var library:[MediaItem]? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController!.navigationBar.isHidden = true self.tabBarController!.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController!.navigationBar.isHidden = false self.tabBarController!.tabBar.isHidden = false } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] // the type of "library" is inferred to be MediaItem[] let selfCenter = self.view.center; //检查类型 let btn = UIButton(frame: CGRect(x: selfCenter.x - 50, y: selfCenter.y - 200, width: 100, height: 40)) btn.backgroundColor = UIColor.gray btn.layer.cornerRadius = 10 btn.setTitle("检查类型", for: UIControlState()) btn.addTarget(self, action: #selector(TypeCastViewController.checkingType(_:)), for: .touchUpInside) self.view.addSubview(btn) //向下转型 let btn2 = UIButton(frame: CGRect(x: selfCenter.x - 50, y: selfCenter.y - 50, width: 100, height: 40)) btn2.backgroundColor = UIColor.gray btn2.layer.cornerRadius = 10 btn2.setTitle("向下转型", for: UIControlState()) btn2.addTarget(self, action: #selector(TypeCastViewController.downcasting(_:)), for: .touchUpInside) self.view.addSubview(btn2) //AnyObject类型 let btn3 = UIButton(frame: CGRect(x: selfCenter.x - 80, y: selfCenter.y + 50, width: 160, height: 40)) btn3.backgroundColor = UIColor.gray btn3.layer.cornerRadius = 10 btn3.setTitle("AnyObject类型", for: UIControlState()) btn3.addTarget(self, action: #selector(TypeCastViewController.anyObject(_:)), for: .touchUpInside) self.view.addSubview(btn3) //Any类型 let btn4 = UIButton(frame: CGRect(x: selfCenter.x - 50, y: selfCenter.y + 200, width: 100, height: 40)) btn4.backgroundColor = UIColor.gray btn4.layer.cornerRadius = 10 btn4.setTitle("Any类型", for: UIControlState()) btn4.addTarget(self, action: #selector(TypeCastViewController.any(_:)), for: .touchUpInside) self.view.addSubview(btn4) } //检查类型(Checking Type) func checkingType(_ btn: UIButton) { //检查类型(Checking Type) var movieCount = 0 var songCount = 0 for item in library! { if item is Movie { movieCount += 1 } else if item is Song { songCount += 1 } } print("Media library contains \(movieCount) movies and \(songCount) songs") // prints "Media library contains 2 movies and 3 songs" } //向下转型(Downcasting) func downcasting(_ btn: UIButton) { //向下转型(Downcasting) for item in library! { if let movie = item as? Movie { print("Movie: '\(movie.name)', dir. \(movie.director)") } else if let song = item as? Song { print("Song: '\(song.name)', by \(song.artist)") } } // Movie: 'Casablanca', dir. Michael Curtiz // Song: 'Blue Suede Shoes', by Elvis Presley // Movie: 'Citizen Kane', dir. Orson Welles // Song: 'The One And Only', by Chesney Hawkes // Song: 'Never Gonna Give You Up', by Rick Astley } //Any和AnyObject的类型转换 //AnyObject类型 func anyObject(_ btn: UIButton) { //AnyObject类型 let someObjects: [AnyObject] = [ Movie(name: "2001: A Space Odyssey", director: "Stanley Kubrick"), Movie(name: "Moon", director: "Duncan Jones"), Movie(name: "Alien", director: "Ridley Scott") ] for object in someObjects { let movie = object as! Movie print("Movie: '\(movie.name)', dir. \(movie.director)") } // Movie: '2001: A Space Odyssey', dir. Stanley Kubrick // Movie: 'Moon', dir. Duncan Jones // Movie: 'Alien', dir. Ridley Scott for movie in someObjects as! [Movie] { print("Movie: '\(movie.name)', dir. \(movie.director)") } // Movie: '2001: A Space Odyssey', dir. Stanley Kubrick // Movie: 'Moon', dir. Duncan Jones // Movie: 'Alien', dir. Ridley Scott } //Any类型 func any(_ btn: UIButton) { //Any类型 var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({ (name: String) -> String in "Hello, \(name)" }) for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of \(someDouble)") case is Double: print("some other double value that I don't want to print") case let someString as String: print("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): print("an (x, y) point at \(x), \(y)") case let movie as Movie: print("a movie called '\(movie.name)', dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("something else") } } // zero as an Int // zero as a Double // an integer value of 42 // a positive double value of 3.14159 // a string value of "hello" // an (x, y) point at 3.0, 5.0 // a movie called 'Ghostbusters', dir. Ivan Reitman // Hello, Michael } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } }
c687727fbfecac77c1515e61d9350c79
32.654709
111
0.562958
false
false
false
false
adafruit/Bluefruit_LE_Connect
refs/heads/master
BLE Test/BLEPeripheral.swift
bsd-3-clause
3
// // BLEPeripheral.swift // Adafruit Bluefruit LE Connect // // Represents a connected peripheral // // Created by Collin Cunningham on 10/29/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import Foundation import CoreBluetooth protocol BLEPeripheralDelegate: Any { var connectionMode:ConnectionMode { get } func didReceiveData(newData:NSData) func connectionFinalized() func uartDidEncounterError(error:NSString) } class BLEPeripheral: NSObject, CBPeripheralDelegate { var currentPeripheral:CBPeripheral! var delegate:BLEPeripheralDelegate! var uartService:CBService? var rxCharacteristic:CBCharacteristic? var txCharacteristic:CBCharacteristic? var knownServices:[CBService] = [] //MARK: Utility methods init(peripheral:CBPeripheral, delegate:BLEPeripheralDelegate){ super.init() self.currentPeripheral = peripheral self.currentPeripheral.delegate = self self.delegate = delegate } func didConnect(withMode:ConnectionMode) { //Respond to peripheral connection //Already discovered services if currentPeripheral.services != nil{ printLog(self, funcName: "didConnect", logString: "Skipping service discovery") peripheral(currentPeripheral, didDiscoverServices: nil) //already discovered services, DO NOT re-discover. Just pass along the peripheral. return } printLog(self, funcName: "didConnect", logString: "Starting service discovery") switch withMode.rawValue { case ConnectionMode.UART.rawValue, ConnectionMode.PinIO.rawValue, ConnectionMode.Controller.rawValue, ConnectionMode.DFU.rawValue: currentPeripheral.discoverServices([uartServiceUUID(), dfuServiceUUID(), deviceInformationServiceUUID()]) // Discover dfu and dis (needed to check if update is available) case ConnectionMode.Info.rawValue: currentPeripheral.discoverServices(nil) break default: printLog(self, funcName: "didConnect", logString: "non-matching mode") break } // currentPeripheral.discoverServices([BLEPeripheral.uartServiceUUID(), BLEPeripheral.deviceInformationServiceUUID()]) // currentPeripheral.discoverServices(nil) } func writeString(string:NSString){ //Send string to peripheral let data = NSData(bytes: string.UTF8String, length: string.length) writeRawData(data) } func writeRawData(data:NSData) { //Send data to peripheral if (txCharacteristic == nil){ printLog(self, funcName: "writeRawData", logString: "Unable to write data without txcharacteristic") return } var writeType:CBCharacteristicWriteType if (txCharacteristic!.properties.rawValue & CBCharacteristicProperties.WriteWithoutResponse.rawValue) != 0 { writeType = CBCharacteristicWriteType.WithoutResponse } else if ((txCharacteristic!.properties.rawValue & CBCharacteristicProperties.Write.rawValue) != 0){ writeType = CBCharacteristicWriteType.WithResponse } else{ printLog(self, funcName: "writeRawData", logString: "Unable to write data without characteristic write property") return } //TODO: Test packetization //send data in lengths of <= 20 bytes let dataLength = data.length let limit = 20 //Below limit, send as-is if dataLength <= limit { currentPeripheral.writeValue(data, forCharacteristic: txCharacteristic!, type: writeType) } //Above limit, send in lengths <= 20 bytes else { var len = limit var loc = 0 var idx = 0 //for debug while loc < dataLength { let rmdr = dataLength - loc if rmdr <= len { len = rmdr } let range = NSMakeRange(loc, len) var newBytes = [UInt8](count: len, repeatedValue: 0) data.getBytes(&newBytes, range: range) let newData = NSData(bytes: newBytes, length: len) // println("\(self.classForCoder.description()) writeRawData : packet_\(idx) : \(newData.hexRepresentationWithSpaces(true))") self.currentPeripheral.writeValue(newData, forCharacteristic: self.txCharacteristic!, type: writeType) loc += len idx += 1 } } } //MARK: CBPeripheral Delegate methods func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) { //Respond to finding a new service on peripheral if error != nil { // handleError("\(self.classForCoder.description()) didDiscoverServices : Error discovering services") printLog(self, funcName: "didDiscoverServices", logString: "\(error.debugDescription)") return } // println("\(self.classForCoder.description()) didDiscoverServices") let services = peripheral.services as [CBService]! for s in services { // Service characteristics already discovered if (s.characteristics != nil){ self.peripheral(peripheral, didDiscoverCharacteristicsForService: s, error: nil) // If characteristics have already been discovered, do not check again } //UART, Pin I/O, or Controller mode else if delegate.connectionMode == ConnectionMode.UART || delegate.connectionMode == ConnectionMode.PinIO || delegate.connectionMode == ConnectionMode.Controller || delegate.connectionMode == ConnectionMode.DFU { if UUIDsAreEqual(s.UUID, secondID: uartServiceUUID()) { uartService = s peripheral.discoverCharacteristics([txCharacteristicUUID(), rxCharacteristicUUID()], forService: uartService!) } } // Info mode else if delegate.connectionMode == ConnectionMode.Info { knownServices.append(s) peripheral.discoverCharacteristics(nil, forService: s) } //DFU / Firmware Updater mode else if delegate.connectionMode == ConnectionMode.DFU { knownServices.append(s) peripheral.discoverCharacteristics(nil, forService: s) } } printLog(self, funcName: "didDiscoverServices", logString: "all top-level services discovered") } func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { //Respond to finding a new characteristic on service if error != nil { // handleError("Error discovering characteristics") printLog(self, funcName: "didDiscoverCharacteristicsForService", logString: "\(error.debugDescription)") return } printLog(self, funcName: "didDiscoverCharacteristicsForService", logString: "\(service.description) with \(service.characteristics!.count) characteristics") // UART mode if delegate.connectionMode == ConnectionMode.UART || delegate.connectionMode == ConnectionMode.PinIO || delegate.connectionMode == ConnectionMode.Controller || delegate.connectionMode == ConnectionMode.DFU { for c in (service.characteristics as [CBCharacteristic]!) { switch c.UUID { case rxCharacteristicUUID(): //"6e400003-b5a3-f393-e0a9-e50e24dcca9e" printLog(self, funcName: "didDiscoverCharacteristicsForService", logString: "\(service.description) : RX") rxCharacteristic = c currentPeripheral.setNotifyValue(true, forCharacteristic: rxCharacteristic!) break case txCharacteristicUUID(): //"6e400002-b5a3-f393-e0a9-e50e24dcca9e" printLog(self, funcName: "didDiscoverCharacteristicsForService", logString: "\(service.description) : TX") txCharacteristic = c break default: // printLog(self, "didDiscoverCharacteristicsForService", "Found Characteristic: Unknown") break } } if rxCharacteristic != nil && txCharacteristic != nil { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate.connectionFinalized() }) } } // Info mode else if delegate.connectionMode == ConnectionMode.Info { for c in (service.characteristics as [CBCharacteristic]!) { //Read readable characteristic values if (c.properties.rawValue & CBCharacteristicProperties.Read.rawValue) != 0 { peripheral.readValueForCharacteristic(c) } peripheral.discoverDescriptorsForCharacteristic(c) } } } func peripheral(peripheral: CBPeripheral, didDiscoverDescriptorsForCharacteristic characteristic: CBCharacteristic, error: NSError?) { if error != nil { // handleError("Error discovering descriptors \(error.debugDescription)") printLog(self, funcName: "didDiscoverDescriptorsForCharacteristic", logString: "\(error.debugDescription)") // return } else { if characteristic.descriptors?.count != 0 { for d in characteristic.descriptors! { let desc = d as CBDescriptor! printLog(self, funcName: "didDiscoverDescriptorsForCharacteristic", logString: "\(desc.description)") // currentPeripheral.readValueForDescriptor(desc) } } } //Check if all characteristics were discovered var allCharacteristics:[CBCharacteristic] = [] for s in knownServices { for c in s.characteristics! { allCharacteristics.append(c as CBCharacteristic!) } } for idx in 0...(allCharacteristics.count-1) { if allCharacteristics[idx] === characteristic { // println("found characteristic index \(idx)") if (idx + 1) == allCharacteristics.count { // println("found last characteristic") if delegate.connectionMode == ConnectionMode.Info { delegate.connectionFinalized() } } } } } // func peripheral(peripheral: CBPeripheral!, didUpdateValueForDescriptor descriptor: CBDescriptor!, error: NSError!) { // // if error != nil { //// handleError("Error reading descriptor value \(error.debugDescription)") // printLog(self, "didUpdateValueForDescriptor", "\(error.debugDescription)") //// return // } // // else { // println("descriptor value = \(descriptor.value)") // println("descriptor description = \(descriptor.description)") // } // // } func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { //Respond to value change on peripheral if error != nil { // handleError("Error updating value for characteristic\(characteristic.description.utf8) \(error.description.utf8)") printLog(self, funcName: "didUpdateValueForCharacteristic", logString: "\(error.debugDescription)") return } //UART mode if delegate.connectionMode == ConnectionMode.UART || delegate.connectionMode == ConnectionMode.PinIO || delegate.connectionMode == ConnectionMode.Controller { if (characteristic == self.rxCharacteristic){ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate.didReceiveData(characteristic.value!) }) } //TODO: Finalize for info mode else if UUIDsAreEqual(characteristic.UUID, secondID: softwareRevisionStringUUID()) { // var swRevision = NSString(string: "") // let bytes:UnsafePointer<Void> = characteristic.value!.bytes // for i in 0...characteristic.value!.length { // // swRevision = NSString(format: "0x%x", UInt8(bytes[i]) ) // } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate.connectionFinalized() }) } } } func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) { //Respond to finding a new characteristic on service if error != nil { printLog(self, funcName: "didDiscoverIncludedServicesForService", logString: "\(error.debugDescription)") return } printLog(self, funcName: "didDiscoverIncludedServicesForService", logString: "service: \(service.description) has \(service.includedServices?.count) included services") // if service.characteristics.count == 0 { // currentPeripheral.discoverIncludedServices(nil, forService: service) // } for s in (service.includedServices as [CBService]!) { printLog(self, funcName: "didDiscoverIncludedServicesForService", logString: "\(s.description)") } } func handleError(errorString:String) { printLog(self, funcName: "Error", logString: "\(errorString)") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.delegate.uartDidEncounterError(errorString) }) } }
4c08a3a5bd532d3d73e8c76e30d9046b
36.320293
188
0.565383
false
false
false
false
lorentey/BigInt
refs/heads/master
Sources/String Conversion.swift
mit
1
// // String Conversion.swift // BigInt // // Created by Károly Lőrentey on 2016-01-03. // Copyright © 2016-2017 Károly Lőrentey. // extension BigUInt { //MARK: String Conversion /// Calculates the number of numerals in a given radix that fit inside a single `Word`. /// /// - Returns: (chars, power) where `chars` is highest that satisfy `radix^chars <= 2^Word.bitWidth`. `power` is zero /// if radix is a power of two; otherwise `power == radix^chars`. fileprivate static func charsPerWord(forRadix radix: Int) -> (chars: Int, power: Word) { var power: Word = 1 var overflow = false var count = 0 while !overflow { let (p, o) = power.multipliedReportingOverflow(by: Word(radix)) overflow = o if !o || p == 0 { count += 1 power = p } } return (count, power) } /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by /// letters from the English alphabet. /// /// - Requires: `radix > 1 && radix < 36` /// - Parameter `text`: A string consisting of characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. public init?<S: StringProtocol>(_ text: S, radix: Int = 10) { precondition(radix > 1) let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) var words: [Word] = [] var end = text.endIndex var start = end var count = 0 while start != text.startIndex { start = text.index(before: start) count += 1 if count == charsPerWord { guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } words.append(d) end = start count = 0 } } if start != end { guard let d = Word.init(text[start ..< end], radix: radix) else { return nil } words.append(d) } if power == 0 { self.init(words: words) } else { self.init() for d in words.reversed() { self.multiply(byWord: power) self.addWord(d) } } } } extension BigInt { /// Initialize a big integer from an ASCII representation in a given radix. Numerals above `9` are represented by /// letters from the English alphabet. /// /// - Requires: `radix > 1 && radix < 36` /// - Parameter `text`: A string optionally starting with "-" or "+" followed by characters corresponding to numerals in the given radix. (0-9, a-z, A-Z) /// - Parameter `radix`: The base of the number system to use, or 10 if unspecified. /// - Returns: The integer represented by `text`, or nil if `text` contains a character that does not represent a numeral in `radix`. public init?<S: StringProtocol>(_ text: S, radix: Int = 10) { var magnitude: BigUInt? var sign: Sign = .plus if text.first == "-" { sign = .minus let text = text.dropFirst() magnitude = BigUInt(text, radix: radix) } else if text.first == "+" { let text = text.dropFirst() magnitude = BigUInt(text, radix: radix) } else { magnitude = BigUInt(text, radix: radix) } guard let m = magnitude else { return nil } self.magnitude = m self.sign = sign } } extension String { /// Initialize a new string with the base-10 representation of an unsigned big integer. /// /// - Complexity: O(v.count^2) public init(_ v: BigUInt) { self.init(v, radix: 10, uppercase: false) } /// Initialize a new string representing an unsigned big integer in the given radix (base). /// /// Numerals greater than 9 are represented as letters from the English alphabet, /// starting with `a` if `uppercase` is false or `A` otherwise. /// /// - Requires: radix > 1 && radix <= 36 /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). public init(_ v: BigUInt, radix: Int, uppercase: Bool = false) { precondition(radix > 1) let (charsPerWord, power) = BigUInt.charsPerWord(forRadix: radix) guard !v.isZero else { self = "0"; return } var parts: [String] if power == 0 { parts = v.words.map { String($0, radix: radix, uppercase: uppercase) } } else { parts = [] var rest = v while !rest.isZero { let mod = rest.divide(byWord: power) parts.append(String(mod, radix: radix, uppercase: uppercase)) } } assert(!parts.isEmpty) self = "" var first = true for part in parts.reversed() { let zeroes = charsPerWord - part.count assert(zeroes >= 0) if !first && zeroes > 0 { // Insert leading zeroes for mid-Words self += String(repeating: "0", count: zeroes) } first = false self += part } } /// Initialize a new string representing a signed big integer in the given radix (base). /// /// Numerals greater than 9 are represented as letters from the English alphabet, /// starting with `a` if `uppercase` is false or `A` otherwise. /// /// - Requires: radix > 1 && radix <= 36 /// - Complexity: O(count) when radix is a power of two; otherwise O(count^2). public init(_ value: BigInt, radix: Int = 10, uppercase: Bool = false) { self = String(value.magnitude, radix: radix, uppercase: uppercase) if value.sign == .minus { self = "-" + self } } } extension BigUInt: ExpressibleByStringLiteral { /// Initialize a new big integer from a Unicode scalar. /// The scalar must represent a decimal digit. public init(unicodeScalarLiteral value: UnicodeScalar) { self = BigUInt(String(value), radix: 10)! } /// Initialize a new big integer from an extended grapheme cluster. /// The cluster must consist of a decimal digit. public init(extendedGraphemeClusterLiteral value: String) { self = BigUInt(value, radix: 10)! } /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. /// The string must contain only decimal digits. public init(stringLiteral value: StringLiteralType) { self = BigUInt(value, radix: 10)! } } extension BigInt: ExpressibleByStringLiteral { /// Initialize a new big integer from a Unicode scalar. /// The scalar must represent a decimal digit. public init(unicodeScalarLiteral value: UnicodeScalar) { self = BigInt(String(value), radix: 10)! } /// Initialize a new big integer from an extended grapheme cluster. /// The cluster must consist of a decimal digit. public init(extendedGraphemeClusterLiteral value: String) { self = BigInt(value, radix: 10)! } /// Initialize a new big integer from a decimal number represented by a string literal of arbitrary length. /// The string must contain only decimal digits. public init(stringLiteral value: StringLiteralType) { self = BigInt(value, radix: 10)! } } extension BigUInt: CustomStringConvertible { /// Return the decimal representation of this integer. public var description: String { return String(self, radix: 10) } } extension BigInt: CustomStringConvertible { /// Return the decimal representation of this integer. public var description: String { return String(self, radix: 10) } } extension BigUInt: CustomPlaygroundDisplayConvertible { /// Return the playground quick look representation of this integer. public var playgroundDescription: Any { let text = String(self) return text + " (\(self.bitWidth) bits)" } } extension BigInt: CustomPlaygroundDisplayConvertible { /// Return the playground quick look representation of this integer. public var playgroundDescription: Any { let text = String(self) return text + " (\(self.magnitude.bitWidth) bits)" } }
a1204032c66960f113e8b2090421408d
35.338983
157
0.597481
false
false
false
false
adapter00/FlickableCalendar
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import FlickableCalendar class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
013f85e1fed68c35cca69932fa69be2a
22.22
60
0.361757
false
false
false
false
wess/reddift
refs/heads/master
reddift/Network/Session+users.swift
mit
1
// // Session+users.swift // reddift // // Created by sonson on 2015/05/19. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation extension Session { // MARK: BDT does not cover following methods. /** Get Links or Comments that a user liked, saved, commented, hide, diskiked and etc. :param: username Name of user. :param: content The type of user's contents as UserContent. :param: paginator Paginator object for paging contents. :param: limit The maximum number of comments to return. Default is 25. :param: completion The completion handler to call when the load request is complete. :returns: Data task which requests search to reddit.com. */ public func getUserContent(username:String, content:UserContent, sort:UserContentSortBy, timeFilterWithin:TimeFilterWithin, paginator:Paginator, limit:Int = 25, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? { var parameter = ["t":timeFilterWithin.param]; parameter["limit"] = "\(limit)" parameter["show"] = "given" parameter["sort"] = sort.param // parameter["sr_detail"] = "true" parameter.update(paginator.parameters()) var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/user/" + username + content.path, parameter:parameter, method:"GET", token:token) return handleRequest(request, completion:completion) } /** Return information about the user, including karma and gold status. :param: username The name of an existing user :param: completion The completion handler to call when the load request is complete. :returns: Data task which requests search to reddit.com. */ public func getUserProfile(username:String, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? { var request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/user/\(username)/about", method:"GET", token:token) return handleRequest(request, completion:completion) } }
4312555aaad9b20b1b90d0a307f1cc80
42.854167
231
0.69962
false
false
false
false
urbanthings/urbanthings-sdk-apple
refs/heads/master
UrbanThingsAPI/Public/GooglePolyline/String+GooglePolyline.swift
apache-2.0
1
// // String+GooglePolyline.swift // SwiftGooglePolyline // // The MIT License (MIT) // // Copyright (c) 2016 Mark Woollard // // 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(watchOS) import MapKit #else import CoreLocation #endif extension String { fileprivate struct CoordinateEncoder { private struct PointEncoder { private var previousValue:Int = 0 mutating func encode(coordinate:CLLocationDegrees) -> String { let intCoord = Int(round(coordinate * 1E5)) let delta = intCoord - self.previousValue self.previousValue = intCoord var value = delta << 1; if delta < 0 { value = ~value } var encoded = "" var hasNext = true while(hasNext) { let next = value >> 5 var encValue = UInt8(value & 0x1f) hasNext = next > 0 if hasNext { encValue = encValue | 0x20 } encoded.append(Character(UnicodeScalar(encValue + 0x3f))) value = next } return encoded } } private var latitudeEncoder = PointEncoder() private var longitudeEncoder = PointEncoder() mutating func encode(coordinate:CLLocationCoordinate2D) -> String { return latitudeEncoder.encode(coordinate: coordinate.latitude) + longitudeEncoder.encode(coordinate: coordinate.longitude) } } private struct PolylineIterator : IteratorProtocol { typealias Element = CLLocationCoordinate2D struct Coordinate { private var value:Double = 0.0 mutating func nextValue(polyline:String.UnicodeScalarView, index:inout String.UnicodeScalarView.Index) -> Double? { if index >= polyline.endIndex { return nil } var byte:Int var res:Int = 0 var shift:Int = 0 repeat { byte = Int(polyline[index].value) - 63; if !(0..<64 ~= byte) { return nil } res |= (byte & 0x1F) << shift; shift += 5; index = polyline.index(after: index) } while (byte >= 0x20 && index < polyline.endIndex); self.value = self.value + Double(((res % 2) == 1) ? ~(res >> 1) : res >> 1); return self.value * 1E-5 } } private var polylineUnicodeChars:String.UnicodeScalarView private var current:String.UnicodeScalarView.Index private var latitude:Coordinate = Coordinate() private var longitude:Coordinate = Coordinate() init(_ polyline:String) { self.polylineUnicodeChars = polyline.unicodeScalars self.current = self.polylineUnicodeChars.startIndex } mutating func next() -> Element? { guard let lat = latitude.nextValue(polyline: self.polylineUnicodeChars, index: &self.current), let lng = longitude.nextValue(polyline: self.polylineUnicodeChars, index: &self.current) else { return nil } return Element(latitude: lat, longitude: lng) } } private struct PolylineSequence : Sequence { typealias Iterator = PolylineIterator private let encodedPolyline:String init(_ encodedPolyline:String) throws { var index = encodedPolyline.startIndex try encodedPolyline.unicodeScalars.forEach { if !(63..<127 ~= $0.value) { throw GooglePolylineError.InvalidPolylineString(string: encodedPolyline, errorPosition: index) } index = encodedPolyline.index(after: index) } self.encodedPolyline = encodedPolyline } func makeIterator() -> PolylineIterator { return PolylineIterator(self.encodedPolyline) } } /** Initialize string to Google encoded polyline for a sequence of Core Location points. - parameter sequence: Sequence of points to encode - returns: Initialized encoded string */ public init<S:Sequence>(googlePolylineLocationCoordinateSequence sequence:S) where S.Iterator.Element == CLLocationCoordinate2D { var encoder = CoordinateEncoder() self.init(sequence.reduce("") { $0 + encoder.encode(coordinate: $1) })! } /** Returns sequence of CLLocationCoordinate2D points for the decoded Google polyline string. - throws: GooglePolylineError.InvalidPolylineString if string is not valid polyline - returns: Sequence of coordinates */ public func asCoordinateSequence() throws -> AnySequence<CLLocationCoordinate2D> { return AnySequence<CLLocationCoordinate2D>(try PolylineSequence(self)) } /** Returns array of CLLocationCoordinate2D points for the decoded Google polyline string. - throws: GooglePolylineError.InvalidPolylineString if string is not valid polyline - returns: Array of coordinates */ public func asCoordinateArray() throws -> [CLLocationCoordinate2D] { return [CLLocationCoordinate2D](try self.asCoordinateSequence()) } } // MapKit is not available for watchOS #if !os(watchOS) extension String { /** Initialize string to Google encoded polyline for a sequence of MKMapPoint points. - parameter sequence: Sequence of points to encode - returns: Initialized encoded string */ @available(tvOS 9.2, *) public init<S:Sequence>(googlePolylineMapPointSequence sequence:S) where S.Iterator.Element == MKMapPoint { self.init(googlePolylineLocationCoordinateSequence:sequence.map { MKCoordinateForMapPoint($0) }) } /** Initialize string to Google encoded polyline from points contained in an instance of MKMultiPoint. - parameter sequence: Sequence of points to encode - returns: Initialized encoded string */ @available(tvOS 9.2, *) public init(googlePolylineMKMultiPoint polyline:MKMultiPoint) { var encoder = CoordinateEncoder() var count = polyline.pointCount var ptr = polyline.points() var s = "" while(count > 0) { let coord = MKCoordinateForMapPoint(ptr.pointee) s = s + encoder.encode(coordinate: coord) ptr = ptr.successor() count -= 1 } self.init(s)! } /** Returns MKPolyline instance containing points from decoded Google polyline string. - throws: GooglePolylineError.InvalidPolylineString if string is not valid polyline - returns: MKPolyline instance */ @available(tvOS 9.2, *) public func asMKPolyline() throws -> MKPolyline { return MKPolyline(sequence:try self.asCoordinateSequence()) } } #endif
60c4f8fe2490c2ab83474692b3923e64
33.28
202
0.591949
false
false
false
false
overtake/TelegramSwift
refs/heads/master
packages/TGUIKit/Sources/HorizontalScrollView.swift
gpl-2.0
1
// // HorizontalScrollView.swift // TGUIKit // // Created by Mikhail Filimonov on 26/12/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa // //public class HorizontalScrollView: ScrollView { // // public override func scrollWheel(with event: NSEvent) { // // var scrollPoint = contentView.bounds.origin // let isInverted: Bool = System.isScrollInverted // if event.scrollingDeltaY != 0 { // if isInverted { // scrollPoint.y += -event.scrollingDeltaY // } else { // scrollPoint.y -= event.scrollingDeltaY // } // } // // if event.scrollingDeltaX != 0 { // if !isInverted { // scrollPoint.y += -event.scrollingDeltaX // } else { // scrollPoint.y -= event.scrollingDeltaX // } // } // // clipView.scroll(to: scrollPoint) // // // } // // // open override var hasVerticalScroller: Bool { // get { // return false // } // set { // super.hasVerticalScroller = newValue // } // } // // required public init?(coder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // //}
e2cdcc77735a6c034a12130f8be435ba
24.461538
61
0.504532
false
false
false
false
johnno1962/GitDiff
refs/heads/master
LNXcodeSupport/KeyPath.swift
mit
1
// // KeyPath.swift // LNProvider // // Created by John Holdsworth on 09/06/2017. // Copyright © 2017 John Holdsworth. All rights reserved. // import Foundation @objc public class KeyPath: NSObject { @objc public class func object(for keyPath: String, from: AnyObject) -> AnyObject? { var out = from for key in keyPath.components(separatedBy: ".") { for (name, value) in Mirror(reflecting: out).children { if name == key || name == key + ".storage" { let mirror = Mirror(reflecting: value) if name == "lineNumberLayers" { let dict = NSMutableDictionary() for (_, pair) in mirror.children { let children = Mirror(reflecting: pair).children let key = children.first!.value as! Int let value = children.dropFirst().first!.value dict[NSNumber(value: key)] = value } out = dict } else if name == "name" { out = value as! String as NSString } else if mirror.displayStyle == .optional, let value = mirror.children.first?.value { out = value as AnyObject } else { out = value as AnyObject } break } } } return out === from ? nil : out } }
ca2207f42fb1623abb7780ef72220e28
36.571429
88
0.458809
false
false
false
false
thankmelater23/MyFitZ
refs/heads/master
MyFitZ/UIImage+Gif.swift
mit
1
// // Gif.swift // SwiftGif // // Created by Arne Bahlo on 07.06.14. // Copyright (c) 2014 Arne Bahlo. All rights reserved. // import UIKit import ImageIO // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } extension UIImage { @objc public class func gifWithData(_ data: Data) -> UIImage? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { print("SwiftGif: Source for the image does not exist") return nil } return UIImage.animatedImageWithSource(source) } @objc public class func gifWithName(_ name: String) -> UIImage? { guard let bundleURL = Bundle.main.url(forResource: name, withExtension: "gif") else { print("SwiftGif: This image named \"\(name)\" does not exist") return nil } guard let imageData = try? Data(contentsOf: bundleURL) else { print("SwiftGif: Cannot turn image named \"\(name)\" into NSData") return nil } return gifWithData(imageData) } @objc class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double { var delay = 0.1 // Get dictionaries let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifProperties: CFDictionary = unsafeBitCast( CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self) // Get delay time var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if delayObject.doubleValue == 0 { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } delay = delayObject as! Double if delay < 0.1 { delay = 0.1 // Make sure they're not too fast } return delay } class func gcdForPair(_ a: Int?, _ b: Int?) -> Int { var a = a, b = b // Check if one of them is nil if b == nil || a == nil { if b != nil { return b! } else if a != nil { return a! } else { return 0 } } // Swap for modulo if a < b { let c = a a = b b = c } // Get greatest common divisor var rest: Int while true { rest = a! % b! if rest == 0 { return b! // Found it } else { a = b b = rest } } } @objc class func gcdForArray(_ array: Array<Int>) -> Int { if array.isEmpty { return 1 } var gcd = array[0] for val in array { gcd = UIImage.gcdForPair(val, gcd) } return gcd } @objc class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images = [CGImage]() var delays = [Int]() // Fill arrays for i in 0..<count { // Add image if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { images.append(image) } // At it's delay in cs let delaySeconds = UIImage.delayForImageAtIndex(Int(i), source: source) delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms } // Calculate full duration let duration: Int = { var sum = 0 for val: Int in delays { sum += val } return sum }() // Get frames let gcd = gcdForArray(delays) var frames = [UIImage]() var frame: UIImage var frameCount: Int for i in 0..<count { frame = UIImage(cgImage: images[Int(i)]) frameCount = Int(delays[Int(i)] / gcd) for _ in 0..<frameCount { frames.append(frame) } } // Heyhey let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0) return animation } }
aba59680a93ba347e90b42e8cc6c5e4a
27.645714
103
0.510872
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Tests/ParserTests/Expression/Postfix/ParserFunctionCallExpressionTests.swift
apache-2.0
2
/* Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import AST class ParserFunctionCallExpressionTests: XCTestCase { func testEmptyParameter() { parseExpressionAndTest("foo()", "foo()", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) XCTAssertNotNil(funcCallExpr.argumentClause) XCTAssertTrue(funcCallExpr.argumentClause?.isEmpty ?? false) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentAsExpression() { parseExpressionAndTest("foo(1)", "foo(1)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is LiteralExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentAsNamedExpression() { parseExpressionAndTest("foo(a: 1)", "foo(a: 1)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case let .namedExpression(name, argExpr) = arguments[0] else { XCTFail("Failed in getting a named expression argument.") return } XCTAssertEqual(name.textDescription, "a") XCTAssertTrue(argExpr is LiteralExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentAsOperator() { parseExpressionAndTest("foo(+)", "foo(+)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case let .operator(op) = arguments[0] else { XCTFail("Failed in getting an operator argument.") return } XCTAssertEqual(op, "+") XCTAssertNil(funcCallExpr.trailingClosure) }) } func testOperators() { parseExpressionAndTest("foo( +)", "foo(+)") parseExpressionAndTest("foo(+ )", "foo(+)") parseExpressionAndTest("foo( + )", "foo(+)") parseExpressionAndTest("foo(<+>)", "foo(<+>)") parseExpressionAndTest("foo(!)", "foo(!)") parseExpressionAndTest("foo(....)", "foo(....)") } func testArgumentAsNamedOperator() { parseExpressionAndTest("foo(op: +)", "foo(op: +)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case let .namedOperator(name, op) = arguments[0] else { XCTFail("Failed in getting an operator argument.") return } XCTAssertEqual(name.textDescription, "op") XCTAssertEqual(op, "+") XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentsStartWithMinusSign() { parseExpressionAndTest( "foo(-,op:-,-bar,expr:-bar)", "foo(-, op: -, -bar, expr: -bar)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 4) guard case let .operator(op0) = arguments[0], op0 == "-" else { XCTFail("Failed in getting an operator argument `-`.") return } guard case let .namedOperator(name1, op1) = arguments[1], name1.textDescription == "op", op1 == "-" else { XCTFail("Failed in getting a named operator argument `op: -`.") return } guard case let .expression(expr2) = arguments[2], expr2 is PrefixOperatorExpression, expr2.textDescription == "-bar" else { XCTFail("Failed in getting an expression argument `-bar`.") return } guard case let .namedExpression(name3, expr3) = arguments[3], name3.textDescription == "expr", expr3 is PrefixOperatorExpression, expr3.textDescription == "-bar" else { XCTFail("Failed in getting an operator argument `expr: -bar`.") return } XCTAssertNil(funcCallExpr.trailingClosure) }) parseExpressionAndTest( "min(-data.yMax*0.1, data.yMin)", "min(-data.yMax * 0.1, data.yMin)") } func testArgumentsStartWithExclamation() { parseExpressionAndTest("assert(!bytes.isEmpty)", "assert(!bytes.isEmpty)") } func testMultipleArguments() { parseExpressionAndTest("foo( +, a:-,b : b , _)", "foo(+, a: -, b: b, _)") } func testClosureArgument() { parseExpressionAndTest("map({ $0.textDescription })", "map({ $0.textDescription })", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is ClosureExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testTrailingClosureOneArgument() { parseExpressionAndTest("foo(1) { self.foo = $0 }", "foo(1) { self.foo = $0 }", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard let closureExpr = funcCallExpr.trailingClosure else { XCTFail("Failed in getting a trailing closure.") return } XCTAssertEqual(closureExpr.textDescription, "{ self.foo = $0 }") }) } func testTrailingClosureZeroArgument() { parseExpressionAndTest("foo() { self.foo = $0 }", "foo() { self.foo = $0 }", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) XCTAssertNotNil(funcCallExpr.argumentClause) XCTAssertTrue(funcCallExpr.argumentClause?.isEmpty ?? false) guard let closureExpr = funcCallExpr.trailingClosure else { XCTFail("Failed in getting a trailing closure.") return } XCTAssertEqual(closureExpr.textDescription, "{ self.foo = $0 }") }) } func testTrailingClosureNoArgumentClause() { parseExpressionAndTest("foo { self.foo = $0 }", "foo { self.foo = $0 }", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) XCTAssertNil(funcCallExpr.argumentClause) guard let closureExpr = funcCallExpr.trailingClosure else { XCTFail("Failed in getting a trailing closure.") return } XCTAssertEqual(closureExpr.textDescription, "{ self.foo = $0 }") }) } func testTrailingClosureSameLine() { parseExpressionAndTest("foo\n{ self.foo = $0 }", "foo") } func testDistinguishFromExplicitMemberExpr() { // with argument names parseExpressionAndTest("foo.bar(x)", "foo.bar(x)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is ExplicitMemberExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is IdentifierExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) // no argument name parseExpressionAndTest("foo.bar()", "foo.bar()", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is ExplicitMemberExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertTrue(arguments.isEmpty) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testMemoryReference() { parseExpressionAndTest("foo(&bar)", "foo(&bar)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .memoryReference(let argExpr) = arguments[0] else { XCTFail("Failed in getting a memory reference argument.") return } XCTAssertTrue(argExpr is IdentifierExpression) XCTAssertEqual(argExpr.textDescription, "bar") XCTAssertNil(funcCallExpr.trailingClosure) }) } func testNamedMemoryReference() { parseExpressionAndTest("foo(a: &A.b)", "foo(a: &A.b)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case let .namedMemoryReference(name, argExpr) = arguments[0] else { XCTFail("Failed in getting a named memory reference argument.") return } XCTAssertEqual(name.textDescription, "a") XCTAssertTrue(argExpr is ExplicitMemberExpression) XCTAssertEqual(argExpr.textDescription, "A.b") XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentAsFunctionCallExprWithTrailingClosure() { parseExpressionAndTest( "foo([1,2,3].map { i in i^2 }.joined())", "foo([1, 2, 3].map { i in\ni ^ 2\n}.joined())", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is FunctionCallExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) parseExpressionAndTest( "foo([1,2,3].map { i in i^2 })", "foo([1, 2, 3].map { i in\ni ^ 2\n})", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is FunctionCallExpression) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testArgumentAsEmptyDictionary() { parseExpressionAndTest("foo([:])", "foo([:])", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } XCTAssertTrue(funcCallExpr.postfixExpression is IdentifierExpression) guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) guard case .expression(let argExpr) = arguments[0] else { XCTFail("Failed in getting an expression argument.") return } XCTAssertTrue(argExpr is LiteralExpression) XCTAssertEqual(argExpr.textDescription, "[:]") XCTAssertNil(funcCallExpr.trailingClosure) }) } func testPostfixExpressionAsLiteralExpression() { // https://github.com/yanagiba/swift-lint/issues/37 parseExpressionAndTest("5.power(of: 2)", "5.power(of: 2)", testClosure: { expr in guard let funcCallExpr = expr as? FunctionCallExpression else { XCTFail("Failed in getting a function call expression") return } guard let explicitMemberExpr = funcCallExpr.postfixExpression as? ExplicitMemberExpression, case let .namedType(postfixExpr, identifier) = explicitMemberExpr.kind else { XCTFail("Failed in getting an explicit member expression") return } XCTAssertTrue(postfixExpr is LiteralExpression) XCTAssertEqual(identifier.textDescription, "power") guard let arguments = funcCallExpr.argumentClause else { XCTFail("Failed in getting an argument clause.") return } XCTAssertEqual(arguments.count, 1) XCTAssertNil(funcCallExpr.trailingClosure) }) } func testSourceRange() { let testExprs: [(testString: String, expectedEndColumn: Int)] = [ ("foo()", 6), ("foo(0)", 7), ("foo() { self.foo = $0 }", 24), ("foo(0) { self.foo = $0 }", 25), ("foo { self.foo = $0 }", 22), ] for t in testExprs { parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn)) }) } } static var allTests = [ ("testEmptyParameter", testEmptyParameter), ("testArgumentAsExpression", testArgumentAsExpression), ("testArgumentAsNamedExpression", testArgumentAsNamedExpression), ("testArgumentAsOperator", testArgumentAsOperator), ("testOperators", testOperators), ("testArgumentAsNamedOperator", testArgumentAsNamedOperator), ("testArgumentsStartWithMinusSign", testArgumentsStartWithMinusSign), ("testArgumentsStartWithExclamation", testArgumentsStartWithExclamation), ("testMultipleArguments", testMultipleArguments), ("testClosureArgument", testClosureArgument), ("testTrailingClosureOneArgument", testTrailingClosureOneArgument), ("testTrailingClosureZeroArgument", testTrailingClosureZeroArgument), ("testTrailingClosureNoArgumentClause", testTrailingClosureNoArgumentClause), ("testTrailingClosureSameLine", testTrailingClosureSameLine), ("testDistinguishFromExplicitMemberExpr", testDistinguishFromExplicitMemberExpr), ("testMemoryReference", testMemoryReference), ("testNamedMemoryReference", testNamedMemoryReference), ("testArgumentAsFunctionCallExprWithTrailingClosure", testArgumentAsFunctionCallExprWithTrailingClosure), ("testArgumentAsEmptyDictionary", testArgumentAsEmptyDictionary), ("testPostfixExpressionAsLiteralExpression", testPostfixExpressionAsLiteralExpression), ("testSourceRange", testSourceRange), ] }
a71017ed569998d5beb94474cc511229
35.564356
111
0.679177
false
true
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/XMLDTDNode.swift
apache-2.0
13
// 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 CoreFoundation /*! @typedef XMLDTDNodeKind @abstract The subkind of a DTD node kind. */ extension XMLDTDNode { public enum DTDKind : UInt { case general case parsed case unparsed case parameter case predefined case cdataAttribute case idAttribute case idRefAttribute case idRefsAttribute case entityAttribute case entitiesAttribute case nmTokenAttribute case nmTokensAttribute case enumerationAttribute case notationAttribute case undefinedDeclaration case emptyDeclaration case anyDeclaration case mixedDeclaration case elementDeclaration } } /*! @class XMLDTDNode @abstract The nodes that are exclusive to a DTD @discussion Every DTD node has a name. Object value is defined as follows:<ul> <li><b>Entity declaration</b> - the string that that entity resolves to eg "&lt;"</li> <li><b>Attribute declaration</b> - the default value, if any</li> <li><b>Element declaration</b> - the validation string</li> <li><b>Notation declaration</b> - no objectValue</li></ul> */ open class XMLDTDNode: XMLNode { /*! @method initWithXMLString: @abstract Returns an element, attribute, entity, or notation DTD node based on the full XML string. */ public init?(xmlString string: String) { guard let ptr = _CFXMLParseDTDNode(string) else { return nil } super.init(ptr: ptr) } //primitive public override init(kind: XMLNode.Kind, options: XMLNode.Options = []) { let ptr: _CFXMLNodePtr switch kind { case .elementDeclaration: ptr = _CFXMLDTDNewElementDesc(nil, nil)! default: super.init(kind: kind, options: options) return } super.init(ptr: ptr) } /*! @method dtdKind @abstract Sets the DTD sub kind. */ open var dtdKind: XMLDTDNode.DTDKind { switch _CFXMLNodeGetType(_xmlNode) { case _kCFXMLDTDNodeTypeElement: switch _CFXMLDTDElementNodeGetType(_xmlNode) { case _kCFXMLDTDNodeElementTypeAny: return .anyDeclaration case _kCFXMLDTDNodeElementTypeEmpty: return .emptyDeclaration case _kCFXMLDTDNodeElementTypeMixed: return .mixedDeclaration case _kCFXMLDTDNodeElementTypeElement: return .elementDeclaration default: return .undefinedDeclaration } case _kCFXMLDTDNodeTypeEntity: switch _CFXMLDTDEntityNodeGetType(_xmlNode) { case _kCFXMLDTDNodeEntityTypeInternalGeneral: return .general case _kCFXMLDTDNodeEntityTypeExternalGeneralUnparsed: return .unparsed case _kCFXMLDTDNodeEntityTypeExternalParameter: fallthrough case _kCFXMLDTDNodeEntityTypeInternalParameter: return .parameter case _kCFXMLDTDNodeEntityTypeInternalPredefined: return .predefined case _kCFXMLDTDNodeEntityTypeExternalGeneralParsed: return .general default: fatalError("Invalid entity declaration type") } case _kCFXMLDTDNodeTypeAttribute: switch _CFXMLDTDAttributeNodeGetType(_xmlNode) { case _kCFXMLDTDNodeAttributeTypeCData: return .cdataAttribute case _kCFXMLDTDNodeAttributeTypeID: return .idAttribute case _kCFXMLDTDNodeAttributeTypeIDRef: return .idRefAttribute case _kCFXMLDTDNodeAttributeTypeIDRefs: return .idRefsAttribute case _kCFXMLDTDNodeAttributeTypeEntity: return .entityAttribute case _kCFXMLDTDNodeAttributeTypeEntities: return .entitiesAttribute case _kCFXMLDTDNodeAttributeTypeNMToken: return .nmTokenAttribute case _kCFXMLDTDNodeAttributeTypeNMTokens: return .nmTokensAttribute case _kCFXMLDTDNodeAttributeTypeEnumeration: return .enumerationAttribute case _kCFXMLDTDNodeAttributeTypeNotation: return .notationAttribute default: fatalError("Invalid attribute declaration type") } case _kCFXMLTypeInvalid: return unsafeBitCast(0, to: DTDKind.self) // this mirrors Darwin default: fatalError("This is not actually a DTD node!") } } /*! @method isExternal @abstract True if the system id is set. Valid for entities and notations. */ open var isExternal: Bool { return systemID != nil } //primitive /*! @method openID @abstract Sets the open id. This identifier should be in the default catalog in /etc/xml/catalog or in a path specified by the environment variable XML_CATALOG_FILES. When the public id is set the system id must also be set. Valid for entities and notations. */ open var publicID: String? { get { return _CFXMLDTDNodeCopyPublicID(_xmlNode)?._swiftObject } set { if let value = newValue { _CFXMLDTDNodeSetPublicID(_xmlNode, value) } else { _CFXMLDTDNodeSetPublicID(_xmlNode, nil) } } } /*! @method systemID @abstract Sets the system id. This should be a URL that points to a valid DTD. Valid for entities and notations. */ open var systemID: String? { get { return _CFXMLDTDNodeCopySystemID(_xmlNode)?._swiftObject } set { if let value = newValue { _CFXMLDTDNodeSetSystemID(_xmlNode, value) } else { _CFXMLDTDNodeSetSystemID(_xmlNode, nil) } } } /*! @method notationName @abstract Set the notation name. Valid for entities only. */ open var notationName: String? { get { guard dtdKind == .unparsed else { return nil } return _CFXMLCopyEntityContent(_xmlNode)?._swiftObject } set { guard dtdKind == .unparsed else { return } if let value = newValue { _CFXMLNodeSetContent(_xmlNode, value) } else { _CFXMLNodeSetContent(_xmlNode, nil) } } }//primitive internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLDTDNode { let type = _CFXMLNodeGetType(node) precondition(type == _kCFXMLDTDNodeTypeAttribute || type == _kCFXMLDTDNodeTypeNotation || type == _kCFXMLDTDNodeTypeEntity || type == _kCFXMLDTDNodeTypeElement) if let privateData = _CFXMLNodeGetPrivateData(node) { return XMLDTDNode.unretainedReference(privateData) } return XMLDTDNode(ptr: node) } internal override init(ptr: _CFXMLNodePtr) { super.init(ptr: ptr) } }
ce9b2ad957bd18281fa13673e6cc2d46
29.083636
266
0.557234
false
false
false
false
937447974/YJPageView
refs/heads/master
YJPageViewSwift/YJPageViewSwift/ViewController.swift
mit
1
// // ViewController.swift // YJPageViewSwift // // CSDN:http://blog.csdn.net/y550918116j // GitHub:https://github.com/937447974 // // Created by 阳君 on 16/5/4. // Copyright © 2016年 YJ. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 初始化 let pageView = YJPageView(frame: CGRectZero) self.view.addSubview(pageView) pageView.boundsLayoutTo(self.view) // 监听点击 pageView.pageViewDidSelect = { (pageVC: YJPageViewController) in print("点击:\(pageVC.pageViewObject!.pageIndex)") } // 填充数据源 for _ in 0..<5 { let obj = YJImagePageViewController.pageViewObject() let model = YJImagePageModel() model.imageNamed = "LaunchImage" obj.pageModel = model pageView.dataSource.addObject(obj) } // 刷新界面 pageView.reloadPage() } }
0380bc451ff28a84df0b19485482e03a
24.25641
72
0.601015
false
false
false
false
BlessNeo/ios-charts
refs/heads/master
Charts/Classes/Utils/ChartTransformer.swift
apache-2.0
26
// // ChartTransformer.swift // Charts // // Created by Daniel Cohen Gindi on 6/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards. public class ChartTransformer: NSObject { /// matrix to map the values to the screen pixels internal var _matrixValueToPx = CGAffineTransformIdentity /// matrix for handling the different offsets of the chart internal var _matrixOffset = CGAffineTransformIdentity internal var _viewPortHandler: ChartViewPortHandler public init(viewPortHandler: ChartViewPortHandler) { _viewPortHandler = viewPortHandler } /// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets. public func prepareMatrixValuePx(#chartXMin: Double, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Double) { var scaleX = (_viewPortHandler.contentWidth / deltaX) var scaleY = (_viewPortHandler.contentHeight / deltaY) // setup all matrices _matrixValueToPx = CGAffineTransformIdentity _matrixValueToPx = CGAffineTransformScale(_matrixValueToPx, scaleX, -scaleY) _matrixValueToPx = CGAffineTransformTranslate(_matrixValueToPx, CGFloat(-chartXMin), CGFloat(-chartYMin)) } /// Prepares the matrix that contains all offsets. public func prepareMatrixOffset(inverted: Bool) { if (!inverted) { _matrixOffset = CGAffineTransformMakeTranslation(_viewPortHandler.offsetLeft, _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom) } else { _matrixOffset = CGAffineTransformMakeScale(1.0, -1.0) _matrixOffset = CGAffineTransformTranslate(_matrixOffset, _viewPortHandler.offsetLeft, -_viewPortHandler.offsetTop) } } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the SCATTERCHART. public func generateTransformedValuesScatter(entries: [ChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) for (var j = 0; j < entries.count; j++) { var e = entries[j] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BUBBLECHART. public func generateTransformedValuesBubble(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint] { let count = to - from var valuePoints = [CGPoint]() valuePoints.reserveCapacity(count) for (var j = 0; j < count; j++) { var e = entries[j + from] valuePoints.append(CGPoint(x: CGFloat(e.xIndex - from) * phaseX + CGFloat(from), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the LINECHART. public func generateTransformedValuesLine(entries: [ChartDataEntry], phaseX: CGFloat, phaseY: CGFloat, from: Int, to: Int) -> [CGPoint] { let count = Int(ceil(CGFloat(to - from) * phaseX)) var valuePoints = [CGPoint]() valuePoints.reserveCapacity(count) for (var j = 0; j < count; j++) { var e = entries[j + from] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the CANDLESTICKCHART. public func generateTransformedValuesCandle(entries: [CandleChartDataEntry], phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) for (var j = 0; j < entries.count; j++) { var e = entries[j] valuePoints.append(CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.high) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesBarChart(entries: [BarChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) var setCount = barData.dataSetCount var space = barData.groupSpace for (var j = 0; j < entries.count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0 var y = e.value valuePoints.append(CGPoint(x: x, y: CGFloat(y) * phaseY)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transforms an arraylist of Entry into a double array containing the x and y values transformed with all matrices for the BARCHART. public func generateTransformedValuesHorizontalBarChart(entries: [ChartDataEntry], dataSet: Int, barData: BarChartData, phaseY: CGFloat) -> [CGPoint] { var valuePoints = [CGPoint]() valuePoints.reserveCapacity(entries.count) var setCount = barData.dataSetCount var space = barData.groupSpace for (var j = 0; j < entries.count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + (j * (setCount - 1)) + dataSet) + space * CGFloat(j) + space / 2.0 var y = e.value valuePoints.append(CGPoint(x: CGFloat(y) * phaseY, y: x)) } pointValuesToPixel(&valuePoints) return valuePoints } /// Transform an array of points with all matrices. // VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming. public func pointValuesToPixel(inout pts: [CGPoint]) { var trans = valueToPixelMatrix for (var i = 0, count = pts.count; i < count; i++) { pts[i] = CGPointApplyAffineTransform(pts[i], trans) } } public func pointValueToPixel(inout point: CGPoint) { point = CGPointApplyAffineTransform(point, valueToPixelMatrix) } /// Transform a rectangle with all matrices. public func rectValueToPixel(inout r: CGRect) { r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixel(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.y > 0.0) { r.origin.y *= phaseY } else { var bottom = r.origin.y + r.size.height bottom *= phaseY r.size.height = bottom - r.origin.y } r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// Transform a rectangle with all matrices with potential animation phases. public func rectValueToPixelHorizontal(inout r: CGRect, phaseY: CGFloat) { // multiply the height of the rect with the phase if (r.origin.x > 0.0) { r.origin.x *= phaseY } else { var right = r.origin.x + r.size.width right *= phaseY r.size.width = right - r.origin.x } r = CGRectApplyAffineTransform(r, valueToPixelMatrix) } /// transforms multiple rects with all matrices public func rectValuesToPixel(inout rects: [CGRect]) { var trans = valueToPixelMatrix for (var i = 0; i < rects.count; i++) { rects[i] = CGRectApplyAffineTransform(rects[i], trans) } } /// Transforms the given array of touch points (pixels) into values on the chart. public func pixelsToValue(inout pixels: [CGPoint]) { var trans = pixelToValueMatrix for (var i = 0; i < pixels.count; i++) { pixels[i] = CGPointApplyAffineTransform(pixels[i], trans) } } /// Transforms the given touch point (pixels) into a value on the chart. public func pixelToValue(inout pixel: CGPoint) { pixel = CGPointApplyAffineTransform(pixel, pixelToValueMatrix) } /// Returns the x and y values in the chart at the given touch point /// (encapsulated in a PointD). This method transforms pixel coordinates to /// coordinates / values in the chart. public func getValueByTouchPoint(point: CGPoint) -> CGPoint { return CGPointApplyAffineTransform(point, pixelToValueMatrix) } public var valueToPixelMatrix: CGAffineTransform { return CGAffineTransformConcat( CGAffineTransformConcat( _matrixValueToPx, _viewPortHandler.touchMatrix ), _matrixOffset ) } public var pixelToValueMatrix: CGAffineTransform { return CGAffineTransformInvert(valueToPixelMatrix) } }
0cf30ce86fa9658004b85bcad3a0bd53
33.780069
153
0.627964
false
false
false
false
xu6148152/binea_project_for_ios
refs/heads/master
ListerforAppleWatchiOSandOSX/Swift/Common/AppConfiguration.swift
mit
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Handles application configuration logic and information. */ import Foundation public typealias StorageState = (storageOption: AppConfiguration.Storage, accountDidChange: Bool, cloudAvailable: Bool) public class AppConfiguration { // MARK: Types private struct Defaults { static let firstLaunchKey = "AppConfiguration.Defaults.firstLaunchKey" static let storageOptionKey = "AppConfiguration.Defaults.storageOptionKey" static let storedUbiquityIdentityToken = "AppConfiguration.Defaults.storedUbiquityIdentityToken" } // Keys used to store relevant list data in the userInfo dictionary of an NSUserActivity for continuation. public struct UserActivity { // The editing user activity is integrated into the ubiquitous UI/NSDocument architecture. public static let editing = "com.example.apple-samplecode.Lister.editing" // The watch user activity is used to continue activities started on the watch on other devices. public static let watch = "com.example.apple-samplecode.Lister.watch" public static let listURLPathUserInfoKey = "listURLPathUserInfoKey" public static let listColorUserInfoKey = "listColorUserInfoKey" } // Constants used in assembling and handling the custom lister:// URL scheme. public struct ListerScheme { public static let name = "lister" public static let colorQueryKey = "color" } /* The value of the `LISTER_BUNDLE_PREFIX` user-defined build setting is written to the Info.plist file of every target in Swift version of the Lister project. Specifically, the value of `LISTER_BUNDLE_PREFIX` is used as the string value for a key of `AAPLListerBundlePrefix`. This value is loaded from the target's bundle by the lazily evaluated static variable "prefix" from the nested "Bundle" struct below the first time that "Bundle.prefix" is accessed. This avoids the need for developers to edit both `LISTER_BUNDLE_PREFIX` and the code below. The value of `Bundle.prefix` is then used as part of an interpolated string to insert the user-defined value of `LISTER_BUNDLE_PREFIX` into several static string constants below. */ private struct Bundle { static var prefix = NSBundle.mainBundle().objectForInfoDictionaryKey("AAPLListerBundlePrefix") as String } struct ApplicationGroups { static let primary = "group.\(Bundle.prefix).Lister.Documents" } #if os(OSX) public struct App { public static let bundleIdentifier = "\(Bundle.prefix).ListerOSX" } #endif public struct Extensions { #if os(iOS) public static let widgetBundleIdentifier = "\(Bundle.prefix).Lister.ListerToday" #elseif os(OSX) public static let widgetBundleIdentifier = "\(Bundle.prefix).Lister.ListerTodayOSX" #endif } public enum Storage: Int { case NotSet = 0, Local, Cloud } public class var sharedConfiguration: AppConfiguration { struct Singleton { static let sharedAppConfiguration = AppConfiguration() } return Singleton.sharedAppConfiguration } public class var listerUTI: String { return "com.example.apple-samplecode.Lister" } public class var listerFileExtension: String { return "list" } public class var defaultListerDraftName: String { return NSLocalizedString("List", comment: "") } public class var localizedTodayDocumentName: String { return NSLocalizedString("Today", comment: "The name of the Today list") } public class var localizedTodayDocumentNameAndExtension: String { return "\(localizedTodayDocumentName).\(listerFileExtension)" } private var applicationUserDefaults: NSUserDefaults { return NSUserDefaults(suiteName: ApplicationGroups.primary)! } public private(set) var isFirstLaunch: Bool { get { registerDefaults() return applicationUserDefaults.boolForKey(Defaults.firstLaunchKey) } set { applicationUserDefaults.setBool(newValue, forKey: Defaults.firstLaunchKey) } } private func registerDefaults() { #if os(iOS) let defaultOptions: [NSObject: AnyObject] = [ Defaults.firstLaunchKey: true, Defaults.storageOptionKey: Storage.NotSet.rawValue ] #elseif os(OSX) let defaultOptions: [NSObject: AnyObject] = [ Defaults.firstLaunchKey: true ] #endif applicationUserDefaults.registerDefaults(defaultOptions) } public func runHandlerOnFirstLaunch(firstLaunchHandler: Void -> Void) { if isFirstLaunch { isFirstLaunch = false firstLaunchHandler() } } public var isCloudAvailable: Bool { return NSFileManager.defaultManager().ubiquityIdentityToken != nil } #if os(iOS) public var storageState: StorageState { return (storageOption, hasAccountChanged(), isCloudAvailable) } public var storageOption: Storage { get { let value = applicationUserDefaults.integerForKey(Defaults.storageOptionKey) return Storage(rawValue: value)! } set { applicationUserDefaults.setInteger(newValue.rawValue, forKey: Defaults.storageOptionKey) } } // MARK: Ubiquity Identity Token Handling (Account Change Info) public func hasAccountChanged() -> Bool { var hasChanged = false let currentToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? = NSFileManager.defaultManager().ubiquityIdentityToken let storedToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? = storedUbiquityIdentityToken let currentTokenNilStoredNonNil = currentToken == nil && storedToken != nil let storedTokenNilCurrentNonNil = currentToken != nil && storedToken == nil // Compare the tokens. let currentNotEqualStored = currentToken != nil && storedToken != nil && !currentToken!.isEqual(storedToken!) if currentTokenNilStoredNonNil || storedTokenNilCurrentNonNil || currentNotEqualStored { persistAccount() hasChanged = true } return hasChanged } private func persistAccount() { var defaults = applicationUserDefaults if let token = NSFileManager.defaultManager().ubiquityIdentityToken { let ubiquityIdentityTokenArchive = NSKeyedArchiver.archivedDataWithRootObject(token) defaults.setObject(ubiquityIdentityTokenArchive, forKey: Defaults.storedUbiquityIdentityToken) } else { defaults.removeObjectForKey(Defaults.storedUbiquityIdentityToken) } } // MARK: Convenience private var storedUbiquityIdentityToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? { var storedToken: protocol<NSCoding, NSCopying, NSObjectProtocol>? // Determine if the logged in iCloud account has changed since the user last launched the app. let archivedObject: AnyObject? = applicationUserDefaults.objectForKey(Defaults.storedUbiquityIdentityToken) if let ubiquityIdentityTokenArchive = archivedObject as? NSData { if let archivedObject = NSKeyedUnarchiver.unarchiveObjectWithData(ubiquityIdentityTokenArchive) as? protocol<NSCoding, NSCopying, NSObjectProtocol> { storedToken = archivedObject } } return storedToken } /** Returns a `ListCoordinator` based on the current configuration that queries based on `pathExtension`. For example, if the user has chosen local storage, a local `ListCoordinator` object will be returned. */ public func listCoordinatorForCurrentConfigurationWithPathExtension(pathExtension: String, firstQueryHandler: (Void -> Void)? = nil) -> ListCoordinator { if AppConfiguration.sharedConfiguration.storageOption != .Cloud { // This will be called if the storage option is either `.Local` or `.NotSet`. return LocalListCoordinator(pathExtension: pathExtension, firstQueryUpdateHandler: firstQueryHandler) } else { return CloudListCoordinator(pathExtension: pathExtension, firstQueryUpdateHandler: firstQueryHandler) } } /** Returns a `ListCoordinator` based on the current configuration that queries based on `lastPathComponent`. For example, if the user has chosen local storage, a local `ListCoordinator` object will be returned. */ public func listCoordinatorForCurrentConfigurationWithLastPathComponent(lastPathComponent: String, firstQueryHandler: (Void -> Void)? = nil) -> ListCoordinator { if AppConfiguration.sharedConfiguration.storageOption != .Cloud { // This will be called if the storage option is either `.Local` or `.NotSet`. return LocalListCoordinator(lastPathComponent: lastPathComponent, firstQueryUpdateHandler: firstQueryHandler) } else { return CloudListCoordinator(lastPathComponent: lastPathComponent, firstQueryUpdateHandler: firstQueryHandler) } } /** Returns a `ListsController` instance based on the current configuration. For example, if the user has chosen local storage, a `ListsController` object will be returned that uses a local list coordinator. `pathExtension` is passed down to the list coordinator to filter results. */ public func listsControllerForCurrentConfigurationWithPathExtension(pathExtension: String, firstQueryHandler: (Void -> Void)? = nil) -> ListsController { let listCoordinator = listCoordinatorForCurrentConfigurationWithPathExtension(pathExtension, firstQueryHandler: firstQueryHandler) return ListsController(listCoordinator: listCoordinator, delegateQueue: NSOperationQueue.mainQueue()) { lhs, rhs in return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .OrderedAscending } } /** Returns a `ListsController` instance based on the current configuration. For example, if the user has chosen local storage, a `ListsController` object will be returned that uses a local list coordinator. `lastPathComponent` is passed down to the list coordinator to filter results. */ public func listsControllerForCurrentConfigurationWithLastPathComponent(lastPathComponent: String, firstQueryHandler: (Void -> Void)? = nil) -> ListsController { let listCoordinator = listCoordinatorForCurrentConfigurationWithLastPathComponent(lastPathComponent, firstQueryHandler: firstQueryHandler) return ListsController(listCoordinator: listCoordinator, delegateQueue: NSOperationQueue.mainQueue()) { lhs, rhs in return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .OrderedAscending } } #endif }
e7e74edbb42ed5ef403777f7d143ef59
41.359259
165
0.686079
false
true
false
false
AgeProducts/WatchRealmSync
refs/heads/master
Share module/WatchIPhoneConnect.swift
mit
1
// // WatchIPhoneConnect.swift // WatchRealmSync // // Created by Takuji Hori on 2016/10/11. // Copyright © 2016 AgePro. All rights reserved. // import Foundation import WatchKit import WatchConnectivity import RealmSwift protocol WatchIPhoneConnectDelegate: class { func receiveTransFile(file: WCSessionFile) func receiveRQSSyncDigest(file: WCSessionFile) func receiveRQSSendItems(userInfo: [String : Any]) func receiveRQSSyncAll() func receiveRQSDeleteAll() } class WatchIPhoneConnect:NSObject, WCSessionDelegate { var IsSupport = false var IsReachable = false var IsPaired = false var IsComplicationEnabled = false var IsWatchAppInstalled = false var sessionActivationState:WCSessionActivationState = .notActivated static let sharedConnectivityManager = WatchIPhoneConnect() weak var delegate: WatchIPhoneConnectDelegate? private override init() { super.init() WatchIPhoneConnectInit() } func WatchIPhoneConnectInit() { if watchSupport()==true { let session = WCSession.default() session.delegate = self session.activate() } else { fatalError("Watch connection : not Supported! error.") } } func sessionReachabilityDidChange(_ session: WCSession) { _ = watchReachable() NotificationCenter.default.post(name: NSNotification.Name(rawValue: WCSessionReachabilityDidChangeNotification), object: nil) } #if os(iOS) func sessionDidBecomeInactive(_ session: WCSession) { _ = watchSessionActivationState() } func sessionDidDeactivate(_ session: WCSession) { _ = watchSessionActivationState() WCSession.default().activate() } func sessionWatchStateDidChange(_ session : WCSession) { _ = watchAppInstalled() _ = watchIsPaired() NotificationCenter.default.post(name: NSNotification.Name(rawValue: WCSessionWatchStateDidChangeNotification), object: nil) } #endif func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { if let error = error { NSLog("session activation failed with error: \(error.localizedDescription)") return } _ = watchSessionActivationState() var status = "" switch sessionActivationState { case .activated: status = "Activated" case .inactive: status = "Inactive" case .notActivated: status = "NotActivated" } NSLog("session activation: \(status)") #if os(iOS) _ = watchIsPaired() #endif } // Connection Status func watchSupport() -> Bool { IsSupport = WCSession.isSupported() return IsSupport } func watchReachable() -> Bool{ IsReachable = WCSession.default().isReachable return IsReachable } #if os(iOS) func watchIsPaired() -> Bool { IsPaired = WCSession.default().isPaired return IsPaired } func watchIsComplicationEnabled() -> Bool { IsComplicationEnabled = WCSession.default().isComplicationEnabled return IsComplicationEnabled } func watchAppInstalled() -> Bool { IsWatchAppInstalled = WCSession.default().isWatchAppInstalled return IsWatchAppInstalled } #endif func watchSessionActivationState() -> WCSessionActivationState { sessionActivationState = WCSession.default().activationState return sessionActivationState } // Transfer User Info Data func transferUserInfo(_ command:String, addInfo:[Any]) { let infoDic:[String:Any] = makeMessageCommon(command:command, addInfo:addInfo) if infoDic.isEmpty == true { NSLog("infoDic error:\(String(describing: infoDic))") return } WCSession.default().transferUserInfo(infoDic) } func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any]) { guard let command = userInfo["command"] as? String else { return } switch command { case "requestSyncAll$$": self.delegate?.receiveRQSSyncAll() case "requestSendItems$$": self.delegate?.receiveRQSSendItems(userInfo:userInfo) case "requestDeleteAll$$": self.delegate?.receiveRQSDeleteAll() default: assertionFailure("Receive userInfo command error: \(command)") } } // Transfer Files func transferFile(_ fileUrl:URL, command:String) { WCSession.default().transferFile(fileUrl, metadata: ["command":command]) } func transferFileHasContentPending() -> Bool { return WCSession.default().hasContentPending } func transferFileArray() -> [WCSessionFileTransfer] { return WCSession.default().outstandingFileTransfers } func session(_ session: WCSession, didReceive file: WCSessionFile) { guard let command = file.metadata?["command"] as? String else { return } switch command { case "sendTransFile$$": self.delegate?.receiveTransFile(file: file) case "sendDigestFile$$": self.delegate?.receiveRQSSyncDigest(file: file) default: assertionFailure("Receive transferFile command error: \(command)") } } // make args private func makeMessageCommon(command:String, addInfo:[Any]) -> Dictionary<String,Any> { if command.hasSuffix("$$")==false { assertionFailure("command format error: \(command)") return [:] } var infoDic = ["command":command as Any] // Xcommand$$ = [command] infoDic[command] = Date() as Any? // timestamp = [Xcommand$$] addInfo.enumerated().forEach { index, addObj in autoreleasepool { let className = String(describing: type(of: addObj as Any)).lowercased() switch className { case _ where className.hasPrefix("array"): infoDic[command + String(format:"Array%02d",index)] = addObj default: assertionFailure("addInfo Unsupport class: \(String(describing: type(of: addObj as Any)))") } } } return infoDic } }
b90e3944d6c51fabdfbbff90e38f590a
32.025381
133
0.623732
false
false
false
false
andreacremaschi/GEOSwift
refs/heads/issue212
GEOSwift/GEOS/WKTConvertible.swift
mit
1
import Foundation import geos public protocol WKTConvertible { func wkt() throws -> String func wkt(useFixedPrecision: Bool, roundingPrecision: Int32) throws -> String } protocol WKTConvertibleInternal: WKTConvertible, GEOSObjectConvertible {} extension WKTConvertibleInternal { public func wkt() throws -> String { let context = try GEOSContext() let writer = try WKTWriter( context: context, useFixedPrecision: .geosDefault, roundingPrecision: .geosDefault) return try writer.write(self) } public func wkt(useFixedPrecision: Bool, roundingPrecision: Int32) throws -> String { let context = try GEOSContext() let writer = try WKTWriter( context: context, useFixedPrecision: .custom(useFixedPrecision), roundingPrecision: .custom(roundingPrecision)) return try writer.write(self) } } extension Point: WKTConvertible, WKTConvertibleInternal {} extension LineString: WKTConvertible, WKTConvertibleInternal {} extension Polygon.LinearRing: WKTConvertible, WKTConvertibleInternal {} extension Polygon: WKTConvertible, WKTConvertibleInternal {} extension MultiPoint: WKTConvertible, WKTConvertibleInternal {} extension MultiLineString: WKTConvertible, WKTConvertibleInternal {} extension MultiPolygon: WKTConvertible, WKTConvertibleInternal {} extension GeometryCollection: WKTConvertible, WKTConvertibleInternal {} extension Geometry: WKTConvertible, WKTConvertibleInternal {} private final class WKTWriter { private let context: GEOSContext private let writer: OpaquePointer init(context: GEOSContext, useFixedPrecision: UseFixedPrecision, roundingPrecision: RoundingPrecision) throws { guard let writer = GEOSWKTWriter_create_r(context.handle) else { throw GEOSError.libraryError(errorMessages: context.errors) } self.context = context self.writer = writer if case let .custom(value) = useFixedPrecision { GEOSWKTWriter_setTrim_r(context.handle, writer, value ? 1 : 0) } if case let .custom(value) = roundingPrecision { GEOSWKTWriter_setRoundingPrecision_r(context.handle, writer, value) } } deinit { GEOSWKTWriter_destroy_r(context.handle, writer) } func write(_ geometry: GEOSObjectConvertible) throws -> String { let geosObject = try geometry.geosObject(with: context) guard let chars = GEOSWKTWriter_write_r(context.handle, writer, geosObject.pointer) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { chars.deallocate() } return String(cString: chars) } enum UseFixedPrecision { case geosDefault case custom(Bool) } enum RoundingPrecision { case geosDefault case custom(Int32) } }
9d27730455ac2cbcd4367540814f4cce
33.034884
98
0.696276
false
false
false
false
dymx101/BallDown
refs/heads/master
BallDown/Extension/SKNodeExtension.swift
mit
1
// // SKNodeExtension.swift // BallDown // // Copyright (c) 2015 ones. All rights reserved. // import Foundation import SpriteKit extension SKNode { var bind: AnyObject? { get { return self.userData?.objectForKey("@bind") } set { if newValue == nil { self.userData?.removeObjectForKey("@bind") } else { if self.userData == nil { self.userData = NSMutableDictionary() } self.userData!.setValue(newValue, forKey: "@bind") } } } }
151b05098d6531b3d2d103cf3d80e65d
19.387097
66
0.478605
false
false
false
false
DarlingXIe/WeiBoProject
refs/heads/master
WeiBo/WeiBo/Classes/View/compose/controller/XDLComposeViewController.swift
mit
1
// // XDLComposeViewController.swift // WeiBo // // Created by DalinXie on 16/9/30. // Copyright © 2016年 itcast. All rights reserved. // import UIKit import SVProgressHUD class XDLComposeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUI() NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(emotionButtonClick(noti:)), name: NSNotification.Name(rawValue: XDLEmoticonButtonDidSelectedNotification), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } //MAEK: - notification funcation @objc private func send(){ //MARK: - decide to update textfile or picture if pictureView.images.count == 0{ updateText() }else{ uploadPictureWithText() } } private func updateText(){ let urlString = "https://api.weibo.com/2/statuses/update.json" let accessToken = XDLUserAccountViewModel.shareModel.access_token let params = [ "access_token" : accessToken, "status": textView.emotionText ?? "" ] XDLNetWorkTools.sharedTools.request(method: .Post, urlSting: urlString, parameters: params) { (response, error) in if response == nil && error != nil { print(error) SVProgressHUD.showError(withStatus: "send error") return }else{ print(response) SVProgressHUD.showSuccess(withStatus: "send successed") } } } private func uploadPictureWithText(){ let urlSting = "https://upload.api.weibo.com/2/statuses/upload.json" let accessToken = XDLUserAccountViewModel.shareModel.access_token let params = [ "access_token" : accessToken, "status" : textView.emotionText ?? "" ] let dict = [ "png" : UIImagePNGRepresentation(self.pictureView.images.first!)! ] XDLNetWorkTools.sharedTools.requestUploadPost(method: .Post, urlSting: urlSting, params: params, fileDict: dict) { (response, error) in if error != nil{ print(error) SVProgressHUD.showError(withStatus: "upload error") return } print(response) SVProgressHUD.showError(withStatus: "uplaod success") } XDLNetWorkTools.sharedTools.post(urlSting, parameters: params, constructingBodyWith: { (formData) in let data = UIImagePNGRepresentation(self.pictureView.images.first!)! formData.appendPart(withFileData: data, name: "png", fileName: "bbbb", mimeType: "application/octet-stream") }, progress: nil, success: { (response, _) in print("request successed") SVProgressHUD.showSuccess(withStatus: "upload success") }) { (_, error) in print("request failed") SVProgressHUD.showSuccess(withStatus: "upload failed") } } @objc private func keyBoardWillChangeFrame(noti: NSNotification){ let frame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue print("键盘的最终的位置\(frame)") composeToolBar.snp_updateConstraints { (make) in make.bottom.equalTo(self.view).offset(frame.origin.y - XDLScreenH) } UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // private func setupUI() { // // self.view.backgroundColor = UIColor.black // // } //MARK: back function @objc internal func back(){ self.dismiss(animated: true, completion: nil) } //MARK: NotificationCenter funciton to observer click emotionButtons @objc private func emotionButtonClick(noti: NSNotification){ if noti.userInfo != nil { let emotion = noti.userInfo!["emotion"]! as! XDLEmotion textView.insertEmotion(emotion: emotion) }else{ textView.deleteBackward() } // if emotion.type == 1{ // textView.insertText((emotion.code! as NSString).emoji()) // }else{ //1. capture the bundle // let bundle = XDLEmotionViewModel.sharedViewModel.emotionBundle // let image = UIImage(named: "\(emotion.path!)/\(emotion.png!)", in: bundle, compatibleWith: nil) // //2. init with TextAttachment for image // // let attachment = NSTextAttachment() // //2.1 get the size of picture // let imageWH = textView.font!.lineHeight // attachment.bounds = CGRect(x: 0, y: -4, width: imageWH, height: imageWH) // //2.2 // attachment.image = image // //3. // let attr = NSMutableAttributedString(attributedString: textView.attributedText) // //attr.append(NSAttributedString(attachment:attachment)) // //3.1 get mouse loaciton // var selectedRange = textView.selectedRange //// //// attr.insert(NSAttributedString(attachment: attachment), at: selectedRange.location) // attr.replaceCharacters(in: selectedRange, with: NSAttributedString(attachment: attachment)) //// // attr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, attr.length)) // // textView.attributedText = attr // // selectedRange.location += 1 //// // selectedRange.length = 0 //// // textView.selectedRange = selectedRange // } } //MARK: - setting UI lazy var internal lazy var titleLable :UILabel = {()-> UILabel in let titleLabel = UILabel() titleLabel.numberOfLines = 0; titleLabel.textAlignment = .center titleLabel.font = UIFont.systemFont(ofSize: 16) if let name = XDLUserAccountViewModel.shareModel.countModel?.name{ let title = "Update Status\n\(name)" let attributedText = NSMutableAttributedString(string: title) let range = (title as NSString).range(of: name) attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName: UIColor.lightGray], range: range) titleLabel.attributedText = attributedText }else{ titleLabel.text = "Update Status" titleLabel.textColor = UIColor.black } titleLabel.sizeToFit() return titleLabel }() internal lazy var rightButton :UIButton = {()-> UIButton in let button = UIButton() button.addTarget(self, action: #selector(send), for: .touchUpInside) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled) button.setTitleColor(UIColor.gray, for: .disabled) button.setTitleColor(UIColor.white, for: .normal) button.setTitle("Post", for: .normal) button.frame.size = CGSize(width: 44, height: 30) return button }() //MARK: myLazyVar textView internal lazy var textView :XDLTextView = {()-> XDLTextView in let textView = XDLTextView() textView.delegate = self textView.placeholder = "What's on your mind?" textView.font = UIFont.systemFont(ofSize: 16) textView.alwaysBounceVertical = true return textView }() internal lazy var composeToolBar :XDLComposeToolBar = {()-> XDLComposeToolBar in let composeToolBar = XDLComposeToolBar() return composeToolBar }() internal lazy var pictureView :XDLComposePictureView = {()-> XDLComposePictureView in let view = XDLComposePictureView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout()) view.backgroundColor = UIColor.white //label.textColor = UIcolor.red view.addImageClosure = {[weak self] in print("click add button") self?.selectPicture() } return view }() internal lazy var emotionKeyBorad :XDLEmotionKeyBoard = {()-> XDLEmotionKeyBoard in let emotionKeyBorad = XDLEmotionKeyBoard() emotionKeyBorad.frame.size = CGSize(width: XDLScreenW, height: 216) return emotionKeyBorad }() var image: UIImage? } //MARK: - delegateTextView extension XDLComposeViewController:UITextViewDelegate{ func textViewDidChange(_ textView: UITextView) { navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } func scrollViewDidScroll(_ scrollView: UIScrollView) { self.view.endEditing(true) } } //MARK: - 在同类中设置extension extension XDLComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { internal func setupUI(){ self.view.backgroundColor = UIColor.white navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back to home", target: self, action: #selector(back)) navigationItem.titleView = titleLable navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton) navigationItem.rightBarButtonItem?.isEnabled = false view.addSubview(self.textView) view.addSubview(self.composeToolBar) textView.addSubview(pictureView) //MARK: - judge buttonsType self.composeToolBar.clickButtonClosure = {[weak self] (type) ->() in print("****clickComposeButtons\(self)") switch type { case .picture: self?.selectPicture() case .mention: self?.selectMention() case .trend: self?.selectTrend() case .emotion: self?.selectEmotion() case .add: self?.selectAdd() } } textView.snp_makeConstraints { (make) in make.edges.equalTo(self.view) } composeToolBar.snp_makeConstraints { (make) in make.bottom.left.right.equalTo(self.view) make.height.equalTo(44) } pictureView.snp_makeConstraints { (make) in make.top.equalTo(textView).offset(100) make.left.equalTo(textView).offset(10) make.width.equalTo(textView.snp_width).offset(-20) make.height.equalTo(textView.snp_height) } } //MARK: - selectButtonsFunc internal func selectPicture(){ let vc = UIImagePickerController() vc.delegate = self // 判断前置或者后置摄像头是否可用 // UIImagePickerController.isCameraDeviceAvailable(UIImagePickerControllerCameraDevice) // 判断某个数据类型是否可用 // if UIImagePickerController.isSourceTypeAvailable(.camera) == false{ // print("照相机不可用") // } vc.sourceType = .photoLibrary vc.allowsEditing = true self.present(vc, animated: true) { print("present UIImagePicker") } } internal func selectMention(){ print("click selectMention button") } internal func selectTrend(){ print("click selectTrend button") } internal func selectEmotion(){ print("click selectEmotion button") if textView.inputView == nil{ textView.inputView = emotionKeyBorad }else{ textView.inputView = nil } textView.reloadInputViews() if !textView.isFirstResponder{ textView.becomeFirstResponder() } composeToolBar.isSystemKeyBorad = textView.inputView == nil } internal func selectAdd(){ print("click selectAdd button") } //MARK: -achieveDelegateFunctionToSelectImagePicker func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage //saving the memory for load images from devices. to shrink the images let img = image.scaleTo(width: 500) pictureView.addImage(image: img) let data = UIImagePNGRepresentation(img)! (data as NSData).write(toFile: "/Users/DalinXie/Desktop/bbbb.png", atomically: true) picker.dismiss(animated: true, completion: nil) } }
a87528a8d314ba8712e4fbcb026b7ed7
31.341686
192
0.580082
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/EditAvatarVC.swift
mit
1
// // EditAvatarVC.swift // TranslationEditor // // Created by Mikko Hilpinen on 30.3.2017. // Copyright © 2017 SIL. All rights reserved. // import UIKit // This view controller is used for editing and creation of new project avatars class EditAvatarVC: UIViewController { // OUTLETS ------------------ @IBOutlet weak var createAvatarView: CreateAvatarView! @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var saveButton: BasicButton! @IBOutlet weak var contentView: KeyboardReactiveView! @IBOutlet weak var contentTopConstraint: NSLayoutConstraint! @IBOutlet weak var contentBottomConstraint: NSLayoutConstraint! // ATTRIBUTES -------------- static let identifier = "EditAvatar" private var editedInfo: (Avatar, AvatarInfo)? private var completionHandler: ((Avatar, AvatarInfo) -> ())? private var presetName: String? // LOAD ---------------------- override func viewDidLoad() { super.viewDidLoad() errorLabel.text = nil // If in editing mode, some fields cannot be edited if let (avatar, info) = editedInfo { createAvatarView.avatarImage = info.image createAvatarView.avatarName = avatar.name createAvatarView.isShared = info.isShared // Sharing can be enabled / disabled for non-shared accounts only // (Shared account avatars have always sharing enabled) do { if let account = try AgricolaAccount.get(avatar.accountId) { createAvatarView.mustBeShared = account.isShared } } catch { print("ERROR: Failed to read account data. \(error)") } } // If creating a new avatar, those created for shared accounts must be shared else { if let presetName = presetName { createAvatarView.avatarName = presetName } do { guard let accountId = Session.instance.accountId, let account = try AgricolaAccount.get(accountId) else { print("ERROR: No account selected") return } createAvatarView.mustBeShared = account.isShared } catch { print("ERROR: Failed to check whether account is shared. \(error)") } } createAvatarView.viewController = self contentView.configure(mainView: view, elements: [createAvatarView, errorLabel, saveButton], topConstraint: contentTopConstraint, bottomConstraint: contentBottomConstraint, style: .squish) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) contentView.startKeyboardListening() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) contentView.endKeyboardListening() } // ACTIONS ------------------ @IBAction func cancelButtonPressed(_ sender: Any) { dismiss(animated: true) } @IBAction func backgroundTapped(_ sender: Any) { dismiss(animated: true) } @IBAction func saveButtonPressed(_ sender: Any) { // Checks that all necessary fields are filled guard createAvatarView.allFieldsFilled else { errorLabel.text = NSLocalizedString("Please fill in the required fields", comment: "An error message displayed when trying to create new avatar without first filling all required fields") return } // Makes sure the passwords match guard createAvatarView.passwordsMatch else { errorLabel.text = NSLocalizedString("The passwords don't match!", comment: "An error message displayed when new avatar password is not repeated correctly") return } do { // Makes the necessary modifications to the avatar if let (avatar, info) = editedInfo { if let newImage = createAvatarView.avatarImage?.scaledToFit(CGSize(width: 320, height: 320)), info.image != newImage { try info.setImage(newImage) } if let newPassword = createAvatarView.offlinePassword { info.setPassword(newPassword) } avatar.name = createAvatarView.avatarName try DATABASE.tryTransaction { try avatar.push() try info.push() } dismiss(animated: true, completion: { self.completionHandler?(avatar, info) }) } // Or creates a new avatar entirely else { guard let accountId = Session.instance.accountId else { print("ERROR: No account selected") return } guard let projectId = Session.instance.projectId, let project = try Project.get(projectId) else { print("ERROR: No project selected") return } let avatarName = createAvatarView.avatarName // Makes sure there is no avatar with the same name yet /* guard try Avatar.get(projectId: projectId, avatarName: avatarName) == nil else { errorLabel.text = "Avatar with the provided name already exists!" return }*/ // Checks whether admin rights should be given to the new avatar // (must be the owner of the project, and the first avatar if account is shared) var makeAdmin = false if project.ownerId == accountId, let account = try AgricolaAccount.get(accountId) { if try (!account.isShared || AvatarView.instance.avatarQuery(projectId: projectId, accountId: accountId).firstResultRow() == nil) { makeAdmin = true } } // Creates the new information let avatar = Avatar(name: avatarName, projectId: projectId, accountId: accountId, isAdmin: makeAdmin) let info = AvatarInfo(avatarId: avatar.idString, password: createAvatarView.offlinePassword, isShared: createAvatarView.isShared) // Saves the changes to the database (inlcuding image attachment) try DATABASE.tryTransaction { try avatar.push() try info.push() if let image = self.createAvatarView.avatarImage { try info.setImage(image) } } dismiss(animated: true, completion: { self.completionHandler?(avatar, info) }) } } catch { print("ERROR: Failed to perform the required database operations. \(error)") } } // OTHER METHODS -------------- func configureForEdit(avatar: Avatar, avatarInfo: AvatarInfo, successHandler: ((Avatar, AvatarInfo) -> ())? = nil) { self.editedInfo = (avatar, avatarInfo) self.completionHandler = successHandler } func configureForCreate(avatarName: String? = nil, successHandler: ((Avatar, AvatarInfo) -> ())? = nil) { self.presetName = avatarName self.completionHandler = successHandler } }
e4f5d8cefd90e381a20b161fe8794799
26.137339
190
0.686225
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/Controller/Personal/PersonalAchievementsCollectionViewCell.swift
mit
1
// // PersonalAchievementsCollectionViewCell.swift // Whereami // // Created by A on 16/6/1. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class PersonalAchievementsCollectionViewCell: UICollectionViewCell { var itemLogo:UIImageView? = nil var progressLabel:UILabel? = nil var itemName:UILabel? = nil override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } func setupUI(){ itemLogo = UIImageView() itemLogo?.backgroundColor = UIColor.lightGrayColor() self.contentView.addSubview(itemLogo!) /* progress = UIProgressView() progress?.progressTintColor = UIColor.greenColor() progress?.trackTintColor = UIColor.grayColor() progress?.progress = 0.5 self.contentView.addSubview(progress!) */ progressLabel = UILabel() progressLabel?.textAlignment = .Center progressLabel?.textColor = UIColor.grayColor() progressLabel?.font = UIFont.customFont(12.0) self.contentView.addSubview(progressLabel!) itemName = UILabel() itemName?.textAlignment = .Center itemName?.textColor = UIColor.grayColor() self.contentView.addSubview(itemName!) itemLogo?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10) itemLogo?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10) itemLogo?.autoPinEdgeToSuperviewEdge(.Top, withInset: 10) itemLogo?.autoSetDimension(.Height, toSize: 60) progressLabel?.autoPinEdge(.Top, toEdge: .Bottom, ofView: itemLogo!, withOffset: 10) progressLabel?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10) progressLabel?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10) progressLabel?.autoSetDimension(.Height, toSize: 13) itemName?.autoPinEdge(.Top, toEdge: .Bottom, ofView: progressLabel!) itemName?.autoPinEdgeToSuperviewEdge(.Left, withInset: 10) itemName?.autoPinEdgeToSuperviewEdge(.Right, withInset: 10) itemName?.autoPinEdgeToSuperviewEdge(.Bottom) } }
3050b915a6f56320bfd28c2d0f205469
33.318182
92
0.656512
false
false
false
false
danielbaak/imperii-viz
refs/heads/master
ImperiiViz - iOS/ImperiiViz/ViewController.swift
mit
1
// // ViewController.swift // ImperiiViz // // Created by Frederik Riedel on 26.04.15. // Copyright (c) 2015 Frederik Riedel. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController,UITextFieldDelegate,TimeLineViewDelegate { var dateIndicator : DateIndicator? var mapView: MKMapView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor=UIColor.whiteColor() //var backgroundImage = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)) //backgroundImage.image=UIImage(named: "Startpage") //self.view.addSubview(backgroundImage) /*var suchfled = UITextField(frame: CGRectMake((self.view.frame.width-400)/2, (self.view.frame.height-44)/2, 400, 44)) suchfled.backgroundColor=UIColor.darkGrayColor() self.view.addSubview(suchfled)*/ NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillChange:", name:UIKeyboardWillChangeFrameNotification, object:nil) var from = NSDateComponents() from.year = 600 var to = NSDateComponents() to.year = 1600 mapView = MKMapView(frame: self.view.frame) mapView!.mapType = MKMapType.Satellite mapView!.showsPointsOfInterest = false mapView!.zoomEnabled = true mapView!.scrollEnabled = true self.view.addSubview(mapView!) var timeLineView = TimeLineView(frame: CGRectMake(0, self.view.frame.height-75, self.view.frame.size.width, 75), from: from, to: to) timeLineView.delegate=self self.view.addSubview(timeLineView) dateIndicator = DateIndicator(frame: CGRectMake(100, timeLineView.frame.origin.y-55 + 15, 100, 55)) self.view.addSubview(dateIndicator!) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func yearChanged(year: Float, position: CGPoint) { dateIndicator?.frame=CGRectMake(position.x, dateIndicator!.frame.origin.y, dateIndicator!.frame.width, dateIndicator!.frame.height) dateIndicator?.center=CGPointMake(position.x, dateIndicator!.center.y) dateIndicator?.setYear(year) } }
4a5c792dd8e1ff2db4ae496ccc4b01a3
33.763889
150
0.659608
false
false
false
false
caiomello/utilities
refs/heads/main
Sources/Utilities/Protocols & Classes/TextInputViewController.swift
mit
1
// // TextInputViewController.swift // Utilities // // Created by Caio Mello on 09.05.20. // Copyright © 2020 Caio Mello. All rights reserved. // import UIKit open class TextInputViewController: UIViewController { @IBOutlet public var scrollView: UIScrollView! } // MARK: - Lifecycle extension TextInputViewController { override open func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil) } } // MARK: - Notifications extension TextInputViewController { @objc private func adjustForKeyboard(notification: Notification) { let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)!.cgRectValue if notification.name == UIResponder.keyboardWillHideNotification { scrollView.contentInset.bottom = 0 } else { let inset = view.convert(keyboardRect, from: nil).size.height scrollView.contentInset.bottom = inset - scrollView.safeAreaInsets.bottom } scrollView.verticalScrollIndicatorInsets.bottom = scrollView.contentInset.bottom } }
bef9eb40109b88487b2dcbc3e0c94b07
35.595238
160
0.743006
false
false
false
false
mlgoogle/viossvc
refs/heads/master
viossvc/Marco/AppConst.swift
apache-2.0
1
// // AppConfig.swift // viossvc // // Created by yaowang on 2016/10/31. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit class AppConst { class Color { static let C0 = UIColor(RGBHex:0x131f32) static let CR = UIColor(RGBHex:0xb82525) static let C1 = UIColor.blackColor() static let C2 = UIColor(RGBHex:0x666666) static let C3 = UIColor(RGBHex:0x999999) static let C4 = UIColor(RGBHex:0xaaaaaa) static let C5 = UIColor(RGBHex:0xe2e2e2) static let C6 = UIColor(RGBHex:0xf2f2f2) }; class SystemFont { static let S1 = UIFont.systemFontOfSize(18) static let S2 = UIFont.systemFontOfSize(15) static let S3 = UIFont.systemFontOfSize(13) static let S4 = UIFont.systemFontOfSize(12) static let S5 = UIFont.systemFontOfSize(10) static let S14 = UIFont.systemFontOfSize(14) }; class Event { static let login = "login" static let sign_btn = "sign_btn" static let sign_confrim = "sign_confrim" static let sign_last = "sign_last" static let sign_next = "sign_next" static let bank_add = "bank_add" static let bank_select = "bank_select" static let drawcash = "drawcash" static let drawcash_pwd = "drawcash_pwd" static let drawcash_total = "drawcash_total" static let message_send = "message_send" static let order_accept = "order_accept" static let order_aply = "order_aply" static let order_unaply = "order_unaply" static let order_chat = "order_chat" static let order_list = "order_list" static let order_refuse = "order_refuse" static let server_add = "server_add" static let server_addPicture = "server_addPicture" static let server_beauty = "server_beauty" static let server_cancelAdd = "server_cancelAdd" static let server_mark = "server_mark" static let server_next = "server_next" static let server_picture = "server_picture" static let server_sure = "server_sure" static let server_delete = "server_delete" static let server_update = "server_update" static let server_start = "server_start" static let server_end = "server_end" static let server_type = "server_type" static let server_price = "server_price" static let share_eat = "share_eat" static let share_fun = "share_fun" static let share_hotel = "share_hotel" static let share_phone = "share_phone" static let share_travel = "share_travel" static let skillshare_comment = "skillshare_comment" static let skillshare_detail = "skillshare_detail" static let user_anthuser = "user_anthuser" static let user_location = "user_location" static let user_logout = "user_logout" static let user_nickname = "user_nickname" static let user_question = "user_question" static let user_resetpwd = "user_resetpwd" static let user_sex = "user_sex" static let user_version = "user_version" static let user_icon = "user_icon" static let user_clearcache = "user_clearcache" } class Network { #if true //是否测试环境 // static let TcpServerIP:String = "192.168.199.131" // static let TcpServerPort:UInt16 = 10001 static let TcpServerIP:String = "139.224.34.22" static let TcpServerPort:UInt16 = 10001 static let TttpHostUrl:String = "http://139.224.34.22"; #else static let TcpServerIP:String = "103.40.192.101"; static let TcpServerPort:UInt16 = 10002 static let HttpHostUrl:String = "http://61.147.114.78"; #endif static let TimeoutSec:UInt16 = 10 static let qiniuHost = "http://ofr5nvpm7.bkt.clouddn.com/" static let qiniuImgStyle = "?imageView2/2/w/160/h/160/interlace/0/q/100" } class Text { static let PhoneFormatErr = "请输入正确的手机号" static let VerifyCodeErr = "请输入正确的验证码" static let CheckInviteCodeErr = "邀请码有误,请重新输入" static let SMSVerifyCodeErr = "获取验证码失败" static let PasswordTwoErr = "两次密码不一致" static let ReSMSVerifyCode = "重新获取" static let ErrorDomain = "com.yundian.viossvc" static let PhoneFormat = "^1[3|4|5|7|8][0-9]\\d{8}$" static let RegisterPhoneError = "输入的手机号已注册" } static let DefaultPageSize = 15 enum Action:UInt { case CallPhone = 10001 case HandleOrder = 11001 case ShowLocation = 11002 } static let UMAppkey = "584a3eb345297d271600127e" }
a13000dbaf77c4bd0f5893c37035a100
38.241667
80
0.627522
false
false
false
false
inaka/Jolly
refs/heads/master
Sources/Cache.swift
apache-2.0
1
// Cache.swift // Jolly // // Copyright 2016 Erlang Solutions, Ltd. - http://erlang-solutions.com/ // // 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 /* Even though the Jolly Hipchat extension works per room, the server is global. Therefore, we must store repos organized per room_id. > Example (Key-Value storage): > ------------------------------ > K room_id_1: > V [repo_1, repo_2] > K room_id_2: > V [repo_1, repo_3, repo_4] */ class Cache { let defaults: UserDefaults init(defaults: UserDefaults = .standard) { self.defaults = defaults } func add(_ repo: Repo, toRoomWithId roomId: String) { let repoId = repo.fullName guard let reposIds = self.defaults.array(forKey: roomId) as? [String] else { self.defaults.set([repoId], forKey: roomId) return } self.defaults.set(reposIds + [repoId], forKey: roomId) } func remove(_ repo: Repo, fromRoomWithId roomId: String) { guard let reposIds = self.defaults.array(forKey: roomId) as? [String] else { return } self.defaults.set(reposIds.filter { $0 != repo.fullName }, forKey: roomId) } func repos(forRoomWithId roomId: String) -> [Repo] { guard let reposIds = self.defaults.array(forKey: roomId) as? [String] else { return [Repo]() } return reposIds .sorted { $0.lowercased() < $1.lowercased() } .flatMap { Repo(fullName: $0) } } }
8ea55a5f4b4598077a946c7b26c34936
32.180328
132
0.632905
false
false
false
false
Endore8/TimePicker
refs/heads/master
TimePicker/Classes/Utils/TimeFormat.swift
mit
1
// // TimeFormat.swift // TimePicker // // Created by Oleh Stasula on 20/02/2017. // Copyright © 2017 Oleh Stasula. All rights reserved. // import Foundation typealias TimeFormat = (hour: String, minute: String, period: String?) func !=(t1: TimeFormat, t2: TimeFormat) -> Bool { return !( t1.hour == t2.hour && t1.minute == t2.minute && t1.period == t2.period ) }
a1f72eeeef09385ea25d9c4908a06392
20.210526
70
0.612903
false
false
false
false
thatseeyou/SpriteKitExamples.playground
refs/heads/master
Pages/Treadmill.xcplaygroundpage/Contents.swift
isc
1
/*: ### PhysicsBody 안에 가두기 - Edge collider는 mass가 없기 때문에 원하는 효과를 주기 어려운 경우가 있다. - 안이 비어있는 physics body를 만들 수는 없기 때문에 휘어서 가두었다. */ import UIKit import SpriteKit class GameScene: SKScene { var contentCreated = false let pi:CGFloat = CGFloat(M_PI) override func didMove(to view: SKView) { if self.contentCreated != true { do { let shape = SKShapeNode(path: makeHalfCircle().cgPath) shape.strokeColor = SKColor.green shape.fillColor = SKColor.red shape.position = CGPoint(x: self.frame.midX, y: self.frame.midY) shape.physicsBody = SKPhysicsBody(polygonFrom: makeHalfCircle().cgPath) shape.physicsBody?.isDynamic = true shape.physicsBody?.pinned = true shape.physicsBody?.affectedByGravity = false shape.physicsBody?.friction = 1.0 addChild(shape) shape.run(angularImpulse()) } do { let picker = SKShapeNode(rect: CGRect(x: -10.0, y: -30.0, width: 20.0, height: 60.0)) picker.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 100.0) picker.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 20.0, height: 60.0)) picker.physicsBody?.affectedByGravity = false addChild(picker) } addBall(CGPoint(x: self.frame.midX, y: self.frame.midY)) addBall(CGPoint(x: self.frame.midX - 40, y: self.frame.midY)) addBall(CGPoint(x: self.frame.midX + 50, y: self.frame.midY)) self.physicsWorld.speed = 0.5 //self.physicsWorld.gravity = CGVectorMake(0, -9) self.contentCreated = true } } func addBall(_ position:CGPoint) { let radius = CGFloat(20.0) let ball = SKShapeNode(circleOfRadius: radius) ball.position = position ball.physicsBody = SKPhysicsBody(circleOfRadius: radius) ball.physicsBody?.friction = 0.5 ball.physicsBody?.density = 0.2 addChild(ball) let label = SKLabelNode(text: "45") label.fontSize = 18.0 label.position = CGPoint( x: 0.0, y: 0.0) label.verticalAlignmentMode = .center // CGRectGetMidX(ball.bounds), // CGRectGetMidY(ball.bounds)); ball.addChild(label) } func makeHalfCircle() -> UIBezierPath { // CGPath가 되면 X축을 중심으로 flipping // physicsBody에 사용하기 위해서는 counter clockwise가 되도록 하는 것이 좋다. (bezierPathByReversingPath를 사용해서 변경하는 것도 가능하다.) let bezierPath = UIBezierPath() let innerRadius = CGFloat(100.0) let outerRadius = innerRadius + 10.0 let startAngle = 0.0 * pi; let endAngle = 0.0001 * pi; let startPoint = CGPoint(x: innerRadius * cos(startAngle), y: innerRadius * sin(startAngle)) bezierPath.move(to: startPoint) // inner circle bezierPath.addArc(withCenter: CGPoint(x: 0.0, y: 0.0), radius: innerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false) //bezierPath.addLineToPoint(CGPointMake(110, 0.0)) // outer circle bezierPath.addArc(withCenter: CGPoint(x: 0.0, y: 0.0), radius: outerRadius , startAngle: endAngle, endAngle: startAngle, clockwise: true) bezierPath.close() return bezierPath } func angularImpulse() -> SKAction { let waitAction = SKAction.wait(forDuration: 2.0) let impulse = SKAction.applyAngularImpulse(0.7, duration: 3.0) let delayImpulse = SKAction.sequence([waitAction, impulse]) return delayImpulse } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
690420d64f137830550545c3607dc621
32.5
145
0.597933
false
false
false
false
biohazardlover/ROer
refs/heads/master
Roer/DatabaseRecordAttributeGroupCell.swift
mit
1
import UIKit class DatabaseRecordAttributeGroupCell: UITableViewCell { var recordAttributeGroup: DatabaseRecordAttributeGroup? { didSet { let attribute1 = recordAttributeGroup?.first attribute1NameLabel?.text = attribute1?.name attribute1ValueLabel?.text = attribute1?.value let attribute2 = recordAttributeGroup?.second attribute2NameLabel?.text = attribute2?.name attribute2ValueLabel?.text = attribute2?.value let attribute3 = recordAttributeGroup?.third attribute3NameLabel?.text = attribute3?.name attribute3ValueLabel?.text = attribute3?.value } } @IBOutlet weak var attribute1NameLabel: UILabel? @IBOutlet weak var attribute1ValueLabel: UILabel? @IBOutlet weak var attribute2NameLabel: UILabel? @IBOutlet weak var attribute2ValueLabel: UILabel? @IBOutlet weak var attribute3NameLabel: UILabel? @IBOutlet weak var attribute3ValueLabel: UILabel? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) } }
58a250d7274d11ca0ed73cf48909f578
34.911765
75
0.666667
false
false
false
false