repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
auth0/Lock.iOS-OSX | Lock/BannerMessagePresenter.swift | 2 | 2375 | // BannerMessagePresenter.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
struct BannerMessagePresenter: MessagePresenter {
weak var root: UIView?
weak var messageView: MessageView?
mutating func showError(_ error: LocalizableError) {
guard error.userVisible else { return }
show(message: error.localizableMessage, flavor: .failure)
}
mutating func showSuccess(_ message: String) {
show(message: message, flavor: .success)
}
mutating func hideCurrent() {
self.messageView?.removeFromSuperview()
self.messageView = nil
}
private mutating func show(message: String, flavor: MessageView.Flavor) {
let view = MessageView()
view.type = flavor
view.message = message
guard let root = self.root else { return }
root.addSubview(view)
constraintEqual(anchor: view.topAnchor, toAnchor: root.layoutMarginsGuide.topAnchor)
constraintEqual(anchor: view.leftAnchor, toAnchor: root.leftAnchor)
constraintEqual(anchor: view.rightAnchor, toAnchor: root.rightAnchor)
view.translatesAutoresizingMaskIntoConstraints = false
self.messageView = view
Queue.main.after(4) { [weak view] in view?.removeFromSuperview() }
}
}
| mit | 4d7b1769a3ca0fb20a3e616ad5720f0c | 37.306452 | 92 | 0.72 | 4.72167 | false | false | false | false |
biohazardlover/NintendoEverything | Pods/ImageViewer/ImageViewer/Source/GalleryConfiguration.swift | 2 | 9940 | //
// GalleryConfiguration.swift
// ImageViewer
//
// Created by Kristian Angyal on 04/03/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
public typealias GalleryConfiguration = [GalleryConfigurationItem]
public enum GalleryConfigurationItem {
/// Allows to stop paging at the beginning and the end of item list or page infinitely in a "carousel" like mode.
case pagingMode(GalleryPagingMode)
/// Distance (width of the area) between images when paged.
case imageDividerWidth(CGFloat)
///Option to set the Close button type.
case closeButtonMode(ButtonMode)
///Option to set the Close button type within the Thumbnails screen.
case seeAllCloseButtonMode(ButtonMode)
///Option to set the Thumbnails button type.
case thumbnailsButtonMode(ButtonMode)
///Option to set the Delete button type.
case deleteButtonMode(ButtonMode)
/// Layout behaviour for the Close button.
case closeLayout(ButtonLayout)
/// Layout behaviour for the Close button within the Thumbnails screen.
case seeAllCloseLayout(ButtonLayout)
/// Layout behaviour for the Thumbnails button.
case thumbnailsLayout(ButtonLayout)
/// Layout behaviour for the Delete button.
case deleteLayout(ButtonLayout)
/// This spinner is shown when we page to an image page, but the image itself is still loading.
case spinnerStyle(UIActivityIndicatorViewStyle)
/// Tint color for the spinner.
case spinnerColor(UIColor)
/// Layout behaviour for optional header view.
case headerViewLayout(HeaderLayout)
/// Layout behaviour for optional footer view.
case footerViewLayout(FooterLayout)
/// Sets the status bar visible/invisible while gallery is presented.
case statusBarHidden(Bool)
/// Sets the close button, header view and footer view visible/invisible on launch. Visibility of these three views is toggled by single tapping anywhere in the gallery area. This setting is global to Gallery.
case hideDecorationViewsOnLaunch(Bool)
///Allows to turn on/off decoration views hiding via single tap.
case toggleDecorationViewsBySingleTap(Bool)
///Allows to uiactivityviewcontroller with itemview via long press.
case activityViewByLongPress(Bool)
/// Allows you to select between different types of initial gallery presentation style
case presentationStyle(GalleryPresentationStyle)
///Allows to set maximum magnification factor for the image
case maximumZoomScale(CGFloat)
///Sets the duration of the animation when item is double tapped and transitions between ScaleToAspectFit & ScaleToAspectFill sizes.
case doubleTapToZoomDuration(TimeInterval)
///Transition duration for the blur layer component of the overlay when Gallery is being presented.
case blurPresentDuration(TimeInterval)
///Delayed start for the transition of the blur layer component of the overlay when Gallery is being presented.
case blurPresentDelay(TimeInterval)
///Transition duration for the color layer component of the overlay when Gallery is being presented.
case colorPresentDuration(TimeInterval)
///Delayed start for the transition of color layer component of the overlay when Gallery is being presented.
case colorPresentDelay(TimeInterval)
///Delayed start for decoration views transition (fade-in) when Gallery is being presented.
case decorationViewsPresentDelay(TimeInterval)
///Transition duration for the blur layer component of the overlay when Gallery is being dismissed.
case blurDismissDuration(TimeInterval)
///Transition delay for the blur layer component of the overlay when Gallery is being dismissed.
case blurDismissDelay(TimeInterval)
///Transition duration for the color layer component of the overlay when Gallery is being dismissed.
case colorDismissDuration(TimeInterval)
///Transition delay for the color layer component of the overlay when Gallery is being dismissed.
case colorDismissDelay(TimeInterval)
///Transition duration for the item when the fade-in/fade-out effect is used globally for items while Gallery is being presented /dismissed.
case itemFadeDuration(TimeInterval)
///Transition duration for decoration views when they fade-in/fade-out after single tap.
case decorationViewsFadeDuration(TimeInterval)
///Duration of animated re-layout after device rotation.
case rotationDuration(TimeInterval)
/// Duration of the displacement effect when gallery is being presented.
case displacementDuration(TimeInterval)
/// Duration of the displacement effect when gallery is being dismissed.
case reverseDisplacementDuration(TimeInterval)
///Setting this to true is useful when your overlay layer is not fully opaque and you have multiple images on screen at once. The problem is image 1 is going to be displaced (gallery is being presented) and you can see that it is missing in the parent canvas because it "left the canvas" and the canvas bleeds its content through the overlay layer. However when you page to a different image and you decide to dismiss the gallery, that different image is going to be returned (using reverse displacement). That looks a bit strange because it is reverse displacing but it actually is already present in the parent canvas whereas the original image 1 is still missing there. There is no meaningful way to manage these displaced views. This setting helps to avoid it his problem by keeping the originals in place while still using the displacement effect.
case displacementKeepOriginalInPlace(Bool)
///Provides the most typical timing curves for the displacement transition.
case displacementTimingCurve(UIViewAnimationCurve)
///Allows to optionally set a spring bounce when the displacement transition finishes.
case displacementTransitionStyle(GalleryDisplacementStyle)
///For the image to be reverse displaced, it must be visible in the parent view frame on screen, otherwise it's pointless to do the reverse displacement animation as we would be animating to out of bounds of the screen. However, there might be edge cases where only a tiny percentage of image is visible on screen, so reverse-displacing to that might not be desirable / visually pleasing. To address this problem, we can define a valid area that will be smaller by a given margin and sit centered inside the parent frame. For example, setting a value of 20 means the reverse displaced image must be in a rect that is inside the parent frame and the margin on all sides is to the parent frame is 20 points.
case displacementInsetMargin(CGFloat)
///Base color of the overlay layer that is mostly visible when images are displaced (gallery is being presented), rotated and interactively dismissed.
case overlayColor(UIColor)
///Allows to select the overall tone on the B&W scale of the blur layer in the overlay.
case overlayBlurStyle(UIBlurEffectStyle)
///The opacity of overlay layer when the displacement effect finishes anf the gallery is fully presented. Valid values are from 0 to 1 where 1 is full opacity i.e the overlay layer is fully opaque, 0 is completely transparent and effectively invisible.
case overlayBlurOpacity(CGFloat)
///The opacity of overlay layer when the displacement effect finishes anf the gallery is fully presented. Valid values are from 0 to 1 where 1 is full opacity i.e the overlay layer is fully opaque, 0 is completely transparent and effectively invisible.
case overlayColorOpacity(CGFloat)
///The minimum velocity needed for the image to continue on its swipe-to-dismiss path instead of returning to its original position. The velocity is in scalar units per second, which in our case represents points on screen per second. When the thumb moves on screen and eventually is lifted, it traveled along a path and the speed represents the number of points it traveled in the last 1000 msec before it was lifted.
case swipeToDismissThresholdVelocity(CGFloat)
///Allows to decide direction of swipe to dismiss, or disable it altogether
case swipeToDismissMode(GallerySwipeToDismissMode)
///Allows to set rotation support support with relation to rotation support in the hosting app.
case rotationMode(GalleryRotationMode)
///Allows the video player to automatically continue playing the next video
case continuePlayVideoOnEnd(Bool)
///Allows auto play video after gallery presented
case videoAutoPlay(Bool)
///Tint color of video controls
case videoControlsColor(UIColor)
}
public enum GalleryRotationMode {
///Gallery will rotate to orientations supported in the application.
case applicationBased
///Gallery will rotate regardless of the rotation setting in the application.
case always
}
public enum ButtonMode {
case none
case builtIn /// Standard Close or Thumbnails button.
case custom(UIButton)
}
public enum GalleryPagingMode {
case standard /// Allows paging through images from 0 to N, when first or last image reached ,horizontal swipe to dismiss kicks in.
case carousel /// Pages through images from 0 to N and the again 0 to N in a loop, works both directions.
}
public enum GalleryDisplacementStyle {
case normal
case springBounce(CGFloat) ///
}
public enum GalleryPresentationStyle {
case fade
case displacement
}
public struct GallerySwipeToDismissMode: OptionSet {
public init(rawValue: Int) { self.rawValue = rawValue }
public let rawValue: Int
public static let never = GallerySwipeToDismissMode(rawValue: 0)
public static let horizontal = GallerySwipeToDismissMode(rawValue: 1 << 0)
public static let vertical = GallerySwipeToDismissMode(rawValue: 1 << 1)
public static let always: GallerySwipeToDismissMode = [ .horizontal, .vertical ]
}
| mit | 66ac6da1c338c31b7b756952787fb24a | 47.247573 | 856 | 0.769695 | 5.123196 | false | false | false | false |
zhangao0086/RageComicGetter | RageComicGetter/RageComicGetter/RCRequestManager.swift | 1 | 3807 | //
// RCRequestManager.swift
// RageComicGetter
//
// Created by 张奥 on 15/2/16.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import Cocoa
let ListAllURL = "http://alltheragefaces.com/api/all/faces"
let requestManager = RCRequestManager()
class RCRequestManager: NSObject {
private let manager = AFHTTPRequestOperationManager()
class func sharedManager() -> RCRequestManager {
return requestManager
}
func getListWithDirectory(directory: NSString) {
var isDir = ObjCBool(true)
let isExists = NSFileManager.defaultManager().fileExistsAtPath(directory, isDirectory:&isDir)
if isExists == false {
println("不是有效的目录")
return
}
manager.GET(ListAllURL, parameters: nil, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
var images = Array<RCImage>()
if let imagesDict = responseObject as? NSArray {
for imageDict in imagesDict {
let image = RCImage()
image.id = imageDict["id"] as NSString
image.title = imageDict["title"] as NSString
image.emotion = imageDict["emotion"] as NSString
image.canonical = imageDict["canonical"] as NSString
image.created = imageDict["created"] as NSString
image.categoryfk = imageDict["categoryfk"] as NSString
if let tags = imageDict["tags"] as? NSString {
image.tags = tags
}
image.views = imageDict["views"] as NSString
image.weeklyViews = imageDict["weekly_views"] as NSString
image.png = imageDict["png"] as NSString
image.jpg = imageDict["jpg"] as NSString
image.largePng = imageDict["largepng"] as NSString
image.svg = imageDict["svg"] as NSString
images.append(image)
}
}
println("共\(images.count)张")
self.downloadsForImages(images, directory: directory)
}) { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
print(error)
}
}
private func downloadsForImages(images: Array<RCImage>, directory: NSString) {
if images.count > 0 {
println("开始下载...")
var i = 0
for image in images {
let request = NSURLRequest(URL: NSURL(string: image.png)!)
var imageName = image.title + "-\(image.id)"
while (imageName.hasPrefix(".")) {
imageName.removeAtIndex(imageName.startIndex)
}
let savedUrl = NSURL(string: directory)
let savedPath = savedUrl!.URLByAppendingPathComponent(imageName + ".png").absoluteString!.stringByRemovingPercentEncoding!
let operation = AFHTTPRequestOperation(request: request)
operation.outputStream = NSOutputStream(toFileAtPath: savedPath, append: false)
operation.setCompletionBlockWithSuccess({ (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
println("File download to \(savedPath)")
println(++i)
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println("error: \(error)")
})
manager.operationQueue.maxConcurrentOperationCount = 3
manager.operationQueue.addOperation(operation)
}
}
}
}
| mit | 3b218427b39b2d4119c220065cf981ee | 40.944444 | 138 | 0.558146 | 5.502915 | false | false | false | false |
LeeShiYoung/DouYu | DouYuAPP/DouYuAPP/Classes/Main/View/Yo_PageTitleView.swift | 1 | 4796 | //
// Yo_PageTitleView.swift
// DouYuAPP
//
// Created by shying li on 2017/4/5.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
private let titleW = kScreenW / 4
private let lineH = CGFloat(2)
private let layerH = CGFloat(0.5)
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0)
protocol PageTitleViewDelegate : class {
func pageTitleView(_ titleView : Yo_PageTitleView, selectedIndex index : Int)
}
class Yo_PageTitleView: UIView {
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
weak var delegate : PageTitleViewDelegate?
fileprivate var currentIndex : Int = 0
init(frame: CGRect, titles: [String]) {
super.init(frame: frame)
addSubview(lineView)
configTitleView(titles: titles)
layer.addSublayer(bottomLayer)
}
fileprivate lazy var lineView: UIView = {[weak self] in
let lineView = UIView()
lineView.backgroundColor = UIColor.orange
lineView.frame = CGRect(x: 0, y: (self?.frame.size.height)! - lineH - layerH, width: kScreenW / 4, height: lineH)
return lineView
}()
fileprivate lazy var bottomLayer: CAShapeLayer = {[weak self] in
let bottomLayer = CAShapeLayer()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: (self?.frame.size.height)! - layerH * 0.5))
path.addLine(to: CGPoint(x: (self?.frame.size.width)!, y: (self?.frame.size.height)! - layerH * 0.5))
bottomLayer.path = path.cgPath
bottomLayer.strokeColor = UIColor.colorWithHex("#9a9a9a")?.cgColor
bottomLayer.lineWidth = layerH
bottomLayer.frame = (self?.bounds)!
return bottomLayer
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension Yo_PageTitleView {
fileprivate func configTitleView(titles: [String]) {
for i in 0 ..< titles.count {
let label = UILabel()
label.textColor = UIColor.colorWithHex("#515151")
label.text = titles[i]
label.frame = CGRect(x: titleW * CGFloat(i), y: 0, width: titleW, height: self.frame.size.height - lineH)
label.tag = i
label.textAlignment = .center
addSubview(label)
titleLabels.append(label)
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
}
extension Yo_PageTitleView {
func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
lineView.frame.origin.x = sourceLabel.frame.origin.x + moveX
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
currentIndex = targetIndex
}
}
extension Yo_PageTitleView {
@objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer) {
// 0.获取当前Label
guard let currentLabel = tapGes.view as? UILabel else { return }
// 1.如果是重复点击同一个Title,那么直接返回
if currentLabel.tag == currentIndex { return }
// 2.获取之前的Label
let oldLabel = titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
// 4.保存最新Label的下标值
currentIndex = currentLabel.tag
// 5.滚动条位置发生改变
let scrollLineX = CGFloat(currentIndex) * lineView.frame.width
UIView.animate(withDuration: 0.15, animations: {
self.lineView.frame.origin.x = scrollLineX
})
// 6.通知代理
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
| apache-2.0 | a9ee07ad56847b5ff3ad9b63eb77ad84 | 35.570313 | 174 | 0.631062 | 4.488015 | false | false | false | false |
abeintopalo/AppIconSetGen | Sources/AppIconSetGenCore/AppIconSet.swift | 1 | 2835 | //
// AppIconSet.swift
// AppIconSetGenCore
//
// Created by Attila Bencze on 11/05/2017.
//
//
import Cocoa
import Foundation
import PathKit
public struct AppIconSet {
let iconInfoItems: [IconInfo]
public func createOnDisk(sourceImage: NSImage, outputFolderPath: String, appIconSetName: String) throws {
let items = iconInfoItems
let imageSizesInPixels = items.reduce(into: Set<CGFloat>()) { (result: inout Set<CGFloat>, iconInfo) in
result.insert(iconInfo.sizeInPixels)
}
// create output folder
let folderPath = Path(outputFolderPath) + Path("\(appIconSetName).appiconset")
print("Creating app icon set in \(folderPath)")
try? folderPath.delete() // ignore errors
try folderPath.mkpath()
// create scaled icons
try imageSizesInPixels.forEach { sizeInPixels in
let iconFileName = appIconFileName(from: sizeInPixels)
print("Creating \(iconFileName)")
if let imageData = sourceImage.imagePNGRepresentation(widthInPixels: sizeInPixels, heightInPixels: sizeInPixels) {
let outputFile = folderPath + Path(iconFileName)
try outputFile.write(imageData as Data)
}
}
// create Contents.json file
let contentsJSONFile = folderPath + Path("Contents.json")
print("Creating \(contentsJSONFile)")
let entries = items.reduce(into: [String]()) { (result: inout [String], iconInfo) in
let iconFileName = appIconFileName(from: iconInfo.sizeInPixels)
let sizeDim = iconInfo.size.cleanValue
let size = "\(sizeDim)x\(sizeDim)"
let scale = "\(iconInfo.scale.cleanValue)x"
var entryLines = [String]()
entryLines.append("\n\"size\":\"\(size)\"")
entryLines.append("\n\"idiom\":\"\(iconInfo.idiom.contentJSONFormat)\"")
if iconInfo.role != .any {
entryLines.append("\n\"role\":\"\(iconInfo.role.contentJSONFormat)\"")
}
if iconInfo.subtype != .any {
entryLines.append("\n\"subtype\":\"\(iconInfo.subtype.contentJSONFormat)\"")
}
entryLines.append("\n\"filename\":\"\(iconFileName)\"")
entryLines.append("\n\"scale\":\"\(scale)\"")
result.append("\n{\(entryLines.joined(separator: ","))\n}")
}.joined(separator: ",")
let contents = "{\n\"images\":[\(entries)\n],\n\"info\":{\n\"version\":1,\n\"author\":\"xcode\"\n}\n}"
try contentsJSONFile.write(contents)
}
public init(iconInfoItems: [IconInfo]) {
self.iconInfoItems = iconInfoItems
}
private func appIconFileName(from sizeInPixels: CGFloat) -> String {
return "appicon_\(sizeInPixels.cleanValue).png"
}
}
| mit | c21dd9b04407ff7ffdda63688b643bc9 | 34.4375 | 126 | 0.607407 | 4.450549 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Lint/UnusedClosureParameterRuleExamples.swift | 1 | 5399 | enum UnusedClosureParameterRuleExamples {
static let nonTriggering = [
Example("[1, 2].map { $0 + 1 }\n"),
Example("[1, 2].map({ $0 + 1 })\n"),
Example("[1, 2].map { number in\n number + 1 \n}\n"),
Example("[1, 2].map { _ in\n 3 \n}\n"),
Example("[1, 2].something { number, idx in\n return number * idx\n}\n"),
Example("let isEmpty = [1, 2].isEmpty()\n"),
Example("violations.sorted(by: { lhs, rhs in \n return lhs.location > rhs.location\n})\n"),
Example("rlmConfiguration.migrationBlock.map { rlmMigration in\n" +
"return { migration, schemaVersion in\n" +
"rlmMigration(migration.rlmMigration, schemaVersion)\n" +
"}\n" +
"}"),
Example("genericsFunc { (a: Type, b) in\n" +
"a + b\n" +
"}\n"),
Example("var label: UILabel = { (lbl: UILabel) -> UILabel in\n" +
" lbl.backgroundColor = .red\n" +
" return lbl\n" +
"}(UILabel())\n"),
Example("hoge(arg: num) { num in\n" +
" return num\n" +
"}\n"),
Example("""
({ (manager: FileManager) in
print(manager)
})(FileManager.default)
"""),
Example("""
withPostSideEffect { input in
if true { print("\\(input)") }
}
"""),
Example("""
viewModel?.profileImage.didSet(weak: self) { (self, profileImage) in
self.profileImageView.image = profileImage
}
"""),
Example("""
let failure: Failure = { task, error in
observer.sendFailed(error, task)
}
"""),
Example("""
List($names) { $name in
Text(name)
}
"""),
Example("""
List($names) { $name in
TextField($name)
}
"""),
Example(#"_ = ["a"].filter { `class` in `class`.hasPrefix("a") }"#)
]
static let triggering = [
Example("[1, 2].map { ↓number in\n return 3\n}\n"),
Example("[1, 2].map { ↓number in\n return numberWithSuffix\n}\n"),
Example("[1, 2].map { ↓number in\n return 3 // number\n}\n"),
Example("[1, 2].map { ↓number in\n return 3 \"number\"\n}\n"),
Example("[1, 2].something { number, ↓idx in\n return number\n}\n"),
Example("genericsFunc { (↓number: TypeA, idx: TypeB) in return idx\n}\n"),
Example("hoge(arg: num) { ↓num in\n" +
"}\n"),
Example("fooFunc { ↓아 in\n }"),
Example("func foo () {\n bar { ↓number in\n return 3\n}\n"),
Example("""
viewModel?.profileImage.didSet(weak: self) { (↓self, profileImage) in
profileImageView.image = profileImage
}
"""),
Example("""
let failure: Failure = { ↓task, error in
observer.sendFailed(error)
}
"""),
Example("""
List($names) { ↓$name in
Text("Foo")
}
"""),
Example("""
let class1 = "a"
_ = ["a"].filter { ↓`class` in `class1`.hasPrefix("a") }
""")
]
static let corrections = [
Example("[1, 2].map { ↓number in\n return 3\n}\n"):
Example("[1, 2].map { _ in\n return 3\n}\n"),
Example("[1, 2].map { ↓number in\n return numberWithSuffix\n}\n"):
Example("[1, 2].map { _ in\n return numberWithSuffix\n}\n"),
Example("[1, 2].map { ↓number in\n return 3 // number\n}\n"):
Example("[1, 2].map { _ in\n return 3 // number\n}\n"),
Example("[1, 2].something { number, ↓idx in\n return number\n}\n"):
Example("[1, 2].something { number, _ in\n return number\n}\n"),
Example("genericsFunc(closure: { (↓int: Int) -> Void in // do something\n})\n"):
Example("genericsFunc(closure: { (_: Int) -> Void in // do something\n})\n"),
Example("genericsFunc { (↓a, ↓b: Type) -> Void in\n}\n"):
Example("genericsFunc { (_, _: Type) -> Void in\n}\n"),
Example("genericsFunc { (↓a: Type, ↓b: Type) -> Void in\n}\n"):
Example("genericsFunc { (_: Type, _: Type) -> Void in\n}\n"),
Example("genericsFunc { (↓a: Type, ↓b) -> Void in\n}\n"):
Example("genericsFunc { (_: Type, _) -> Void in\n}\n"),
Example("genericsFunc { (a: Type, ↓b) -> Void in\nreturn a\n}\n"):
Example("genericsFunc { (a: Type, _) -> Void in\nreturn a\n}\n"),
Example("hoge(arg: num) { ↓num in\n}\n"):
Example("hoge(arg: num) { _ in\n}\n"),
Example("""
func foo () {
bar { ↓number in
return 3
}
}
"""):
Example("""
func foo () {
bar { _ in
return 3
}
}
"""),
Example("class C {\n #if true\n func f() {\n [1, 2].map { ↓number in\n return 3\n }\n }\n #endif\n}"):
Example("class C {\n #if true\n func f() {\n [1, 2].map { _ in\n return 3\n }\n }\n #endif\n}"),
Example("""
let failure: Failure = { ↓task, error in
observer.sendFailed(error)
}
"""):
Example("""
let failure: Failure = { _, error in
observer.sendFailed(error)
}
""")
]
}
| mit | b6b1e3eb3514b7f620d4a064d396b5ab | 37.688406 | 110 | 0.46844 | 3.72575 | false | false | false | false |
lvillani/theine | ChaiHelper/AppDelegate.swift | 1 | 1514 | // SPDX-License-Identifier: GPL-3.0-only
//
// Chai - Don't let your Mac fall asleep, like a sir
// Copyright (C) 2021 Chai authors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import Cocoa
import os
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_: Notification) {
// Find whether parent application is running
let isRunning = NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == "me.villani.lorenzo.Chai"
}
if isRunning {
os_log("Parent application already running")
return
}
// Launch parent application
os_log("Launching parent application")
let bundlePath = NSString(string: Bundle.main.bundlePath).pathComponents
let parentPath = Array(bundlePath[..<(bundlePath.count - 4)])
NSWorkspace.shared.launchApplication(NSString.path(withComponents: parentPath))
NSRunningApplication.current.terminate()
}
}
| gpl-3.0 | 7cee2fae87bbd7b39dc285cae506ad87 | 34.209302 | 83 | 0.737781 | 4.466077 | false | false | false | false |
pecuniabanking/pecunia-client | Source/ExSwift/ExSwift.swift | 1 | 8090 | //
// ExSwift.swift
// ExSwift
//
// Created by pNre on 07/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
infix operator =~
infix operator |~
infix operator ..
infix operator <=>
public typealias Ex = ExSwift
open class ExSwift {
/**
Creates a wrapper that, executes function only after being called n times.
- parameter n: No. of times the wrapper has to be called before function is invoked
- parameter function: Function to wrap
- returns: Wrapper function
*/
open class func after <P, T> (_ n: Int, function: @escaping (P...) -> T) -> ((P...) -> T?) {
typealias Function = ([P]) -> T
var times = n
return {
(params: P...) -> T? in
// Workaround for the now illegal (T...) type.
let adaptedFunction = unsafeBitCast(function, to: Function.self)
if times <= 0 {
return adaptedFunction(params)
}
times = times - 1;
return nil
}
}
/**
Creates a wrapper that, executes function only after being called n times
- parameter n: No. of times the wrapper has to be called before function is invoked
- parameter function: Function to wrap
- returns: Wrapper function
*/
/*public class func after <T> (n: Int, function: Void -> T) -> (Void -> T?) {
func callAfter (args: Any?...) -> T {
return function()
}
let f = ExSwift.after(n, function: callAfter)
return { f([nil]) }
}*/
/**
Creates a wrapper function that invokes function once.
Repeated calls to the wrapper function will return the value of the first call.
- parameter function: Function to wrap
- returns: Wrapper function
*/
open class func once <P, T> (_ function: @escaping (P...) -> T) -> ((P...) -> T) {
typealias Function = ([P]) -> T
var returnValue: T? = nil
return { (params: P...) -> T in
if returnValue != nil {
return returnValue!
}
let adaptedFunction = unsafeBitCast(function, to: Function.self)
returnValue = adaptedFunction(params)
return returnValue!
}
}
/**
Creates a wrapper function that invokes function once.
Repeated calls to the wrapper function will return the value of the first call.
- parameter function: Function to wrap
- returns: Wrapper function
*/
/*public class func once <T> (function: Void -> T) -> (Void -> T) {
let f = ExSwift.once {
(params: Any?...) -> T in
return function()
}
return { f([nil]) }
}*/
/**
Creates a wrapper that, when called, invokes function with any additional
partial arguments prepended to those provided to the new function.
- parameter function: Function to wrap
- parameter parameters: Arguments to prepend
- returns: Wrapper function
*/
open class func partial <P, T> (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((P...) -> T) {
typealias Function = ([P]) -> T
return { (params: P...) -> T in
let adaptedFunction = unsafeBitCast(function, to: Function.self)
return adaptedFunction(parameters + params)
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function with one parameter to cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P) -> R) -> ((P) -> R) {
var cache = [P:R]()
return { (param: P) -> R in
let key = param
if let cachedValue = cache[key] {
return cachedValue
} else {
let value = function(param)
cache[key] = value
return value
}
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function to cache
- parameter hash: Parameters based hashing function that computes the key used to store each result in the cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R, hash: @escaping ((P...) -> P)) -> ((P...) -> R) {
typealias Function = ([P]) -> R
typealias Hash = ([P]) -> P
var cache = [P:R]()
return { (params: P...) -> R in
let adaptedFunction = unsafeBitCast(function, to: Function.self)
let adaptedHash = unsafeBitCast(hash, to: Hash.self)
let key = adaptedHash(params)
if let cachedValue = cache[key] {
return cachedValue
} else {
let value = adaptedFunction(params)
cache[key] = value
return value
}
}
}
/**
Creates a wrapper for function that caches the result of function's invocations.
- parameter function: Function to cache
- returns: Wrapper function
*/
open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R) -> ((P...) -> R) {
return cached(function, hash: { (params: P...) -> P in return params[0] })
}
/**
Utility method to return an NSRegularExpression object given a pattern.
- parameter pattern: Regex pattern
- parameter ignoreCase: If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag
- returns: NSRegularExpression object
*/
internal class func regex (_ pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? {
var options = NSRegularExpression.Options.dotMatchesLineSeparators.rawValue
if ignoreCase {
options = NSRegularExpression.Options.caseInsensitive.rawValue | options
}
return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: options))
}
}
func <=> <T: Comparable>(lhs: T, rhs: T) -> Int {
if lhs < rhs {
return -1
} else if lhs > rhs {
return 1
} else {
return 0
}
}
/**
* Internal methods
*/
extension ExSwift {
/**
* Converts, if possible, and flattens an object from its Objective-C
* representation to the Swift one.
* @param object Object to convert
* @returns Flattenend array of converted values
*/
internal class func bridgeObjCObject <T, S> (_ object: S) -> [T] {
var result = [T]()
let reflection = Mirror(reflecting: object)
let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children)
// object has an Objective-C type
if let obj = object as? T {
// object has type T
result.append(obj)
} else if reflection.subjectType == NSArray.self {
// If it is an NSArray, flattening will produce the expected result
if let array = object as? NSArray {
result += array.flatten()
} else if let bridged = mirrorChildrenCollection as? T {
result.append(bridged)
}
} else if object is Array<T> {
// object is a native Swift array
// recursively convert each item
for (_, value) in mirrorChildrenCollection! {
result += Ex.bridgeObjCObject(value)
}
}
return result
}
}
| gpl-2.0 | 9b0953a72b1c8c490a7cb865c1db994a | 29.877863 | 131 | 0.538813 | 4.960147 | false | false | false | false |
fuzongjian/SwiftStudy | SwiftStudy/Project/常见功能集锦/Block传值/BlockController.swift | 1 | 1273 | //
// BlockController.swift
// SwiftStudy
//
// Created by 付宗建 on 16/8/16.
// Copyright © 2016年 youran. All rights reserved.
//
import UIKit
class BlockController: SuperViewController {
var testLable : UILabel?
override func viewDidLoad() {
super.viewDidLoad()
configBlockControllerUI()
}
func configBlockControllerUI(){
testLable = UILabel.init(frame: CGRectMake(0, 80, 200, 40))
testLable?.center.x = self.view.center.x
testLable?.textAlignment = .Center
testLable?.text = "测试专用"
self.view.addSubview(testLable!)
let button = UIButton.init(type: .System)
button.frame = CGRectMake(0, 150, 300, 50)
button.center.x = self.view.center.x
button.setTitle("跳转到下一个界面", forState: .Normal)
button.addTarget(self, action: #selector(buttonClicked(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonClicked(sender: UIButton) {
let secondController = NextBlockController()
secondController.block = {str in
self.testLable?.text = str
}
self.navigationController?.pushViewController(secondController, animated: true)
}
}
| apache-2.0 | 0f5b4eb5a667f8983ed8ab900af03f23 | 30.794872 | 102 | 0.644355 | 4.20339 | false | true | false | false |
soh335/FileWatch | FileWatch/FileWatch.swift | 1 | 7607 | import Foundation
public class FileWatch {
// wrap FSEventStreamEventFlags as OptionSetType
public struct EventFlag: OptionSet {
public let rawValue: FSEventStreamEventFlags
public init(rawValue: FSEventStreamEventFlags) {
self.rawValue = rawValue
}
public static let None = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagNone))
public static let MustScanSubDirs = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs))
public static let UserDropped = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagUserDropped))
public static let KernelDropped = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagKernelDropped))
public static let EventIdsWrapped = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagEventIdsWrapped))
public static let HistoryDone = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagHistoryDone))
public static let RootChanged = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagRootChanged))
public static let Mount = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagMount))
public static let Unmount = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagUnmount))
@available(OSX 10.7, *)
public static let ItemCreated = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemCreated))
@available(OSX 10.7, *)
public static let ItemRemoved = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemRemoved))
@available(OSX 10.7, *)
public static let ItemInodeMetaMod = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemInodeMetaMod))
@available(OSX 10.7, *)
public static let ItemRenamed = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemRenamed))
@available(OSX 10.7, *)
public static let ItemModified = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemModified))
@available(OSX 10.7, *)
public static let ItemFinderInfoMod = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemFinderInfoMod))
@available(OSX 10.7, *)
public static let ItemChangeOwner = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemChangeOwner))
@available(OSX 10.7, *)
public static let ItemXattrMod = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemXattrMod))
@available(OSX 10.7, *)
public static let ItemIsFile = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemIsFile))
@available(OSX 10.7, *)
public static let ItemIsDir = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemIsDir))
@available(OSX 10.7, *)
public static let ItemIsSymlink = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemIsSymlink))
@available(OSX 10.9, *)
public static let OwnEvent = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagOwnEvent))
@available(OSX 10.10, *)
public static let ItemIsHardlink = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemIsHardlink))
@available(OSX 10.10, *)
public static let ItemIsLastHardlink = EventFlag(rawValue: FSEventStreamEventFlags(kFSEventStreamEventFlagItemIsLastHardlink))
}
// wrap FSEventStreamCreateFlags as OptionSetType
public struct CreateFlag: OptionSet {
public let rawValue: FSEventStreamCreateFlags
public init(rawValue: FSEventStreamCreateFlags) {
self.rawValue = rawValue
}
public static let None = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagNone))
public static let UseCFTypes = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes))
public static let NoDefer = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagNoDefer))
public static let WatchRoot = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagWatchRoot))
@available(OSX 10.6, *)
public static let IgnoreSelf = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagIgnoreSelf))
@available(OSX 10.7, *)
public static let FileEvents = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents))
@available(OSX 10.9, *)
public static let MarkSelf = CreateFlag(rawValue: FSEventStreamCreateFlags(kFSEventStreamCreateFlagMarkSelf))
}
public struct Event {
public let path: String
public let flag: EventFlag
public let eventID: FSEventStreamEventId
}
public enum Error: Swift.Error {
case startFailed
case streamCreateFailed
case notContainUseCFTypes
}
public typealias EventHandler = (Event) -> Void
open let eventHandler: EventHandler
private var eventStream: FSEventStreamRef?
public init(paths: [String], createFlag: CreateFlag, runLoop: RunLoop, latency: CFTimeInterval, eventHandler: @escaping EventHandler) throws {
self.eventHandler = eventHandler
var ctx = FSEventStreamContext(version: 0, info: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()), retain: nil, release: nil, copyDescription: nil)
if !createFlag.contains(.UseCFTypes) {
throw Error.notContainUseCFTypes
}
guard let eventStream = FSEventStreamCreate(kCFAllocatorDefault, streamCallback, &ctx, paths as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), latency, createFlag.rawValue) else {
throw Error.streamCreateFailed
}
FSEventStreamScheduleWithRunLoop(eventStream, runLoop.getCFRunLoop(), CFRunLoopMode.defaultMode.rawValue)
if !FSEventStreamStart(eventStream) {
throw Error.startFailed
}
self.eventStream = eventStream
}
deinit {
guard let eventStream = self.eventStream else {
return
}
FSEventStreamStop(eventStream)
FSEventStreamInvalidate(eventStream)
FSEventStreamRelease(eventStream)
self.eventStream = nil
}
}
fileprivate func streamCallback(streamRef: ConstFSEventStreamRef, clientCallBackInfo: UnsafeMutableRawPointer?, numEvents: Int, eventPaths: UnsafeMutableRawPointer, eventFlags: UnsafePointer<FSEventStreamEventFlags>, eventIds: UnsafePointer<FSEventStreamEventId>) -> Void {
let `self` = unsafeBitCast(clientCallBackInfo, to: FileWatch.self)
guard let eventPathArray = unsafeBitCast(eventPaths, to: NSArray.self) as? [String] else {
return
}
var eventFlagArray = Array(UnsafeBufferPointer(start: eventFlags, count: numEvents))
var eventIdArray = Array(UnsafeBufferPointer(start: eventIds, count: numEvents))
for i in 0..<numEvents {
let path = eventPathArray[i]
let flag = eventFlagArray[i]
let eventID = eventIdArray[i]
let event = FileWatch.Event(path: path, flag: FileWatch.EventFlag(rawValue: flag), eventID: eventID)
self.eventHandler(event)
}
}
| mit | 155f31bc563f7d7b69c5d366d8ac5fef | 48.396104 | 273 | 0.721309 | 5.520319 | false | false | false | false |
SwiftArchitect/BezierCurveView | BezierCurveExample/BezierCurveExample/ViewController.swift | 1 | 3333 | // @file: ViewController.swift
// @project: BezierCurveExample
//
// Copyright © 2017, 2018 Xavier Schott
//
// 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 ViewController: UIViewController {
@IBOutlet weak var verticalConstraint: NSLayoutConstraint!
@IBOutlet weak var horizontalConstraint: NSLayoutConstraint!
var saveConstants = CGSize.zero
@IBAction func doPanAction(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .possible:
break
case .began:
saveConstants = CGSize(width: horizontalConstraint.constant,
height: verticalConstraint.constant)
case .changed:
let translation = sender.translation(in: view)
horizontalConstraint.constant = saveConstants.width + translation.x
verticalConstraint.constant = saveConstants.height + translation.y
view.layoutIfNeeded()
case .ended:
fallthrough
// UIView.animate(withDuration: 0.7,
// delay: 0,
// usingSpringWithDamping: 0.5,
// initialSpringVelocity: 0,
// options: .curveLinear,
// animations: {
// self.horizontalConstraint.constant = self.saveConstants.width
// self.verticalConstraint.constant = self.saveConstants.height
// self.view.layoutIfNeeded()},
// completion: nil)
case .cancelled:
fallthrough
case .failed:
self.horizontalConstraint.constant = self.saveConstants.width
self.verticalConstraint.constant = self.saveConstants.height
self.view.layoutIfNeeded()
}
}
@IBAction func doHintAction(_ sender: Any) {
let alert = UIAlertController(title: nil,
message: "Touch and drag anywhere to animate",
preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true, completion: nil)
}
}
| mit | c20e162ab0e1bfa8d2e4490a19dfb014 | 42.272727 | 91 | 0.62425 | 5.141975 | false | false | false | false |
superk589/CGSSGuide | DereGuide/View/NavigationTitleLabel.swift | 2 | 583 | //
// NavigationTitleLabel.swift
// DereGuide
//
// Created by zzk on 2017/1/16.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class NavigationTitleLabel: UILabel {
init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
numberOfLines = 2
font = UIFont.systemFont(ofSize: 12)
textAlignment = .center
adjustsFontSizeToFitWidth = true
baselineAdjustment = .alignCenters
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | a151f867409410a44ff48ea814535199 | 21.384615 | 67 | 0.627148 | 4.06993 | false | false | false | false |
vpeschenkov/LetterAvatarKit | LetterAvatarKit/Extensions/UIColor+LetterAvatarKit.swift | 1 | 5002 | //
// UIColor+LetterAvatarKit.swift
// LetterAvatarKit
//
// Copyright 2017 Victor Peschenkov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// o this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Foundation
/// Returns a color by HEX code.
///
/// - Parameters:
/// - hex: HEX code.
/// - Returns: The color by HEX code.
func LKUIColorByHEX(_ hex: Int) -> UIColor {
return LKUIColorByRGB(
red: CGFloat((hex & 0xFF0000) >> 16),
green: CGFloat((hex & 0x00FF00) >> 8),
blue: CGFloat((hex & 0x0000FF))
)
}
/// Returns a UIColor instance.
///
/// - Parameters:
/// - red: A value of the red color component.
/// - green: A value of the green color component.
/// - blue: A value of the blue color component.
/// - Returns: A UIColor instance.
func LKUIColorByRGB(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: CGFloat(1.0))
}
extension UIColor {
private struct ColorKey {
static var propertyReference = "org.peschenkov.LetterAvatarKit.UIColor.colors"
}
/// Colors from http://flatuicolors.com/
public enum HEXColor {
/// TURQUOISE
static let turquoiseColor = 0x1ABC9C
/// EMERALD
static let emeraldColor = 0x2ECC71
/// PITER RIVER
static let piterRiverColor = 0x3498DB
/// AMETHYST
static let amethystColor = 0x9B59B6
/// WET ASPHALT
static let wetAsphaltColor = 0x34495E
/// GREEN SEA
static let greenSeaColor = 0x16A085
/// NEPHRITIS
static let nephritisColor = 0x27AE60
/// BELIZE HOLE
static let belizeHoldeColor = 0x2980B9
/// WISTERIA
static let wisteriaColor = 0x8E44AD
/// MIDNIGHT BLUE
static let midnightBlueColor = 0x2C3E50
/// SUN FLOWER
static let sunflowerColor = 0xF1C40F
/// CARROT
static let carrotColor = 0xE67E22
/// ALIZARIN
static let alizarinColor = 0xE74C3C
/// CONCRETE
static let concreteColor = 0x95A5A6
/// ORANGE
static let orangeColor = 0xF39C12
/// PUMPKIN
static let pumpkinColor = 0xD35400
/// POMEGRANATE
static let pomegranateColor = 0xC0392B
/// SILVER
static let silverColor = 0xBDC3C7
/// ASBESTOS
static let asbestosColor = 0x7F8C8D
}
static public var colors: [UIColor] {
var colors = objc_getAssociatedObject(self, &ColorKey.propertyReference)
if colors == nil {
colors = [
LKUIColorByHEX(HEXColor.turquoiseColor),
LKUIColorByHEX(HEXColor.emeraldColor),
LKUIColorByHEX(HEXColor.piterRiverColor),
LKUIColorByHEX(HEXColor.amethystColor),
LKUIColorByHEX(HEXColor.wetAsphaltColor),
LKUIColorByHEX(HEXColor.greenSeaColor),
LKUIColorByHEX(HEXColor.nephritisColor),
LKUIColorByHEX(HEXColor.belizeHoldeColor),
LKUIColorByHEX(HEXColor.wisteriaColor),
LKUIColorByHEX(HEXColor.midnightBlueColor),
LKUIColorByHEX(HEXColor.sunflowerColor),
LKUIColorByHEX(HEXColor.carrotColor),
LKUIColorByHEX(HEXColor.alizarinColor),
LKUIColorByHEX(HEXColor.concreteColor),
LKUIColorByHEX(HEXColor.orangeColor),
LKUIColorByHEX(HEXColor.pumpkinColor),
LKUIColorByHEX(HEXColor.pomegranateColor),
LKUIColorByHEX(HEXColor.silverColor),
LKUIColorByHEX(HEXColor.asbestosColor)
]
objc_setAssociatedObject(
self,
&ColorKey.propertyReference,
colors,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
return colors as? [UIColor] ?? []
}
return colors as? [UIColor] ?? []
}
}
| mit | 2a612d0991db6793745bb1f2da0ed3cc | 36.609023 | 93 | 0.636146 | 4.008013 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/QOSConfig.swift | 1 | 2634 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* 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 CocoaAsyncSocket
//////////////////
// QOS
//////////////////
/// default qos socket character encoding
let QOS_SOCKET_DEFAULT_CHARACTER_ENCODING: UInt = String.Encoding.utf8.rawValue
///
let QOS_CONTROL_CONNECTION_TIMEOUT_NS: UInt64 = 10_000_000_000
let QOS_CONTROL_CONNECTION_TIMEOUT_SEC = TimeInterval(QOS_CONTROL_CONNECTION_TIMEOUT_NS / NSEC_PER_SEC)
///
let QOS_DEFAULT_TIMEOUT_NS: UInt64 = 10_000_000_000 // default timeout value in nano seconds
///
let QOS_TLS_SETTINGS: [String: NSNumber] = [
GCDAsyncSocketManuallyEvaluateTrust: NSNumber(value: true as Bool)
]
///
let WALLED_GARDEN_URL: String = "http://nettest.org/generate_204" // TODO: use url from settings request
///
let WALLED_GARDEN_SOCKET_TIMEOUT_MS: Double = 10_000
///
#if DEBUG
let QOS_ENABLED_TESTS: [QosMeasurementType] = [
.JITTER,
.HttpProxy,
.NonTransparentProxy,
.WEBSITE,
.DNS,
.TCP,
.UDP,
.VOIP, //Must be uncommented. Without it we can't get jitter and packet loss
.TRACEROUTE
]
/// determine the tests which should show log messages
let QOS_ENABLED_TESTS_LOG: [QosMeasurementType] = [
.HttpProxy,
// .NonTransparentProxy,
// .WEBSITE,
// .DNS,
// .TCP,
// .UDP,
.VOIP, //Must be uncommented. Without it we can't get jitter and packet loss
// .TRACEROUTE
]
#else
// BETA / PRODUCTION
let QOS_ENABLED_TESTS: [QosMeasurementType] = [
.JITTER,
.HttpProxy,
.NonTransparentProxy,
.WEBSITE,
.DNS,
.TCP,
.UDP,
.VOIP, //Must be uncommented. Without it we can't get jitter and packet loss
.TRACEROUTE
]
/// determine the tests which should show log messages
let QOS_ENABLED_TESTS_LOG: [QosMeasurementType] = [
.HttpProxy,
.NonTransparentProxy,
// .WEBSITE,
.DNS,
.TCP,
.UDP,
.VOIP,
.TRACEROUTE
]
#endif
| apache-2.0 | 756d4ff78594872d0309b1f9027edd54 | 25.606061 | 104 | 0.627183 | 3.720339 | false | true | false | false |
venticake/RetricaImglyKit-iOS | RetricaImglyKit/Classes/Frontend/Stores/JSONStore.swift | 1 | 2929 | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
The `JSONStore` provides methods to retrieve JSON data from any URL.
*/
@available(iOS 8, *)
@objc(IMGLYJSONStoreProtocol) public protocol JSONStoreProtocol {
/**
Retrieves JSON data from the specified URL.
- parameter url: A valid URL.
- parameter completionBlock: A completion block.
*/
func get(url: NSURL, completionBlock: (NSDictionary?, NSError?) -> Void)
}
/**
The `JSONStore` class provides methods to retrieve JSON data from any URL.
It also caches the data due to efficiency.
*/
@available(iOS 8, *)
@objc(IMGLYJSONStore) public class JSONStore: NSObject, JSONStoreProtocol {
/// A shared instance for convenience.
public static let sharedStore = JSONStore()
/// A service that is used to perform http get requests.
public var requestService: RequestServiceProtocol = RequestService()
private var store: [NSURL : NSDictionary?] = [ : ]
/**
Retrieves JSON data from the specified URL.
- parameter url: A valid URL.
- parameter completionBlock: A completion block.
*/
public func get(url: NSURL, completionBlock: (NSDictionary?, NSError?) -> Void) {
if let dict = store[url] {
completionBlock(dict, nil)
} else {
startJSONRequest(url, completionBlock: completionBlock)
}
}
private func startJSONRequest(url: NSURL, completionBlock: (NSDictionary?, NSError?) -> Void) {
requestService.get(url, cached: false, callback: {
(data, error) -> Void in
if error != nil {
completionBlock(nil, error)
} else {
if let data = data {
if let dict = self.dictionaryFromData(data) {
self.store[url] = dict
completionBlock(dict, nil)
} else {
completionBlock(nil, NSError(info: Localize("No valid json found at ") + url.absoluteString))
}
}
}
})
}
private func dictionaryFromData(data: NSData) -> NSDictionary? {
do {
let jsonObject: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let dict = jsonObject as? NSDictionary {
return dict
}
} catch _ {
return nil
}
return nil
}
}
| mit | 9586c725c0362a24c909f0a8199e088f | 33.869048 | 117 | 0.614544 | 4.770358 | false | false | false | false |
xedin/swift | test/SILOptimizer/character_literals.swift | 25 | 2077 | // RUN: %target-swift-frontend -parse-as-library -O -target-cpu core2 -emit-ir %s | %FileCheck %s
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib,CPU=x86_64
// This is an end-to-end test to ensure that the optimizer generates
// a simple literal for character literals.
// Please note: this test targets "core2" to ensure consistent output
// on all x86 host processors.
// We generate this as an LLVM constant global directly, no runtime heap
// allocation. Match that.
// CHECK-LABEL: @"{{.*}}charArrayy{{.*}}" ={{.*}} global {{.*}}ContiguousArrayStorage{{.*}} {{.*}}{ i64 97 }{{.*}}{ i64 98 }{{.*}}{ i64 99 }{{.*}}{ i64 100 }{{.*}}
//
// CHECK-LABEL: define {{.*}}charArray
// CHECK: {{.*}} = tail call %swift.refcounted* @swift_initStaticObject({{.*}} @"{{.*}}charArrayy{{.*}}"
// CHECK: ret
public func charArray(_ i: Int) -> [Character] {
return [ "a", "b", "c", "d" ]
}
// NOTE: 97 = 'a'
// NOTE: -2233785415175766016 = 0xE1 = 0xE0 (ASCII discrim) | 0x01 (count)
//
// CHECK-LABEL: define {{.*}}singleChar
// CHECK-NEXT: entry:
// CHECK-NEXT: ret { i64, %swift.bridge* } { i64 97, %swift.bridge* inttoptr (i64 -2233785415175766016 to %swift.bridge*) }
public func singleChar() -> Character {
return "a"
}
// NOTE: 10852326 = 0xE6 0x97 0xA5 (little endian), the encoding of U+65E5
// NOTE: -6701356245527298048 = 0xA3 = 0xA0 (non-ASCII discrim) | 0x03 (count)
//
// CHECK-LABEL: define {{.*}}singleNonAsciiChar
// CHECK-NEXT: entry:
// CHECK-NEXT: ret { i64, %swift.bridge* } { i64 10852326, %swift.bridge* inttoptr (i64 -6701356245527298048 to %swift.bridge*) }
public func singleNonAsciiChar() -> Character {
return "日"
}
// NOTE: -9223372036854775808 = 0x80 = immortal large discrim
// NOTE: 1152921504606847001 = 25 (code unit length) | `isTailAllocated` perf flag
//
// CHECK-LABEL: define {{.*}}singleNonSmolChar
// CHECK-NEXT: entry:
// CHECK: ret { i64, %swift.bridge* } { i64 1152921504606847001, %swift.bridge* {{.*}}@0{{.*}}i64 -9223372036854775808
public func singleNonSmolChar() -> Character {
return "👩👩👦👦"
}
| apache-2.0 | dfae8d9b43aa8954c99a2e9f3190095d | 40.14 | 163 | 0.655809 | 3.12614 | false | false | false | false |
franklinsch/usagi | iOS/usagi-iOS/usagi-iOS/AppDelegate.swift | 1 | 6118 | //
// AppDelegate.swift
// usagi-iOS
//
// Created by Franklin Schrans on 30/01/2016.
// Copyright © 2016 Franklin Schrans. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.franklinschrans.com.usagi_iOS" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("usagi_iOS", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | ca9ca4eab5be428dddae3f47079c0e3a | 54.609091 | 291 | 0.720124 | 5.847992 | false | false | false | false |
ghclara/hackaLink | LinkHub/LinkHub/PastaDetailViewController.swift | 1 | 1898 | //
// PastaDetailViewController.swift
// LinkHub
//
// Created by Student on 12/16/15.
// Copyright © 2015 Student. All rights reserved.
//
import UIKit
import CoreData
class PastaDetailViewController: UIViewController {
//contexto contendo as informacoes do banco de dados
let contexto = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
@IBOutlet weak var PastaLabel: UITextField!
var pasta: Pasta? = nil
override func viewDidLoad() {
super.viewDidLoad()
if pasta != nil {
PastaLabel.text = pasta?.nome
}
}
@IBAction func cancel(sender: AnyObject) {
dismissViewController()
}
@IBAction func done(sender: AnyObject) {
if pasta != nil {
editPasta()
} else {
createPasta()
}
dismissViewController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK:- Dismiss ViewControllers
func dismissViewController() {
navigationController?.popViewControllerAnimated(true)
}
// MARK:- Create task
func createPasta() {
let entityDescription = NSEntityDescription.entityForName("Pasta", inManagedObjectContext: contexto)
let pasta = Pasta(entity: entityDescription!, insertIntoManagedObjectContext: contexto)
pasta.nome = PastaLabel.text
do {
try contexto.save()
} catch let error as NSError {
print("Erro ao editar pasta")
print(error)
}
}
// MARK:- Edit task
func editPasta() {
pasta?.nome = PastaLabel.text
do {
try contexto.save()
} catch _ {
print("Erro ao editar pasta")
}
}
}
| mit | a2f25c3d835f4d0e52adccea2b5a7c07 | 23.960526 | 108 | 0.59884 | 4.778338 | false | false | false | false |
groue/GRDB.swift | Tests/GRDBTests/AssociationHasManyRowScopeTests.swift | 1 | 3764 | import XCTest
import GRDB
class AssociationHasManyRowScopeTests: GRDBTestCase {
func testSingularTable() throws {
struct Child : TableRecord {
}
struct Parent : TableRecord {
static let children = hasMany(Child.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
INSERT INTO child (id, parentId) VALUES (2, 1);
""")
let request = Parent.including(required: Parent.children)
let row = try Row.fetchOne(db, request)!
XCTAssertEqual(row.unscoped, ["id": 1])
XCTAssertEqual(row.scopes["child"], ["id": 2, "parentId": 1])
}
}
func testPluralTable() throws {
struct Child : TableRecord {
static let databaseTableName = "children"
}
struct Parent : TableRecord {
static let databaseTableName = "parents"
static let children = hasMany(Child.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "children") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parents")
}
try db.execute(sql: """
INSERT INTO parents (id) VALUES (1);
INSERT INTO children (id, parentId) VALUES (2, 1);
""")
let request = Parent.including(required: Parent.children)
let row = try Row.fetchOne(db, request)!
XCTAssertEqual(row.unscoped, ["id": 1])
XCTAssertEqual(row.scopes["child"], ["id": 2, "parentId": 1])
}
}
func testCustomKey() throws {
struct Child : TableRecord {
}
struct Parent : TableRecord {
static let littlePuppies = hasMany(Child.self, key: "littlePuppies")
static let kittens = hasMany(Child.self).forKey("kittens")
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
INSERT INTO child (id, parentId) VALUES (2, 1);
""")
do {
let request = Parent.including(required: Parent.littlePuppies)
let row = try Row.fetchOne(db, request)!
XCTAssertEqual(row.unscoped, ["id": 1])
XCTAssertEqual(row.scopes["littlePuppy"], ["id": 2, "parentId": 1])
}
do {
let request = Parent.including(required: Parent.kittens)
let row = try Row.fetchOne(db, request)!
XCTAssertEqual(row.unscoped, ["id": 1])
XCTAssertEqual(row.scopes["kitten"], ["id": 2, "parentId": 1])
}
}
}
}
| mit | 6203fe25624cfc955104d55b198fd323 | 35.543689 | 83 | 0.510627 | 4.920261 | false | true | false | false |
apple/swift-format | Sources/SwiftFormatWhitespaceLinter/WhitespaceFindingCategory.swift | 1 | 1640 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftFormatCore
/// Categories for findings emitted by the whitespace linter.
enum WhitespaceFindingCategory: FindingCategorizing {
/// Findings related to trailing whitespace on a line.
case trailingWhitespace
/// Findings related to indentation (i.e., whitespace at the beginning of a line).
case indentation
/// Findings related to interior whitespace (i.e., neither leading nor trailing space).
case spacing
/// Findings related to specific characters used for interior whitespace.
case spacingCharacter
/// Findings related to the removal of line breaks.
case removeLine
/// Findings related to the addition of line breaks.
case addLines
/// Findings related to the length of a line.
case lineLength
var description: String {
switch self {
case .trailingWhitespace: return "TrailingWhitespace"
case .indentation: return "Indentation"
case .spacing: return "Spacing"
case .spacingCharacter: return "SpacingCharacter"
case .removeLine: return "RemoveLine"
case .addLines: return "AddLines"
case .lineLength: return "LineLength"
}
}
}
| apache-2.0 | c79334182201e05a1497392fe8c6edc2 | 32.469388 | 89 | 0.667073 | 4.969697 | false | false | false | false |
AnthonyMDev/KeychainAccess | Lib/KeychainAccess/Keychain.swift | 1 | 133774 | //
// Keychain.swift
// KeychainAccess
//
// Created by kishikawa katsumi on 2014/12/24.
// Copyright (c) 2014 kishikawa katsumi. All rights reserved.
//
import Foundation
import Security
public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error"
public enum ItemClass {
case GenericPassword
case InternetPassword
}
public enum ProtocolType {
case FTP
case FTPAccount
case HTTP
case IRC
case NNTP
case POP3
case SMTP
case SOCKS
case IMAP
case LDAP
case AppleTalk
case AFP
case Telnet
case SSH
case FTPS
case HTTPS
case HTTPProxy
case HTTPSProxy
case FTPProxy
case SMB
case RTSP
case RTSPProxy
case DAAP
case EPPC
case IPP
case NNTPS
case LDAPS
case TelnetS
case IMAPS
case IRCS
case POP3S
}
public enum AuthenticationType {
case NTLM
case MSN
case DPA
case RPA
case HTTPBasic
case HTTPDigest
case HTMLForm
case Default
}
public enum Accessibility {
case WhenUnlocked
case AfterFirstUnlock
case Always
case WhenPasscodeSetThisDeviceOnly
case WhenUnlockedThisDeviceOnly
case AfterFirstUnlockThisDeviceOnly
case AlwaysThisDeviceOnly
}
public enum AuthenticationPolicy : Int {
case UserPresence
}
public class Keychain {
public var itemClass: ItemClass {
return options.itemClass
}
public var service: String {
return options.service
}
public var accessGroup: String? {
return options.accessGroup
}
public var server: NSURL {
return options.server
}
public var protocolType: ProtocolType {
return options.protocolType
}
public var authenticationType: AuthenticationType {
return options.authenticationType
}
public var accessibility: Accessibility {
return options.accessibility
}
@available(iOS, introduced=8.0)
@available(OSX, introduced=10.10)
public var authenticationPolicy: AuthenticationPolicy? {
return options.authenticationPolicy
}
public var synchronizable: Bool {
return options.synchronizable
}
public var label: String? {
return options.label
}
public var comment: String? {
return options.comment
}
@available(iOS, introduced=8.0)
@available(OSX, unavailable)
public var authenticationPrompt: String? {
return options.authenticationPrompt
}
private let options: Options
private let NSFoundationVersionNumber_iOS_7_1 = 1047.25
private let NSFoundationVersionNumber_iOS_8_0 = 1140.11
private let NSFoundationVersionNumber_iOS_8_1 = 1141.1
private let NSFoundationVersionNumber10_9_2 = 1056.13
// MARK:
public convenience init() {
var options = Options()
if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier {
options.service = bundleIdentifier
}
self.init(options)
}
public convenience init(service: String) {
var options = Options()
options.service = service
self.init(options)
}
public convenience init(accessGroup: String) {
var options = Options()
if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier {
options.service = bundleIdentifier
}
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(service: String, accessGroup: String) {
var options = Options()
options.service = service
options.accessGroup = accessGroup
self.init(options)
}
public convenience init(server: String, protocolType: ProtocolType) {
self.init(server: NSURL(string: server)!, protocolType: protocolType)
}
public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType) {
self.init(server: NSURL(string: server)!, protocolType: protocolType, authenticationType: .Default)
}
public convenience init(server: NSURL, protocolType: ProtocolType) {
self.init(server: server, protocolType: protocolType, authenticationType: .Default)
}
public convenience init(server: NSURL, protocolType: ProtocolType, authenticationType: AuthenticationType) {
var options = Options()
options.itemClass = .InternetPassword
options.server = server
options.protocolType = protocolType
options.authenticationType = authenticationType
self.init(options)
}
private init(_ opts: Options) {
options = opts
}
// MARK:
public func accessibility(accessibility: Accessibility) -> Keychain {
var options = self.options
options.accessibility = accessibility
return Keychain(options)
}
@available(iOS, introduced=8.0)
@available(OSX, introduced=10.10)
public func accessibility(accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain {
var options = self.options
options.accessibility = accessibility
options.authenticationPolicy = authenticationPolicy
return Keychain(options)
}
public func synchronizable(synchronizable: Bool) -> Keychain {
var options = self.options
options.synchronizable = synchronizable
return Keychain(options)
}
public func label(label: String) -> Keychain {
var options = self.options
options.label = label
return Keychain(options)
}
public func comment(comment: String) -> Keychain {
var options = self.options
options.comment = comment
return Keychain(options)
}
@available(iOS, introduced=8.0)
@available(OSX, unavailable)
public func authenticationPrompt(authenticationPrompt: String) -> Keychain {
var options = self.options
options.authenticationPrompt = authenticationPrompt
return Keychain(options)
}
// MARK:
public func get(key: String) throws -> String? {
return try getString(key)
}
public func getString(key: String) throws -> String? {
guard let data = try getData(key) else {
return nil
}
guard let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String else {
throw conversionError(message: "failed to convert data to string")
}
return string
}
public func getData(key: String) throws -> NSData? {
var query = options.query()
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecAttrAccount as String] = key
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
switch status {
case errSecSuccess:
guard let data = result as? NSData else {
throw Status.UnexpectedError
}
return data
case errSecItemNotFound:
return nil
default:
throw securityError(status: status)
}
}
// MARK:
public func set(value: String, key: String) throws {
guard let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else {
throw conversionError(message: "failed to convert string to data")
}
try set(data, key: key)
}
public func set(value: NSData, key: String) throws {
var query = options.query()
query[kSecAttrAccount as String] = key
#if os(iOS)
if floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) {
query[kSecUseNoAuthenticationUI as String] = kCFBooleanTrue
}
#endif
var status = SecItemCopyMatching(query, nil)
switch status {
case errSecSuccess, errSecInteractionNotAllowed:
var query = options.query()
query[kSecAttrAccount as String] = key
let (attributes, error) = options.attributes(key: nil, value: value)
if let error = error {
print("error:[\(error.code)] \(error.localizedDescription)")
throw error
}
if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) {
try remove(key)
try set(value, key: key)
} else {
status = SecItemUpdate(query, attributes)
if status != errSecSuccess {
throw securityError(status: status)
}
}
case errSecItemNotFound:
let (attributes, error) = options.attributes(key: key, value: value)
if let error = error {
print("error:[\(error.code)] \(error.localizedDescription)")
throw error
}
status = SecItemAdd(attributes, nil)
if status != errSecSuccess {
throw securityError(status: status)
}
default:
throw securityError(status: status)
}
}
// MARK:
public func remove(key: String) throws {
var query = options.query()
query[kSecAttrAccount as String] = key
let status = SecItemDelete(query)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
public func removeAll() throws {
var query = options.query()
#if !os(iOS)
query[kSecMatchLimit as String] = kSecMatchLimitAll
#endif
let status = SecItemDelete(query)
if status != errSecSuccess && status != errSecItemNotFound {
throw securityError(status: status)
}
}
// MARK:
public func contains(key: String) throws -> Bool {
var query = options.query()
query[kSecAttrAccount as String] = key
let status = SecItemCopyMatching(query, nil)
switch status {
case errSecSuccess:
return true
case errSecItemNotFound:
return false
default:
throw securityError(status: status)
}
}
// MARK:
public subscript(key: String) -> String? {
get {
return (try? get(key)).flatMap { $0 }
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
public subscript(string key: String) -> String? {
get {
return self[key]
}
set {
self[key] = newValue
}
}
public subscript(data key: String) -> NSData? {
get {
return (try? getData(key))?.flatMap { $0 }
}
set {
if let value = newValue {
do {
try set(value, key: key)
} catch {}
} else {
do {
try remove(key)
} catch {}
}
}
}
// MARK:
public class func allKeys(itemClass: ItemClass) -> [(String, String)] {
var query = [String: AnyObject]()
query[kSecClass as String] = itemClass.rawValue
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
switch status {
case errSecSuccess:
if let items = result as? [[String: AnyObject]] {
return prettify(itemClass: itemClass, items: items).map {
switch itemClass {
case .GenericPassword:
return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String)
case .InternetPassword:
return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String)
}
}
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allKeys() -> [String] {
return self.dynamicType.prettify(itemClass: itemClass, items: items()).map { $0["key"] as! String }
}
public class func allItems(itemClass: ItemClass) -> [[String: AnyObject]] {
var query = [String: AnyObject]()
query[kSecClass as String] = itemClass.rawValue
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
#if os(iOS)
query[kSecReturnData as String] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
switch status {
case errSecSuccess:
if let items = result as? [[String: AnyObject]] {
return prettify(itemClass: itemClass, items: items)
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
public func allItems() -> [[String: AnyObject]] {
return self.dynamicType.prettify(itemClass: itemClass, items: items())
}
#if os(iOS)
@available(iOS, introduced=8.0)
public func getSharedPassword(completion: (account: String?, password: String?, error: NSError?) -> () = { account, password, error -> () in }) {
if let domain = server.host {
self.dynamicType.requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in
if let credential = credentials.first {
let account = credential["account"]
let password = credential["password"]
completion(account: account, password: password, error: error)
} else {
completion(account: nil, password: nil, error: error)
}
}
} else {
let error = securityError(status: Status.Param.rawValue)
completion(account: nil, password: nil, error: error)
}
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public func getSharedPassword(account: String, completion: (password: String?, error: NSError?) -> () = { password, error -> () in }) {
if let domain = server.host {
self.dynamicType.requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in
if let credential = credentials.first {
if let password = credential["password"] {
completion(password: password, error: error)
} else {
completion(password: nil, error: error)
}
} else {
completion(password: nil, error: error)
}
}
} else {
let error = securityError(status: Status.Param.rawValue)
completion(password: nil, error: error)
}
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public func setSharedPassword(password: String, account: String, completion: (error: NSError?) -> () = { e -> () in }) {
setSharedPassword(password as String?, account: account, completion: completion)
}
#endif
#if os(iOS)
private func setSharedPassword(password: String?, account: String, completion: (error: NSError?) -> () = { e -> () in }) {
if let domain = server.host {
SecAddSharedWebCredential(domain, account, password) { error -> () in
if let error = error {
completion(error: error.error)
} else {
completion(error: nil)
}
}
} else {
let error = securityError(status: Status.Param.rawValue)
completion(error: error)
}
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public func removeSharedPassword(account: String, completion: (error: NSError?) -> () = { e -> () in }) {
setSharedPassword(nil, account: account, completion: completion)
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public class func requestSharedWebCredential(completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: nil, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public class func requestSharedWebCredential(domain domain: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: domain, account: nil, completion: completion)
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public class func requestSharedWebCredential(domain domain: String, account: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) {
requestSharedWebCredential(domain: domain as String?, account: account as String?, completion: completion)
}
#endif
#if os(iOS)
private class func requestSharedWebCredential(domain domain: String?, account: String?, completion: (credentials: [[String: String]], error: NSError?) -> ()) {
SecRequestSharedWebCredential(domain, account) { (credentials, error) -> () in
var remoteError: NSError?
if let error = error {
remoteError = error.error
if remoteError?.code != Int(errSecItemNotFound) {
print("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)")
}
}
if let credentials = credentials as? [[String: AnyObject]] {
let credentials = credentials.map { credentials -> [String: String] in
var credential = [String: String]()
if let server = credentials[kSecAttrServer as String] as? String {
credential["server"] = server
}
if let account = credentials[kSecAttrAccount as String] as? String {
credential["account"] = account
}
if let password = credentials[kSecSharedPassword as String] as? String {
credential["password"] = password
}
return credential
}
completion(credentials: credentials, error: remoteError)
} else {
completion(credentials: [], error: remoteError)
}
}
}
#endif
#if os(iOS)
@available(iOS, introduced=8.0)
public class func generatePassword() -> String {
return SecCreateSharedWebCredentialPassword() as! String
}
#endif
// MARK:
private func items() -> [[String: AnyObject]] {
var query = options.query()
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
#if os(iOS)
query[kSecReturnData as String] = kCFBooleanTrue
#endif
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
switch status {
case errSecSuccess:
if let items = result as? [[String: AnyObject]] {
return items
}
case errSecItemNotFound:
return []
default: ()
}
securityError(status: status)
return []
}
private class func prettify(itemClass itemClass: ItemClass, items: [[String: AnyObject]]) -> [[String: AnyObject]] {
let items = items.map { attributes -> [String: AnyObject] in
var item = [String: AnyObject]()
item["class"] = itemClass.description
switch itemClass {
case .GenericPassword:
if let service = attributes[kSecAttrService as String] as? String {
item["service"] = service
}
if let accessGroup = attributes[kSecAttrAccessGroup as String] as? String {
item["accessGroup"] = accessGroup
}
case .InternetPassword:
if let server = attributes[kSecAttrServer as String] as? String {
item["server"] = server
}
if let proto = attributes[kSecAttrProtocol as String] as? String {
if let protocolType = ProtocolType(rawValue: proto) {
item["protocol"] = protocolType.description
}
}
if let auth = attributes[kSecAttrAuthenticationType as String] as? String {
if let authenticationType = AuthenticationType(rawValue: auth) {
item["authenticationType"] = authenticationType.description
}
}
}
if let key = attributes[kSecAttrAccount as String] as? String {
item["key"] = key
}
if let data = attributes[kSecValueData as String] as? NSData {
if let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
item["value"] = text
} else {
item["value"] = data
}
}
if let accessible = attributes[kSecAttrAccessible as String] as? String {
if let accessibility = Accessibility(rawValue: accessible) {
item["accessibility"] = accessibility.description
}
}
if let synchronizable = attributes[kSecAttrSynchronizable as String] as? Bool {
item["synchronizable"] = synchronizable ? "true" : "false"
}
return item
}
return items
}
// MARK:
private class func conversionError(message message: String) -> NSError {
let error = NSError(domain: KeychainAccessErrorDomain, code: Int(Status.ConversionError.rawValue), userInfo: [NSLocalizedDescriptionKey: message])
print("error:[\(error.code)] \(error.localizedDescription)")
return error
}
private func conversionError(message message: String) -> NSError {
return self.dynamicType.conversionError(message: message)
}
private class func securityError(status status: OSStatus) -> NSError {
let message = Status(rawValue: status)!.description
let error = NSError(domain: KeychainAccessErrorDomain, code: Int(status), userInfo: [NSLocalizedDescriptionKey: message])
print("OSStatus error:[\(error.code)] \(error.localizedDescription)")
return error
}
private func securityError(status status: OSStatus) -> NSError {
return self.dynamicType.securityError(status: status)
}
}
struct Options {
var itemClass: ItemClass = .GenericPassword
var service: String = ""
var accessGroup: String? = nil
var server: NSURL!
var protocolType: ProtocolType!
var authenticationType: AuthenticationType = .Default
var accessibility: Accessibility = .AfterFirstUnlock
var authenticationPolicy: AuthenticationPolicy?
var synchronizable: Bool = false
var label: String?
var comment: String?
var authenticationPrompt: String?
init() {}
}
extension Keychain : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
let items = allItems()
if items.isEmpty {
return "[]"
}
var description = "[\n"
for item in items {
description += " "
description += "\(item)\n"
}
description += "]"
return description
}
public var debugDescription: String {
return "\(items())"
}
}
extension Options {
func query() -> [String: AnyObject] {
var query = [String: AnyObject]()
query[kSecClass as String] = itemClass.rawValue
query[kSecAttrSynchronizable as String] = kSecAttrSynchronizableAny
switch itemClass {
case .GenericPassword:
query[kSecAttrService as String] = service
#if (!arch(i386) && !arch(x86_64)) || !os(iOS)
if let accessGroup = self.accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup
}
#endif
case .InternetPassword:
query[kSecAttrServer as String] = server.host
query[kSecAttrPort as String] = server.port
query[kSecAttrProtocol as String] = protocolType.rawValue
query[kSecAttrAuthenticationType as String] = authenticationType.rawValue
}
#if os(iOS)
if authenticationPrompt != nil {
query[kSecUseOperationPrompt as String] = authenticationPrompt
}
#endif
return query
}
func attributes(key key: String?, value: NSData) -> ([String: AnyObject], NSError?) {
var attributes: [String: AnyObject]
if key != nil {
attributes = query()
attributes[kSecAttrAccount as String] = key
} else {
attributes = [String: AnyObject]()
}
attributes[kSecValueData as String] = value
if label != nil {
attributes[kSecAttrLabel as String] = label
}
if comment != nil {
attributes[kSecAttrComment as String] = comment
}
if let policy = authenticationPolicy {
if #available(OSX 10.10, *) {
var error: Unmanaged<CFError>?
guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, accessibility.rawValue, SecAccessControlCreateFlags(rawValue: policy.rawValue), &error) else {
if let error = error?.takeUnretainedValue() {
return (attributes, error.error)
}
let message = Status.UnexpectedError.description
return (attributes, NSError(domain: KeychainAccessErrorDomain, code: Int(Status.UnexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: message]))
}
attributes[kSecAttrAccessControl as String] = accessControl
} else {
print("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.")
}
} else {
attributes[kSecAttrAccessible as String] = accessibility.rawValue
}
attributes[kSecAttrSynchronizable as String] = synchronizable
return (attributes, nil)
}
}
// MARK:
extension ItemClass : RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecClassGenericPassword):
self = GenericPassword
case String(kSecClassInternetPassword):
self = InternetPassword
default:
return nil
}
}
public var rawValue: String {
switch self {
case GenericPassword:
return String(kSecClassGenericPassword)
case InternetPassword:
return String(kSecClassInternetPassword)
}
}
public var description : String {
switch self {
case GenericPassword:
return "GenericPassword"
case InternetPassword:
return "InternetPassword"
}
}
}
extension ProtocolType : RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecAttrProtocolFTP):
self = FTP
case String(kSecAttrProtocolFTPAccount):
self = FTPAccount
case String(kSecAttrProtocolHTTP):
self = HTTP
case String(kSecAttrProtocolIRC):
self = IRC
case String(kSecAttrProtocolNNTP):
self = NNTP
case String(kSecAttrProtocolPOP3):
self = POP3
case String(kSecAttrProtocolSMTP):
self = SMTP
case String(kSecAttrProtocolSOCKS):
self = SOCKS
case String(kSecAttrProtocolIMAP):
self = IMAP
case String(kSecAttrProtocolLDAP):
self = LDAP
case String(kSecAttrProtocolAppleTalk):
self = AppleTalk
case String(kSecAttrProtocolAFP):
self = AFP
case String(kSecAttrProtocolTelnet):
self = Telnet
case String(kSecAttrProtocolSSH):
self = SSH
case String(kSecAttrProtocolFTPS):
self = FTPS
case String(kSecAttrProtocolHTTPS):
self = HTTPS
case String(kSecAttrProtocolHTTPProxy):
self = HTTPProxy
case String(kSecAttrProtocolHTTPSProxy):
self = HTTPSProxy
case String(kSecAttrProtocolFTPProxy):
self = FTPProxy
case String(kSecAttrProtocolSMB):
self = SMB
case String(kSecAttrProtocolRTSP):
self = RTSP
case String(kSecAttrProtocolRTSPProxy):
self = RTSPProxy
case String(kSecAttrProtocolDAAP):
self = DAAP
case String(kSecAttrProtocolEPPC):
self = EPPC
case String(kSecAttrProtocolIPP):
self = IPP
case String(kSecAttrProtocolNNTPS):
self = NNTPS
case String(kSecAttrProtocolLDAPS):
self = LDAPS
case String(kSecAttrProtocolTelnetS):
self = TelnetS
case String(kSecAttrProtocolIMAPS):
self = IMAPS
case String(kSecAttrProtocolIRCS):
self = IRCS
case String(kSecAttrProtocolPOP3S):
self = POP3S
default:
return nil
}
}
public var rawValue: String {
switch self {
case FTP:
return kSecAttrProtocolFTP as String
case FTPAccount:
return kSecAttrProtocolFTPAccount as String
case HTTP:
return kSecAttrProtocolHTTP as String
case IRC:
return kSecAttrProtocolIRC as String
case NNTP:
return kSecAttrProtocolNNTP as String
case POP3:
return kSecAttrProtocolPOP3 as String
case SMTP:
return kSecAttrProtocolSMTP as String
case SOCKS:
return kSecAttrProtocolSOCKS as String
case IMAP:
return kSecAttrProtocolIMAP as String
case LDAP:
return kSecAttrProtocolLDAP as String
case AppleTalk:
return kSecAttrProtocolAppleTalk as String
case AFP:
return kSecAttrProtocolAFP as String
case Telnet:
return kSecAttrProtocolTelnet as String
case SSH:
return kSecAttrProtocolSSH as String
case FTPS:
return kSecAttrProtocolFTPS as String
case HTTPS:
return kSecAttrProtocolHTTPS as String
case HTTPProxy:
return kSecAttrProtocolHTTPProxy as String
case HTTPSProxy:
return kSecAttrProtocolHTTPSProxy as String
case FTPProxy:
return kSecAttrProtocolFTPProxy as String
case SMB:
return kSecAttrProtocolSMB as String
case RTSP:
return kSecAttrProtocolRTSP as String
case RTSPProxy:
return kSecAttrProtocolRTSPProxy as String
case DAAP:
return kSecAttrProtocolDAAP as String
case EPPC:
return kSecAttrProtocolEPPC as String
case IPP:
return kSecAttrProtocolIPP as String
case NNTPS:
return kSecAttrProtocolNNTPS as String
case LDAPS:
return kSecAttrProtocolLDAPS as String
case TelnetS:
return kSecAttrProtocolTelnetS as String
case IMAPS:
return kSecAttrProtocolIMAPS as String
case IRCS:
return kSecAttrProtocolIRCS as String
case POP3S:
return kSecAttrProtocolPOP3S as String
}
}
public var description : String {
switch self {
case FTP:
return "FTP"
case FTPAccount:
return "FTPAccount"
case HTTP:
return "HTTP"
case IRC:
return "IRC"
case NNTP:
return "NNTP"
case POP3:
return "POP3"
case SMTP:
return "SMTP"
case SOCKS:
return "SOCKS"
case IMAP:
return "IMAP"
case LDAP:
return "LDAP"
case AppleTalk:
return "AppleTalk"
case AFP:
return "AFP"
case Telnet:
return "Telnet"
case SSH:
return "SSH"
case FTPS:
return "FTPS"
case HTTPS:
return "HTTPS"
case HTTPProxy:
return "HTTPProxy"
case HTTPSProxy:
return "HTTPSProxy"
case FTPProxy:
return "FTPProxy"
case SMB:
return "SMB"
case RTSP:
return "RTSP"
case RTSPProxy:
return "RTSPProxy"
case DAAP:
return "DAAP"
case EPPC:
return "EPPC"
case IPP:
return "IPP"
case NNTPS:
return "NNTPS"
case LDAPS:
return "LDAPS"
case TelnetS:
return "TelnetS"
case IMAPS:
return "IMAPS"
case IRCS:
return "IRCS"
case POP3S:
return "POP3S"
}
}
}
extension AuthenticationType : RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
switch rawValue {
case String(kSecAttrAuthenticationTypeNTLM):
self = NTLM
case String(kSecAttrAuthenticationTypeMSN):
self = MSN
case String(kSecAttrAuthenticationTypeDPA):
self = DPA
case String(kSecAttrAuthenticationTypeRPA):
self = RPA
case String(kSecAttrAuthenticationTypeHTTPBasic):
self = HTTPBasic
case String(kSecAttrAuthenticationTypeHTTPDigest):
self = HTTPDigest
case String(kSecAttrAuthenticationTypeHTMLForm):
self = HTMLForm
case String(kSecAttrAuthenticationTypeDefault):
self = Default
default:
return nil
}
}
public var rawValue: String {
switch self {
case NTLM:
return kSecAttrAuthenticationTypeNTLM as String
case MSN:
return kSecAttrAuthenticationTypeMSN as String
case DPA:
return kSecAttrAuthenticationTypeDPA as String
case RPA:
return kSecAttrAuthenticationTypeRPA as String
case HTTPBasic:
return kSecAttrAuthenticationTypeHTTPBasic as String
case HTTPDigest:
return kSecAttrAuthenticationTypeHTTPDigest as String
case HTMLForm:
return kSecAttrAuthenticationTypeHTMLForm as String
case Default:
return kSecAttrAuthenticationTypeDefault as String
}
}
public var description : String {
switch self {
case NTLM:
return "NTLM"
case MSN:
return "MSN"
case DPA:
return "DPA"
case RPA:
return "RPA"
case HTTPBasic:
return "HTTPBasic"
case HTTPDigest:
return "HTTPDigest"
case HTMLForm:
return "HTMLForm"
case Default:
return "Default"
}
}
}
extension Accessibility : RawRepresentable, CustomStringConvertible {
public init?(rawValue: String) {
guard #available(OSX 10.10, *) else {
return nil
}
switch rawValue {
case String(kSecAttrAccessibleWhenUnlocked):
self = WhenUnlocked
case String(kSecAttrAccessibleAfterFirstUnlock):
self = AfterFirstUnlock
case String(kSecAttrAccessibleAlways):
self = Always
case String(kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly):
self = WhenPasscodeSetThisDeviceOnly
case String(kSecAttrAccessibleWhenUnlockedThisDeviceOnly):
self = WhenUnlockedThisDeviceOnly
case String(kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly):
self = AfterFirstUnlockThisDeviceOnly
case String(kSecAttrAccessibleAlwaysThisDeviceOnly):
self = AlwaysThisDeviceOnly
default:
return nil
}
}
public var rawValue: String {
switch self {
case WhenUnlocked:
return kSecAttrAccessibleWhenUnlocked as String
case AfterFirstUnlock:
return kSecAttrAccessibleAfterFirstUnlock as String
case Always:
return kSecAttrAccessibleAlways as String
case WhenPasscodeSetThisDeviceOnly:
if #available(OSX 10.10, *) {
return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String
} else {
fatalError("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.")
}
case WhenUnlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String
case AfterFirstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String
case AlwaysThisDeviceOnly:
return kSecAttrAccessibleAlwaysThisDeviceOnly as String
}
}
public var description : String {
switch self {
case WhenUnlocked:
return "WhenUnlocked"
case AfterFirstUnlock:
return "AfterFirstUnlock"
case Always:
return "Always"
case WhenPasscodeSetThisDeviceOnly:
return "WhenPasscodeSetThisDeviceOnly"
case WhenUnlockedThisDeviceOnly:
return "WhenUnlockedThisDeviceOnly"
case AfterFirstUnlockThisDeviceOnly:
return "AfterFirstUnlockThisDeviceOnly"
case AlwaysThisDeviceOnly:
return "AlwaysThisDeviceOnly"
}
}
}
extension AuthenticationPolicy : RawRepresentable, CustomStringConvertible {
public init?(rawValue: Int) {
guard #available(OSX 10.10, *) else {
return nil
}
let flags = SecAccessControlCreateFlags.UserPresence
switch rawValue {
case flags.rawValue:
self = UserPresence
default:
return nil
}
}
public var rawValue: Int {
switch self {
case UserPresence:
if #available(OSX 10.10, *) {
return SecAccessControlCreateFlags.UserPresence.rawValue
} else {
fatalError("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.")
}
}
}
public var description : String {
switch self {
case UserPresence:
return "UserPresence"
}
}
}
extension CFError {
var error: NSError {
let domain = CFErrorGetDomain(self) as String
let code = CFErrorGetCode(self)
let userInfo = CFErrorCopyUserInfo(self) as [NSObject: AnyObject]
return NSError(domain: domain, code: code, userInfo: userInfo)
}
}
public enum Status : OSStatus, ErrorType {
case Success
case Unimplemented
case Param
case Allocate
case NotAvailable
case ReadOnly
case AuthFailed
case NoSuchKeychain
case InvalidKeychain
case DuplicateKeychain
case DuplicateCallback
case InvalidCallback
case DuplicateItem
case ItemNotFound
case BufferTooSmall
case DataTooLarge
case NoSuchAttr
case InvalidItemRef
case InvalidSearchRef
case NoSuchClass
case NoDefaultKeychain
case InteractionNotAllowed
case ReadOnlyAttr
case WrongSecVersion
case KeySizeNotAllowed
case NoStorageModule
case NoCertificateModule
case NoPolicyModule
case InteractionRequired
case DataNotAvailable
case DataNotModifiable
case CreateChainFailed
case InvalidPrefsDomain
case ACLNotSimple
case PolicyNotFound
case InvalidTrustSetting
case NoAccessForItem
case InvalidOwnerEdit
case TrustNotAvailable
case UnsupportedFormat
case UnknownFormat
case KeyIsSensitive
case MultiplePrivKeys
case PassphraseRequired
case InvalidPasswordRef
case InvalidTrustSettings
case NoTrustSettings
case Pkcs12VerifyFailure
case InvalidCertificate
case NotSigner
case PolicyDenied
case InvalidKey
case Decode
case Internal
case UnsupportedAlgorithm
case UnsupportedOperation
case UnsupportedPadding
case ItemInvalidKey
case ItemInvalidKeyType
case ItemInvalidValue
case ItemClassMissing
case ItemMatchUnsupported
case UseItemListUnsupported
case UseKeychainUnsupported
case UseKeychainListUnsupported
case ReturnDataUnsupported
case ReturnAttributesUnsupported
case ReturnRefUnsupported
case ReturnPersitentRefUnsupported
case ValueRefUnsupported
case ValuePersistentRefUnsupported
case ReturnMissingPointer
case MatchLimitUnsupported
case ItemIllegalQuery
case WaitForCallback
case MissingEntitlement
case UpgradePending
case MPSignatureInvalid
case OTRTooOld
case OTRIDTooNew
case ServiceNotAvailable
case InsufficientClientID
case DeviceReset
case DeviceFailed
case AppleAddAppACLSubject
case ApplePublicKeyIncomplete
case AppleSignatureMismatch
case AppleInvalidKeyStartDate
case AppleInvalidKeyEndDate
case ConversionError
case AppleSSLv2Rollback
case DiskFull
case QuotaExceeded
case FileTooBig
case InvalidDatabaseBlob
case InvalidKeyBlob
case IncompatibleDatabaseBlob
case IncompatibleKeyBlob
case HostNameMismatch
case UnknownCriticalExtensionFlag
case NoBasicConstraints
case NoBasicConstraintsCA
case InvalidAuthorityKeyID
case InvalidSubjectKeyID
case InvalidKeyUsageForPolicy
case InvalidExtendedKeyUsage
case InvalidIDLinkage
case PathLengthConstraintExceeded
case InvalidRoot
case CRLExpired
case CRLNotValidYet
case CRLNotFound
case CRLServerDown
case CRLBadURI
case UnknownCertExtension
case UnknownCRLExtension
case CRLNotTrusted
case CRLPolicyFailed
case IDPFailure
case SMIMEEmailAddressesNotFound
case SMIMEBadExtendedKeyUsage
case SMIMEBadKeyUsage
case SMIMEKeyUsageNotCritical
case SMIMENoEmailAddress
case SMIMESubjAltNameNotCritical
case SSLBadExtendedKeyUsage
case OCSPBadResponse
case OCSPBadRequest
case OCSPUnavailable
case OCSPStatusUnrecognized
case EndOfData
case IncompleteCertRevocationCheck
case NetworkFailure
case OCSPNotTrustedToAnchor
case RecordModified
case OCSPSignatureError
case OCSPNoSigner
case OCSPResponderMalformedReq
case OCSPResponderInternalError
case OCSPResponderTryLater
case OCSPResponderSignatureRequired
case OCSPResponderUnauthorized
case OCSPResponseNonceMismatch
case CodeSigningBadCertChainLength
case CodeSigningNoBasicConstraints
case CodeSigningBadPathLengthConstraint
case CodeSigningNoExtendedKeyUsage
case CodeSigningDevelopment
case ResourceSignBadCertChainLength
case ResourceSignBadExtKeyUsage
case TrustSettingDeny
case InvalidSubjectName
case UnknownQualifiedCertStatement
case MobileMeRequestQueued
case MobileMeRequestRedirected
case MobileMeServerError
case MobileMeServerNotAvailable
case MobileMeServerAlreadyExists
case MobileMeServerServiceErr
case MobileMeRequestAlreadyPending
case MobileMeNoRequestPending
case MobileMeCSRVerifyFailure
case MobileMeFailedConsistencyCheck
case NotInitialized
case InvalidHandleUsage
case PVCReferentNotFound
case FunctionIntegrityFail
case InternalError
case MemoryError
case InvalidData
case MDSError
case InvalidPointer
case SelfCheckFailed
case FunctionFailed
case ModuleManifestVerifyFailed
case InvalidGUID
case InvalidHandle
case InvalidDBList
case InvalidPassthroughID
case InvalidNetworkAddress
case CRLAlreadySigned
case InvalidNumberOfFields
case VerificationFailure
case UnknownTag
case InvalidSignature
case InvalidName
case InvalidCertificateRef
case InvalidCertificateGroup
case TagNotFound
case InvalidQuery
case InvalidValue
case CallbackFailed
case ACLDeleteFailed
case ACLReplaceFailed
case ACLAddFailed
case ACLChangeFailed
case InvalidAccessCredentials
case InvalidRecord
case InvalidACL
case InvalidSampleValue
case IncompatibleVersion
case PrivilegeNotGranted
case InvalidScope
case PVCAlreadyConfigured
case InvalidPVC
case EMMLoadFailed
case EMMUnloadFailed
case AddinLoadFailed
case InvalidKeyRef
case InvalidKeyHierarchy
case AddinUnloadFailed
case LibraryReferenceNotFound
case InvalidAddinFunctionTable
case InvalidServiceMask
case ModuleNotLoaded
case InvalidSubServiceID
case AttributeNotInContext
case ModuleManagerInitializeFailed
case ModuleManagerNotFound
case EventNotificationCallbackNotFound
case InputLengthError
case OutputLengthError
case PrivilegeNotSupported
case DeviceError
case AttachHandleBusy
case NotLoggedIn
case AlgorithmMismatch
case KeyUsageIncorrect
case KeyBlobTypeIncorrect
case KeyHeaderInconsistent
case UnsupportedKeyFormat
case UnsupportedKeySize
case InvalidKeyUsageMask
case UnsupportedKeyUsageMask
case InvalidKeyAttributeMask
case UnsupportedKeyAttributeMask
case InvalidKeyLabel
case UnsupportedKeyLabel
case InvalidKeyFormat
case UnsupportedVectorOfBuffers
case InvalidInputVector
case InvalidOutputVector
case InvalidContext
case InvalidAlgorithm
case InvalidAttributeKey
case MissingAttributeKey
case InvalidAttributeInitVector
case MissingAttributeInitVector
case InvalidAttributeSalt
case MissingAttributeSalt
case InvalidAttributePadding
case MissingAttributePadding
case InvalidAttributeRandom
case MissingAttributeRandom
case InvalidAttributeSeed
case MissingAttributeSeed
case InvalidAttributePassphrase
case MissingAttributePassphrase
case InvalidAttributeKeyLength
case MissingAttributeKeyLength
case InvalidAttributeBlockSize
case MissingAttributeBlockSize
case InvalidAttributeOutputSize
case MissingAttributeOutputSize
case InvalidAttributeRounds
case MissingAttributeRounds
case InvalidAlgorithmParms
case MissingAlgorithmParms
case InvalidAttributeLabel
case MissingAttributeLabel
case InvalidAttributeKeyType
case MissingAttributeKeyType
case InvalidAttributeMode
case MissingAttributeMode
case InvalidAttributeEffectiveBits
case MissingAttributeEffectiveBits
case InvalidAttributeStartDate
case MissingAttributeStartDate
case InvalidAttributeEndDate
case MissingAttributeEndDate
case InvalidAttributeVersion
case MissingAttributeVersion
case InvalidAttributePrime
case MissingAttributePrime
case InvalidAttributeBase
case MissingAttributeBase
case InvalidAttributeSubprime
case MissingAttributeSubprime
case InvalidAttributeIterationCount
case MissingAttributeIterationCount
case InvalidAttributeDLDBHandle
case MissingAttributeDLDBHandle
case InvalidAttributeAccessCredentials
case MissingAttributeAccessCredentials
case InvalidAttributePublicKeyFormat
case MissingAttributePublicKeyFormat
case InvalidAttributePrivateKeyFormat
case MissingAttributePrivateKeyFormat
case InvalidAttributeSymmetricKeyFormat
case MissingAttributeSymmetricKeyFormat
case InvalidAttributeWrappedKeyFormat
case MissingAttributeWrappedKeyFormat
case StagedOperationInProgress
case StagedOperationNotStarted
case VerifyFailed
case QuerySizeUnknown
case BlockSizeMismatch
case PublicKeyInconsistent
case DeviceVerifyFailed
case InvalidLoginName
case AlreadyLoggedIn
case InvalidDigestAlgorithm
case InvalidCRLGroup
case CertificateCannotOperate
case CertificateExpired
case CertificateNotValidYet
case CertificateRevoked
case CertificateSuspended
case InsufficientCredentials
case InvalidAction
case InvalidAuthority
case VerifyActionFailed
case InvalidCertAuthority
case InvaldCRLAuthority
case InvalidCRLEncoding
case InvalidCRLType
case InvalidCRL
case InvalidFormType
case InvalidID
case InvalidIdentifier
case InvalidIndex
case InvalidPolicyIdentifiers
case InvalidTimeString
case InvalidReason
case InvalidRequestInputs
case InvalidResponseVector
case InvalidStopOnPolicy
case InvalidTuple
case MultipleValuesUnsupported
case NotTrusted
case NoDefaultAuthority
case RejectedForm
case RequestLost
case RequestRejected
case UnsupportedAddressType
case UnsupportedService
case InvalidTupleGroup
case InvalidBaseACLs
case InvalidTupleCredendtials
case InvalidEncoding
case InvalidValidityPeriod
case InvalidRequestor
case RequestDescriptor
case InvalidBundleInfo
case InvalidCRLIndex
case NoFieldValues
case UnsupportedFieldFormat
case UnsupportedIndexInfo
case UnsupportedLocality
case UnsupportedNumAttributes
case UnsupportedNumIndexes
case UnsupportedNumRecordTypes
case FieldSpecifiedMultiple
case IncompatibleFieldFormat
case InvalidParsingModule
case DatabaseLocked
case DatastoreIsOpen
case MissingValue
case UnsupportedQueryLimits
case UnsupportedNumSelectionPreds
case UnsupportedOperator
case InvalidDBLocation
case InvalidAccessRequest
case InvalidIndexInfo
case InvalidNewOwner
case InvalidModifyMode
case UnexpectedError
}
extension Status : RawRepresentable, CustomStringConvertible {
public init?(rawValue: OSStatus) {
switch rawValue {
case 0:
self = Success
case -4:
self = Unimplemented
case -50:
self = Param
case -108:
self = Allocate
case -25291:
self = NotAvailable
case -25292:
self = ReadOnly
case -25293:
self = AuthFailed
case -25294:
self = NoSuchKeychain
case -25295:
self = InvalidKeychain
case -25296:
self = DuplicateKeychain
case -25297:
self = DuplicateCallback
case -25298:
self = InvalidCallback
case -25299:
self = DuplicateItem
case -25300:
self = ItemNotFound
case -25301:
self = BufferTooSmall
case -25302:
self = DataTooLarge
case -25303:
self = NoSuchAttr
case -25304:
self = InvalidItemRef
case -25305:
self = InvalidSearchRef
case -25306:
self = NoSuchClass
case -25307:
self = NoDefaultKeychain
case -25308:
self = InteractionNotAllowed
case -25309:
self = ReadOnlyAttr
case -25310:
self = WrongSecVersion
case -25311:
self = KeySizeNotAllowed
case -25312:
self = NoStorageModule
case -25313:
self = NoCertificateModule
case -25314:
self = NoPolicyModule
case -25315:
self = InteractionRequired
case -25316:
self = DataNotAvailable
case -25317:
self = DataNotModifiable
case -25318:
self = CreateChainFailed
case -25319:
self = InvalidPrefsDomain
case -25240:
self = ACLNotSimple
case -25241:
self = PolicyNotFound
case -25242:
self = InvalidTrustSetting
case -25243:
self = NoAccessForItem
case -25244:
self = InvalidOwnerEdit
case -25245:
self = TrustNotAvailable
case -25256:
self = UnsupportedFormat
case -25257:
self = UnknownFormat
case -25258:
self = KeyIsSensitive
case -25259:
self = MultiplePrivKeys
case -25260:
self = PassphraseRequired
case -25261:
self = InvalidPasswordRef
case -25262:
self = InvalidTrustSettings
case -25263:
self = NoTrustSettings
case -25264:
self = Pkcs12VerifyFailure
case -26265:
self = InvalidCertificate
case -26267:
self = NotSigner
case -26270:
self = PolicyDenied
case -26274:
self = InvalidKey
case -26275:
self = Decode
case -26276:
self = Internal
case -26268:
self = UnsupportedAlgorithm
case -26271:
self = UnsupportedOperation
case -26273:
self = UnsupportedPadding
case -34000:
self = ItemInvalidKey
case -34001:
self = ItemInvalidKeyType
case -34002:
self = ItemInvalidValue
case -34003:
self = ItemClassMissing
case -34004:
self = ItemMatchUnsupported
case -34005:
self = UseItemListUnsupported
case -34006:
self = UseKeychainUnsupported
case -34007:
self = UseKeychainListUnsupported
case -34008:
self = ReturnDataUnsupported
case -34009:
self = ReturnAttributesUnsupported
case -34010:
self = ReturnRefUnsupported
case -34011:
self = ReturnPersitentRefUnsupported
case -34012:
self = ValueRefUnsupported
case -34013:
self = ValuePersistentRefUnsupported
case -34014:
self = ReturnMissingPointer
case -34015:
self = MatchLimitUnsupported
case -34016:
self = ItemIllegalQuery
case -34017:
self = WaitForCallback
case -34018:
self = MissingEntitlement
case -34019:
self = UpgradePending
case -25327:
self = MPSignatureInvalid
case -25328:
self = OTRTooOld
case -25329:
self = OTRIDTooNew
case -67585:
self = ServiceNotAvailable
case -67586:
self = InsufficientClientID
case -67587:
self = DeviceReset
case -67588:
self = DeviceFailed
case -67589:
self = AppleAddAppACLSubject
case -67590:
self = ApplePublicKeyIncomplete
case -67591:
self = AppleSignatureMismatch
case -67592:
self = AppleInvalidKeyStartDate
case -67593:
self = AppleInvalidKeyEndDate
case -67594:
self = ConversionError
case -67595:
self = AppleSSLv2Rollback
case -34:
self = DiskFull
case -67596:
self = QuotaExceeded
case -67597:
self = FileTooBig
case -67598:
self = InvalidDatabaseBlob
case -67599:
self = InvalidKeyBlob
case -67600:
self = IncompatibleDatabaseBlob
case -67601:
self = IncompatibleKeyBlob
case -67602:
self = HostNameMismatch
case -67603:
self = UnknownCriticalExtensionFlag
case -67604:
self = NoBasicConstraints
case -67605:
self = NoBasicConstraintsCA
case -67606:
self = InvalidAuthorityKeyID
case -67607:
self = InvalidSubjectKeyID
case -67608:
self = InvalidKeyUsageForPolicy
case -67609:
self = InvalidExtendedKeyUsage
case -67610:
self = InvalidIDLinkage
case -67611:
self = PathLengthConstraintExceeded
case -67612:
self = InvalidRoot
case -67613:
self = CRLExpired
case -67614:
self = CRLNotValidYet
case -67615:
self = CRLNotFound
case -67616:
self = CRLServerDown
case -67617:
self = CRLBadURI
case -67618:
self = UnknownCertExtension
case -67619:
self = UnknownCRLExtension
case -67620:
self = CRLNotTrusted
case -67621:
self = CRLPolicyFailed
case -67622:
self = IDPFailure
case -67623:
self = SMIMEEmailAddressesNotFound
case -67624:
self = SMIMEBadExtendedKeyUsage
case -67625:
self = SMIMEBadKeyUsage
case -67626:
self = SMIMEKeyUsageNotCritical
case -67627:
self = SMIMENoEmailAddress
case -67628:
self = SMIMESubjAltNameNotCritical
case -67629:
self = SSLBadExtendedKeyUsage
case -67630:
self = OCSPBadResponse
case -67631:
self = OCSPBadRequest
case -67632:
self = OCSPUnavailable
case -67633:
self = OCSPStatusUnrecognized
case -67634:
self = EndOfData
case -67635:
self = IncompleteCertRevocationCheck
case -67636:
self = NetworkFailure
case -67637:
self = OCSPNotTrustedToAnchor
case -67638:
self = RecordModified
case -67639:
self = OCSPSignatureError
case -67640:
self = OCSPNoSigner
case -67641:
self = OCSPResponderMalformedReq
case -67642:
self = OCSPResponderInternalError
case -67643:
self = OCSPResponderTryLater
case -67644:
self = OCSPResponderSignatureRequired
case -67645:
self = OCSPResponderUnauthorized
case -67646:
self = OCSPResponseNonceMismatch
case -67647:
self = CodeSigningBadCertChainLength
case -67648:
self = CodeSigningNoBasicConstraints
case -67649:
self = CodeSigningBadPathLengthConstraint
case -67650:
self = CodeSigningNoExtendedKeyUsage
case -67651:
self = CodeSigningDevelopment
case -67652:
self = ResourceSignBadCertChainLength
case -67653:
self = ResourceSignBadExtKeyUsage
case -67654:
self = TrustSettingDeny
case -67655:
self = InvalidSubjectName
case -67656:
self = UnknownQualifiedCertStatement
case -67657:
self = MobileMeRequestQueued
case -67658:
self = MobileMeRequestRedirected
case -67659:
self = MobileMeServerError
case -67660:
self = MobileMeServerNotAvailable
case -67661:
self = MobileMeServerAlreadyExists
case -67662:
self = MobileMeServerServiceErr
case -67663:
self = MobileMeRequestAlreadyPending
case -67664:
self = MobileMeNoRequestPending
case -67665:
self = MobileMeCSRVerifyFailure
case -67666:
self = MobileMeFailedConsistencyCheck
case -67667:
self = NotInitialized
case -67668:
self = InvalidHandleUsage
case -67669:
self = PVCReferentNotFound
case -67670:
self = FunctionIntegrityFail
case -67671:
self = InternalError
case -67672:
self = MemoryError
case -67673:
self = InvalidData
case -67674:
self = MDSError
case -67675:
self = InvalidPointer
case -67676:
self = SelfCheckFailed
case -67677:
self = FunctionFailed
case -67678:
self = ModuleManifestVerifyFailed
case -67679:
self = InvalidGUID
case -67680:
self = InvalidHandle
case -67681:
self = InvalidDBList
case -67682:
self = InvalidPassthroughID
case -67683:
self = InvalidNetworkAddress
case -67684:
self = CRLAlreadySigned
case -67685:
self = InvalidNumberOfFields
case -67686:
self = VerificationFailure
case -67687:
self = UnknownTag
case -67688:
self = InvalidSignature
case -67689:
self = InvalidName
case -67690:
self = InvalidCertificateRef
case -67691:
self = InvalidCertificateGroup
case -67692:
self = TagNotFound
case -67693:
self = InvalidQuery
case -67694:
self = InvalidValue
case -67695:
self = CallbackFailed
case -67696:
self = ACLDeleteFailed
case -67697:
self = ACLReplaceFailed
case -67698:
self = ACLAddFailed
case -67699:
self = ACLChangeFailed
case -67700:
self = InvalidAccessCredentials
case -67701:
self = InvalidRecord
case -67702:
self = InvalidACL
case -67703:
self = InvalidSampleValue
case -67704:
self = IncompatibleVersion
case -67705:
self = PrivilegeNotGranted
case -67706:
self = InvalidScope
case -67707:
self = PVCAlreadyConfigured
case -67708:
self = InvalidPVC
case -67709:
self = EMMLoadFailed
case -67710:
self = EMMUnloadFailed
case -67711:
self = AddinLoadFailed
case -67712:
self = InvalidKeyRef
case -67713:
self = InvalidKeyHierarchy
case -67714:
self = AddinUnloadFailed
case -67715:
self = LibraryReferenceNotFound
case -67716:
self = InvalidAddinFunctionTable
case -67717:
self = InvalidServiceMask
case -67718:
self = ModuleNotLoaded
case -67719:
self = InvalidSubServiceID
case -67720:
self = AttributeNotInContext
case -67721:
self = ModuleManagerInitializeFailed
case -67722:
self = ModuleManagerNotFound
case -67723:
self = EventNotificationCallbackNotFound
case -67724:
self = InputLengthError
case -67725:
self = OutputLengthError
case -67726:
self = PrivilegeNotSupported
case -67727:
self = DeviceError
case -67728:
self = AttachHandleBusy
case -67729:
self = NotLoggedIn
case -67730:
self = AlgorithmMismatch
case -67731:
self = KeyUsageIncorrect
case -67732:
self = KeyBlobTypeIncorrect
case -67733:
self = KeyHeaderInconsistent
case -67734:
self = UnsupportedKeyFormat
case -67735:
self = UnsupportedKeySize
case -67736:
self = InvalidKeyUsageMask
case -67737:
self = UnsupportedKeyUsageMask
case -67738:
self = InvalidKeyAttributeMask
case -67739:
self = UnsupportedKeyAttributeMask
case -67740:
self = InvalidKeyLabel
case -67741:
self = UnsupportedKeyLabel
case -67742:
self = InvalidKeyFormat
case -67743:
self = UnsupportedVectorOfBuffers
case -67744:
self = InvalidInputVector
case -67745:
self = InvalidOutputVector
case -67746:
self = InvalidContext
case -67747:
self = InvalidAlgorithm
case -67748:
self = InvalidAttributeKey
case -67749:
self = MissingAttributeKey
case -67750:
self = InvalidAttributeInitVector
case -67751:
self = MissingAttributeInitVector
case -67752:
self = InvalidAttributeSalt
case -67753:
self = MissingAttributeSalt
case -67754:
self = InvalidAttributePadding
case -67755:
self = MissingAttributePadding
case -67756:
self = InvalidAttributeRandom
case -67757:
self = MissingAttributeRandom
case -67758:
self = InvalidAttributeSeed
case -67759:
self = MissingAttributeSeed
case -67760:
self = InvalidAttributePassphrase
case -67761:
self = MissingAttributePassphrase
case -67762:
self = InvalidAttributeKeyLength
case -67763:
self = MissingAttributeKeyLength
case -67764:
self = InvalidAttributeBlockSize
case -67765:
self = MissingAttributeBlockSize
case -67766:
self = InvalidAttributeOutputSize
case -67767:
self = MissingAttributeOutputSize
case -67768:
self = InvalidAttributeRounds
case -67769:
self = MissingAttributeRounds
case -67770:
self = InvalidAlgorithmParms
case -67771:
self = MissingAlgorithmParms
case -67772:
self = InvalidAttributeLabel
case -67773:
self = MissingAttributeLabel
case -67774:
self = InvalidAttributeKeyType
case -67775:
self = MissingAttributeKeyType
case -67776:
self = InvalidAttributeMode
case -67777:
self = MissingAttributeMode
case -67778:
self = InvalidAttributeEffectiveBits
case -67779:
self = MissingAttributeEffectiveBits
case -67780:
self = InvalidAttributeStartDate
case -67781:
self = MissingAttributeStartDate
case -67782:
self = InvalidAttributeEndDate
case -67783:
self = MissingAttributeEndDate
case -67784:
self = InvalidAttributeVersion
case -67785:
self = MissingAttributeVersion
case -67786:
self = InvalidAttributePrime
case -67787:
self = MissingAttributePrime
case -67788:
self = InvalidAttributeBase
case -67789:
self = MissingAttributeBase
case -67790:
self = InvalidAttributeSubprime
case -67791:
self = MissingAttributeSubprime
case -67792:
self = InvalidAttributeIterationCount
case -67793:
self = MissingAttributeIterationCount
case -67794:
self = InvalidAttributeDLDBHandle
case -67795:
self = MissingAttributeDLDBHandle
case -67796:
self = InvalidAttributeAccessCredentials
case -67797:
self = MissingAttributeAccessCredentials
case -67798:
self = InvalidAttributePublicKeyFormat
case -67799:
self = MissingAttributePublicKeyFormat
case -67800:
self = InvalidAttributePrivateKeyFormat
case -67801:
self = MissingAttributePrivateKeyFormat
case -67802:
self = InvalidAttributeSymmetricKeyFormat
case -67803:
self = MissingAttributeSymmetricKeyFormat
case -67804:
self = InvalidAttributeWrappedKeyFormat
case -67805:
self = MissingAttributeWrappedKeyFormat
case -67806:
self = StagedOperationInProgress
case -67807:
self = StagedOperationNotStarted
case -67808:
self = VerifyFailed
case -67809:
self = QuerySizeUnknown
case -67810:
self = BlockSizeMismatch
case -67811:
self = PublicKeyInconsistent
case -67812:
self = DeviceVerifyFailed
case -67813:
self = InvalidLoginName
case -67814:
self = AlreadyLoggedIn
case -67815:
self = InvalidDigestAlgorithm
case -67816:
self = InvalidCRLGroup
case -67817:
self = CertificateCannotOperate
case -67818:
self = CertificateExpired
case -67819:
self = CertificateNotValidYet
case -67820:
self = CertificateRevoked
case -67821:
self = CertificateSuspended
case -67822:
self = InsufficientCredentials
case -67823:
self = InvalidAction
case -67824:
self = InvalidAuthority
case -67825:
self = VerifyActionFailed
case -67826:
self = InvalidCertAuthority
case -67827:
self = InvaldCRLAuthority
case -67828:
self = InvalidCRLEncoding
case -67829:
self = InvalidCRLType
case -67830:
self = InvalidCRL
case -67831:
self = InvalidFormType
case -67832:
self = InvalidID
case -67833:
self = InvalidIdentifier
case -67834:
self = InvalidIndex
case -67835:
self = InvalidPolicyIdentifiers
case -67836:
self = InvalidTimeString
case -67837:
self = InvalidReason
case -67838:
self = InvalidRequestInputs
case -67839:
self = InvalidResponseVector
case -67840:
self = InvalidStopOnPolicy
case -67841:
self = InvalidTuple
case -67842:
self = MultipleValuesUnsupported
case -67843:
self = NotTrusted
case -67844:
self = NoDefaultAuthority
case -67845:
self = RejectedForm
case -67846:
self = RequestLost
case -67847:
self = RequestRejected
case -67848:
self = UnsupportedAddressType
case -67849:
self = UnsupportedService
case -67850:
self = InvalidTupleGroup
case -67851:
self = InvalidBaseACLs
case -67852:
self = InvalidTupleCredendtials
case -67853:
self = InvalidEncoding
case -67854:
self = InvalidValidityPeriod
case -67855:
self = InvalidRequestor
case -67856:
self = RequestDescriptor
case -67857:
self = InvalidBundleInfo
case -67858:
self = InvalidCRLIndex
case -67859:
self = NoFieldValues
case -67860:
self = UnsupportedFieldFormat
case -67861:
self = UnsupportedIndexInfo
case -67862:
self = UnsupportedLocality
case -67863:
self = UnsupportedNumAttributes
case -67864:
self = UnsupportedNumIndexes
case -67865:
self = UnsupportedNumRecordTypes
case -67866:
self = FieldSpecifiedMultiple
case -67867:
self = IncompatibleFieldFormat
case -67868:
self = InvalidParsingModule
case -67869:
self = DatabaseLocked
case -67870:
self = DatastoreIsOpen
case -67871:
self = MissingValue
case -67872:
self = UnsupportedQueryLimits
case -67873:
self = UnsupportedNumSelectionPreds
case -67874:
self = UnsupportedOperator
case -67875:
self = InvalidDBLocation
case -67876:
self = InvalidAccessRequest
case -67877:
self = InvalidIndexInfo
case -67878:
self = InvalidNewOwner
case -67879:
self = InvalidModifyMode
default:
self = UnexpectedError
}
}
public var rawValue: OSStatus {
switch self {
case Success:
return 0
case Unimplemented:
return -4
case Param:
return -50
case Allocate:
return -108
case NotAvailable:
return -25291
case ReadOnly:
return -25292
case AuthFailed:
return -25293
case NoSuchKeychain:
return -25294
case InvalidKeychain:
return -25295
case DuplicateKeychain:
return -25296
case DuplicateCallback:
return -25297
case InvalidCallback:
return -25298
case DuplicateItem:
return -25299
case ItemNotFound:
return -25300
case BufferTooSmall:
return -25301
case DataTooLarge:
return -25302
case NoSuchAttr:
return -25303
case InvalidItemRef:
return -25304
case InvalidSearchRef:
return -25305
case NoSuchClass:
return -25306
case NoDefaultKeychain:
return -25307
case InteractionNotAllowed:
return -25308
case ReadOnlyAttr:
return -25309
case WrongSecVersion:
return -25310
case KeySizeNotAllowed:
return -25311
case NoStorageModule:
return -25312
case NoCertificateModule:
return -25313
case NoPolicyModule:
return -25314
case InteractionRequired:
return -25315
case DataNotAvailable:
return -25316
case DataNotModifiable:
return -25317
case CreateChainFailed:
return -25318
case InvalidPrefsDomain:
return -25319
case ACLNotSimple:
return -25240
case PolicyNotFound:
return -25241
case InvalidTrustSetting:
return -25242
case NoAccessForItem:
return -25243
case InvalidOwnerEdit:
return -25244
case TrustNotAvailable:
return -25245
case UnsupportedFormat:
return -25256
case UnknownFormat:
return -25257
case KeyIsSensitive:
return -25258
case MultiplePrivKeys:
return -25259
case PassphraseRequired:
return -25260
case InvalidPasswordRef:
return -25261
case InvalidTrustSettings:
return -25262
case NoTrustSettings:
return -25263
case Pkcs12VerifyFailure:
return -25264
case InvalidCertificate:
return -26265
case NotSigner:
return -26267
case PolicyDenied:
return -26270
case InvalidKey:
return -26274
case Decode:
return -26275
case Internal:
return -26276
case UnsupportedAlgorithm:
return -26268
case UnsupportedOperation:
return -26271
case UnsupportedPadding:
return -26273
case ItemInvalidKey:
return -34000
case ItemInvalidKeyType:
return -34001
case ItemInvalidValue:
return -34002
case ItemClassMissing:
return -34003
case ItemMatchUnsupported:
return -34004
case UseItemListUnsupported:
return -34005
case UseKeychainUnsupported:
return -34006
case UseKeychainListUnsupported:
return -34007
case ReturnDataUnsupported:
return -34008
case ReturnAttributesUnsupported:
return -34009
case ReturnRefUnsupported:
return -34010
case ReturnPersitentRefUnsupported:
return -34011
case ValueRefUnsupported:
return -34012
case ValuePersistentRefUnsupported:
return -34013
case ReturnMissingPointer:
return -34014
case MatchLimitUnsupported:
return -34015
case ItemIllegalQuery:
return -34016
case WaitForCallback:
return -34017
case MissingEntitlement:
return -34018
case UpgradePending:
return -34019
case MPSignatureInvalid:
return -25327
case OTRTooOld:
return -25328
case OTRIDTooNew:
return -25329
case ServiceNotAvailable:
return -67585
case InsufficientClientID:
return -67586
case DeviceReset:
return -67587
case DeviceFailed:
return -67588
case AppleAddAppACLSubject:
return -67589
case ApplePublicKeyIncomplete:
return -67590
case AppleSignatureMismatch:
return -67591
case AppleInvalidKeyStartDate:
return -67592
case AppleInvalidKeyEndDate:
return -67593
case ConversionError:
return -67594
case AppleSSLv2Rollback:
return -67595
case DiskFull:
return -34
case QuotaExceeded:
return -67596
case FileTooBig:
return -67597
case InvalidDatabaseBlob:
return -67598
case InvalidKeyBlob:
return -67599
case IncompatibleDatabaseBlob:
return -67600
case IncompatibleKeyBlob:
return -67601
case HostNameMismatch:
return -67602
case UnknownCriticalExtensionFlag:
return -67603
case NoBasicConstraints:
return -67604
case NoBasicConstraintsCA:
return -67605
case InvalidAuthorityKeyID:
return -67606
case InvalidSubjectKeyID:
return -67607
case InvalidKeyUsageForPolicy:
return -67608
case InvalidExtendedKeyUsage:
return -67609
case InvalidIDLinkage:
return -67610
case PathLengthConstraintExceeded:
return -67611
case InvalidRoot:
return -67612
case CRLExpired:
return -67613
case CRLNotValidYet:
return -67614
case CRLNotFound:
return -67615
case CRLServerDown:
return -67616
case CRLBadURI:
return -67617
case UnknownCertExtension:
return -67618
case UnknownCRLExtension:
return -67619
case CRLNotTrusted:
return -67620
case CRLPolicyFailed:
return -67621
case IDPFailure:
return -67622
case SMIMEEmailAddressesNotFound:
return -67623
case SMIMEBadExtendedKeyUsage:
return -67624
case SMIMEBadKeyUsage:
return -67625
case SMIMEKeyUsageNotCritical:
return -67626
case SMIMENoEmailAddress:
return -67627
case SMIMESubjAltNameNotCritical:
return -67628
case SSLBadExtendedKeyUsage:
return -67629
case OCSPBadResponse:
return -67630
case OCSPBadRequest:
return -67631
case OCSPUnavailable:
return -67632
case OCSPStatusUnrecognized:
return -67633
case EndOfData:
return -67634
case IncompleteCertRevocationCheck:
return -67635
case NetworkFailure:
return -67636
case OCSPNotTrustedToAnchor:
return -67637
case RecordModified:
return -67638
case OCSPSignatureError:
return -67639
case OCSPNoSigner:
return -67640
case OCSPResponderMalformedReq:
return -67641
case OCSPResponderInternalError:
return -67642
case OCSPResponderTryLater:
return -67643
case OCSPResponderSignatureRequired:
return -67644
case OCSPResponderUnauthorized:
return -67645
case OCSPResponseNonceMismatch:
return -67646
case CodeSigningBadCertChainLength:
return -67647
case CodeSigningNoBasicConstraints:
return -67648
case CodeSigningBadPathLengthConstraint:
return -67649
case CodeSigningNoExtendedKeyUsage:
return -67650
case CodeSigningDevelopment:
return -67651
case ResourceSignBadCertChainLength:
return -67652
case ResourceSignBadExtKeyUsage:
return -67653
case TrustSettingDeny:
return -67654
case InvalidSubjectName:
return -67655
case UnknownQualifiedCertStatement:
return -67656
case MobileMeRequestQueued:
return -67657
case MobileMeRequestRedirected:
return -67658
case MobileMeServerError:
return -67659
case MobileMeServerNotAvailable:
return -67660
case MobileMeServerAlreadyExists:
return -67661
case MobileMeServerServiceErr:
return -67662
case MobileMeRequestAlreadyPending:
return -67663
case MobileMeNoRequestPending:
return -67664
case MobileMeCSRVerifyFailure:
return -67665
case MobileMeFailedConsistencyCheck:
return -67666
case NotInitialized:
return -67667
case InvalidHandleUsage:
return -67668
case PVCReferentNotFound:
return -67669
case FunctionIntegrityFail:
return -67670
case InternalError:
return -67671
case MemoryError:
return -67672
case InvalidData:
return -67673
case MDSError:
return -67674
case InvalidPointer:
return -67675
case SelfCheckFailed:
return -67676
case FunctionFailed:
return -67677
case ModuleManifestVerifyFailed:
return -67678
case InvalidGUID:
return -67679
case InvalidHandle:
return -67680
case InvalidDBList:
return -67681
case InvalidPassthroughID:
return -67682
case InvalidNetworkAddress:
return -67683
case CRLAlreadySigned:
return -67684
case InvalidNumberOfFields:
return -67685
case VerificationFailure:
return -67686
case UnknownTag:
return -67687
case InvalidSignature:
return -67688
case InvalidName:
return -67689
case InvalidCertificateRef:
return -67690
case InvalidCertificateGroup:
return -67691
case TagNotFound:
return -67692
case InvalidQuery:
return -67693
case InvalidValue:
return -67694
case CallbackFailed:
return -67695
case ACLDeleteFailed:
return -67696
case ACLReplaceFailed:
return -67697
case ACLAddFailed:
return -67698
case ACLChangeFailed:
return -67699
case InvalidAccessCredentials:
return -67700
case InvalidRecord:
return -67701
case InvalidACL:
return -67702
case InvalidSampleValue:
return -67703
case IncompatibleVersion:
return -67704
case PrivilegeNotGranted:
return -67705
case InvalidScope:
return -67706
case PVCAlreadyConfigured:
return -67707
case InvalidPVC:
return -67708
case EMMLoadFailed:
return -67709
case EMMUnloadFailed:
return -67710
case AddinLoadFailed:
return -67711
case InvalidKeyRef:
return -67712
case InvalidKeyHierarchy:
return -67713
case AddinUnloadFailed:
return -67714
case LibraryReferenceNotFound:
return -67715
case InvalidAddinFunctionTable:
return -67716
case InvalidServiceMask:
return -67717
case ModuleNotLoaded:
return -67718
case InvalidSubServiceID:
return -67719
case AttributeNotInContext:
return -67720
case ModuleManagerInitializeFailed:
return -67721
case ModuleManagerNotFound:
return -67722
case EventNotificationCallbackNotFound:
return -67723
case InputLengthError:
return -67724
case OutputLengthError:
return -67725
case PrivilegeNotSupported:
return -67726
case DeviceError:
return -67727
case AttachHandleBusy:
return -67728
case NotLoggedIn:
return -67729
case AlgorithmMismatch:
return -67730
case KeyUsageIncorrect:
return -67731
case KeyBlobTypeIncorrect:
return -67732
case KeyHeaderInconsistent:
return -67733
case UnsupportedKeyFormat:
return -67734
case UnsupportedKeySize:
return -67735
case InvalidKeyUsageMask:
return -67736
case UnsupportedKeyUsageMask:
return -67737
case InvalidKeyAttributeMask:
return -67738
case UnsupportedKeyAttributeMask:
return -67739
case InvalidKeyLabel:
return -67740
case UnsupportedKeyLabel:
return -67741
case InvalidKeyFormat:
return -67742
case UnsupportedVectorOfBuffers:
return -67743
case InvalidInputVector:
return -67744
case InvalidOutputVector:
return -67745
case InvalidContext:
return -67746
case InvalidAlgorithm:
return -67747
case InvalidAttributeKey:
return -67748
case MissingAttributeKey:
return -67749
case InvalidAttributeInitVector:
return -67750
case MissingAttributeInitVector:
return -67751
case InvalidAttributeSalt:
return -67752
case MissingAttributeSalt:
return -67753
case InvalidAttributePadding:
return -67754
case MissingAttributePadding:
return -67755
case InvalidAttributeRandom:
return -67756
case MissingAttributeRandom:
return -67757
case InvalidAttributeSeed:
return -67758
case MissingAttributeSeed:
return -67759
case InvalidAttributePassphrase:
return -67760
case MissingAttributePassphrase:
return -67761
case InvalidAttributeKeyLength:
return -67762
case MissingAttributeKeyLength:
return -67763
case InvalidAttributeBlockSize:
return -67764
case MissingAttributeBlockSize:
return -67765
case InvalidAttributeOutputSize:
return -67766
case MissingAttributeOutputSize:
return -67767
case InvalidAttributeRounds:
return -67768
case MissingAttributeRounds:
return -67769
case InvalidAlgorithmParms:
return -67770
case MissingAlgorithmParms:
return -67771
case InvalidAttributeLabel:
return -67772
case MissingAttributeLabel:
return -67773
case InvalidAttributeKeyType:
return -67774
case MissingAttributeKeyType:
return -67775
case InvalidAttributeMode:
return -67776
case MissingAttributeMode:
return -67777
case InvalidAttributeEffectiveBits:
return -67778
case MissingAttributeEffectiveBits:
return -67779
case InvalidAttributeStartDate:
return -67780
case MissingAttributeStartDate:
return -67781
case InvalidAttributeEndDate:
return -67782
case MissingAttributeEndDate:
return -67783
case InvalidAttributeVersion:
return -67784
case MissingAttributeVersion:
return -67785
case InvalidAttributePrime:
return -67786
case MissingAttributePrime:
return -67787
case InvalidAttributeBase:
return -67788
case MissingAttributeBase:
return -67789
case InvalidAttributeSubprime:
return -67790
case MissingAttributeSubprime:
return -67791
case InvalidAttributeIterationCount:
return -67792
case MissingAttributeIterationCount:
return -67793
case InvalidAttributeDLDBHandle:
return -67794
case MissingAttributeDLDBHandle:
return -67795
case InvalidAttributeAccessCredentials:
return -67796
case MissingAttributeAccessCredentials:
return -67797
case InvalidAttributePublicKeyFormat:
return -67798
case MissingAttributePublicKeyFormat:
return -67799
case InvalidAttributePrivateKeyFormat:
return -67800
case MissingAttributePrivateKeyFormat:
return -67801
case InvalidAttributeSymmetricKeyFormat:
return -67802
case MissingAttributeSymmetricKeyFormat:
return -67803
case InvalidAttributeWrappedKeyFormat:
return -67804
case MissingAttributeWrappedKeyFormat:
return -67805
case StagedOperationInProgress:
return -67806
case StagedOperationNotStarted:
return -67807
case VerifyFailed:
return -67808
case QuerySizeUnknown:
return -67809
case BlockSizeMismatch:
return -67810
case PublicKeyInconsistent:
return -67811
case DeviceVerifyFailed:
return -67812
case InvalidLoginName:
return -67813
case AlreadyLoggedIn:
return -67814
case InvalidDigestAlgorithm:
return -67815
case InvalidCRLGroup:
return -67816
case CertificateCannotOperate:
return -67817
case CertificateExpired:
return -67818
case CertificateNotValidYet:
return -67819
case CertificateRevoked:
return -67820
case CertificateSuspended:
return -67821
case InsufficientCredentials:
return -67822
case InvalidAction:
return -67823
case InvalidAuthority:
return -67824
case VerifyActionFailed:
return -67825
case InvalidCertAuthority:
return -67826
case InvaldCRLAuthority:
return -67827
case InvalidCRLEncoding:
return -67828
case InvalidCRLType:
return -67829
case InvalidCRL:
return -67830
case InvalidFormType:
return -67831
case InvalidID:
return -67832
case InvalidIdentifier:
return -67833
case InvalidIndex:
return -67834
case InvalidPolicyIdentifiers:
return -67835
case InvalidTimeString:
return -67836
case InvalidReason:
return -67837
case InvalidRequestInputs:
return -67838
case InvalidResponseVector:
return -67839
case InvalidStopOnPolicy:
return -67840
case InvalidTuple:
return -67841
case MultipleValuesUnsupported:
return -67842
case NotTrusted:
return -67843
case NoDefaultAuthority:
return -67844
case RejectedForm:
return -67845
case RequestLost:
return -67846
case RequestRejected:
return -67847
case UnsupportedAddressType:
return -67848
case UnsupportedService:
return -67849
case InvalidTupleGroup:
return -67850
case InvalidBaseACLs:
return -67851
case InvalidTupleCredendtials:
return -67852
case InvalidEncoding:
return -67853
case InvalidValidityPeriod:
return -67854
case InvalidRequestor:
return -67855
case RequestDescriptor:
return -67856
case InvalidBundleInfo:
return -67857
case InvalidCRLIndex:
return -67858
case NoFieldValues:
return -67859
case UnsupportedFieldFormat:
return -67860
case UnsupportedIndexInfo:
return -67861
case UnsupportedLocality:
return -67862
case UnsupportedNumAttributes:
return -67863
case UnsupportedNumIndexes:
return -67864
case UnsupportedNumRecordTypes:
return -67865
case FieldSpecifiedMultiple:
return -67866
case IncompatibleFieldFormat:
return -67867
case InvalidParsingModule:
return -67868
case DatabaseLocked:
return -67869
case DatastoreIsOpen:
return -67870
case MissingValue:
return -67871
case UnsupportedQueryLimits:
return -67872
case UnsupportedNumSelectionPreds:
return -67873
case UnsupportedOperator:
return -67874
case InvalidDBLocation:
return -67875
case InvalidAccessRequest:
return -67876
case InvalidIndexInfo:
return -67877
case InvalidNewOwner:
return -67878
case InvalidModifyMode:
return -67879
default:
return -99999
}
}
public var description : String {
switch self {
case Success:
return "No error."
case Unimplemented:
return "Function or operation not implemented."
case Param:
return "One or more parameters passed to a function were not valid."
case Allocate:
return "Failed to allocate memory."
case NotAvailable:
return "No keychain is available. You may need to restart your computer."
case ReadOnly:
return "This keychain cannot be modified."
case AuthFailed:
return "The user name or passphrase you entered is not correct."
case NoSuchKeychain:
return "The specified keychain could not be found."
case InvalidKeychain:
return "The specified keychain is not a valid keychain file."
case DuplicateKeychain:
return "A keychain with the same name already exists."
case DuplicateCallback:
return "The specified callback function is already installed."
case InvalidCallback:
return "The specified callback function is not valid."
case DuplicateItem:
return "The specified item already exists in the keychain."
case ItemNotFound:
return "The specified item could not be found in the keychain."
case BufferTooSmall:
return "There is not enough memory available to use the specified item."
case DataTooLarge:
return "This item contains information which is too large or in a format that cannot be displayed."
case NoSuchAttr:
return "The specified attribute does not exist."
case InvalidItemRef:
return "The specified item is no longer valid. It may have been deleted from the keychain."
case InvalidSearchRef:
return "Unable to search the current keychain."
case NoSuchClass:
return "The specified item does not appear to be a valid keychain item."
case NoDefaultKeychain:
return "A default keychain could not be found."
case InteractionNotAllowed:
return "User interaction is not allowed."
case ReadOnlyAttr:
return "The specified attribute could not be modified."
case WrongSecVersion:
return "This keychain was created by a different version of the system software and cannot be opened."
case KeySizeNotAllowed:
return "This item specifies a key size which is too large."
case NoStorageModule:
return "A required component (data storage module) could not be loaded. You may need to restart your computer."
case NoCertificateModule:
return "A required component (certificate module) could not be loaded. You may need to restart your computer."
case NoPolicyModule:
return "A required component (policy module) could not be loaded. You may need to restart your computer."
case InteractionRequired:
return "User interaction is required, but is currently not allowed."
case DataNotAvailable:
return "The contents of this item cannot be retrieved."
case DataNotModifiable:
return "The contents of this item cannot be modified."
case CreateChainFailed:
return "One or more certificates required to validate this certificate cannot be found."
case InvalidPrefsDomain:
return "The specified preferences domain is not valid."
case ACLNotSimple:
return "The specified access control list is not in standard (simple) form."
case PolicyNotFound:
return "The specified policy cannot be found."
case InvalidTrustSetting:
return "The specified trust setting is invalid."
case NoAccessForItem:
return "The specified item has no access control."
case InvalidOwnerEdit:
return "Invalid attempt to change the owner of this item."
case TrustNotAvailable:
return "No trust results are available."
case UnsupportedFormat:
return "Import/Export format unsupported."
case UnknownFormat:
return "Unknown format in import."
case KeyIsSensitive:
return "Key material must be wrapped for export."
case MultiplePrivKeys:
return "An attempt was made to import multiple private keys."
case PassphraseRequired:
return "Passphrase is required for import/export."
case InvalidPasswordRef:
return "The password reference was invalid."
case InvalidTrustSettings:
return "The Trust Settings Record was corrupted."
case NoTrustSettings:
return "No Trust Settings were found."
case Pkcs12VerifyFailure:
return "MAC verification failed during PKCS12 import (wrong password?)"
case InvalidCertificate:
return "This certificate could not be decoded."
case NotSigner:
return "A certificate was not signed by its proposed parent."
case PolicyDenied:
return "The certificate chain was not trusted due to a policy not accepting it."
case InvalidKey:
return "The provided key material was not valid."
case Decode:
return "Unable to decode the provided data."
case Internal:
return "An internal error occured in the Security framework."
case UnsupportedAlgorithm:
return "An unsupported algorithm was encountered."
case UnsupportedOperation:
return "The operation you requested is not supported by this key."
case UnsupportedPadding:
return "The padding you requested is not supported."
case ItemInvalidKey:
return "A string key in dictionary is not one of the supported keys."
case ItemInvalidKeyType:
return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef."
case ItemInvalidValue:
return "A value in a dictionary is an invalid (or unsupported) CF type."
case ItemClassMissing:
return "No kSecItemClass key was specified in a dictionary."
case ItemMatchUnsupported:
return "The caller passed one or more kSecMatch keys to a function which does not support matches."
case UseItemListUnsupported:
return "The caller passed in a kSecUseItemList key to a function which does not support it."
case UseKeychainUnsupported:
return "The caller passed in a kSecUseKeychain key to a function which does not support it."
case UseKeychainListUnsupported:
return "The caller passed in a kSecUseKeychainList key to a function which does not support it."
case ReturnDataUnsupported:
return "The caller passed in a kSecReturnData key to a function which does not support it."
case ReturnAttributesUnsupported:
return "The caller passed in a kSecReturnAttributes key to a function which does not support it."
case ReturnRefUnsupported:
return "The caller passed in a kSecReturnRef key to a function which does not support it."
case ReturnPersitentRefUnsupported:
return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it."
case ValueRefUnsupported:
return "The caller passed in a kSecValueRef key to a function which does not support it."
case ValuePersistentRefUnsupported:
return "The caller passed in a kSecValuePersistentRef key to a function which does not support it."
case ReturnMissingPointer:
return "The caller passed asked for something to be returned but did not pass in a result pointer."
case MatchLimitUnsupported:
return "The caller passed in a kSecMatchLimit key to a call which does not support limits."
case ItemIllegalQuery:
return "The caller passed in a query which contained too many keys."
case WaitForCallback:
return "This operation is incomplete, until the callback is invoked (not an error)."
case MissingEntitlement:
return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements."
case UpgradePending:
return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command."
case MPSignatureInvalid:
return "Signature invalid on MP message"
case OTRTooOld:
return "Message is too old to use"
case OTRIDTooNew:
return "Key ID is too new to use! Message from the future?"
case ServiceNotAvailable:
return "The required service is not available."
case InsufficientClientID:
return "The client ID is not correct."
case DeviceReset:
return "A device reset has occurred."
case DeviceFailed:
return "A device failure has occurred."
case AppleAddAppACLSubject:
return "Adding an application ACL subject failed."
case ApplePublicKeyIncomplete:
return "The public key is incomplete."
case AppleSignatureMismatch:
return "A signature mismatch has occurred."
case AppleInvalidKeyStartDate:
return "The specified key has an invalid start date."
case AppleInvalidKeyEndDate:
return "The specified key has an invalid end date."
case ConversionError:
return "A conversion error has occurred."
case AppleSSLv2Rollback:
return "A SSLv2 rollback error has occurred."
case DiskFull:
return "The disk is full."
case QuotaExceeded:
return "The quota was exceeded."
case FileTooBig:
return "The file is too big."
case InvalidDatabaseBlob:
return "The specified database has an invalid blob."
case InvalidKeyBlob:
return "The specified database has an invalid key blob."
case IncompatibleDatabaseBlob:
return "The specified database has an incompatible blob."
case IncompatibleKeyBlob:
return "The specified database has an incompatible key blob."
case HostNameMismatch:
return "A host name mismatch has occurred."
case UnknownCriticalExtensionFlag:
return "There is an unknown critical extension flag."
case NoBasicConstraints:
return "No basic constraints were found."
case NoBasicConstraintsCA:
return "No basic CA constraints were found."
case InvalidAuthorityKeyID:
return "The authority key ID is not valid."
case InvalidSubjectKeyID:
return "The subject key ID is not valid."
case InvalidKeyUsageForPolicy:
return "The key usage is not valid for the specified policy."
case InvalidExtendedKeyUsage:
return "The extended key usage is not valid."
case InvalidIDLinkage:
return "The ID linkage is not valid."
case PathLengthConstraintExceeded:
return "The path length constraint was exceeded."
case InvalidRoot:
return "The root or anchor certificate is not valid."
case CRLExpired:
return "The CRL has expired."
case CRLNotValidYet:
return "The CRL is not yet valid."
case CRLNotFound:
return "The CRL was not found."
case CRLServerDown:
return "The CRL server is down."
case CRLBadURI:
return "The CRL has a bad Uniform Resource Identifier."
case UnknownCertExtension:
return "An unknown certificate extension was encountered."
case UnknownCRLExtension:
return "An unknown CRL extension was encountered."
case CRLNotTrusted:
return "The CRL is not trusted."
case CRLPolicyFailed:
return "The CRL policy failed."
case IDPFailure:
return "The issuing distribution point was not valid."
case SMIMEEmailAddressesNotFound:
return "An email address mismatch was encountered."
case SMIMEBadExtendedKeyUsage:
return "The appropriate extended key usage for SMIME was not found."
case SMIMEBadKeyUsage:
return "The key usage is not compatible with SMIME."
case SMIMEKeyUsageNotCritical:
return "The key usage extension is not marked as critical."
case SMIMENoEmailAddress:
return "No email address was found in the certificate."
case SMIMESubjAltNameNotCritical:
return "The subject alternative name extension is not marked as critical."
case SSLBadExtendedKeyUsage:
return "The appropriate extended key usage for SSL was not found."
case OCSPBadResponse:
return "The OCSP response was incorrect or could not be parsed."
case OCSPBadRequest:
return "The OCSP request was incorrect or could not be parsed."
case OCSPUnavailable:
return "OCSP service is unavailable."
case OCSPStatusUnrecognized:
return "The OCSP server did not recognize this certificate."
case EndOfData:
return "An end-of-data was detected."
case IncompleteCertRevocationCheck:
return "An incomplete certificate revocation check occurred."
case NetworkFailure:
return "A network failure occurred."
case OCSPNotTrustedToAnchor:
return "The OCSP response was not trusted to a root or anchor certificate."
case RecordModified:
return "The record was modified."
case OCSPSignatureError:
return "The OCSP response had an invalid signature."
case OCSPNoSigner:
return "The OCSP response had no signer."
case OCSPResponderMalformedReq:
return "The OCSP responder was given a malformed request."
case OCSPResponderInternalError:
return "The OCSP responder encountered an internal error."
case OCSPResponderTryLater:
return "The OCSP responder is busy, try again later."
case OCSPResponderSignatureRequired:
return "The OCSP responder requires a signature."
case OCSPResponderUnauthorized:
return "The OCSP responder rejected this request as unauthorized."
case OCSPResponseNonceMismatch:
return "The OCSP response nonce did not match the request."
case CodeSigningBadCertChainLength:
return "Code signing encountered an incorrect certificate chain length."
case CodeSigningNoBasicConstraints:
return "Code signing found no basic constraints."
case CodeSigningBadPathLengthConstraint:
return "Code signing encountered an incorrect path length constraint."
case CodeSigningNoExtendedKeyUsage:
return "Code signing found no extended key usage."
case CodeSigningDevelopment:
return "Code signing indicated use of a development-only certificate."
case ResourceSignBadCertChainLength:
return "Resource signing has encountered an incorrect certificate chain length."
case ResourceSignBadExtKeyUsage:
return "Resource signing has encountered an error in the extended key usage."
case TrustSettingDeny:
return "The trust setting for this policy was set to Deny."
case InvalidSubjectName:
return "An invalid certificate subject name was encountered."
case UnknownQualifiedCertStatement:
return "An unknown qualified certificate statement was encountered."
case MobileMeRequestQueued:
return "The MobileMe request will be sent during the next connection."
case MobileMeRequestRedirected:
return "The MobileMe request was redirected."
case MobileMeServerError:
return "A MobileMe server error occurred."
case MobileMeServerNotAvailable:
return "The MobileMe server is not available."
case MobileMeServerAlreadyExists:
return "The MobileMe server reported that the item already exists."
case MobileMeServerServiceErr:
return "A MobileMe service error has occurred."
case MobileMeRequestAlreadyPending:
return "A MobileMe request is already pending."
case MobileMeNoRequestPending:
return "MobileMe has no request pending."
case MobileMeCSRVerifyFailure:
return "A MobileMe CSR verification failure has occurred."
case MobileMeFailedConsistencyCheck:
return "MobileMe has found a failed consistency check."
case NotInitialized:
return "A function was called without initializing CSSM."
case InvalidHandleUsage:
return "The CSSM handle does not match with the service type."
case PVCReferentNotFound:
return "A reference to the calling module was not found in the list of authorized callers."
case FunctionIntegrityFail:
return "A function address was not within the verified module."
case InternalError:
return "An internal error has occurred."
case MemoryError:
return "A memory error has occurred."
case InvalidData:
return "Invalid data was encountered."
case MDSError:
return "A Module Directory Service error has occurred."
case InvalidPointer:
return "An invalid pointer was encountered."
case SelfCheckFailed:
return "Self-check has failed."
case FunctionFailed:
return "A function has failed."
case ModuleManifestVerifyFailed:
return "A module manifest verification failure has occurred."
case InvalidGUID:
return "An invalid GUID was encountered."
case InvalidHandle:
return "An invalid handle was encountered."
case InvalidDBList:
return "An invalid DB list was encountered."
case InvalidPassthroughID:
return "An invalid passthrough ID was encountered."
case InvalidNetworkAddress:
return "An invalid network address was encountered."
case CRLAlreadySigned:
return "The certificate revocation list is already signed."
case InvalidNumberOfFields:
return "An invalid number of fields were encountered."
case VerificationFailure:
return "A verification failure occurred."
case UnknownTag:
return "An unknown tag was encountered."
case InvalidSignature:
return "An invalid signature was encountered."
case InvalidName:
return "An invalid name was encountered."
case InvalidCertificateRef:
return "An invalid certificate reference was encountered."
case InvalidCertificateGroup:
return "An invalid certificate group was encountered."
case TagNotFound:
return "The specified tag was not found."
case InvalidQuery:
return "The specified query was not valid."
case InvalidValue:
return "An invalid value was detected."
case CallbackFailed:
return "A callback has failed."
case ACLDeleteFailed:
return "An ACL delete operation has failed."
case ACLReplaceFailed:
return "An ACL replace operation has failed."
case ACLAddFailed:
return "An ACL add operation has failed."
case ACLChangeFailed:
return "An ACL change operation has failed."
case InvalidAccessCredentials:
return "Invalid access credentials were encountered."
case InvalidRecord:
return "An invalid record was encountered."
case InvalidACL:
return "An invalid ACL was encountered."
case InvalidSampleValue:
return "An invalid sample value was encountered."
case IncompatibleVersion:
return "An incompatible version was encountered."
case PrivilegeNotGranted:
return "The privilege was not granted."
case InvalidScope:
return "An invalid scope was encountered."
case PVCAlreadyConfigured:
return "The PVC is already configured."
case InvalidPVC:
return "An invalid PVC was encountered."
case EMMLoadFailed:
return "The EMM load has failed."
case EMMUnloadFailed:
return "The EMM unload has failed."
case AddinLoadFailed:
return "The add-in load operation has failed."
case InvalidKeyRef:
return "An invalid key was encountered."
case InvalidKeyHierarchy:
return "An invalid key hierarchy was encountered."
case AddinUnloadFailed:
return "The add-in unload operation has failed."
case LibraryReferenceNotFound:
return "A library reference was not found."
case InvalidAddinFunctionTable:
return "An invalid add-in function table was encountered."
case InvalidServiceMask:
return "An invalid service mask was encountered."
case ModuleNotLoaded:
return "A module was not loaded."
case InvalidSubServiceID:
return "An invalid subservice ID was encountered."
case AttributeNotInContext:
return "An attribute was not in the context."
case ModuleManagerInitializeFailed:
return "A module failed to initialize."
case ModuleManagerNotFound:
return "A module was not found."
case EventNotificationCallbackNotFound:
return "An event notification callback was not found."
case InputLengthError:
return "An input length error was encountered."
case OutputLengthError:
return "An output length error was encountered."
case PrivilegeNotSupported:
return "The privilege is not supported."
case DeviceError:
return "A device error was encountered."
case AttachHandleBusy:
return "The CSP handle was busy."
case NotLoggedIn:
return "You are not logged in."
case AlgorithmMismatch:
return "An algorithm mismatch was encountered."
case KeyUsageIncorrect:
return "The key usage is incorrect."
case KeyBlobTypeIncorrect:
return "The key blob type is incorrect."
case KeyHeaderInconsistent:
return "The key header is inconsistent."
case UnsupportedKeyFormat:
return "The key header format is not supported."
case UnsupportedKeySize:
return "The key size is not supported."
case InvalidKeyUsageMask:
return "The key usage mask is not valid."
case UnsupportedKeyUsageMask:
return "The key usage mask is not supported."
case InvalidKeyAttributeMask:
return "The key attribute mask is not valid."
case UnsupportedKeyAttributeMask:
return "The key attribute mask is not supported."
case InvalidKeyLabel:
return "The key label is not valid."
case UnsupportedKeyLabel:
return "The key label is not supported."
case InvalidKeyFormat:
return "The key format is not valid."
case UnsupportedVectorOfBuffers:
return "The vector of buffers is not supported."
case InvalidInputVector:
return "The input vector is not valid."
case InvalidOutputVector:
return "The output vector is not valid."
case InvalidContext:
return "An invalid context was encountered."
case InvalidAlgorithm:
return "An invalid algorithm was encountered."
case InvalidAttributeKey:
return "A key attribute was not valid."
case MissingAttributeKey:
return "A key attribute was missing."
case InvalidAttributeInitVector:
return "An init vector attribute was not valid."
case MissingAttributeInitVector:
return "An init vector attribute was missing."
case InvalidAttributeSalt:
return "A salt attribute was not valid."
case MissingAttributeSalt:
return "A salt attribute was missing."
case InvalidAttributePadding:
return "A padding attribute was not valid."
case MissingAttributePadding:
return "A padding attribute was missing."
case InvalidAttributeRandom:
return "A random number attribute was not valid."
case MissingAttributeRandom:
return "A random number attribute was missing."
case InvalidAttributeSeed:
return "A seed attribute was not valid."
case MissingAttributeSeed:
return "A seed attribute was missing."
case InvalidAttributePassphrase:
return "A passphrase attribute was not valid."
case MissingAttributePassphrase:
return "A passphrase attribute was missing."
case InvalidAttributeKeyLength:
return "A key length attribute was not valid."
case MissingAttributeKeyLength:
return "A key length attribute was missing."
case InvalidAttributeBlockSize:
return "A block size attribute was not valid."
case MissingAttributeBlockSize:
return "A block size attribute was missing."
case InvalidAttributeOutputSize:
return "An output size attribute was not valid."
case MissingAttributeOutputSize:
return "An output size attribute was missing."
case InvalidAttributeRounds:
return "The number of rounds attribute was not valid."
case MissingAttributeRounds:
return "The number of rounds attribute was missing."
case InvalidAlgorithmParms:
return "An algorithm parameters attribute was not valid."
case MissingAlgorithmParms:
return "An algorithm parameters attribute was missing."
case InvalidAttributeLabel:
return "A label attribute was not valid."
case MissingAttributeLabel:
return "A label attribute was missing."
case InvalidAttributeKeyType:
return "A key type attribute was not valid."
case MissingAttributeKeyType:
return "A key type attribute was missing."
case InvalidAttributeMode:
return "A mode attribute was not valid."
case MissingAttributeMode:
return "A mode attribute was missing."
case InvalidAttributeEffectiveBits:
return "An effective bits attribute was not valid."
case MissingAttributeEffectiveBits:
return "An effective bits attribute was missing."
case InvalidAttributeStartDate:
return "A start date attribute was not valid."
case MissingAttributeStartDate:
return "A start date attribute was missing."
case InvalidAttributeEndDate:
return "An end date attribute was not valid."
case MissingAttributeEndDate:
return "An end date attribute was missing."
case InvalidAttributeVersion:
return "A version attribute was not valid."
case MissingAttributeVersion:
return "A version attribute was missing."
case InvalidAttributePrime:
return "A prime attribute was not valid."
case MissingAttributePrime:
return "A prime attribute was missing."
case InvalidAttributeBase:
return "A base attribute was not valid."
case MissingAttributeBase:
return "A base attribute was missing."
case InvalidAttributeSubprime:
return "A subprime attribute was not valid."
case MissingAttributeSubprime:
return "A subprime attribute was missing."
case InvalidAttributeIterationCount:
return "An iteration count attribute was not valid."
case MissingAttributeIterationCount:
return "An iteration count attribute was missing."
case InvalidAttributeDLDBHandle:
return "A database handle attribute was not valid."
case MissingAttributeDLDBHandle:
return "A database handle attribute was missing."
case InvalidAttributeAccessCredentials:
return "An access credentials attribute was not valid."
case MissingAttributeAccessCredentials:
return "An access credentials attribute was missing."
case InvalidAttributePublicKeyFormat:
return "A public key format attribute was not valid."
case MissingAttributePublicKeyFormat:
return "A public key format attribute was missing."
case InvalidAttributePrivateKeyFormat:
return "A private key format attribute was not valid."
case MissingAttributePrivateKeyFormat:
return "A private key format attribute was missing."
case InvalidAttributeSymmetricKeyFormat:
return "A symmetric key format attribute was not valid."
case MissingAttributeSymmetricKeyFormat:
return "A symmetric key format attribute was missing."
case InvalidAttributeWrappedKeyFormat:
return "A wrapped key format attribute was not valid."
case MissingAttributeWrappedKeyFormat:
return "A wrapped key format attribute was missing."
case StagedOperationInProgress:
return "A staged operation is in progress."
case StagedOperationNotStarted:
return "A staged operation was not started."
case VerifyFailed:
return "A cryptographic verification failure has occurred."
case QuerySizeUnknown:
return "The query size is unknown."
case BlockSizeMismatch:
return "A block size mismatch occurred."
case PublicKeyInconsistent:
return "The public key was inconsistent."
case DeviceVerifyFailed:
return "A device verification failure has occurred."
case InvalidLoginName:
return "An invalid login name was detected."
case AlreadyLoggedIn:
return "The user is already logged in."
case InvalidDigestAlgorithm:
return "An invalid digest algorithm was detected."
case InvalidCRLGroup:
return "An invalid CRL group was detected."
case CertificateCannotOperate:
return "The certificate cannot operate."
case CertificateExpired:
return "An expired certificate was detected."
case CertificateNotValidYet:
return "The certificate is not yet valid."
case CertificateRevoked:
return "The certificate was revoked."
case CertificateSuspended:
return "The certificate was suspended."
case InsufficientCredentials:
return "Insufficient credentials were detected."
case InvalidAction:
return "The action was not valid."
case InvalidAuthority:
return "The authority was not valid."
case VerifyActionFailed:
return "A verify action has failed."
case InvalidCertAuthority:
return "The certificate authority was not valid."
case InvaldCRLAuthority:
return "The CRL authority was not valid."
case InvalidCRLEncoding:
return "The CRL encoding was not valid."
case InvalidCRLType:
return "The CRL type was not valid."
case InvalidCRL:
return "The CRL was not valid."
case InvalidFormType:
return "The form type was not valid."
case InvalidID:
return "The ID was not valid."
case InvalidIdentifier:
return "The identifier was not valid."
case InvalidIndex:
return "The index was not valid."
case InvalidPolicyIdentifiers:
return "The policy identifiers are not valid."
case InvalidTimeString:
return "The time specified was not valid."
case InvalidReason:
return "The trust policy reason was not valid."
case InvalidRequestInputs:
return "The request inputs are not valid."
case InvalidResponseVector:
return "The response vector was not valid."
case InvalidStopOnPolicy:
return "The stop-on policy was not valid."
case InvalidTuple:
return "The tuple was not valid."
case MultipleValuesUnsupported:
return "Multiple values are not supported."
case NotTrusted:
return "The trust policy was not trusted."
case NoDefaultAuthority:
return "No default authority was detected."
case RejectedForm:
return "The trust policy had a rejected form."
case RequestLost:
return "The request was lost."
case RequestRejected:
return "The request was rejected."
case UnsupportedAddressType:
return "The address type is not supported."
case UnsupportedService:
return "The service is not supported."
case InvalidTupleGroup:
return "The tuple group was not valid."
case InvalidBaseACLs:
return "The base ACLs are not valid."
case InvalidTupleCredendtials:
return "The tuple credentials are not valid."
case InvalidEncoding:
return "The encoding was not valid."
case InvalidValidityPeriod:
return "The validity period was not valid."
case InvalidRequestor:
return "The requestor was not valid."
case RequestDescriptor:
return "The request descriptor was not valid."
case InvalidBundleInfo:
return "The bundle information was not valid."
case InvalidCRLIndex:
return "The CRL index was not valid."
case NoFieldValues:
return "No field values were detected."
case UnsupportedFieldFormat:
return "The field format is not supported."
case UnsupportedIndexInfo:
return "The index information is not supported."
case UnsupportedLocality:
return "The locality is not supported."
case UnsupportedNumAttributes:
return "The number of attributes is not supported."
case UnsupportedNumIndexes:
return "The number of indexes is not supported."
case UnsupportedNumRecordTypes:
return "The number of record types is not supported."
case FieldSpecifiedMultiple:
return "Too many fields were specified."
case IncompatibleFieldFormat:
return "The field format was incompatible."
case InvalidParsingModule:
return "The parsing module was not valid."
case DatabaseLocked:
return "The database is locked."
case DatastoreIsOpen:
return "The data store is open."
case MissingValue:
return "A missing value was detected."
case UnsupportedQueryLimits:
return "The query limits are not supported."
case UnsupportedNumSelectionPreds:
return "The number of selection predicates is not supported."
case UnsupportedOperator:
return "The operator is not supported."
case InvalidDBLocation:
return "The database location is not valid."
case InvalidAccessRequest:
return "The access request is not valid."
case InvalidIndexInfo:
return "The index information is not valid."
case InvalidNewOwner:
return "The new owner is not valid."
case InvalidModifyMode:
return "The modify mode is not valid."
default:
return "Unexpected error has occurred."
}
}
}
| mit | 951309aea5f234eb0fb31d0d5626ff05 | 33.047849 | 194 | 0.605514 | 5.898325 | false | false | false | false |
plus44/mhml-2016 | app/Helmo/Helmo/Model.swift | 1 | 7392 | //
// Model.swift
// Helmo
//
// Created by Mihnea Rusu on 06/03/17.
// Copyright © 2017 Mihnea Rusu. All rights reserved.
//
import Foundation
import Metal
import MetalKit
import QuartzCore
import simd
class Model {
let name: String
var device: MTLDevice
var vertexDescriptor: MDLVertexDescriptor
var bufferProvider: BufferProvider
var asset: MDLAsset
var texture: MTLTexture?
var vertexBuffer: MTKMeshBuffer
let submesh: MTKSubmesh
lazy var samplerState: MTLSamplerState? = Model.defaultSampler(device: self.device)
// Position coordinates in the world
var posX: Float = 0.0
var posY: Float = 0.0
var posZ: Float = 0.0
var rotX: Float = 0.0
var rotY: Float = 0.0
var rotZ: Float = 0.0
var scale: Float = 1.0
let light = Light(color: (1.0, 1.0, 1.0), ambientIntensity: 0.1, direction: (0.0, 0.0, 1.0), diffuseIntensity: 0.8, shininess: 5.0, specularIntensity: 1)
var time: CFTimeInterval = 0.0
/**
Initialize the model from a path containing the .obj file, with the MetalViewController's vertexDescriptor a buffer allocator and a texture (optionally).
*/
init(name: String, modelPath: String, texturePath: String?, device: MTLDevice, vertexDescriptor: MDLVertexDescriptor, mtkBufferAllocator: MTKMeshBufferAllocator, textureLoader: MTKTextureLoader?) {
let url = Bundle.main.url(forResource: modelPath, withExtension: nil)
// Load the asset from file
self.asset = MDLAsset(url: url!, vertexDescriptor: vertexDescriptor, bufferAllocator: mtkBufferAllocator)
let mesh = asset.object(at: 0) as? MDLMesh
print("Model '\(name)': Loaded mesh with \(mesh?.vertexCount) vertices")
// mesh!.generateAmbientOcclusionVertexColors(withQuality: 1, attenuationFactor: 0.98, objectsToConsider: [mesh!], vertexAttributeNamed: MDLVertexAttributeOcclusionValue)
let meshes = try! MTKMesh.newMeshes(from: asset, device: device, sourceMeshes: nil)
print("Model '\(name)': Number of meshes: \(meshes.count)")
let firstMesh = (meshes.first)!
self.vertexBuffer = firstMesh.vertexBuffers[0]
submesh = firstMesh.submeshes.first!
print("Model '\(name)': Number of submeshes in firstMesh: \(firstMesh.submeshes.count)")
self.name = name
self.device = device
self.vertexDescriptor = vertexDescriptor
self.bufferProvider = BufferProvider(device: device, inflightBuffersCount: 3)
// Load the model texture
if let textureLoader = textureLoader {
let url = Bundle.main.url(forResource: texturePath, withExtension: nil)
let data = try! Data(contentsOf: url!)
do {
self.texture = try textureLoader.newTexture(with: data, options: nil)
} catch let error {
print("Model '\(name)': Failed loading texture with error: \(error).")
}
}
}
/**
Called every new frame, when the model requires rendering
*/
func render(commandQueue: MTLCommandQueue, pipelineState: MTLRenderPipelineState, depthStencilState: MTLDepthStencilState, drawable: CAMetalDrawable, parentModelViewMatrix: float4x4, projectionMatrix: float4x4, clearColor: MTLClearColor?) {
// Check whether we need to stall the CPU thread or not
let _ = self.bufferProvider.availableResourcesSemaphore.wait(timeout: .distantFuture)
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = drawable.texture
renderPassDescriptor.colorAttachments[0].loadAction = .clear
if let clearColor = clearColor {
renderPassDescriptor.colorAttachments[0].clearColor = clearColor
} else {
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(113.0/255.0, 198.0/255.0, 240.0/255.0, 1.0)
}
// Create a buffer of commands on the command queue
let commandBuffer = commandQueue.makeCommandBuffer()
commandBuffer.addCompletedHandler { (commandBuffer) -> Void in
self.bufferProvider.availableResourcesSemaphore.signal()
}
// Create an encoder in our command buffer and link it to the pipeline
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
renderEncoder.setRenderPipelineState(pipelineState)
renderEncoder.setDepthStencilState(depthStencilState)
if let texture = self.texture {
renderEncoder.setFragmentTexture(texture, at: 0)
}
if let samplerState = samplerState {
renderEncoder.setFragmentSamplerState(samplerState, at: 0)
}
// Create a model matrix for the current state of the model
var nodeModelMatrix = self.modelMatrix()
// Shift the model to the camera perspective (pre-multiply) before passing to the GPU for efficiency
nodeModelMatrix.multiplyLeft(parentModelViewMatrix)
// Fetch the next available buffer
let uniformBuffer = bufferProvider.nextUniformsBuffer(projectionMatrix: projectionMatrix, modelViewMatrix: nodeModelMatrix, light: light)
// Pass the uniforms buffer to both vertex and fragment shaders
renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, at: 1)
renderEncoder.setFragmentBuffer(uniformBuffer, offset: 0, at: 1)
renderEncoder.setVertexBuffer(self.vertexBuffer.buffer, offset: self.vertexBuffer.offset, at: 0)
renderEncoder.drawIndexedPrimitives(type: submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: submesh.indexBuffer.buffer, indexBufferOffset: submesh.indexBuffer.offset)
renderEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
/**
Return a float4x4 representation of the model
*/
func modelMatrix() -> float4x4 {
var matrix = float4x4()
matrix.translate(posX, y: posY, z: posZ)
matrix.rotateAroundX(rotX, y: rotY, z: rotZ)
matrix.scale(scale, y: scale, z: scale)
return matrix
}
/**
Creates a default texture sampler on the provided MTLDevice
*/
class func defaultSampler(device: MTLDevice) -> MTLSamplerState? {
let pSamplerDescriptor: MTLSamplerDescriptor? = MTLSamplerDescriptor()
if let sampler = pSamplerDescriptor {
sampler.minFilter = .nearest
sampler.magFilter = .nearest
sampler.mipFilter = .nearest
sampler.maxAnisotropy = 1
sampler.sAddressMode = .clampToEdge
sampler.tAddressMode = .clampToEdge
sampler.rAddressMode = .clampToEdge
sampler.normalizedCoordinates = true
sampler.lodMinClamp = 0
sampler.lodMaxClamp = FLT_MAX
return device.makeSamplerState(descriptor: pSamplerDescriptor!)
} else {
print("Error: Failed creating a sampler descriptor")
return nil
}
}
}
| gpl-3.0 | 86c84cfa84689f02bf7107339ad66ae9 | 43.524096 | 244 | 0.655933 | 4.865701 | false | false | false | false |
railsdog/CleanroomLogger | Code/Implementation/DefaultLogFormatter.swift | 2 | 8734 | //
// DefaultLogFormatter.swift
// Cleanroom Project
//
// Created by Evan Maloney on 3/18/15.
// Copyright (c) 2015 Gilt Groupe. All rights reserved.
//
import Foundation
/**
The `DefaultLogFormatter` is a basic implementation of the `LogFormatter`
protocol.
This implementation is used by default if no other log formatters are specified.
*/
public struct DefaultLogFormatter: LogFormatter
{
/** If `true`, the receiver will include the timestamp of the log entry when
formatting the log message. */
public let includeTimestamp: Bool
/** If `true`, the receiver will include an identifier for the calling thread when
formatting the log message. This makes it possible to distinguish between distinct
paths of execution when analyzing logs generated by multi-threaded applications. */
public let includeThreadID: Bool
private static let timestampFormatter: NSDateFormatter = {
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS zzz"
return fmt
}()
/**
Initializes the DefaultLogFormatter using the given settings.
:param: includeTimestamp If `true`, the log entry timestamp will be
included in the formatted message.
:param: includeThreadID If `true`, an identifier for the calling thread
will be included in the formatted message.
*/
public init(includeTimestamp: Bool = false, includeThreadID: Bool = false)
{
self.includeTimestamp = includeTimestamp
self.includeThreadID = includeThreadID
}
/**
Returns a formatted representation of the given `LogEntry`.
:param: entry The `LogEntry` being formatted.
:returns: The formatted representation of `entry`. This particular
implementation will never return `nil`.
*/
public func formatLogEntry(entry: LogEntry)
-> String?
{
let severity = DefaultLogFormatter.stringRepresentationOfSeverity(entry.severity)
let caller = DefaultLogFormatter.stringRepresentationForCallingFile(entry.callingFilePath, line: entry.callingFileLine)
let message = DefaultLogFormatter.stringRepresentationForPayload(entry)
var timestamp: String?
if includeTimestamp {
timestamp = DefaultLogFormatter.stringRepresentationOfTimestamp(entry.timestamp)
}
var threadID: String?
if includeThreadID {
threadID = DefaultLogFormatter.stringRepresentationOfThreadID(entry.callingThreadID)
}
return DefaultLogFormatter.formatLogMessageWithSeverity(severity, caller: caller, message: message, timestamp: timestamp, threadID: threadID)
}
/**
Returns the formatted log message given the string representation of the
severity, caller and message associated with a given `LogEntry`.
This implementation is used by the `DefaultLogFormatter` for creating
the log messages that will be recorded.
:param: severity The string representation of the log entry's severity.
:param: caller The string representation of the caller's source file
and line.
:param: message The log message.
:param: timestamp An optional timestamp string to include in the
message.
:param: threadID An optional thread ID to include in the message.
:returns: The formatted log message.
*/
public static func formatLogMessageWithSeverity(severity: String, caller: String, message: String, timestamp: String?, threadID: String?)
-> String
{
var fmt = ""
if let timestamp = timestamp {
fmt += "\(timestamp) | "
}
if let threadID = threadID {
fmt += "\(threadID) | "
}
fmt += "\(severity) | \(caller) — \(message)"
return fmt
}
/**
Returns a string representation of a given `LogSeverity` value.
This implementation is used by the `DefaultLogFormatter` for creating
string representations for representing the `severity` value of
`LogEntry` instances.
:param: severity The `LogSeverity` for which a string representation
is desired.
:returns: A string representation of the `severity` value.
*/
public static func stringRepresentationOfSeverity(severity: LogSeverity)
-> String
{
var severityTag = severity.printableValueName.uppercaseString
while severityTag.utf16.count < 7 {
severityTag = " " + severityTag
}
return severityTag
}
/**
Returns a string representation for a calling file and line.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of a `LogEntry`'s `callingFilePath` and
`callingFileLine` properties.
:param: filePath The full file path of the calling file.
:param: line The line number within the calling file.
:returns: The string representation of `filePath` and `line`.
*/
public static func stringRepresentationForCallingFile(filePath: String, line: Int)
-> String
{
let file = filePath.pathComponents.last ?? "(unknown)"
return "\(file):\(line)"
}
/**
Returns a string representation of an arbitrary optional value.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of `LogEntry` payloads.
:param: entry The `LogEntry` whose payload is desired in string form.
:returns: The string representation of `entry`'s payload.
*/
public static func stringRepresentationForPayload(entry: LogEntry)
-> String
{
switch entry.payload {
case .Trace: return entry.callingFunction
case .Message(let msg): return msg
case .Value(let value): return stringRepresentationForValue(value)
}
}
/**
Returns a string representation of an arbitrary optional value.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of `LogEntry` instances containing `.Value` payloads.
:param: value The value for which a string representation is desired.
:returns: If value is `nil`, the string "`(nil)`" is returned; otherwise,
the return value of `stringRepresentationForValue(Any)` is
returned.
*/
public static func stringRepresentationForValue(value: Any?)
-> String
{
if let value = value {
return stringRepresentationForValue(value)
} else {
return "(nil)"
}
}
/**
Returns a string representation of an arbitrary value.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of `LogEntry` instances containing `.Value` payloads.
:param: value The value for which a string representation is desired.
:returns: A string representation of `value`.
*/
public static func stringRepresentationForValue(value: Any)
-> String
{
let type = Mirror(reflecting: value).subjectType
let desc: String
if let debugValue = value as? CustomDebugStringConvertible {
desc = debugValue.debugDescription
}
else if let printValue = value as? CustomStringConvertible {
desc = printValue.description
}
else if let objcValue = value as? NSObject {
desc = objcValue.description
}
else {
desc = "(no description)"
}
return "<\(type): \(desc)>"
}
/**
Returns a string representation of an `NSDate` timestamp.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of a `LogEntry`'s `timestamp` property.
:param: timestamp The timestamp.
:returns: The string representation of `timestamp`.
*/
public static func stringRepresentationOfTimestamp(timestamp: NSDate)
-> String
{
return timestampFormatter.stringFromDate(timestamp)
}
/**
Returns a string representation of a thread identifier.
This implementation is used by the `DefaultLogFormatter` for creating
string representations of a `LogEntry`'s `callingThreadID` property.
:param: threadID The thread identifier.
:returns: The string representation of `threadID`.
*/
public static func stringRepresentationOfThreadID(threadID: UInt64)
-> String
{
return NSString(format: "%08X", threadID) as String
}
}
| mit | 646dcd0c199380940cb1c6e436e2a718 | 32.584615 | 149 | 0.660215 | 5.179122 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Model/Category.swift | 1 | 619 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
public struct Category: Decodable {
public var id: Int = -1
public var name: String = ""
public var slug: String = ""
public var isPublic: Bool = false
enum CodingKeys: String, CodingKey {
case id
case name
case slug
case isPublic = "public"
}
}
extension Category: Equatable {
static public func == (lhs: Category, rhs: Category) -> Bool {
return lhs.id == rhs.id
&& lhs.isPublic == rhs.isPublic
&& lhs.name == rhs.name
&& lhs.slug == rhs.slug
}
}
| mit | 9aee168e32b98b26e0c31ae8e665f308 | 22.769231 | 66 | 0.564725 | 4.147651 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Views/SegmentedView/SegmentedView.swift | 1 | 4490 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxRelay
import RxSwift
import UIKit
/// The standard wallet `UISegmentedControl`.
/// - see also: [SegmentedViewModel](x-source-tag://SegmentedViewModel).
public final class SegmentedView: UISegmentedControl {
// MARK: - Rx
private var disposeBag = DisposeBag()
// MARK: - Dependencies
public var viewModel: SegmentedViewModel? {
willSet {
disposeBag = DisposeBag()
}
didSet {
guard let viewModel = viewModel else { return }
layer.cornerRadius = viewModel.cornerRadius
// Set accessibility
accessibility = viewModel.accessibility
// Bind backgroundColor
viewModel.backgroundColor
.drive(rx.backgroundColor)
.disposed(by: disposeBag)
// Set the divider color
viewModel.dividerColor
.drive(rx.dividerColor)
.disposed(by: disposeBag)
// Set the text attributes
Driver
.zip(viewModel.contentColor, viewModel.normalFont)
.map { tuple -> [NSAttributedString.Key: Any]? in
var attributes: [NSAttributedString.Key: Any] = [:]
attributes[.font] = tuple.1
if let color = tuple.0 {
attributes[.foregroundColor] = color
}
return attributes
}
.drive(rx.normalTextAttributes)
.disposed(by: disposeBag)
Driver
.zip(viewModel.selectedFontColor, viewModel.selectedFont)
.map { tuple -> [NSAttributedString.Key: Any]? in
var attributes: [NSAttributedString.Key: Any] = [:]
attributes[.font] = tuple.1
if let color = tuple.0 {
attributes[.foregroundColor] = color
}
return attributes
}
.drive(rx.selectedTextAttributes)
.disposed(by: disposeBag)
// Bind border color
viewModel.borderColor
.drive(layer.rx.borderColor)
.disposed(by: disposeBag)
// Bind view model enabled indication to button
viewModel.isEnabled
.drive(rx.isEnabled)
.disposed(by: disposeBag)
// Bind opacity
viewModel.alpha
.drive(rx.alpha)
.disposed(by: disposeBag)
rx.value
.bindAndCatch(to: viewModel.tapRelay)
.disposed(by: disposeBag)
isMomentary = viewModel.isMomentary
removeAllSegments()
viewModel.items.enumerated().forEach {
switch $1.content {
case .imageName(let imageName):
insertSegment(with: UIImage(named: imageName), at: $0, animated: false)
case .title(let title):
insertSegment(withTitle: title, at: $0, animated: false)
}
}
for item in viewModel.items {
switch item.content {
case .title(let title):
setAccessibilityIdentifier(String(describing: item.id.or(default: title)), for: title)
default:
break
}
}
guard isMomentary == false else { return }
selectedSegmentIndex = viewModel.defaultSelectedSegmentIndex
sendActions(for: .valueChanged)
}
}
// MARK: - Setup
public convenience init() {
self.init(frame: .zero)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
layer.borderWidth = 1
selectedSegmentTintColor = .white
}
func setAccessibilityIdentifier(_ accessibilityIdentifier: String, for segmentTitle: String) {
guard let segment = subviews.first(
where: { $0.subviews.filter(UILabel.self).contains(where: { $0.text == segmentTitle }) }
) else {
return
}
segment.accessibilityIdentifier = accessibilityIdentifier
}
}
| lgpl-3.0 | 3dab70fa2ed6bcd5bb4ff28155b73dfa | 30.612676 | 106 | 0.533972 | 5.555693 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/processes/Dolphin/GCController.swift | 1 | 11579 | //
// GCController.swift
// GoD Tool
//
// Created by Stars Momodu on 30/09/2021.
//
import Foundation
#if !GAME_PBR
enum GameController: Int, Codable {
case p1 = 1, p2, p3, p4
var startOffset: Int {
if game == .XD {
switch region {
case .US:
return 0x80444b20 + ((rawValue - 1) * 0x7c)
case .EU:
return -1
case .JP:
return -1
case .OtherGame:
return -1
}
} else{
switch region {
case .US:
return 0x80401c28 + ((rawValue - 1) * 0x6c)
case .EU:
return -1
case .JP:
return -1
case .OtherGame:
return -1
}
}
}
}
enum ControllerButtons: Int, Codable {
case NONE = 0x0
case LEFT = 0x1
case RIGHT = 0x2
case DOWN = 0x4
case UP = 0x8
case Z = 0x10
case R = 0x20
case L = 0x40
case A = 0x100
case B = 0x200
case X = 0x400
case Y = 0x800
case START = 0x1000
}
struct ControllerStickInput: Codable {
enum StickDirectionX: Int, Codable {
case left, right, neutral
var offsets: [Int] {
switch self {
case .left, .right: return [0]
case .neutral: return [0, 1]
}
}
}
enum StickDirectionY: Int, Codable {
case up, down, neutral
var offsets: [Int] {
switch self {
case .up, .down: return [1]
case .neutral: return [0, 1]
}
}
}
private(set) var directionX: StickDirectionX = .neutral
private(set) var directionY: StickDirectionY = .neutral
private(set) var percentageX: UInt = 0
private(set) var percentageY: UInt = 0
var rawValue: UInt16 {
var result: UInt16 = 0
let scaleX = min(percentageX, 100)
let scaleY = min(percentageY, 100)
if percentageX > 0 {
switch directionX {
case .left: result += UInt16(0x100 - ((scaleX * 0x80) / 100)) << 8
case .right: result += UInt16((scaleX * 0x7F) / 100) << 8
case .neutral: break
}
}
if percentageY > 0 {
switch directionY {
case .up: result += UInt16(0x100 - ((scaleY * 0x80) / 100))
case .down: result += UInt16((scaleY * 0x7F) / 100)
case .neutral: break
}
}
return result
}
func maskedWith(stick: ControllerStickInput) -> ControllerStickInput {
var directionX = self.directionX
var percentageX = self.percentageX
if stick.directionX != self.directionX {
percentageX = UInt(min( 100, max(0 ,abs(Int(self.percentageX) - Int(stick.percentageX)))))
if percentageX == 0 {
directionX = .neutral
} else {
directionX = self.percentageX > stick.percentageX ? self.directionX : stick.directionX
}
} else {
percentageX = min(100, self.percentageX + stick.percentageX)
if percentageX == 0 {
directionX = .neutral
}
}
var directionY = self.directionY
var percentageY = self.percentageY
if stick.directionY != self.directionY {
percentageY = UInt(min( 100, max(0 ,abs(Int(self.percentageY) - Int(stick.percentageY)))))
if percentageY == 0 {
directionY = .neutral
} else {
directionY = self.percentageY > stick.percentageY ? self.directionY : stick.directionY
}
} else {
percentageY = min(100, self.percentageY + stick.percentageY)
if percentageX == 0 {
directionX = .neutral
}
}
return ControllerStickInput(directionX: directionX, directionY: directionY, percentageX: percentageX, percentageY: percentageY)
}
}
extension ControllerStickInput {
init(rawValue: UInt16) {
func stickPercentage(_ value: Int) -> UInt {
if value > 0 {
return UInt(value * 100 / 127)
} else if value < 0 {
return UInt((-value) * 100 / 128)
} else {
return 0
}
}
let x = Int(rawValue >> 8)
let y = Int(rawValue & 0xFF)
self.percentageX = stickPercentage(x)
self.percentageY = stickPercentage(y)
self.directionX = x < 0 ? .left : .right
self.directionY = y < 0 ? .up : .down
}
}
struct GCPad: Codable {
var player: GameController = .p1
var duration = XGSettings.current.inputDuration
var Start = false
var A = false
var B = false
var X = false
var Y = false
var R = false
var L = false
var Z = false
var Up = false
var Down = false
var Left = false
var Right = false
var stick = ControllerStickInput()
var cStick = ControllerStickInput()
var tag: String?
var rawData: XGMutableData {
let data = XGMutableData(length: 12)
var buttonMask = 0
if A { buttonMask |= ControllerButtons.A.rawValue }
if B { buttonMask |= ControllerButtons.B.rawValue }
if X { buttonMask |= ControllerButtons.X.rawValue }
if Y { buttonMask |= ControllerButtons.Y.rawValue }
if R { buttonMask |= ControllerButtons.R.rawValue }
if L { buttonMask |= ControllerButtons.L.rawValue }
if Z { buttonMask |= ControllerButtons.Z.rawValue }
if Up { buttonMask |= ControllerButtons.UP.rawValue }
if Down { buttonMask |= ControllerButtons.DOWN.rawValue }
if Left { buttonMask |= ControllerButtons.LEFT.rawValue }
if Right { buttonMask |= ControllerButtons.RIGHT.rawValue }
if Start { buttonMask |= ControllerButtons.START.rawValue }
data.replace2BytesAtOffset(0, withBytes: buttonMask)
data.replace2BytesAtOffset(2, withBytes: Int(stick.rawValue))
data.replace2BytesAtOffset(4, withBytes: Int(cStick.rawValue))
return data
}
func maskedWith(pad: GCPad) -> GCPad {
var newPad = GCPad()
newPad.A = self.A || pad.A
newPad.B = self.B || pad.B
newPad.X = self.X || pad.X
newPad.Y = self.Y || pad.Y
newPad.R = self.R || pad.R
newPad.L = self.L || pad.L
newPad.Z = self.Z || pad.Z
newPad.Up = self.Up || pad.Up
newPad.Down = self.Down || pad.Down
newPad.Left = self.Left || pad.Left
newPad.Right = self.Right || pad.Right
newPad.Start = self.Start || pad.Start
newPad.stick = self.stick.maskedWith(stick: pad.stick)
newPad.cStick = self.cStick.maskedWith(stick: pad.cStick)
newPad.tag = self.tag
return newPad
}
func disableButtons(_ buttons: [ControllerButtons]) -> GCPad {
var pad = self
buttons.forEach { (button) in
switch button {
case .NONE: break
case .UP: pad.Up = false
case .RIGHT: pad.Right = false
case .DOWN: pad.Down = false
case .LEFT: pad.Left = false
case .Z: pad.Z = false
case .R: pad.R = false
case .L: pad.L = false
case .A: pad.A = false
case .B: pad.B = false
case .X: pad.X = false
case .Y: pad.Y = false
case .START: pad.Start = false
}
}
return pad
}
static func button(_ button: ControllerButtons, duration: Double = XGSettings.current.inputDuration, player: GameController = .p1) -> GCPad {
var pad = GCPad(player: player, duration: duration)
switch button {
case .NONE: break
case .UP: pad.Up = true
case .RIGHT: pad.Right = true
case .DOWN: pad.Down = true
case .LEFT: pad.Left = true
case .Z: pad.Z = true
case .R: pad.R = true
case .L: pad.L = true
case .A: pad.A = true
case .B: pad.B = true
case .X: pad.X = true
case .Y: pad.Y = true
case .START: pad.Start = true
}
return pad
}
static func neutral(duration: Double, player: GameController = .p1) -> GCPad {
return GCPad(player: player, duration: duration)
}
}
extension GCPad {
init(rawData: XGMutableData, player: GameController, tag: String? = nil) {
self.player = player
self.tag = tag
let mask = rawData.get2BytesAtOffset(0)
let stick = rawData.getHalfAtOffset(2)
let cStick = rawData.getHalfAtOffset(4)
self.Left = mask & 0x1 > 0
self.Right = mask & 0x2 > 0
self.Down = mask & 0x4 > 0
self.Up = mask & 0x8 > 0
self.Z = mask & 0x10 > 0
self.R = mask & 0x20 > 0
self.L = mask & 0x40 > 0
self.A = mask & 0x100 > 0
self.B = mask & 0x200 > 0
self.X = mask & 0x400 > 0
self.Y = mask & 0x800 > 0
self.Start = mask & 0x1000 > 0
self.stick = ControllerStickInput(rawValue: stick)
self.cStick = ControllerStickInput(rawValue: cStick)
}
}
class ControllerInputs {
typealias GCPadInputSequence = [GCPad] // pads within a sequence are input serially
private(set) var inputsSequences = SafeArray<GCPadInputSequence>() // all sequences are input concurrently
// buttons currently pressed in game by player
var nextInput: [GCPad] {
var pads = [
GCPad(player: .p1), GCPad(player: .p2), GCPad(player: .p3), GCPad(player: .p4),
GCPad(player: .p1, tag: "write:origin"), GCPad(player: .p2, tag: "write:origin"), GCPad(player: .p3, tag: "write:origin"), GCPad(player: .p4, tag: "write:origin")
]
var hasWriteOrigin = false
inputsSequences.perform(operation: { (inputSequences) in
for sequence in inputSequences {
if let next = sequence.first(where: { (pad) -> Bool in
pad.duration > 0
}) {
var index = next.player.rawValue - 1
if next.tag?.contains("write:origin") ?? false {
index += 4
hasWriteOrigin = true
}
pads[index] = pads[index].maskedWith(pad: next)
}
}
})
if !hasWriteOrigin {
pads = Array(pads[0 ... 3])
}
return pads
}
func wait(duration: Double = XGSettings.current.inputDuration, player: GameController = .p1, tag: String? = nil) {
input(GCPad(player: player, duration: duration, tag: tag))
}
func input(_ button: ControllerButtons, duration: Double = XGSettings.current.inputDuration, player: GameController = .p1, tag: String? = nil) {
input(buttons: [button], duration: duration, player: player)
}
func stickInput(_ stick: ControllerStickInput, duration: Double = XGSettings.current.inputDuration, player: GameController = .p1, tag: String? = nil) {
input(stick: stick, duration: duration, player: player)
}
func cStickInput(_ stick: ControllerStickInput, duration: Double = XGSettings.current.inputDuration, player: GameController = .p1, tag: String? = nil) {
input(cStick: stick, duration: duration, player: player)
}
func input(buttons: [ControllerButtons] = [], stick: ControllerStickInput? = nil, cStick: ControllerStickInput? = nil, duration: Double = XGSettings.current.inputDuration, player: GameController = .p1, tag: String? = nil) {
var pad = GCPad(player: player, duration: duration)
for button in buttons {
switch button {
case .NONE: break
case .UP: pad.Up = true
case .RIGHT: pad.Right = true
case .DOWN: pad.Down = true
case .LEFT: pad.Left = true
case .Z: pad.Z = true
case .R: pad.R = true
case .L: pad.L = true
case .A: pad.A = true
case .B: pad.B = true
case .X: pad.X = true
case .Y: pad.Y = true
case .START: pad.Start = true
}
}
if let stick = stick {
pad.stick = stick
}
if let cStick = cStick {
pad.cStick = cStick
}
input(pad)
}
func input(_ pad: GCPad) {
input([pad])
}
func input(_ sequence: GCPadInputSequence) {
inputsSequences.append(sequence)
}
func delayPendingInput(duration: Double) {
inputsSequences.perform { (inputSequences) -> [GCPadInputSequence] in
var newSequences = [GCPadInputSequence]()
for sequence in inputSequences {
newSequences.append([GCPad(duration: duration)] + sequence)
}
return newSequences
}
}
func clearPendingInput() {
inputsSequences.removeAll()
}
func elapseTime(_ duration: Double) {
var newSequences = [GCPadInputSequence]()
inputsSequences.perform { (inputSequences) -> [GCPadInputSequence] in
for sequence in inputSequences {
var newSequence = GCPadInputSequence()
var nextInputDecreased = false
for pad in sequence {
var updatedPad = pad
if !nextInputDecreased, pad.duration > 0 {
nextInputDecreased = true
updatedPad.duration = max(0, pad.duration - duration)
}
newSequence.append(updatedPad)
}
if nextInputDecreased {
newSequences.append(newSequence)
}
}
return newSequences
}
}
}
#endif
| gpl-2.0 | 85ea65f2c23783e898ceed0cd817d474 | 25.865429 | 224 | 0.656015 | 2.995085 | false | false | false | false |
ajohnson388/rss-reader | RSS Reader/RSS Reader/ArticlesListViewController.swift | 1 | 2292 | //
// ArticlesListViewController.swift
// RSS Reader
//
// Created by Andrew Johnson on 9/5/16.
// Copyright © 2016 Andrew Johnson. All rights reserved.
//
import Foundation
import UIKit
final class ArticlesListViewController: SearchableTableViewController {
// MARK: Fields
var feed: Feed
var articles: [Article] = []
// MARK: Initializers
init(feed: Feed) {
self.feed = feed
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) should not be used")
}
// MARK: Abstract Method Implementations
override func reloadDataSource() {
isSearching() ? loadArticlesForSearchText() : loadAllArticles()
}
// MARK: Helper Methods
func loadAllArticles() {
}
func loadArticlesForSearchText() {
// guard let searchText = searchB
// articles = DBService.sharedInstance.getObjects().filter({
// $0.
// })
}
// MARK: UIViewController LifeCycle Callbacks
// MARK: UITableView DataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let article = articles[(indexPath as NSIndexPath).row]
let reuseId = "article_cell"
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) ?? UITableViewCell(style: .subtitle, reuseIdentifier: reuseId)
cell.textLabel?.text = article.title
cell.detailTextLabel?.text = article.description
cell.accessoryType = .disclosureIndicator
return cell
}
// MARK: UITableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let article = articles[indexPath.row]
// TODO - Go to article
}
}
// MARK: UISearchBar Delegate
extension ArticlesListViewController {
}
| apache-2.0 | a956b0d9130e05806c3c55c04e865d2f | 23.902174 | 136 | 0.632475 | 5.206818 | false | false | false | false |
folse/Member_iOS | member/Trade.swift | 1 | 6107 | //
// Trade.swift
// member
//
// Created by Jennifer on 7/1/15.
// Copyright (c) 2015 Folse. All rights reserved.
//
import UIKit
class Trade: UITableViewController {
var realName : String = ""
var vaildQuantity : String = ""
var punchedQuantity : String = ""
var customerUsername : String = ""
@IBOutlet weak var quantityTextField: UITextField!
@IBOutlet weak var vaildQuantityLabel: UILabel!
@IBOutlet weak var punchedQuantityLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = realName
vaildQuantityLabel.text = vaildQuantity
punchedQuantityLabel.text = punchedQuantity
NSNotificationCenter.defaultCenter().addObserverForName("updateVaildQuantity", object:nil, queue:NSOperationQueue.mainQueue(), usingBlock:{notification in
let newVaildQuantity = notification.object as! Int
println(newVaildQuantity)
self.vaildQuantity = "\(newVaildQuantity)"
self.vaildQuantityLabel.text = self.vaildQuantity
})
NSNotificationCenter.defaultCenter().addObserverForName("updatePunchedQuantity", object:nil, queue:NSOperationQueue.mainQueue(), usingBlock:{notification in
let newPunchedQuantity = notification.object as! Int
println(newPunchedQuantity)
self.punchedQuantity = "\(newPunchedQuantity)"
self.punchedQuantityLabel.text = self.punchedQuantity
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func memberTradeButtonAction(sender: AnyObject) {
self.view.endEditing(true)
if quantityTextField.text.length == 0 {
trade(customerUsername, quantity : "1")
}else{
trade(customerUsername, quantity : quantityTextField.text)
}
}
func trade(username:String,quantity:String) {
var indicator = WIndicator.showIndicatorAddedTo(self.view, animation: true)
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet().setByAddingObject("text/html")
let url = API_ROOT + "trade_add"
println(url)
let shopId : String = NSUserDefaults.standardUserDefaults().objectForKey("shopId") as! String
let params:NSDictionary = ["customer_username":username,
"shop_id":shopId,
"quantity":quantity,
"trade_type":"1"]
println(params)
manager.GET(url,
parameters: params as [NSObject : AnyObject],
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println(responseObject.description)
WIndicator.removeIndicatorFrom(self.view, animation: true)
let responseDict = responseObject as! Dictionary<String,AnyObject>
let responseCode = responseDict["resp"] as! String
if responseCode == "0000"{
var orderQuantity = quantity.toInt()!
var vaildQuantityInt = self.vaildQuantity.toInt()! - orderQuantity
self.vaildQuantity = "\(vaildQuantityInt)"
self.vaildQuantityLabel.text = self.vaildQuantity
self.punchedQuantityLabel.text = self.punchedQuantity
var indicator = WIndicator.showSuccessInView(self.view, text:" ", timeOut:1)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "dismissView", userInfo: nil, repeats: false)
}else {
let message = responseDict["msg"] as! String
let alert = UIAlertView()
alert.title = "Denna operation kan inte slutföras"
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
WIndicator.removeIndicatorFrom(self.view, animation: true)
let alert = UIAlertView()
alert.title = "Denna operation kan inte slutföras"
alert.message = "Försök igen eller kontakta vår kundtjänst. För bättre och snabbare service, rekommenderar vi att du skickar oss en skärmdump." + error.localizedDescription + "\(error.code)"
alert.addButtonWithTitle("OK")
alert.show()
})
}
func dismissView() {
self.navigationController?.popViewControllerAnimated(true)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "punch"{
var segue = segue.destinationViewController as! Punch
segue.punchedQuantity = self.punchedQuantity.toInt()!
segue.customerUsername = self.customerUsername
}else if segue.identifier == "charge"{
var segue = segue.destinationViewController as! Charge
segue.customerUsername = self.customerUsername
}
}
}
extension String {
var length: Int { return count(self) } // Swift 1.2
}
| mit | bf28691e98d2b13cba77f958f27bd051 | 34.660819 | 206 | 0.563299 | 5.543636 | false | false | false | false |
rporzuc/FindFriends | FindFriends/FindFriends/MyAccount/Image User/EditUserImageViewController.swift | 1 | 2172 |
import UIKit
class EditUserImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var userImage : UIImage = UIImage()
let pickerController = UIImagePickerController()
@IBOutlet var userImageView: UIImageView!
@IBAction func btnReturnClicked(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
}
@IBAction func btnOkClicked(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
editUserNameViewController.userImage = self.userImageView.image
}
@IBAction func btnCameraClicked(_ sender: UIButton) {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
pickerController.sourceType = UIImagePickerControllerSourceType.camera
pickerController.allowsEditing = true
self.present(pickerController, animated: true, completion: nil)
}else
{
self.showInformationAlertView(message: "Camera isn't available, please select a photo from the gallery.")
}
}
@IBAction func btnPhotoGalleryClicked(_ sender: Any) {
pickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
pickerController.allowsEditing = true
self.present(pickerController, animated: true, completion: nil)
}
@IBAction func btnDeleteImageClicked(_ sender: Any) {
self.userImageView.image = UIImage(named: "ImagePerson")
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let theInfo = info as NSDictionary
let img : UIImage = theInfo.object(forKey: UIImagePickerControllerEditedImage) as! UIImage
self.userImageView.image = img
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
userImageView.image = userImage
pickerController.delegate = self
}
}
| gpl-3.0 | 68bc6233856f1d34c7fb937b53060a5c | 32.9375 | 119 | 0.678177 | 5.918256 | false | false | false | false |
Joywii/ImageView | Swift/ImageViewDemo/ImageViewDemo/ImageView/ImageViewer/KZImageViewer.swift | 2 | 10768 | //
// KZImageViewer.swift
// ImageViewDemo
//
// Created by joywii on 15/4/30.
// Copyright (c) 2015年 joywii. All rights reserved.
//
import UIKit
let kPadding = 10
class KZImageViewer: UIView , UIScrollViewDelegate ,KZImageScrollViewDelegate{
private var scrollView : UIScrollView?
private var selectIndex : NSInteger?
private var scrollImageViewArray : NSMutableArray?
private var selectImageView : UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
self.backgroundColor = UIColor.blackColor()
self.scrollImageViewArray = NSMutableArray()
self.scrollView = UIScrollView(frame: self.frameForPagingScrollView())
self.scrollView?.pagingEnabled = true
self.scrollView?.showsHorizontalScrollIndicator = false
self.scrollView?.showsVerticalScrollIndicator = false
self.scrollView?.backgroundColor = UIColor.clearColor()
self.scrollView?.delegate = self
self.addSubview(self.scrollView!)
}
func showImages(imageArray:NSArray,index:NSInteger) {
self.alpha = 0.0
var window : UIWindow = UIApplication.sharedApplication().keyWindow!
window.addSubview(self)
let currentPage = index
self.selectIndex = index
var kzSelectImage : KZImage = imageArray.objectAtIndex(Int(index)) as! KZImage
var selectImage : UIImage? = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(kzSelectImage.imageUrl?.absoluteString)
if(selectImage == nil) {
selectImage = kzSelectImage.thumbnailImage
}
var selectImageView : UIImageView = kzSelectImage.srcImageView!
self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height)
self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0)
//动画
var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview)
var imageView = UIImageView(frame: selectImageViewFrame)
imageView.contentMode = selectImageView.contentMode
imageView.clipsToBounds = true
imageView.image = selectImage
imageView.backgroundColor = UIColor.clearColor()
imageView.userInteractionEnabled = true
window.addSubview(imageView)
let fullWidth = window.frame.size.width
let fullHeight = window.frame.size.height
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.alpha = 1.0
imageView.transform = CGAffineTransformIdentity
var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size
var ratio = min(fullWidth / size!.width,fullHeight / size!.height)
var w = ratio > 1 ? size!.width : ratio * size!.width
var h = ratio > 1 ? size!.height : ratio * size!.height
imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h)
}) { (finished) -> Void in
for(var i = 0 ; i < imageArray.count ; i++) {
var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage
var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i)))
zoomImageView.kzImage = kzImage
zoomImageView.imageDelegate = self
zoomImageView.userInteractionEnabled = true
if(i == Int(currentPage)){
if(kzImage.image == nil) {
zoomImageView.startLoadImage()
}
}
self.scrollView?.addSubview(zoomImageView)
self.scrollImageViewArray?.addObject(zoomImageView)
}
self.preLoadImage(currentPage)
imageView.removeFromSuperview()
}
}
func showImages(imageArray:NSArray,selectImageView:UIImageView,index:NSInteger) {
self.alpha = 0.0
var window : UIWindow = UIApplication.sharedApplication().keyWindow!
window.addSubview(self)
let currentPage = index
self.selectIndex = index
self.selectImageView = selectImageView
self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height)
self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0)
//动画
var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview)
var imageView = UIImageView(frame: selectImageViewFrame)
imageView.contentMode = selectImageView.contentMode
imageView.clipsToBounds = true
imageView.image = selectImageView.image
imageView.backgroundColor = UIColor.clearColor()
imageView.userInteractionEnabled = true
window.addSubview(imageView)
let fullWidth = window.frame.size.width
let fullHeight = window.frame.size.height
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.alpha = 1.0
imageView.transform = CGAffineTransformIdentity
var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size
var ratio = min(fullWidth / size!.width,fullHeight / size!.height)
var w = ratio > 1 ? size!.width : ratio * size!.width
var h = ratio > 1 ? size!.height : ratio * size!.height
imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h)
}) { (finished) -> Void in
for(var i = 0 ; i < imageArray.count ; i++) {
var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage
var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i)))
zoomImageView.kzImage = kzImage
zoomImageView.imageDelegate = self
zoomImageView.userInteractionEnabled = true
if(i == Int(currentPage)){
if(kzImage.image == nil) {
zoomImageView.startLoadImage()
}
}
self.scrollView?.addSubview(zoomImageView)
self.scrollImageViewArray?.addObject(zoomImageView)
}
self.preLoadImage(currentPage)
imageView.removeFromSuperview()
}
}
private func tappedScrollView(tap:UITapGestureRecognizer) {
self.hide()
}
private func hide() {
for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] {
imageView.cancelLoadImage()
imageView.removeFromSuperview()
}
var window : UIWindow = UIApplication.sharedApplication().keyWindow!
let fullWidth = window.frame.size.width
let fullHeight = window.frame.size.height
var index = self.pageIndex()
var zoomImageView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView
var size = zoomImageView.kzImage?.image != nil ? zoomImageView.kzImage?.image?.size : zoomImageView.frame.size
var ratio = min(fullWidth / size!.width, fullHeight / size!.height)
var w = ratio > 1 ? size!.width : ratio*size!.width
var h = ratio > 1 ? size!.height : ratio*size!.height
var frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h)
var imageView = UIImageView(frame: frame)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = zoomImageView.kzImage!.image
imageView.backgroundColor = UIColor.clearColor()
imageView.userInteractionEnabled = true
window.addSubview(imageView)
var selectImageViewFrame = window.convertRect(zoomImageView.kzImage!.srcImageView!.frame, fromView: zoomImageView.kzImage!.srcImageView!.superview)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.alpha = 0.0
imageView.frame = selectImageViewFrame
}) { (finished) -> Void in
for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] {
SDImageCache.sharedImageCache().removeImageForKey(imageView.kzImage?.imageUrl?.absoluteString, fromDisk: false)
}
imageView.removeFromSuperview()
self.removeFromSuperview()
}
}
private func pageIndex() -> NSInteger{
return NSInteger(self.scrollView!.contentOffset.x / self.scrollView!.frame.size.width)
}
private func frameForPagingScrollView() -> CGRect {
var frame = self.bounds
frame.origin.x -= CGFloat(kPadding)
frame.size.width += 2 * CGFloat(kPadding)
return CGRectIntegral(frame)
}
private func frameForPageAtIndex(index:UInt) -> CGRect {
var bounds = self.scrollView?.bounds
var pageFrame = bounds
pageFrame?.size.width -= (2*CGFloat(kPadding))
pageFrame?.origin.x = (bounds!.size.width * CGFloat(index)) + CGFloat(kPadding)
return CGRectIntegral(pageFrame!)
}
func imageScrollViewSingleTap(imageScrollView: KZImageScrollView) {
self.hide()
}
func preLoadImage(currentIndex:NSInteger) {
var preIndex = currentIndex - 1
if(preIndex > 1) {
var preZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(preIndex)) as! KZImageScrollView
preZoomImageView.startLoadImage()
}
var nextIndex = currentIndex + 1
if(nextIndex < self.scrollImageViewArray?.count) {
var nextZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(nextIndex)) as! KZImageScrollView
nextZoomImageView.startLoadImage()
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
var index = self.pageIndex()
var zoomImageView : KZImageScrollView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView
zoomImageView.startLoadImage()
self.preLoadImage(index)
}
}
| mit | 9eb2944527c9cde28aaa75a7b6952379 | 43.639004 | 155 | 0.630508 | 5.022409 | false | false | false | false |
ymyzk/swift-benchmarks | SwiftBenchmarks/ViewController.swift | 1 | 3310 | //
// ViewController.swift
// SwiftBenchmarks
//
// Copyright (c) 2014 Yusuke Miyazaki.
//
import UIKit
class ViewController: UIViewController {
@IBAction func runDowncastBenchmark(sender: AnyObject) {
var start: NSDate
var sum: Int = 0
var error: NSError?
let resourceFilePath = NSBundle.mainBundle().pathForResource("sample", ofType: "json")
let data = NSData(contentsOfFile: resourceFilePath!)
start = NSDate()
let list1 = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as [[String: Int]]
sum = list1.reduce(0, combine: { $0 + reduce($1.values, 0, +) })
let result1 = -start.timeIntervalSinceNow
start = NSDate()
let list2 = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as [AnyObject]
sum = list2.reduce(sum, combine: { $0 + reduce(($1 as [String: Int]).values, 0, +) })
let result2 = -start.timeIntervalSinceNow
let result = String(
format: "%@: %.3f [sec]\n%@: %.3f [sec]\n%d",
"AnyObject? -> [[String: Int]]", result1,
"AnyObject? -> [AnyObject], AnyObject -> [String: Int]", result2, sum)
println(result)
UIAlertView(
title: "Result",
message: result,
delegate: nil,
cancelButtonTitle: "OK").show()
}
@IBAction func runArrayBenchmark(sender: AnyObject) {
var start: NSDate
start = NSDate()
let mutableArray = NSMutableArray()
for i in 0...1000000 {
mutableArray.addObject(i)
}
let mutableArrayResult = -start.timeIntervalSinceNow
start = NSDate()
var swiftArray = [Int]()
for i in 0...1000000 {
swiftArray.append(i)
}
let swiftArrayResult = -start.timeIntervalSinceNow
let result = String(
format: "%@: %.3f [sec]\n%@: %.3f [sec]",
"NSMutableArray", mutableArrayResult,
"Swift Array", swiftArrayResult)
println(result)
UIAlertView(
title: "Result",
message: result,
delegate: nil,
cancelButtonTitle: "OK").show()
}
@IBAction func runDictionaryBenchmark(sender: AnyObject) {
var start: NSDate
start = NSDate()
let mutableDictionary = NSMutableDictionary()
for i in 0...100000 {
mutableDictionary[i] = i
}
let mutableDictionaryResult = -start.timeIntervalSinceNow
start = NSDate()
var swiftDictionary = [Int: Int]()
for i in 0...100000 {
swiftDictionary[i] = i
}
let swiftDictionaryResult = -start.timeIntervalSinceNow
let result = String(
format: "%@: %.3f [sec]\n%@: %.3f [sec]",
"NSMutableDictionary", mutableDictionaryResult,
"Swift Dictionary", swiftDictionaryResult)
println(result)
UIAlertView(
title: "Result",
message: result,
delegate: nil,
cancelButtonTitle: "OK").show()
}
} | mit | 87ce9b53f788518ac1b3735dff1becda | 32.11 | 144 | 0.55861 | 4.839181 | false | false | false | false |
justinhester/hacking-with-swift | src/Project17/Project17/GameScene.swift | 1 | 18014 | //
// GameScene.swift
// Project17
//
// Created by Justin Lawrence Hester on 2/6/16.
// Copyright (c) 2016 Justin Lawrence Hester. All rights reserved.
//
import AVFoundation
//import UIKit
import SpriteKit
enum SequenceType: Int {
case OneNoBomb, One, TwoWithOneBomb, Two, Three, Four, Chain, FastChain
}
enum ForceBomb {
case Never, Always, Default
}
class GameScene: SKScene {
var gameScore: SKLabelNode!
var score: Int = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
var livesImages = [SKSpriteNode]()
var lives = 3
var activeSliceBG: SKShapeNode!
var activeSliceFG: SKShapeNode!
/* array of slice points */
var activeSlicePoints = [CGPoint]()
var swooshSoundActive = false
/* array of flying enemies. */
var activeEnemies = [SKSpriteNode]()
var bombSoundEffect: AVAudioPlayer!
/* properties for the enemy sequences. */
var popupTime = 0.9
var sequence: [SequenceType]!
var sequencePosition = 0
var chainDelay = 3.0
var nextSequenceQueued = true
var gameEnded = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let background = SKSpriteNode(imageNamed: "sliceBackground")
background.position = CGPoint(x: size.width / 2, y: size.height / 2)
background.blendMode = .Replace
background.zPosition = -1
addChild(background)
/* Adjust default gravity to allow objects to stay in air longer. */
physicsWorld.gravity = CGVector(dx: 0, dy: -6)
physicsWorld.speed = 0.85
createScore()
createLives()
createSlices()
/* Fix the first sequence types to ease the player into game mechanics. */
sequence = [
.OneNoBomb,
.OneNoBomb,
.TwoWithOneBomb,
.TwoWithOneBomb,
.Three,
.One,
.Chain
]
/* Add more difficult sequences. */
for _ in 0 ... 1000 {
let nextSequence = SequenceType(rawValue: RandomInt(min: 2, max: 7))!
sequence.append(nextSequence)
}
RunAfterDelay(2) { [unowned self] in
self.tossEnemies()
}
}
func createScore() {
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.text = "Score: 0"
gameScore.horizontalAlignmentMode = .Left
gameScore.fontSize = 48
addChild(gameScore)
gameScore.position = CGPoint(x: 8, y: 8)
}
func createLives() {
for i in 0 ..< 3 {
let spriteNode = SKSpriteNode(imageNamed: "sliceLife")
spriteNode.position = CGPoint(x: CGFloat(834 + (i * 70)), y: 720)
addChild(spriteNode)
livesImages.append(spriteNode)
}
}
func createSlices() {
/* Ensure slices always appear on top of everything. */
activeSliceBG = SKShapeNode()
activeSliceBG.zPosition = 2
activeSliceFG = SKShapeNode()
activeSliceFG.zPosition = 2
/* yellow slice */
activeSliceBG.strokeColor = UIColor(red: 1, green: 0.9, blue: 0, alpha: 1)
activeSliceBG.lineWidth = 9
/* white slice */
activeSliceFG.strokeColor = UIColor.whiteColor()
activeSliceFG.lineWidth = 5
addChild(activeSliceBG)
addChild(activeSliceFG)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
/* Remove all existing slice points. */
activeSlicePoints.removeAll(keepCapacity: true)
/* Get the touch location and it to the slice points array. */
if let touch = touches.first {
let location = touch.locationInNode(self)
activeSlicePoints.append(location)
/* Clear the slice shapes. */
redrawActiveSlice()
/* Remove shape actions (e.g. fadeOutWithDuration()). */
activeSliceBG.removeAllActions()
activeSliceFG.removeAllActions()
/* Make slice shapes full visible. */
activeSliceBG.alpha = 1
activeSliceFG.alpha = 1
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if gameEnded {
return
}
guard let touch = touches.first else { return }
let location = touch.locationInNode(self)
activeSlicePoints.append(location)
redrawActiveSlice()
if !swooshSoundActive {
playSwooshSound()
}
let nodes = nodesAtPoint(location)
for node in nodes {
/* Destroy the penguin. */
if node.name == "enemy" {
/* Create a particle effect over the penguin. */
let emitter = SKEmitterNode(fileNamed: "sliceHitEnemy")!
emitter.position = node.position
addChild(emitter)
/* Clear its node name so that it can't be swiped repeatedly. */
node.name = ""
/* Disable the dynamic of its physic body so that it doesn't carry on falling. */
node.physicsBody!.dynamic = false
/* Make the penguin scale out and fade out at the same time. */
let scaleOut = SKAction.scaleTo(0.001, duration: 0.2)
let fadeOut = SKAction.fadeOutWithDuration(0.2)
let group = SKAction.group([scaleOut, fadeOut])
/* After making the penguin scale out and fade out, we should remove it from the scene. */
let seq = SKAction.sequence([group, SKAction.removeFromParent()])
node.runAction(seq)
emitter.runAction(SKAction.removeFromParent())
/* Add one to the player's score. */
score += 1
/* Remove the enemy from our activeEnemies array. */
let index = activeEnemies.indexOf(node as! SKSpriteNode)!
activeEnemies.removeAtIndex(index)
/* Play a sound so the play knows they hit the penguin. */
runAction(SKAction.playSoundFileNamed("whack.caf", waitForCompletion: false))
/* Destroy the bomb. */
} else if node.name == "bomb" {
let emitter = SKEmitterNode(fileNamed: "sliceHitBomb")!
emitter.position = node.parent!.position
addChild(emitter)
node.name = ""
node.parent!.physicsBody!.dynamic = false
let scaleOut = SKAction.scaleTo(0.001, duration: 0.2)
let fadeOut = SKAction.fadeOutWithDuration(0.2)
let group = SKAction.group([scaleOut, fadeOut])
let seq = SKAction.sequence([group, SKAction.removeFromParent()])
node.parent!.runAction(seq)
emitter.runAction(SKAction.removeFromParent())
let index = activeEnemies.indexOf(node.parent as! SKSpriteNode)!
activeEnemies.removeAtIndex(index)
runAction(SKAction.playSoundFileNamed("explosion.caf", waitForCompletion: false))
endGame(triggeredByBomb: true)
}
}
}
func endGame(triggeredByBomb triggeredByBomb: Bool) {
if gameEnded {
return
}
gameEnded = true
physicsWorld.speed = 0
userInteractionEnabled = false
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
if triggeredByBomb {
livesImages[0].texture = SKTexture(imageNamed: "sliceLifeGone")
livesImages[1].texture = SKTexture(imageNamed: "sliceLifeGone")
livesImages[2].texture = SKTexture(imageNamed: "sliceLifeGone")
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
activeSliceBG.runAction(SKAction.fadeOutWithDuration(0.25))
activeSliceFG.runAction(SKAction.fadeOutWithDuration(0.25))
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let touches = touches {
touchesEnded(touches, withEvent: event)
}
}
func redrawActiveSlice() {
/* Exit the method if there are not enough points to draw a line. */
if activeSlicePoints.count < 2 {
activeSliceBG.path = nil
activeSliceFG.path = nil
return
}
/* Remove old points until the slice points array has at most 12 points. */
while activeSlicePoints.count > 12 {
activeSlicePoints.removeAtIndex(0)
}
/* Start drawing the line from the first slice point. */
let path = UIBezierPath()
path.moveToPoint(activeSlicePoints[0])
for i in 1 ..< activeSlicePoints.count {
path.addLineToPoint(activeSlicePoints[i])
}
/* Update the slice path to draw the slice. */
activeSliceBG.path = path.CGPath
activeSliceFG.path = path.CGPath
}
func playSwooshSound() {
swooshSoundActive = true
let randomNumber = RandomInt(min: 1, max: 3)
let soundName = "swoosh\(randomNumber).caf"
let swooshSound = SKAction.playSoundFileNamed(soundName, waitForCompletion: true)
/*
runAction's trailing closure ensures playSwooshSound()
is not called again until the current sound stops playing.
*/
runAction(swooshSound) { [unowned self] in
self.swooshSoundActive = false
}
}
func tossEnemies() {
if gameEnded {
return
}
/* Increase game difficulty. */
popupTime *= 0.991
chainDelay *= 0.99
physicsWorld.speed *= 1.02
let sequenceType = sequence[sequencePosition]
switch sequenceType {
case .OneNoBomb:
createEnemy(forceBomb: .Never)
case .One:
createEnemy()
case .TwoWithOneBomb:
createEnemy(forceBomb: .Never)
createEnemy(forceBomb: .Always)
case .Two:
createEnemy()
createEnemy()
case .Three:
createEnemy()
createEnemy()
createEnemy()
case .Four:
createEnemy()
createEnemy()
createEnemy()
createEnemy()
case .Chain:
createEnemy()
RunAfterDelay(chainDelay / 5.0) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 5.0 * 2) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 5.0 * 3) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 5.0 * 4) { [unowned self] in self.createEnemy() }
case .FastChain:
createEnemy()
RunAfterDelay(chainDelay / 10.0) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 10.0 * 2) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 10.0 * 3) { [unowned self] in self.createEnemy() }
RunAfterDelay(chainDelay / 10.0 * 4) { [unowned self] in self.createEnemy() }
}
sequencePosition += 1
nextSequenceQueued = false
}
func createEnemy(forceBomb forceBomb: ForceBomb = .Default) {
var enemy: SKSpriteNode
var enemyType = RandomInt(min: 0, max: 6) /* 0 means bomb */
if forceBomb == .Never {
enemyType = 1
} else if forceBomb == .Always {
/* Make a bomb. */
enemyType = 0
}
if enemyType == 0 {
/* Create container that will hold the fuse and the bomb image. */
enemy = SKSpriteNode()
/* Set the container's z position above the penguin images. */
enemy.zPosition = 1
enemy.name = "bombContainer"
/* Create the bomb image and add it to the container. */
let bombImage = SKSpriteNode(imageNamed: "sliceBomb")
bombImage.name = "bomb"
enemy.addChild(bombImage)
/* If the bomb fuse sound effect is playing, stop it and destroy it. */
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
/* Create a new bomb fuse sound effect, then play it. */
let path = NSBundle.mainBundle().pathForResource("sliceBombFuse.caf", ofType: nil)!
let url = NSURL(fileURLWithPath: path)
let sound = try! AVAudioPlayer(contentsOfURL: url)
bombSoundEffect = sound
sound.play()
/* Create a particle emitter node and add it to the container. */
let emitter = SKEmitterNode(fileNamed: "sliceFuse")!
emitter.position = CGPoint(x: 76, y: 64) /* hard-coded position for tip of bomb */
enemy.addChild(emitter)
} else {
enemy = SKSpriteNode(imageNamed: "penguin")
runAction(SKAction.playSoundFileNamed("launch.caf", waitForCompletion: false))
enemy.name = "enemy"
}
/* Give the enemy a random position off the bottom edge of the screen. */
let randomPosition = CGPoint(x: RandomInt(min: 64, max: 960), y: -128)
enemy.position = randomPosition
/* Create a random angular velocity, which is how fast something should spin. */
let randomAngularVelocity = CGFloat(RandomInt(min: -6, max: 6)) / 2.0
var randomXVelocity = 0
/* Create a random X velocity that takes into account the position. */
if randomPosition.x < 256 {
randomXVelocity = RandomInt(min: 8, max: 15)
} else if randomPosition.x < 512 {
randomXVelocity = RandomInt(min: 3, max: 5)
} else if randomPosition.x < 768 {
randomXVelocity = -RandomInt(min: 3, max: 5)
} else {
randomXVelocity = -RandomInt(min: 8, max: 15)
}
/* Create a random Y velocity to make things fly at different speeds. */
let randomYVelocity = RandomInt(min: 24, max: 32)
/* Give all enemies a circular physics body where the collisionBitMake is set to 0 so they don't collied. */
enemy.physicsBody = SKPhysicsBody(circleOfRadius: 64)
enemy.physicsBody!.velocity = CGVector(dx: randomXVelocity * 40, dy: randomYVelocity * 40)
enemy.physicsBody!.angularVelocity = randomAngularVelocity
enemy.physicsBody!.collisionBitMask = 0
addChild(enemy)
activeEnemies.append(enemy)
}
func subtractLife() {
lives -= 1
runAction(SKAction.playSoundFileNamed("wrong.caf", waitForCompletion: false))
var life: SKSpriteNode
if lives == 2 {
life = livesImages[0]
} else if lives == 1 {
life = livesImages[1]
} else {
life = livesImages[2]
endGame(triggeredByBomb: false)
}
life.texture = SKTexture(imageNamed: "sliceLifeGone")
life.xScale = 1.3
life.yScale = 1.3
life.runAction(SKAction.scaleTo(1, duration: 0.1))
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
var bombCount = 0
for node in activeEnemies {
if node.name == "bombContainer" {
bombCount += 1
break
}
}
if bombCount == 0 {
/* No bombs; stop the fuse sound. */
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
/* Remove enemies that have fallen off the screen. */
if activeEnemies.count > 0 {
for node in activeEnemies {
if node.position.y < -140 {
node.removeAllActions()
if node.name == "enemy" {
node.name = ""
subtractLife()
node.removeFromParent()
if let index = activeEnemies.indexOf(node) {
activeEnemies.removeAtIndex(index)
}
} else if node.name == "bombContainer" {
node.name = ""
node.removeFromParent()
if let index = activeEnemies.indexOf(node) {
activeEnemies.removeAtIndex(index)
}
}
}
}
} else {
/* Only run tossEnemies() if tossEnemies() is not currently undergoing exeuction. */
if !nextSequenceQueued {
RunAfterDelay(popupTime) { [unowned self] in
self.tossEnemies()
}
nextSequenceQueued = true
}
}
}
}
| gpl-3.0 | 0780829bd6f50482db7f0a0e7805a725 | 32.797373 | 116 | 0.537471 | 5.029034 | false | false | false | false |
vanshg/MacAssistant | Pods/SwiftGRPC/Sources/SwiftGRPC/Core/Channel.swift | 1 | 9144 | /*
* Copyright 2016, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if SWIFT_PACKAGE
import CgRPC
import Dispatch
#endif
import Foundation
/// A gRPC Channel
public class Channel {
/// Pointer to underlying C representation
private let underlyingChannel: UnsafeMutableRawPointer
/// Completion queue for channel call operations
private let completionQueue: CompletionQueue
/// Timeout for new calls
public var timeout: TimeInterval = 600.0
/// Default host to use for new calls
public var host: String
/// Connectivity state observers
private var connectivityObservers: [ConnectivityObserver] = []
/// Initializes a gRPC channel
///
/// - Parameter address: the address of the server to be called
/// - Parameter secure: if true, use TLS
/// - Parameter arguments: list of channel configuration options
public init(address: String, secure: Bool = true, arguments: [Argument] = []) {
gRPC.initialize()
host = address
let argumentWrappers = arguments.map { $0.toCArg() }
var argumentValues = argumentWrappers.map { $0.wrapped }
if secure {
underlyingChannel = cgrpc_channel_create_secure(address, roots_pem(), nil, nil, &argumentValues, Int32(arguments.count))
} else {
underlyingChannel = cgrpc_channel_create(address, &argumentValues, Int32(arguments.count))
}
completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
completionQueue.run() // start a loop that watches the channel's completion queue
}
/// Initializes a gRPC channel
///
/// - Parameter address: the address of the server to be called
/// - Parameter arguments: list of channel configuration options
public init(googleAddress: String, arguments: [Argument] = []) {
gRPC.initialize()
host = googleAddress
let argumentWrappers = arguments.map { $0.toCArg() }
var argumentValues = argumentWrappers.map { $0.wrapped }
underlyingChannel = cgrpc_channel_create_google(googleAddress, &argumentValues, Int32(arguments.count))
completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
completionQueue.run() // start a loop that watches the channel's completion queue
}
/// Initializes a gRPC channel
///
/// - Parameter address: the address of the server to be called
/// - Parameter certificates: a PEM representation of certificates to use
/// - Parameter clientCertificates: a PEM representation of the client certificates to use
/// - Parameter clientKey: a PEM representation of the client key to use
/// - Parameter arguments: list of channel configuration options
public init(address: String, certificates: String, clientCertificates: String? = nil, clientKey: String? = nil, arguments: [Argument] = []) {
gRPC.initialize()
host = address
let argumentWrappers = arguments.map { $0.toCArg() }
var argumentValues = argumentWrappers.map { $0.wrapped }
underlyingChannel = cgrpc_channel_create_secure(address, certificates, clientCertificates, clientKey, &argumentValues, Int32(arguments.count))
completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
completionQueue.run() // start a loop that watches the channel's completion queue
}
deinit {
connectivityObservers.forEach { $0.shutdown() }
cgrpc_channel_destroy(underlyingChannel)
completionQueue.shutdown()
}
/// Constructs a Call object to make a gRPC API call
///
/// - Parameter method: the gRPC method name for the call
/// - Parameter host: the gRPC host name for the call. If unspecified, defaults to the Client host
/// - Parameter timeout: a timeout value in seconds
/// - Returns: a Call object that can be used to perform the request
public func makeCall(_ method: String, host: String = "", timeout: TimeInterval? = nil) -> Call {
let host = (host == "") ? self.host : host
let timeout = timeout ?? self.timeout
let underlyingCall = cgrpc_channel_create_call(underlyingChannel, method, host, timeout)!
return Call(underlyingCall: underlyingCall, owned: true, completionQueue: completionQueue)
}
/// Check the current connectivity state
///
/// - Parameter tryToConnect: boolean value to indicate if should try to connect if channel's connectivity state is idle
/// - Returns: a ConnectivityState value representing the current connectivity state of the channel
public func connectivityState(tryToConnect: Bool = false) -> ConnectivityState {
return ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(underlyingChannel, tryToConnect ? 1 : 0))
}
/// Subscribe to connectivity state changes
///
/// - Parameter callback: block executed every time a new connectivity state is detected
public func subscribe(callback: @escaping (ConnectivityState) -> Void) {
connectivityObservers.append(ConnectivityObserver(underlyingChannel: underlyingChannel, currentState: connectivityState(), callback: callback))
}
}
private extension Channel {
class ConnectivityObserver {
private let completionQueue: CompletionQueue
private let underlyingChannel: UnsafeMutableRawPointer
private let underlyingCompletionQueue: UnsafeMutableRawPointer
private let callback: (ConnectivityState) -> Void
private var lastState: ConnectivityState
init(underlyingChannel: UnsafeMutableRawPointer, currentState: ConnectivityState, callback: @escaping (ConnectivityState) -> ()) {
self.underlyingChannel = underlyingChannel
self.underlyingCompletionQueue = cgrpc_completion_queue_create_for_next()
self.completionQueue = CompletionQueue(underlyingCompletionQueue: self.underlyingCompletionQueue, name: "Connectivity State")
self.callback = callback
self.lastState = currentState
run()
}
deinit {
shutdown()
}
private func run() {
let spinloopThreadQueue = DispatchQueue(label: "SwiftGRPC.ConnectivityObserver.run.spinloopThread")
spinloopThreadQueue.async {
while true {
guard let underlyingState = self.lastState.underlyingState else { return }
let deadline: TimeInterval = 0.2
cgrpc_channel_watch_connectivity_state(self.underlyingChannel, self.underlyingCompletionQueue, underlyingState, deadline, nil)
let event = self.completionQueue.wait(timeout: deadline)
switch event.type {
case .complete:
let newState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 0))
if newState != self.lastState {
self.callback(newState)
}
self.lastState = newState
case .queueTimeout:
continue
case .queueShutdown:
return
default:
continue
}
}
}
}
func shutdown() {
completionQueue.shutdown()
}
}
}
extension Channel {
public enum ConnectivityState {
/// Channel has just been initialized
case initialized
/// Channel is idle
case idle
/// Channel is connecting
case connecting
/// Channel is ready for work
case ready
/// Channel has seen a failure but expects to recover
case transientFailure
/// Channel has seen a failure that it cannot recover from
case shutdown
/// Channel connectivity state is unknown
case unknown
fileprivate static func connectivityState(_ value: grpc_connectivity_state) -> ConnectivityState {
switch value {
case GRPC_CHANNEL_INIT:
return .initialized
case GRPC_CHANNEL_IDLE:
return .idle
case GRPC_CHANNEL_CONNECTING:
return .connecting
case GRPC_CHANNEL_READY:
return .ready
case GRPC_CHANNEL_TRANSIENT_FAILURE:
return .transientFailure
case GRPC_CHANNEL_SHUTDOWN:
return .shutdown
default:
return .unknown
}
}
fileprivate var underlyingState: grpc_connectivity_state? {
switch self {
case .initialized:
return GRPC_CHANNEL_INIT
case .idle:
return GRPC_CHANNEL_IDLE
case .connecting:
return GRPC_CHANNEL_CONNECTING
case .ready:
return GRPC_CHANNEL_READY
case .transientFailure:
return GRPC_CHANNEL_TRANSIENT_FAILURE
case .shutdown:
return GRPC_CHANNEL_SHUTDOWN
default:
return nil
}
}
}
}
| mit | 8398939167d57e265a596974795c8611 | 36.941909 | 147 | 0.707021 | 4.75507 | false | false | false | false |
cabarique/TheProposalGame | MyProposalGame/Entities/CoinEntity.swift | 1 | 1398 | //
// CoinEntity.swift
// MyProposalGame
//
// Created by Luis Cabarique on 9/29/16.
// Copyright © 2016 Luis Cabarique. All rights reserved.
//
import SpriteKit
import GameplayKit
class CoinEntity: SGEntity {
var spriteComponent: SpriteComponent!
var physicsComponent: PhysicsComponent!
init(position: CGPoint, size: CGSize, texture:SKTexture) {
super.init()
//Initialize components
spriteComponent = SpriteComponent(entity: self, texture: texture, size: size, position:position)
addComponent(spriteComponent)
physicsComponent = PhysicsComponent(entity: self, bodySize: CGSize(width: spriteComponent.node.size.width * 0.8, height: spriteComponent.node.size.height * 0.8), bodyShape: .square, rotation: false)
physicsComponent.setCategoryBitmask(ColliderType.Collectable.rawValue, dynamic: false)
physicsComponent.setPhysicsCollisions(ColliderType.None.rawValue)
physicsComponent.setPhysicsContacts(ColliderType.Player.rawValue)
addComponent(physicsComponent)
//Final setup of components
spriteComponent.node.physicsBody = physicsComponent.physicsBody
spriteComponent.node.name = "coinNode"
name = "coinEntity"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 5ea499fbb71700a486e113b23337cf9c | 33.073171 | 206 | 0.701503 | 4.40694 | false | false | false | false |
BoxJeon/funjcam-ios | Application/Application/ImageViewer/ImageViewerViewController.swift | 1 | 2668 | import Combine
import UIKit
import BoxKit
import Entity
protocol ImageViewerControllable {
var observableState: ObservableState<ImageViewerState> { get }
var observableEvent: ObservableEvent<ImageViewerEvent> { get }
func activate(with viewController: ImageViewerViewControllable)
func handleShareImage()
}
final class ImageViewerViewController: ViewController, ImageViewerViewControllable {
private weak var imageView: UIImageView?
private var controller: ImageViewerControllable
private var cancellables: Set<AnyCancellable>
init(controller: ImageViewerControllable) {
self.controller = controller
self.cancellables = Set<AnyCancellable>()
super.init(nibName: nil, bundle: nil)
self.controller.activate(with: self)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemBackground
self.setupNavigation()
self.setupImageViewer()
self.observeState()
self.observeEvent()
}
private func setupNavigation() {
let close = Resource.string("common:close")
let closeButton = UIBarButtonItem(title: close, style: .plain, target: self, action: #selector(closeButtonDidTap))
self.navigationItem.leftBarButtonItem = closeButton
let share = Resource.string("imageViewer:share")
let shareButton = UIBarButtonItem(title: share, style: .plain, target: self, action: #selector(shareButtonDidTap))
self.navigationItem.rightBarButtonItem = shareButton
}
private func setupImageViewer() {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
self.view.addSubview(imageView)
imageView.edgesToSuperview()
self.imageView = imageView
}
private func observeState() {
self.controller.observableState
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
self?.updateImageViewer(imageURL: state.searchImage.url)
}
.store(in: &(self.cancellables))
}
private func observeEvent() {
self.controller.observableEvent
.receive(on: DispatchQueue.main)
.sink { _ in
}
.store(in: &(self.cancellables))
}
private func updateImageViewer(imageURL: URL?) {
self.imageView?.setImage(url: imageURL) { (image) -> Void in
if let url = imageURL, image == nil {
Log.e("Image Download Failure: \(url)")
}
}
}
@objc private func closeButtonDidTap() {
self.dismiss(animated: true, completion: nil)
}
@objc private func shareButtonDidTap() {
self.controller.handleShareImage()
}
}
| mit | b1627ac807429db3eb975378cceaff7d | 28.318681 | 118 | 0.705772 | 4.607945 | false | false | false | false |
bordplate/sociabl | Sources/App/Models/Post.swift | 1 | 2038 | import Vapor
import Fluent
import Foundation
final class Post: Model {
var id: Node?
var content: String
var date: Date
var user: User?
var exists: Bool = false
init(content: String, date: Date, user: User?) {
self.content = content
self.date = date
self.user = user
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
content = try node.extract("content")
user = try node.extract("user_id") { (userId: Node) throws -> User? in
return try User.find(userId)
}
date = try node.extract("date") { (timestamp: Int) -> Date in
return Date(timeIntervalSince1970: TimeInterval(timestamp))
}
}
func makeNode(context: Context) throws -> Node {
if let context = context as? Dictionary<String, Bool> {
if context["public"] == true {
return try self.makePublicNode()
}
}
return try Node(node: [
"id": id,
"content": content,
"date": date.timeIntervalSince1970,
"user_id": user?.id
])
}
public func makePublicNode() throws -> Node {
return try Node(node: [
"id": id,
"content": content,
"date": "Nicely formatted date",
"user": try user?.makeEmbedNode()
])
}
}
extension Post {
public static func posts(for users: [Node]) throws -> [Post] {
return try Post.query().filter("user_id", .in, users).sort("date", .descending).all()
}
}
extension Post: Preparation {
static func prepare(_ database: Database) throws {
try database.create("posts") { post in
post.id()
post.string("content")
post.int("date")
post.parent(User.self, optional: false, unique: false)
}
}
static func revert(_ database: Database) throws {
try database.delete("posts")
}
}
| mit | b0e4206e9b64319f1ca39867d040d946 | 25.815789 | 93 | 0.537291 | 4.254697 | false | false | false | false |
michalciurus/KatanaRouter | Pods/Katana/Katana/Core/Animations/Animation.swift | 1 | 2327 | //
// Animation.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import Foundation
/**
The animation for a child of a `NodeDescription`.
The idea is that, for elements that are either created or destroyed during an animation,
we will compute initial or final state and then animate to/from there.
When an element is created during an animated update, we take the final state (that is, the state
you have returned in the `childrenDescription` method) and we apply the transformers
you have specified in `entryTransformers`.
The resulting props are used to render an intermediated state that will be animated to the final state.
When an element is destroyed during an animated update, something similar happens. The only difference is that
we take the initial state (that is, the state of the last render when the element was present) and we apply the
transformers you have specified in `leaveTransformers`
*/
public struct Animation {
/// The animation type to perform for the child
let type: AnimationType
/// The entry phase transformers
let entryTransformers: [AnimationPropsTransformer]
/// The leave entry phase transformers
let leaveTransformers: [AnimationPropsTransformer]
/// An empty animation
static let none = Animation(type: .none)
/**
Creates an animation with the given values
- parameter type: the type of animation to apply to the child
- parameter entryTransformers: the transformers to use in the entry phase
- parameter leaveTransformers: the transformers to use in the leave phase
- returns: an animation with the given parameters
*/
public init(type: AnimationType,
entryTransformers: [AnimationPropsTransformer],
leaveTransformers: [AnimationPropsTransformer]) {
self.type = type
self.entryTransformers = entryTransformers
self.leaveTransformers = leaveTransformers
}
/**
Creates an animation with the given values
- parameter type: the type of animation to apply to the child
- returns: an animation with the given animation type and no transformers
*/
public init(type: AnimationType) {
self.type = type
self.entryTransformers = []
self.leaveTransformers = []
}
}
| mit | 0be2180c77d0b927789b7a04ba46d308 | 33.716418 | 112 | 0.741617 | 4.786008 | false | false | false | false |
apple/swift | validation-test/compiler_crashers_fixed/00114-swift-constraints-solution-computesubstitutions.swift | 65 | 768 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol l : p {
}
protocol m {
j f = p
}
f m : m {
j f = o
}
func i<o : o, m : m n m.f == o> (l: m) {
}
k: m
}
func p<m>() -> [l<m>] {
return []
}
f
m)
func f<o>() -> (o, o -> o) -> o {
m o m.i = {
}
{
o) {
p }
}
protocol f {
class func i()
}
class m: f{ class func i {}
protocol p {
class func l()
}
class o: p {
class func l() { }
| apache-2.0 | b84f447a3d9a04e572e8aa1883d5bea3 | 17.731707 | 79 | 0.585938 | 2.844444 | false | false | false | false |
takehaya/ArcherySocket | ach_1/OldPlayDataIndexViewController.swift | 1 | 8479 | //
// OldPlayDataIndexViewController.swift
// ach_1
//
// Created by 早坂彪流 on 2015/07/18.
// Copyright © 2015年 早坂彪流. All rights reserved.
//
import UIKit
class OldPlayDataIndexViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
private var indicator:MBProgressHUD! = nil
@IBOutlet weak var tableview: UITableView!
var OldScoreCardIndex = Array<OldScoreCardIndexData>()
struct OldScoreCardIndexData {
var arrows:Int! //射数
var sc_id:Int! // 得点表ID
var matchName:String! // 得点表が作成された試合名
var created:String! // 得点表が作成された日時
var sum:Int! // 得点合計
var perEnd:Int!
}
var selectedCell:Int!
override func viewDidLoad() {
super.viewDidLoad()
HTTPres()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// --tabelViewDatasouce
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
print("cell")
let cell: OldPlayDataIndexTableViewCell = self.tableview.dequeueReusableCellWithIdentifier("OldPlayDataCell",forIndexPath: indexPath) as! OldPlayDataIndexTableViewCell
cell.playname_label.text = OldScoreCardIndex[indexPath.row].matchName
cell.playcellCreate_when_time_label.text = OldScoreCardIndex[indexPath.row].created
cell.sum_Label.text = String(OldScoreCardIndex[indexPath.row].sum)
print(indexPath.row)
// baTableView.reloadSections(NSIndexSet(index: indexPath.row), withRowAnimation: UITableViewRowAnimation.Automatic)
//buttonの関連ずけ
cell.getdetails_button.tag = indexPath.row
cell.getdetails_button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
cell.getdetails_button.enabled = false
// cell.getdetails_button.addTarget(self, action: "getdetails_button_event:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("count")
return OldScoreCardIndex.count//arr_of_extractMatchIndex.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let data = OldScoreCardIndex[indexPath.row]
//アラートのインスタンスを生成
let alert = UIAlertController(title: "ルーム内容", message: "試合開始日:\(data.created)\n試合名:\(data.matchName)\n射数:\(data.arrows)\n得点表ID:\(data.sc_id)\n射数:\(data.arrows)\nセット数:\(data.perEnd)\n得点合計:\(data.sum)", preferredStyle: UIAlertControllerStyle.Alert)
//Actionadd
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {action in
print(action.title)
self.performSegueWithIdentifier("OldPlayDataIndex_to_cellpoint_is_see", sender: self)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler:{ action in print(action.title)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}))
selectedCell = indexPath.row
// アラートを表示
self.presentViewController(alert,
animated: true,
completion: {
print("Alert displayed")
})
}
//buttonevents
func getdetails_button_event(sender:UIButton){
}
func HTTPres(){
if OldScoreCardIndex.count != 0{
OldScoreCardIndex.removeAll()
}
// アニメーションを開始する.
self.indicator = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
self.indicator.dimBackground = true
self.indicator.labelText = "Loading..."
self.indicator.labelColor = UIColor.whiteColor()
//スレッドの設定((UIKitのための
// let q_global: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
let q_main: dispatch_queue_t = dispatch_get_main_queue();
// dispatch_async(q_main, {
// self.performSegueWithIdentifier("login_to_mypage", sender: self)
// })
//Request
let URLStr = "/app/personal/record/"
let loginRequest = NSMutableURLRequest(URL: NSURL(string:Utility_inputs_limit().URLdataSet+URLStr)!)
// set the method(HTTP-GET)
loginRequest.HTTPMethod = "GET"
//GET 付属情報
//set requestbody on data(JSON)
loginRequest.allHTTPHeaderFields = ["cookie":"sessionID="+Utility_inputs_limit().keych_access]
// use NSURLSession
let task = NSURLSession.sharedSession().dataTaskWithRequest(loginRequest, completionHandler: { data, response, error in
if (error == nil) {
//convert json data to dictionary
do{
let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(dict);//かくにんよう
if dict["status"] as? Int != 0{
let OldScoreCardIndexData:NSArray = dict["record"] as! NSArray
for var i=0; i < OldScoreCardIndexData.count;i++ {
let dicrecorddata:NSDictionary = (OldScoreCardIndexData[i] as? NSDictionary)!
let _sc_id = dicrecorddata["sc_id"] as? Int
let _matchName = dicrecorddata["matchName"] as? String
let _created = dicrecorddata["created"] as? String
let _sum = dicrecorddata["sum"] as? Int
let _perEnd = dicrecorddata["perEnd"] as? Int
let _arrows = dicrecorddata["arrows"] as? Int
self.OldScoreCardIndex.append(OldPlayDataIndexViewController.OldScoreCardIndexData(arrows: _arrows, sc_id: _sc_id, matchName: _matchName, created: _created, sum: _sum, perEnd: _perEnd))
}
}
} catch{
}
dispatch_async(q_main, {
self.tableview.reloadData()
MBProgressHUD.hideHUDForView(self.view, animated: true)
})
} else {
print(error)
//login出来ない時の処理
let alert = UIAlertController(title: "エラー", message: "サーバーに到達できません。管理者に連絡または時間をおいて再度アクセスしてください", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:{ action in print(action.title)}))
// アラートを表示
self.presentViewController(alert,
animated: true,
completion: {
print("Alert displayed")
MBProgressHUD.hideHUDForView(self.view, animated: true)
})
}
})
task.resume()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "OldPlayDataIndex_to_cellpoint_is_see") {
let nextViewController: cellpointViewControllerSeen = segue.destinationViewController as! cellpointViewControllerSeen
nextViewController.set_sc_id = OldScoreCardIndex[selectedCell].sc_id
}
}
@IBAction func returnOldPlayDataIndex_to_cellpointviewsee(segue:UIStoryboardSegue){
HTTPres()
self.setNeedsStatusBarAppearanceUpdate()
}
}
class OldPlayDataIndexTableViewCell: UITableViewCell {
@IBOutlet weak var playname_label: UILabel!
@IBOutlet weak var playcellCreate_when_time_label: UILabel!
@IBOutlet weak var sum_Label: UILabel!
@IBOutlet weak var getdetails_button: UIButton!
} | mit | 853a974b95493b736237be5029289c5d | 42.352941 | 254 | 0.612633 | 4.653272 | false | false | false | false |
kareman/FileSmith | Sources/FileSmith/File.swift | 1 | 7871 | //
// File.swift
// FileSmith
//
// Created by Kåre Morstøl on 03/12/2016.
//
import Foundation
import SwiftShell
public protocol File: FileSystemItem {
/// The path to the file
var path: FilePath { get }
/// The encoding for the text, if any, in the file.
var encoding: String.Encoding { get set }
/// The type of file or file-like item this is.
var type: FileType { get }
/// Opens the file at ‘stringpath’.
init(open stringpath: String) throws
/// Opens the file at ‘path’.
init(open path: FilePath) throws
}
extension File {
/// Opens the file at ‘stringpath’.
///
/// - Parameter stringpath: the path to the file.
/// - Throws: FileSystemError.notFound, .isDirectory, .invalidAccess.
public init(open stringpath: String) throws {
try self.init(open: FilePath(stringpath))
}
fileprivate static func errorForFile(at path: FilePath, writing: Bool) throws {
guard let type = FileType(path) else {
throw FileSystemError.notFound(path: path)
}
if type == .directory {
throw FileSystemError.isDirectory(path: DirectoryPath(path))
}
throw FileSystemError.invalidAccess(path: path, writing: writing)
}
}
/// A class for reading text from a file.
public final class ReadableFile: File, ReadableStream {
/// The path to the file
public let path: FilePath
/// The encoding for the text in the file.
public var encoding: String.Encoding = .utf8
/// The type of file or file-like item this is.
public let type: FileType
public let filehandle: FileHandle
private init(path: FilePath, filehandle: FileHandle) {
self.filehandle = filehandle
self.path = path
self.type = FileType(fileDescriptor: filehandle.fileDescriptor)
}
/// Opens the file at ‘path’ for reading.
///
/// - Parameter path: the path to the file.
/// - Throws: FileSystemError.notFound, .isDirectory, .invalidAccess.
public convenience init(open path: FilePath) throws {
guard let filehandle = FileHandle(forReadingAtPath: path.absoluteString) else {
try ReadableFile.errorForFile(at: path, writing: false)
fatalError("Should have thrown error when opening \(path.absoluteString)")
}
self.init(path: path, filehandle: filehandle)
}
/// Creates a new ReadableFile which reads from the provided file handle.
/// The path is "/dev/fd/" + the file handle's filedescriptor.
public convenience init(_ filehandle: FileHandle) {
self.init(path: FilePath("/dev/fd/\(filehandle.fileDescriptor)"), filehandle: filehandle)
}
/// A ReadableStream which reads from standard input.
static public var stdin: ReadableStream = {
ReadableFile(path: "/dev/stdin", filehandle: FileHandle.standardInput)
}()
}
extension FilePath {
/// Opens the file at ‘path’ for reading.
///
/// - Returns: A ReadableFile ready to read from the file.
/// - Throws: FileSystemError.notFound, .isDirectory, .invalidAccess.
public func open() throws -> ReadableFile {
return try ReadableFile(open: self)
}
}
/// A class for writing text to a file.
public final class WritableFile: File, WritableStream, MutableFileSystemItem {
/// The path to the file
public internal(set) var path: FilePath
/// The encoding for the text in the file.
public var encoding: String.Encoding = .utf8
/// The type of file or file-like item this is.
public let type: FileType
public let filehandle: FileHandle
private init(path: FilePath, filehandle: FileHandle) {
self.filehandle = filehandle
self.path = path
self.type = FileType(fileDescriptor: filehandle.fileDescriptor)
if self.type == .regularFile { _ = self.filehandle.seekToEndOfFile() }
}
/// Opens the file at ‘path’ for writing.
///
/// - Parameter path: the path to the file.
/// - Throws: FileSystemError.notFound, .isDirectory, .invalidAccess.
public convenience init(open path: FilePath) throws {
try path.verifyIsInSandbox()
guard let filehandle = FileHandle(forWritingAtPath: path.absoluteString) else {
try WritableFile.errorForFile(at: path, writing: true)
fatalError("Should have thrown error when opening \(path.absoluteString)")
}
self.init(path: path, filehandle: filehandle)
}
/// Creates a new WritableFile which writes to the provided file handle.
/// The path is "/dev/fd/" + the file handle's filedescriptor.
public convenience init(_ filehandle: FileHandle) {
self.init(path: FilePath("/dev/fd/\(filehandle.fileDescriptor)"), filehandle: filehandle)
}
fileprivate static func createFile(path: FilePath, ifExists: AlreadyExistsOptions) throws {
if let type = FileType(path) {
guard type != .directory else {
throw FileSystemError.isDirectory(path: DirectoryPath(path))
}
switch ifExists {
case .throwError: throw FileSystemError.alreadyExists(path: path)
case .open: return
case .replace: break
}
} else {
try path.verifyIsInSandbox()
try path.parent().create(ifExists: .open)
}
try path.verifyIsInSandbox()
guard FileManager().createFile(atPath: path.absoluteString, contents: Data(), attributes: nil) else {
throw FileSystemError.couldNotCreate(path: path)
}
}
/// Creates a new file at 'path' for writing.
///
/// - Parameters:
/// - path: The path where the new file should be created.
/// - ifExists: What to do if it already exists: open, throw error or replace.
/// - Throws: FileSystemError.isDirectory, .couldNotCreate, .alreadyExists, .outsideSandbox.
public convenience init(create path: FilePath, ifExists: AlreadyExistsOptions) throws {
try WritableFile.createFile(path: path, ifExists: ifExists)
try self.init(open: path)
}
/// Creates a new file at 'stringpath' for writing.
///
/// - Parameters:
/// - stringpath: The path where the new file should be created.
/// - ifExists: What to do if it already exists: open, throw error or replace.
/// - Throws: FileSystemError.isDirectory, .couldNotCreate, .alreadyExists, .outsideSandbox.
public convenience init(create stringpath: String, ifExists: AlreadyExistsOptions) throws {
try self.init(create: FilePath(stringpath), ifExists: ifExists)
}
/// Deletes this file. For ever.
public func delete() throws {
try FileManager().removeItem(atPath: path.absoluteString)
}
/// Appends the string to the file.
/// Nothing is overwritten, just added to the end of the file.
public func write(_ string: String) {
filehandle.write(string, encoding: encoding)
}
/// Closes the file. No more writing.
public func close() {
filehandle.closeFile()
}
/// Replaces the entire contents of the file with the string.
/// - warning: The current contents of the file will be lost.
/// - warning: Will crash if this is not a regular file.
public func overwrite(_ string: String) {
filehandle.seek(toFileOffset: 0)
filehandle.write(string, encoding: encoding)
filehandle.truncateFile(atOffset: filehandle.offsetInFile)
filehandle.synchronizeFile()
}
/// A WritableStream which writes to standard output.
static public var stdout: WritableStream = StdoutStream.default
/// A WritableStream which writes to standard error.
static public var stderror: WritableStream = {
WritableFile(path: "/dev/stderr", filehandle: FileHandle.standardError)
}()
}
extension FilePath {
/// Opens the file at this path for writing.
/// - Returns: A WritableFile for writing to the new file.
/// - Throws: FileSystemError.notFound, .isDirectory, .invalidAccess.
public func edit() throws -> WritableFile {
return try WritableFile(open: self)
}
/// Creates a new file at this path for writing.
/// - Parameters:
/// - ifExists: What to do if it already exists: open, throw error or replace.
/// - Throws: FileSystemError.isDirectory, .couldNotCreate, .alreadyExists, .outsideSandbox.
@discardableResult
public func create(ifExists: AlreadyExistsOptions) throws -> WritableFile {
return try WritableFile(create: self, ifExists: ifExists)
}
}
| mit | 8456d9cff926bbcc19cacd5cb7f9dcce | 32.101266 | 103 | 0.722881 | 3.730385 | false | false | false | false |
ReactiveKit/ReactiveUIKit | Sources/UICollectionView.swift | 1 | 4727 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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 ReactiveKit
import UIKit
private func applyRowUnitChangeSet<C: CollectionChangesetType where C.Collection.Index == Int>(changeSet: C, collectionView: UICollectionView, sectionIndex: Int) {
if changeSet.inserts.count > 0 {
let indexPaths = changeSet.inserts.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
collectionView.insertItemsAtIndexPaths(indexPaths)
}
if changeSet.updates.count > 0 {
let indexPaths = changeSet.updates.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
collectionView.reloadItemsAtIndexPaths(indexPaths)
}
if changeSet.deletes.count > 0 {
let indexPaths = changeSet.deletes.map { NSIndexPath(forItem: $0, inSection: sectionIndex) }
collectionView.deleteItemsAtIndexPaths(indexPaths)
}
}
extension StreamType where Element: ArrayConvertible {
public func bindTo(collectionView: UICollectionView, animated: Bool = true, createCell: (NSIndexPath, [Element.Element], UICollectionView) -> UICollectionViewCell) -> Disposable {
return map { CollectionChangeset.initial($0.toArray()) }.bindTo(collectionView, animated: animated, createCell: createCell)
}
}
extension StreamType where Element: CollectionChangesetType, Element.Collection.Index == Int, Event.Element == Element {
public func bindTo(collectionView: UICollectionView, animated: Bool = true, createCell: (NSIndexPath, Element.Collection, UICollectionView) -> UICollectionViewCell) -> Disposable {
typealias Collection = Element.Collection
let dataSource = collectionView.rDataSource
let numberOfItems = Property(0)
let collection = Property<Collection!>(nil)
dataSource.feed(
collection,
to: #selector(UICollectionViewDataSource.collectionView(_:cellForItemAtIndexPath:)),
map: { (value: Collection!, collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell in
return createCell(indexPath, value, collectionView)
})
dataSource.feed(
numberOfItems,
to: #selector(UICollectionViewDataSource.collectionView(_:numberOfItemsInSection:)),
map: { (value: Int, _: UICollectionView, _: Int) -> Int in value }
)
dataSource.feed(
Property(1),
to: #selector(UICollectionViewDataSource.numberOfSectionsInCollectionView(_:)),
map: { (value: Int, _: UICollectionView) -> Int in value }
)
collectionView.reloadData()
let serialDisposable = SerialDisposable(otherDisposable: nil)
serialDisposable.otherDisposable = observeNext { [weak collectionView] event in
ImmediateOnMainExecutionContext {
guard let collectionView = collectionView else { serialDisposable.dispose(); return }
let justReload = collection.value == nil
collection.value = event.collection
numberOfItems.value = event.collection.count
if justReload || !animated || event.inserts.count + event.deletes.count + event.updates.count == 0 {
collectionView.reloadData()
} else {
collectionView.performBatchUpdates({
applyRowUnitChangeSet(event, collectionView: collectionView, sectionIndex: 0)
}, completion: nil)
}
}
}
return serialDisposable
}
}
extension UICollectionView {
public var rDelegate: ProtocolProxy {
return protocolProxyFor(UICollectionViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var rDataSource: ProtocolProxy {
return protocolProxyFor(UICollectionViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
| mit | 276b07c1996ac74e998d1f386f578c4b | 41.205357 | 182 | 0.73535 | 4.981033 | false | false | false | false |
migueloruiz/la-gas-app-swift | lasgasmx/UILoadingIndicator.swift | 1 | 1815 | //
// UILoadingIndicator.swift
//
// Created by Desarrollo on 4/28/17.
// Copyright © 2017 migueloruiz. All rights reserved.
//
import UIKit
import Foundation
public class UILoadingIndicator {
private var overlayView = UIView()
private var activityIndicator = UIActivityIndicatorView()
private var visible = false {
didSet{
UIApplication.shared.isNetworkActivityIndicatorVisible = visible
}
}
class var shared: UILoadingIndicator {
struct Static {
static let instance: UILoadingIndicator = UILoadingIndicator()
}
return Static.instance
}
public func show() {
guard !visible else { return }
guard let window = UIApplication.shared.keyWindow else { return }
DispatchQueue.main.async {
self.overlayView = UIView(frame: UIScreen.main.bounds)
self.overlayView.clipsToBounds = true
self.overlayView.center = window.center
self.overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
self.overlayView.addSubview(self.activityIndicator)
self.activityIndicator.fillSuperview()
self.activityIndicator.startAnimating()
window.addSubview(self.overlayView)
self.visible = true
}
}
public func hide() {
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.activityIndicator.removeFromSuperview()
self.overlayView.removeFromSuperview()
self.visible = false
}
}
public func isVisible() -> Bool {
return visible
}
}
| mit | 49bea2bd1ad4c5d270ba8e2ae85ffaf9 | 30.824561 | 125 | 0.642778 | 5.382789 | false | false | false | false |
kgn/KGNAutoLayout | Tests/KGNAutoLayoutTestsPinSuperview.swift | 1 | 8057 | //
// KGNAutoLayoutTests.swift
// KGNAutoLayoutTests
//
// Created by David Keegan on 10/12/15.
// Copyright © 2015 David Keegan. All rights reserved.
//
import XCTest
@testable import KGNAutoLayout
class KGNAutoLayoutTestsPinSuperview: KGNAutoLayoutTests {
func testPinToEdgesOfSuperview() {
let priority = UILayoutPriority.defaultLow
let childViewFrame = self.compareViewFrame {
let constraints = $0.pinToEdgesOfSuperview(priority: priority)
XCTAssertEqual(priority, constraints.top?.priority)
XCTAssertEqual(priority, constraints.right?.priority)
XCTAssertEqual(priority, constraints.bottom?.priority)
XCTAssertEqual(priority, constraints.left?.priority)
}
XCTAssertEqual(childViewFrame, self.parentViewFrame)
}
func testPinToEdgesOfSuperviewOffset() {
let offset: CGFloat = 10
let priority = UILayoutPriority.defaultLow
let childViewFrame = self.compareViewFrame {
let constraints = $0.pinToEdgesOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraints.top?.priority)
XCTAssertEqual(priority, constraints.right?.priority)
XCTAssertEqual(priority, constraints.bottom?.priority)
XCTAssertEqual(priority, constraints.left?.priority)
}
XCTAssertEqual(childViewFrame, self.parentViewFrame.insetBy(dx: offset, dy: offset))
}
func testPinToTopEdgeOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToTopEdgeOfSuperview(priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: 0, width: size, height: size))
}
func testPinToTopEdgeOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToTopEdgeOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: offset, width: size, height: size))
}
func testPinToRightEdgeOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToRightEdgeOfSuperview(priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
let right = self.parentViewFrame.maxX-size
XCTAssertEqual(childViewFrame, CGRect(x: right, y: 0, width: size, height: size))
}
func testPinToRightEdgeOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToRightEdgeOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
let right = self.parentViewFrame.maxX-size-offset
XCTAssertEqual(childViewFrame, CGRect(x: right, y: 0, width: size, height: size))
}
func testPinToBottomEdgeOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.required
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToBottomEdgeOfSuperview()
XCTAssertEqual(priority, constraint?.priority)
}
let bottom = self.parentViewFrame.maxY-size
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: bottom, width: size, height: size))
}
func testPinToBottomEdgeOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.required
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToBottomEdgeOfSuperview(withOffset: offset)
XCTAssertEqual(priority, constraint?.priority)
}
let bottom = self.parentViewFrame.maxY-size-offset
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: bottom, width: size, height: size))
}
func testPinToLeftEdgeOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.required
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToLeftEdgeOfSuperview(priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: 0, width: size, height: size))
}
func testPinToLeftEdgeOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.defaultLow
let childViewFrame = self.compareViewFrame {
$0.width = size
$0.height = size
let constraint = $0.pinToLeftEdgeOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraint?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: offset, y: 0, width: size, height: size))
}
func testPinToSideEdgesOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.height = size
let constraints = $0.pinToSideEdgesOfSuperview(priority: priority)
XCTAssertEqual(priority, constraints.left?.priority)
XCTAssertEqual(priority, constraints.right?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: 0, width: self.parentViewFrame.width, height: size))
}
func testPinToSideEdgesOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.defaultLow
let childViewFrame = self.compareViewFrame {
$0.height = size
let constraints = $0.pinToSideEdgesOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraints.left?.priority)
XCTAssertEqual(priority, constraints.right?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: offset, y: 0, width: self.parentViewFrame.width-offset*2, height: size))
}
func testPinToTopAndBottomEdgesOfSuperview() {
let size: CGFloat = 10
let priority = UILayoutPriority.required
let childViewFrame = self.compareViewFrame {
$0.width = size
let constraints = $0.pinToTopAndBottomEdgesOfSuperview(priority: priority)
XCTAssertEqual(priority, constraints.top?.priority)
XCTAssertEqual(priority, constraints.bottom?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: 0, width: size, height: self.parentViewFrame.height))
}
func testPinToTopAndBottomEdgesOfSuperviewOffset() {
let size: CGFloat = 10
let offset: CGFloat = 20
let priority = UILayoutPriority.defaultHigh
let childViewFrame = self.compareViewFrame {
$0.width = size
let constraints = $0.pinToTopAndBottomEdgesOfSuperview(withOffset: offset, priority: priority)
XCTAssertEqual(priority, constraints.top?.priority)
XCTAssertEqual(priority, constraints.bottom?.priority)
}
XCTAssertEqual(childViewFrame, CGRect(x: 0, y: offset, width: size, height: self.parentViewFrame.height-offset*2))
}
}
| mit | 0bacba1ee4bdf054f3959e09c493b647 | 40.740933 | 122 | 0.654047 | 4.906212 | false | true | false | false |
TTVS/NightOut | Clubber/SignUpViewController.swift | 1 | 12796 | //
// SignUpViewController.swift
// Clubber
//
// Created by Terra on 6/1/15.
// Copyright (c) 2015 Dino Media Asia. All rights reserved.
//
import UIKit
// Check for valid email address
extension String {
func isValidEmail(testStr:String) -> Bool {
// println("validate calendar: \(testStr)")
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(testStr)
}
}
class SignUpViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate {
var activeField : UITextField?
var colorX : UIColor = UIColor(red: (10/255.0), green: (237/255.0), blue: (213/255.0), alpha: 1.0) //custom Cyan Color
// swipe to go back
let swipeBack = UISwipeGestureRecognizer()
@IBOutlet var emailTextField: UITextField!
@IBOutlet var firstNameTextField: UITextField!
@IBOutlet var lastNameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var passwordConfirmationTextField: UITextField!
@IBOutlet var contactNumberTextField: UITextField!
@IBOutlet var signUpImageView: UIImageView!
@IBOutlet var scrollView: UIScrollView!
@IBAction func back(sender: AnyObject) {
if((self.presentingViewController) != nil){
self.dismissViewControllerAnimated(true, completion: nil)
NSLog("back")
}
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
self.setNeedsStatusBarAppearanceUpdate()
}
// Password Reveal Button
@IBOutlet var passwordRevealBtn: UIButton!
@IBAction func passwordRevealBtnTapped(sender: AnyObject) {
self.passwordRevealBtn.selected = !self.passwordRevealBtn.selected
if self.passwordRevealBtn.selected {
self.passwordTextField.secureTextEntry = false
}
else {
self.passwordTextField.secureTextEntry = true
}
}
@IBOutlet var passwordConfirmationRevealBtn: UIButton!
@IBAction func passwordConfirmationRevealBtnTapped(sender: AnyObject) {
self.passwordRevealBtn.selected = !self.passwordRevealBtn.selected
if self.passwordRevealBtn.selected {
self.passwordConfirmationTextField.secureTextEntry = false
}
else {
self.passwordConfirmationTextField.secureTextEntry = true
}
}
// UIAlertView Alert
func displayAlertMessage(alertTitle:String, alertDescription:String) -> Void {
let errorAlert = UIAlertView(title:alertTitle, message:alertDescription, delegate:nil, cancelButtonTitle:"OK")
errorAlert.show()
}
@IBAction func signUpButtonPressed(sender: UIButton) {
// validate presence of all required parameters
if self.emailTextField.text!.isValidEmail(self.emailTextField.text!) == false {
self.displayAlertMessage("Invalid Email Address", alertDescription:
"Please input valid email address. Email is Case Sensitive.")
} else if self.firstNameTextField.text!.characters.count == 0 {
self.displayAlertMessage("Invalid First Name", alertDescription:
"Please input a First Name.")
} else if self.lastNameTextField.text!.characters.count == 0 {
self.displayAlertMessage("Invalid Last Name", alertDescription:
"Please input a Last Name.")
} else if self.passwordTextField.text!.characters.count < 8 {
self.displayAlertMessage("Invalid Password", alertDescription:
"Passwords must contain 8 values or more.")
} else if self.passwordConfirmationTextField.text! != self.passwordTextField.text! {
self.displayAlertMessage("Invalid Password Confirmation", alertDescription:
"Please make sure password confirmation field is identical to password field.")
} else {
makeSignUpRequest()
}
}
func makeSignUpRequest() {
let manager = AFHTTPRequestOperationManager()
let url = "https://nightout.herokuapp.com/api/v1/users?"
let signUpParams = [
"user[email]" : "\(emailTextField.text!)",
"user[password]" : "\(passwordTextField.text!)",
"user[password_confirmation]" : "\(passwordConfirmationTextField.text!)",
"user[first_name]" : "\(firstNameTextField.text!)",
"user[last_name]" : "\(lastNameTextField.text!)",
"user[type]" : "Guest"
]
// print("\(emailTextField.text)")
// print("\(passwordTextField.text)")
// print("\(passwordConfirmationTextField.text)")
// print("\(firstNameTextField.text)")
// print("\(lastNameTextField.text)")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(url,
parameters: signUpParams,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
// print("Yes this was a success.. \(responseObject.description)")
self.displayAlertMessage("Success", alertDescription: "Account has been created")
let signInViewController: UIViewController = self.storyboard!.instantiateViewControllerWithIdentifier("signInVC")
self.presentViewController(signInViewController, animated: true, completion: nil)
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
self.setNeedsStatusBarAppearanceUpdate()
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
print("We got an error here.. \(error.localizedDescription)")
})
}
override func viewDidLoad() {
super.viewDidLoad()
// swipe to go back
swipeBack.direction = UISwipeGestureRecognizerDirection.Right
swipeBack.addTarget(self, action: "swipeBack:")
self.view.addGestureRecognizer(swipeBack)
//keyboard functions
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
notificationCenter.addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
self.emailTextField.delegate = self
self.passwordTextField.delegate = self
self.passwordConfirmationTextField.delegate = self
self.contactNumberTextField.delegate = self
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
self.view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.firstNameTextField.resignFirstResponder()
self.lastNameTextField.resignFirstResponder()
self.emailTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.passwordConfirmationTextField.resignFirstResponder()
self.contactNumberTextField.resignFirstResponder()
return true
}
//MARK: - Add TextFieldInput Navigation Arrows above Keyboard
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
let keyboardToolBar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
let keyboardBarButtonItems = [
UIBarButtonItem(image: UIImage(named: "upButton"), style: UIBarButtonItemStyle.Plain, target: self, action: "previousTextField"),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
UIBarButtonItem(image: UIImage(named: "downButton"), style: UIBarButtonItemStyle.Plain, target: self, action: "nextTextField")
]
keyboardToolBar.setItems(keyboardBarButtonItems, animated: false)
keyboardToolBar.tintColor = colorX
keyboardToolBar.barStyle = UIBarStyle.Black
keyboardToolBar.sizeToFit()
textField.inputAccessoryView = keyboardToolBar
return true
}
func nextTextField() {
if emailTextField.isFirstResponder() == true {
emailTextField.resignFirstResponder()
firstNameTextField.becomeFirstResponder()
} else if firstNameTextField.isFirstResponder() == true {
firstNameTextField.resignFirstResponder()
lastNameTextField.becomeFirstResponder()
} else if lastNameTextField.isFirstResponder() == true {
lastNameTextField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
} else if passwordTextField.isFirstResponder() == true {
passwordTextField.resignFirstResponder()
passwordConfirmationTextField.becomeFirstResponder()
} else if passwordConfirmationTextField.isFirstResponder() == true {
}
}
func previousTextField() {
if emailTextField.isFirstResponder() == true {
} else if firstNameTextField.isFirstResponder() == true {
firstNameTextField.resignFirstResponder()
emailTextField.becomeFirstResponder()
} else if lastNameTextField.isFirstResponder() == true {
lastNameTextField.resignFirstResponder()
firstNameTextField.becomeFirstResponder()
} else if passwordTextField.isFirstResponder() == true {
passwordTextField.resignFirstResponder()
lastNameTextField.becomeFirstResponder()
} else if passwordConfirmationTextField.isFirstResponder() == true {
passwordConfirmationTextField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
}
}
//MARK: - Keyboard Functions
func keyboardWasShown (notification: NSNotification) {
let viewHeight = self.view.frame.size.height
let info : NSDictionary = notification.userInfo!
let keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size
let keyboardInset = keyboardSize.height - viewHeight/3
self.scrollView.setContentOffset(CGPointMake(0, keyboardInset), animated: true)
}
func keyboardWillBeHidden(notification: NSNotification) {
self.scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
}
func textFieldDidBeginEditing(textField: UITextField) {
activeField = textField
self.emailTextField.delegate = self
self.firstNameTextField.delegate = self
self.lastNameTextField.delegate = self
self.passwordTextField.delegate = self
self.passwordConfirmationTextField.delegate = self
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Fade)
}
func textFieldDidEndEditing(textField: UITextField) {
activeField = nil
}
//MARK:- Calls this function when the tap is recognized.
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//MARK: Swipe to go Back Gesture
func swipeBack(sender: UISwipeGestureRecognizer) {
if((self.presentingViewController) != nil){
self.dismissViewControllerAnimated(true, completion: nil)
NSLog("back")
}
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
self.setNeedsStatusBarAppearanceUpdate()
}
}
| apache-2.0 | 4cfade49aedcb1148ad983acb02f7ec6 | 39.112853 | 160 | 0.659425 | 5.837591 | false | false | false | false |
DianQK/Flix | Example/Example/CalendarEvent/Location/SelectLocationViewController.swift | 1 | 12840 | //
// SelectLocationViewController.swift
// Example
//
// Created by DianQK on 25/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
import CoreLocation
import MapKit
class Storage {
static var recentSelectedPlacemarks = BehaviorRelay(value: [CLPlacemark]())
}
class PlainTitleTableViewHeaderSectionProvider: UniqueCustomTableViewSectionProvider {
let textLabel = UILabel()
init(text: String) {
super.init(tableElementKindSection: .header)
self.sectionHeight = { _ in return 32 }
textLabel.font = UIFont.boldSystemFont(ofSize: 15)
textLabel.text = text
self.contentView.addSubview(textLabel)
textLabel.translatesAutoresizingMaskIntoConstraints = false
textLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 15).isActive = true
textLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
}
}
extension LocalSearchProvider {
static func createRecentSelectedPlacemarksProvider() -> LocalSearchProvider {
return LocalSearchProvider(result: Storage.recentSelectedPlacemarks.asObservable())
}
}
class SelectLocationViewController: UIViewController {
let searchBar = UISearchBar()
let tableView = UITableView(frame: .zero, style: .plain)
let disposeBag = DisposeBag()
let geocoder = CLGeocoder()
let cancelBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: nil, action: nil)
let didSelectLocation = PublishSubject<EventLocation>()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Location"
self.searchBar.placeholder = "Enter Location"
self.searchBar.tintColor = UIColor(named: "Bittersweet")
_ = self.searchBar.becomeFirstResponder()
self.view.backgroundColor = UIColor.white
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.tableView.sectionHeaderHeight = CGFloat.leastNonzeroMagnitude
self.tableView.sectionFooterHeight = CGFloat.leastNonzeroMagnitude
self.tableView.keyboardDismissMode = .onDrag
self.tableView.rowHeight = 44
self.tableView.backgroundColor = UIColor(named: "Background")
self.tableView.separatorColor = UIColor(named: "Background")
self.view.addSubview(searchBar)
searchBar.translatesAutoresizingMaskIntoConstraints = false
searchBar.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
searchBar.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
searchBar.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
searchBar.heightAnchor.constraint(equalToConstant: 55).isActive = true
self.view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: self.searchBar.bottomAnchor).isActive = true
tableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
let customLocalProvider = SingleUITableViewCellProvider()
customLocalProvider.separatorInset = UIEdgeInsets(top: 0, left: 56, bottom: 0, right: 0)
let customLocalLabel = UILabel()
customLocalProvider.contentView.addSubview(customLocalLabel)
customLocalLabel.translatesAutoresizingMaskIntoConstraints = false
customLocalLabel.leadingAnchor.constraint(equalTo: customLocalProvider.contentView.leadingAnchor, constant: 56).isActive = true
customLocalLabel.centerYAnchor.constraint(equalTo: customLocalProvider.contentView.centerYAnchor).isActive = true
let locationImageView = UIImageView(image: #imageLiteral(resourceName: "Icon Location Gray"))
customLocalProvider.contentView.addSubview(locationImageView)
locationImageView.translatesAutoresizingMaskIntoConstraints = false
locationImageView.leadingAnchor.constraint(equalTo: customLocalProvider.contentView.leadingAnchor, constant: 15).isActive = true
locationImageView.centerYAnchor.constraint(equalTo: customLocalProvider.contentView.centerYAnchor).isActive = true
searchBar.rx.text.orEmpty.bind(to: customLocalLabel.rx.text).disposed(by: disposeBag)
let currentLocationProvider = SingleUITableViewCellProvider()
currentLocationProvider.separatorInset = UIEdgeInsets(top: 0, left: 56, bottom: 0, right: 0)
let currentPlacemark = GeolocationService.instance.location.asObservable()
.flatMap { (location) -> Observable<CLPlacemark?> in
guard let location = location else { return Observable.just(nil) }
let geocoder = CLGeocoder() // TODO
return Observable.create({ (observer) -> Disposable in
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
observer.onNext(placemarks?.first)
observer.onCompleted()
})
return Disposables.create {
geocoder.cancelGeocode()
}
})
}
.share(replay: 1, scope: .forever)
let currentLocalLabel = UILabel()
currentLocalLabel.text = "Current Location"
currentLocationProvider.contentView.addSubview(currentLocalLabel)
currentLocalLabel.translatesAutoresizingMaskIntoConstraints = false
currentLocalLabel.leadingAnchor.constraint(equalTo: currentLocationProvider.contentView.leadingAnchor, constant: 56).isActive = true
currentLocalLabel.centerYAnchor.constraint(equalTo: currentLocationProvider.contentView.centerYAnchor).isActive = true
GeolocationService.instance.authorized.asObservable()
.map { !$0 }
.bind(to: currentLocationProvider.rx.isHidden).disposed(by: disposeBag)
// currentPlacemark.startWith(nil).map { $0 == nil }.bind(to: currentLocationProvider.isHidden).disposed(by: disposeBag)
currentPlacemark.map { $0?.name ?? "" }.map { "Current Location " + $0 }
.bind(to: currentLocalLabel.rx.text)
.disposed(by: disposeBag)
let currentlocationImageView = UIImageView(image: #imageLiteral(resourceName: "Icon Current Location"))
currentLocationProvider.contentView.addSubview(currentlocationImageView)
currentlocationImageView.translatesAutoresizingMaskIntoConstraints = false
currentlocationImageView.leadingAnchor.constraint(equalTo: currentLocationProvider.contentView.leadingAnchor, constant: 20).isActive = true
currentlocationImageView.centerYAnchor.constraint(equalTo: currentLocationProvider.contentView.centerYAnchor).isActive = true
searchBar.rx.text.orEmpty.map { $0.isEmpty }
.distinctUntilChanged()
.bind(to: customLocalProvider.rx.isHidden)
.disposed(by: disposeBag)
let customLocalSectionProvider = AnimatableTableViewSectionProvider(providers: [customLocalProvider, currentLocationProvider])
let recentSelectedPlacemarksProvider = LocalSearchProvider.createRecentSelectedPlacemarksProvider()
recentSelectedPlacemarksProvider.canDelete = true
recentSelectedPlacemarksProvider.event.modelDeleted
.subscribe(onNext: { (placemark) in
Storage.recentSelectedPlacemarks.accept(Storage.recentSelectedPlacemarks.value.filter({ $0.identity != placemark.identity }))
})
.disposed(by: disposeBag)
let recentSelectedPlacemarksSectionProvider = AnimatableTableViewSectionProvider(
providers: [recentSelectedPlacemarksProvider],
headerProvider: PlainTitleTableViewHeaderSectionProvider(text: "Recents")
)
Storage.recentSelectedPlacemarks.asObservable().map { $0.isEmpty }
.bind(to: recentSelectedPlacemarksSectionProvider.rx.isHidden)
.disposed(by: disposeBag)
let localSearchProvider = LocalSearchProvider(naturalLanguageQuery: searchBar.rx.text.orEmpty.asObservable())
let localSearchSectionProvider = AnimatableTableViewSectionProvider(
providers: [localSearchProvider],
headerProvider: PlainTitleTableViewHeaderSectionProvider(text: "Locations")
)
localSearchProvider.event.modelSelected
.subscribe(onNext: { [weak self] (placemark) in
_ = self?.navigationController?.popViewController(animated: true)
var recentSelectedPlacemarks = Storage.recentSelectedPlacemarks.value
if let index = recentSelectedPlacemarks.firstIndex(where: { $0.identity == placemark.identity }) {
recentSelectedPlacemarks.remove(at: index)
}
recentSelectedPlacemarks.append(placemark)
Storage.recentSelectedPlacemarks.accept(recentSelectedPlacemarks)
})
.disposed(by: disposeBag)
localSearchProvider.result.map { $0.isEmpty }
.distinctUntilChanged()
.bind(to: localSearchSectionProvider.rx.isHidden)
.disposed(by: disposeBag)
Observable<EventLocation>
.merge(
[
customLocalProvider.event.selectedEvent.withLatestFrom(searchBar.rx.text.orEmpty).map { EventLocation.custom($0) },
currentLocationProvider.event.selectedEvent.withLatestFrom(currentPlacemark.filter { $0 != nil }.map { EventLocation.placemark($0!) }),
recentSelectedPlacemarksProvider.event.modelSelected.map { EventLocation.placemark($0) },
localSearchProvider.event.modelSelected.asObservable().map { EventLocation.placemark($0) }
]
)
.bind(to: didSelectLocation)
.disposed(by: disposeBag)
self.tableView.flix.animatable
.build([
customLocalSectionProvider,
recentSelectedPlacemarksSectionProvider,
localSearchSectionProvider
])
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
_ = self.searchBar.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
_ = self.searchBar.resignFirstResponder()
}
}
func dismissViewController(_ viewController: UIViewController, animated: Bool) {
if viewController.isBeingDismissed || viewController.isBeingPresented {
DispatchQueue.main.async {
dismissViewController(viewController, animated: animated)
}
return
}
if viewController.presentingViewController != nil {
viewController.dismiss(animated: animated, completion: nil)
}
}
extension Reactive where Base: SelectLocationViewController {
var didCancel: ControlEvent<()> {
return self.base.cancelBarButtonItem.rx.tap
}
static func createWithParent(_ parent: UIViewController?, configure: @escaping (SelectLocationViewController) throws -> () = { x in }) -> Observable<SelectLocationViewController> {
return Observable.create { [weak parent] observer in
let selectLocation = SelectLocationViewController()
let dismissDisposable = selectLocation.rx
.didCancel
.subscribe(onNext: { [weak selectLocation] _ in
guard let selectLocation = selectLocation else {
return
}
dismissViewController(selectLocation, animated: true)
})
do {
try configure(selectLocation)
}
catch let error {
observer.on(.error(error))
return Disposables.create()
}
guard let parent = parent else {
observer.on(.completed)
return Disposables.create()
}
let nav = UINavigationController(rootViewController: selectLocation)
parent.present(nav, animated: true, completion: nil)
observer.on(.next(selectLocation))
return Disposables.create(dismissDisposable, Disposables.create {
dismissViewController(selectLocation, animated: true)
})
}
}
}
| mit | 3c11172c33bc15f797f5b8caf89b651d | 44.690391 | 184 | 0.689228 | 5.498501 | false | false | false | false |
oisdk/SwiftSequence | Tests/InterposeTests.swift | 1 | 3584 | import XCTest
import SwiftSequence
class InterposeTests: XCTestCase {
var allTests : [(String, () -> ())] {
return [
("testInterposeSingle", testInterposeSingle),
("testInterposeMultiple", testInterposeMultiple),
("testInterposeColSingle", testInterposeColSingle),
("testInterposeColMultiple", testInterposeColMultiple),
("testInterdigitate", testInterdigitate),
("testInterdigitateMultiple", testInterdigitateMultiple),
("testLazyInterposeSingle", testLazyInterposeSingle),
("testLazyInterposeMultiple", testLazyInterposeMultiple),
("testLazyInterposeColSingle", testLazyInterposeColSingle),
("testLazyInterposeColMultiple", testLazyInterposeColMultiple),
("testLazyInterdigitate", testLazyInterdigitate),
("testLazyInterdigitateMultiple", testLazyInterdigitateMultiple)
]
}
// MARK: Eager
func testInterposeSingle() {
let interposed = [1, 2, 3].interpose(10)
let expectation = [1, 10, 2, 10, 3]
XCTAssertEqual(interposed, expectation)
}
func testInterposeMultiple() {
let interposed = [1, 2, 3, 4, 5].interpose(10, n: 2)
let expectation = [1, 2, 10, 3, 4, 10, 5]
XCTAssertEqual(interposed, expectation)
}
func testInterposeColSingle() {
let interposed = [1, 2, 3].interpose([10, 20])
let expectation = [1, 10, 20, 2, 10, 20, 3]
XCTAssertEqual(interposed, expectation)
}
func testInterposeColMultiple() {
let interposed = [1, 2, 3, 4, 5].interpose([10, 20], n: 2)
let expectation = [1, 2, 10, 20, 3, 4, 10, 20, 5]
XCTAssertEqual(interposed, expectation)
}
func testInterdigitate() {
let interdigged = interdig([1, 2, 3], [10, 20, 30])
let expectation = [1, 10, 2, 20, 3, 30]
XCTAssertEqual(interdigged, expectation)
}
func testInterdigitateMultiple() {
let interdigged = interdig([1, 2, 3, 4, 5], [10, 20, 30, 40, 50, 60], s0Len: 2, s1Len: 3)
let expectation = [1, 2, 10, 20, 30, 3, 4, 40, 50, 60, 5]
XCTAssertEqual(interdigged, expectation)
}
// MARK: Lazy
func testLazyInterposeSingle() {
let interposed = [1, 2, 3].lazy.interpose(10)
let expectation = [1, 10, 2, 10, 3, 10].lazy
XCTAssertEqualSeq(interposed, expectation)
}
func testLazyInterposeMultiple() {
let interposed = [1, 2, 3, 4, 5].lazy.interpose(10, n: 2)
let expectation = [1, 2, 10, 3, 4, 10, 5].lazy
XCTAssertEqualSeq(interposed, expectation)
}
func testLazyInterposeColSingle() {
let interposed = [1, 2, 3].lazy.interpose([10, 20])
let expectation = [1, 10, 20, 2, 10, 20, 3, 10, 20]
XCTAssertEqualSeq(interposed, expectation)
}
func testLazyInterposeColMultiple() {
let interposed = [1, 2, 3, 4, 5].lazy.interpose([10, 20], n: 2)
let expectation = [1, 2, 10, 20, 3, 4, 10, 20, 5]
XCTAssertEqualSeq(interposed, expectation)
}
func testLazyInterdigitate() {
let interdigged = interdig([1, 2, 3].lazy, [10, 20, 30].lazy)
let expectation = [1, 10, 2, 20, 3, 30]
XCTAssertEqualSeq(interdigged, expectation)
}
func testLazyInterdigitateMultiple() {
let interdigged = interdig([1, 2, 3, 4, 5].lazy, [10, 20, 30, 40, 50, 60].lazy, s0Len: 2, s1Len: 3)
let expectation = [1, 2, 10, 20, 30, 3, 4, 40, 50, 60, 5]
XCTAssertEqualSeq(interdigged, expectation)
}
} | mit | e4141f880206e82a0b5ddee260af889f | 23.554795 | 103 | 0.608259 | 3.541502 | false | true | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Classes/Controller/CSPagerController.swift | 1 | 1680 | //
// Created by Rene Dohan on 1/27/21.
//
import UIKit
import Renetik
public protocol CSPagerPage {
}
public protocol HasPages {
associatedtype Page: CSViewController, CSPagerPage
var pages: [Page] { get }
}
public class CSPagerController<Pages: HasPages>: CSViewController {
public var currentIndex: Int = -1
public var current: Pages.Page { pages[currentIndex] }
private var _pages: Pages!
public var pages: [Pages.Page] { _pages.pages }
@discardableResult
public func construct(_ parent: UIViewController, pages: Pages) -> Self {
construct(parent)
_pages = pages
return self
}
public override func onViewWillAppearFirstTime() {
super.onViewWillAppearFirstTime()
show(index: 0)
}
public func show(page: Pages.Page) { pages.index(of: page)?.also { index in show(index, page) } }
public func show(index: Int) { pages.at(index)?.also { page in show(index, page) } }
private func show(_ index: Int, _ page: Pages.Page, _ animated: Bool = true) {
if index == currentIndex { return }
pages.at(currentIndex)?.also { current in
dismissChild(controller: current)
if currentIndex < index {
CATransition.create(for: view, type: .push, subtype: .fromRight)
} else if currentIndex > index {
CATransition.create(for: view, type: .push, subtype: .fromLeft)
}
}
add(controller: page).view.matchParent()
currentIndex = index
}
public override func onViewDismissing() {
super.onViewDismissing()
pages.forEach { $0.onViewDismissing() }
}
}
| mit | 4fb46a41c0554ca3f59e5a98addfc734 | 27.965517 | 101 | 0.629167 | 4.2 | false | false | false | false |
sayanee/ios-learning | Cassini/Cassini/ViewController.swift | 1 | 912 | //
// ViewController.swift
// Cassini
//
// Created by Sayanee Basu on 12/1/16.
// Copyright © 2016 Sayanee Basu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let ivc = segue.destinationViewController as? ImageViewController {
if let identifier = segue.identifier {
switch identifier {
case "Earth":
ivc.imageURL = DemoURL.NASA.Earth
ivc.title = "Earth"
case "Cassini":
ivc.imageURL = DemoURL.NASA.Cassini
ivc.title = "Cassini"
case "Saturn":
ivc.imageURL = DemoURL.NASA.Saturn
ivc.title = "Saturn"
default: break
}
}
}
}
}
| mit | 2e717b919a1f39f5398e747bb8626f62 | 26.606061 | 81 | 0.5236 | 4.720207 | false | false | false | false |
nextcloud/ios | iOSClient/Extensions/UIToolbar+Extension.swift | 1 | 2785 | //
// UIToolbar+Extension.swift
// Nextcloud
//
// Created by Henrik Storch on 18.03.22.
// Copyright © 2022 Henrik Storch. All rights reserved.
//
// Author Henrik Storch <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
extension UIToolbar {
static func toolbar(onClear: (() -> Void)?, completion: @escaping () -> Void) -> UIToolbar {
let toolbar = UIToolbar()
toolbar.sizeToFit()
var buttons: [UIBarButtonItem] = []
if let onClear = onClear {
let clearButton = UIBarButtonItem(title: NSLocalizedString("_clear_", comment: ""), style: .plain) {
onClear()
}
buttons.append(clearButton)
}
buttons.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil))
let doneButton = UIBarButtonItem(title: NSLocalizedString("_done_", comment: ""), style: .done) {
completion()
}
buttons.append(doneButton)
toolbar.setItems(buttons, animated: false)
return toolbar
}
// by default inputAccessoryView does not respect safeArea
var wrappedSafeAreaContainer: UIView {
let view = InputBarWrapper()
view.addSubview(self)
self.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.topAnchor.constraint(equalTo: view.topAnchor),
self.leftAnchor.constraint(equalTo: view.leftAnchor),
self.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
self.rightAnchor.constraint(equalTo: view.rightAnchor)
])
return view
}
}
// https://stackoverflow.com/a/67985180/9506784
class InputBarWrapper: UIView {
var desiredHeight: CGFloat = 0 {
didSet { invalidateIntrinsicContentSize() }
}
override var intrinsicContentSize: CGSize { CGSize(width: 0, height: desiredHeight) }
required init?(coder aDecoder: NSCoder) { fatalError() }
override init(frame: CGRect) {
super.init(frame: frame)
autoresizingMask = .flexibleHeight
}
}
| gpl-3.0 | 3386023ccb967edb869c0f63c563c829 | 35.155844 | 128 | 0.672414 | 4.601653 | false | false | false | false |
zhuhaow/soca | soca/Socket/Tunnel/Tunnel.swift | 1 | 3973 | //
// SocketTunnel.swift
// Soca
//
// Created by Zhuhao Wang on 2/15/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
class Tunnel {
unowned let proxySocket :ProxySocket
let adapter :Adapter
var connectRequest :ConnectMessage
var connectResponse :ConnectMessage?
enum TunnelReadTag :Int {
case HTTP_REQUEST_HEADER = 4000, HTTP_REQUEST_CONTENT, DATA
}
enum TunnelWriteTag :Int {
case HTTP_RESPONSE_HEADER = 5000, HTTP_RESPONSE_CONTENT, DATA
}
enum TunnelSendTag :Int {
case HTTP_REQUEST_HEADER = 6000, HTTP_REQUEST_CONTENT, DATA
}
enum TunnelReceiveTag :Int {
case HTTP_RESPONSE_HEADER = 7000, HTTP_RESPONSE_CONTENT, DATA
}
init(fromSocket proxySocket: ProxySocket, connectTo request: ConnectMessage, withAdapterFactory adapterFactory: AdapterFactory) {
self.proxySocket = proxySocket
self.connectRequest = request
self.adapter = adapterFactory.getAdapter(request, delegateQueue: self.proxySocket.getDelegateQueue())
self.adapter.tunnel = self
}
func connect() {
self.adapter.connect()
}
func updateRequest(request: ConnectMessage) {
self.connectRequest = request
self.adapter.connectRequest = request
}
// MARK: helper methods for adapter
func sendData(data: NSData, withTag tag: TunnelSendTag) {
self.adapter.writeData(data, withTag: tag.rawValue)
}
func receiveData(#tag: TunnelReceiveTag) {
self.adapter.readData(tag: tag.rawValue)
}
func receiveDataToLength(length :Int, withTimeout timeout: Double, withTag tag: TunnelReceiveTag) {
self.adapter.readDataToLength(length, withTimeout: timeout, withTag: tag.rawValue)
}
func receiveDataToLength(length: Int, withTag tag: TunnelReceiveTag) {
self.receiveDataToLength(length, withTimeout: -1, withTag: tag)
}
func receiveDataToData(data: NSData, withTimeout timeout: Double, withTag tag: TunnelReceiveTag) {
self.adapter.readDataToData(data, withTimeout: timeout, withTag: tag.rawValue)
}
func receiveDataToData(data: NSData, withTag tag: TunnelReceiveTag){
self.receiveDataToData(data, withTimeout: -1, withTag: tag)
}
// MARK: helper methods for proxy socket
func writeData(data: NSData, withTag tag: TunnelWriteTag) {
self.proxySocket.socket.writeData(data, withTag: tag.rawValue)
}
func readData(#tag: TunnelReadTag) {
self.proxySocket.socket.readData(tag: tag.rawValue)
}
func readDataToLength(length :Int, withTimeout timeout: Double, withTag tag: TunnelReadTag) {
self.proxySocket.socket.readDataToLength(length, withTimeout: timeout, withTag: tag.rawValue)
}
func readDataToLength(length: Int, withTag tag: TunnelReadTag) {
self.readDataToLength(length, withTimeout: -1, withTag: tag)
}
func readDataToData(data: NSData, withTimeout timeout: Double, withTag tag: TunnelReadTag) {
self.proxySocket.socket.readDataToData(data, withTimeout: timeout, withTag: tag.rawValue)
}
func readDataToData(data: NSData, withTag tag: TunnelReadTag){
self.readDataToData(data, withTimeout: -1, withTag: tag)
}
func sendHTTPHeader(data: NSData) {}
// MARK: delegate methods
func didReadData(data: NSData, withTag tag: TunnelReadTag) {}
func didWriteData(data: NSData, withTag tag: TunnelWriteTag) {}
func didSendData(data: NSData, withTag tag: TunnelSendTag) {}
func didReceiveData(data: NSData, withTag tag: TunnelReceiveTag) {}
func connectDidFail() {
self.proxySocket.connectDidFail()
}
func adapterBecameReady(response: ConnectMessage? = nil) {
self.connectResponse = response
self.proxySocket.adapterBecameReady(response)
}
func proxySocketBecameReady() {}
}
| mit | 64d1ababb94070e0f4112b293689d386 | 33.850877 | 133 | 0.685628 | 4.346827 | false | false | false | false |
wwdc14/SkyNet | SkyNet/Classes/Network/NetworkTableViewController.swift | 1 | 2385 | //
// NetworkTableViewController.swift
// Pods
//
// Created by FD on 10/08/2017.
//
//
import UIKit
class NetworkTableViewController: UITableViewController {
var items:[NetworkModel]? = nil
override func viewDidLoad() {
super.viewDidLoad()
items = NetworkModelMangaer.shared.getModels()
tableView.register(NetworkTableViewCell.self, forCellReuseIdentifier: "network")
navigationItem.title = "network"
tableView.separatorStyle = .none
let dismissBarItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: SkyNet.shared, action: #selector(SkyNet.shared.dismissSelf))
let deleteBarItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(removeAll))
navigationItem.rightBarButtonItems = [deleteBarItem,dismissBarItem]
}
@objc func removeAll() {
NetworkModelMangaer.shared.clear()
items?.removeAll()
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (items?.count)!
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:NetworkTableViewCell = tableView.dequeueReusableCell(withIdentifier: "network", for: indexPath) as! NetworkTableViewCell
_ = items?[indexPath.row]
cell.configForObject((items?[indexPath.row])!)
return cell
}
//MARK: - tableview deledate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 58
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let new = NetworkDetailViewController()
new.hidesBottomBarWhenPushed = true
new.selectedModel((items?[indexPath.row])!)
navigationController?.pushViewController(new, animated: true)
}
}
| mit | f9636b0a64d3b702ddadff6c706940d4 | 32.125 | 162 | 0.675891 | 5.323661 | false | false | false | false |
josherick/DailySpend | DailySpend/Adjustment+CoreDataClass.swift | 1 | 11169 | //
// Adjustment+CoreDataClass.swift
// DailySpend
//
// Created by Josh Sherick on 10/14/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Adjustment)
class Adjustment: NSManagedObject {
func json(jsonIds: [NSManagedObjectID: Int]) -> [String: Any]? {
var jsonObj = [String: Any]()
if let amountPerDay = amountPerDay {
let num = amountPerDay as NSNumber
jsonObj["amountPerDay"] = num
} else {
Logger.debug("couldn't unwrap amountPerDay in Adjustment")
return nil
}
if let shortDescription = shortDescription {
jsonObj["shortDescription"] = shortDescription
} else {
Logger.debug("couldn't unwrap shortDescription in Adjustment")
return nil
}
if let date = firstDayEffective?.start {
let num = date.gmtDate.timeIntervalSince1970 as NSNumber
jsonObj["firstDateEffective"] = num
} else {
Logger.debug("couldn't unwrap firstDateEffective in Adjustment")
return nil
}
if let date = lastDayEffective?.start {
let num = date.gmtDate.timeIntervalSince1970 as NSNumber
jsonObj["lastDateEffective"] = num
} else {
Logger.debug("couldn't unwrap lastDateEffective in Adjustment")
return nil
}
if let dateCreated = dateCreated {
let num = dateCreated.timeIntervalSince1970 as NSNumber
jsonObj["dateCreated"] = num
} else {
Logger.debug("couldn't unwrap dateCreated in Adjustment")
return nil
}
if let goals = goals {
var goalJsonIds = [Int]()
for goal in goals {
if let jsonId = jsonIds[goal.objectID] {
goalJsonIds.append(jsonId)
} else {
Logger.debug("a goal didn't have an associated jsonId in Adjustment")
return nil
}
}
jsonObj["goals"] = goalJsonIds
} else {
Logger.debug("couldn't unwrap goals in Adjustment")
return nil
}
return jsonObj
}
func serialize(jsonIds: [NSManagedObjectID: Int]) -> Data? {
if let jsonObj = self.json(jsonIds: jsonIds) {
let serialization = try? JSONSerialization.data(withJSONObject: jsonObj)
return serialization
}
return nil
}
class func create(context: NSManagedObjectContext,
json: [String: Any],
jsonIds: [Int: NSManagedObjectID]) -> Adjustment? {
let adjustment = Adjustment(context: context)
if let amountPerDay = json["amountPerDay"] as? NSNumber {
let decimal = Decimal(amountPerDay.doubleValue)
if decimal == 0 {
Logger.debug("amountPerDay equal to 0 in Adjustment")
return nil
}
adjustment.amountPerDay = decimal
} else {
Logger.debug("couldn't unwrap amountPerDay in Adjustment")
return nil
}
if let dateNumber = json["firstDateEffective"] as? NSNumber {
let date = Date(timeIntervalSince1970: dateNumber.doubleValue)
let calDay = CalendarDay(dateInDay: GMTDate(date))
if calDay.start.gmtDate != date {
// The date isn't a beginning of day
Logger.debug("The firstDateEffective isn't a beginning of day in Adjustment")
return nil
}
adjustment.firstDayEffective = calDay
} else {
Logger.debug("couldn't unwrap firstDateEffective in Adjustment")
return nil
}
if let dateNumber = json["lastDateEffective"] as? NSNumber {
let date = Date(timeIntervalSince1970: dateNumber.doubleValue)
let calDay = CalendarDay(dateInDay: GMTDate(date))
if calDay.start.gmtDate != date ||
calDay < adjustment.firstDayEffective! {
// The date isn't a beginning of day
Logger.debug("The lastDateEffective isn't a beginning of day or is earlier than firstDateEffective in Adjustment")
return nil
}
adjustment.lastDayEffective = calDay
} else {
Logger.debug("couldn't unwrap lastDateEffective in Adjustment")
return nil
}
if let shortDescription = json["shortDescription"] as? String {
if shortDescription.count == 0 {
Logger.debug("shortDescription empty in Adjustment")
return nil
}
adjustment.shortDescription = shortDescription
} else {
Logger.debug("couldn't unwrap shortDescription in Adjustment")
return nil
}
if let dateCreated = json["dateCreated"] as? NSNumber {
let date = Date(timeIntervalSince1970: dateCreated.doubleValue)
if date > Date() {
Logger.debug("dateCreated after today in Adjustment")
return nil
}
adjustment.dateCreated = date
} else {
Logger.debug("couldn't unwrap dateCreated in Adjustment")
return nil
}
if let goalJsonIds = json["goals"] as? Array<Int> {
for goalJsonId in goalJsonIds {
if let objectID = jsonIds[goalJsonId],
let goal = context.object(with: objectID) as? Goal {
adjustment.addGoal(goal)
} else {
Logger.debug("a goal didn't have an associated objectID in Adjustment")
return nil
}
}
} else {
Logger.debug("couldn't unwrap goals in Adjustment")
return nil
}
return adjustment
}
class func get(context: NSManagedObjectContext,
predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil,
fetchLimit: Int = 0) -> [Adjustment]? {
let fetchRequest: NSFetchRequest<Adjustment> = Adjustment.fetchRequest()
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
fetchRequest.fetchLimit = fetchLimit
let adjustmentResults = try? context.fetch(fetchRequest)
return adjustmentResults
}
/**
* Accepts all members of Adjustment. If the passed variables, attached to
* corresponding variables on an Adjustment object, will form a valid
* object, this function will assign the passed variables to this object
* and return `(valid: true, problem: nil)`. Otherwise, this function will
* return `(valid: false, problem: ...)` with problem set to a user
* readable string describing why this adjustment wouldn't be valid.
*/
func propose(shortDescription: String?? = nil,
amountPerDay: Decimal?? = nil,
firstDayEffective: CalendarDay?? = nil,
lastDayEffective: CalendarDay?? = nil,
dateCreated: Date?? = nil) -> (valid: Bool, problem: String?) {
let _shortDescription = shortDescription ?? self.shortDescription
let _amountPerDay = amountPerDay ?? self.amountPerDay
let _firstDayEffective = firstDayEffective ?? self.firstDayEffective
let _lastDayEffective = lastDayEffective ?? self.lastDayEffective
let _dateCreated = dateCreated ?? self.dateCreated
if _shortDescription == nil || _shortDescription!.count == 0 {
return (false, "This adjustment must have a description.")
}
if _amountPerDay == nil || _amountPerDay! == 0 {
return (false, "This adjustment must have an amount specified.")
}
if _firstDayEffective == nil || _lastDayEffective == nil ||
_firstDayEffective! > _lastDayEffective! {
return (false, "The first day effective be before the last day effective.")
}
if _dateCreated == nil {
return (false, "The adjustment must have a date created.")
}
self.shortDescription = _shortDescription
self.amountPerDay = _amountPerDay
self.firstDayEffective = _firstDayEffective
self.lastDayEffective = _lastDayEffective
self.dateCreated = _dateCreated
return (true, nil)
}
// Accessor functions (for Swift 3 classes)
var dateCreated: Date? {
get {
return dateCreated_ as Date?
}
set {
if newValue != nil {
dateCreated_ = newValue! as NSDate
} else {
dateCreated_ = nil
}
}
}
var shortDescription: String? {
get {
return shortDescription_
}
set {
shortDescription_ = newValue
}
}
var amountPerDay: Decimal? {
get {
return amountPerDay_ as Decimal?
}
set {
if newValue != nil {
amountPerDay_ = NSDecimalNumber(decimal: newValue!)
} else {
amountPerDay_ = nil
}
}
}
var firstDayEffective: CalendarDay? {
get {
if let day = firstDateEffective_ as Date? {
return CalendarDay(dateInDay: GMTDate(day))
} else {
return nil
}
}
set {
if newValue != nil {
firstDateEffective_ = newValue!.start.gmtDate as NSDate
} else {
firstDateEffective_ = nil
}
}
}
var lastDayEffective: CalendarDay? {
get {
if let day = lastDateEffective_ as Date? {
return CalendarDay(dateInDay: GMTDate(day))
} else {
return nil
}
}
set {
if newValue != nil {
lastDateEffective_ = newValue!.start.gmtDate as NSDate
} else {
lastDateEffective_ = nil
}
}
}
/**
* `goals` sorted in a deterministic way.
*/
var sortedGoals: [Goal]? {
if let g = goals {
return g.sorted(by: { $0.dateCreated! < $1.dateCreated! })
} else {
return nil
}
}
var goals: Set<Goal>? {
get {
return goals_ as! Set?
}
set {
if newValue != nil {
goals_ = NSSet(set: newValue!)
} else {
goals_ = nil
}
}
}
func addGoal(_ goal: Goal) {
addToGoals_(goal)
}
func removeGoal(_ goal: Goal) {
removeFromGoals_(goal)
}
}
| mit | de477b6a244964841fbef8f3b7479858 | 32.437126 | 130 | 0.538055 | 5.340985 | false | false | false | false |
QuiverApps/PiPass-iOS | PiPass-iOS/GetCurrentState.swift | 1 | 1218 | //
// GetCurrentState.swift
// PiPass-iOS
//
// Created by Jeremy Roberts on 11/22/15.
// Copyright © 2015 Jeremy Roberts. All rights reserved.
//
import Alamofire
import Mantle
public class GetCurrentState: NSObject {
public static func doApiCall(rpiAddress:String, success:(CurrentState) -> Void, failure:() -> Void) {
let address = String(format: Constants.JsonEnpoints.CURRENT_STATE, arguments: [rpiAddress])
Alamofire.request(.GET, address)
.responseJSON { response in
var currentState:CurrentState = CurrentState()
if(response.result.isSuccess) {
if let responseValue = response.result.value {
let array = responseValue as! NSArray
if(array.count > 0) {
currentState = CurrentState.deserializeObjectFromJSON(array[0] as! [NSObject : AnyObject]) as! CurrentState
}
success(currentState)
}
} else {
failure()
}
}
}
}
| mit | d19795e6c44f7b54a4be74d36c83ec73 | 31.891892 | 135 | 0.511093 | 5.223176 | false | false | false | false |
LbfAiYxx/douyuTV | DouYu/DouYu/Classes/Main/controller/AnimationViewController.swift | 1 | 1220 |
//
// AnimationViewController.swift
// DouYu
//
// Created by 刘冰峰 on 2017/1/16.
// Copyright © 2017年 LBF. All rights reserved.
//
import UIKit
class AnimationViewController: UIViewController {
var contentView: UIView?
lazy var animationView: UIImageView = { [unowned self] in
let animationView = UIImageView(image: UIImage.init(named: "img_loading_1"))
animationView.center = self.view.center
animationView.animationImages = [UIImage.init(named: "img_loading_1")!,UIImage.init(named: "img_loading_2")!]
animationView.animationDuration = 0.5
animationView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]
return animationView
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
}
}
extension AnimationViewController{
func setUpView() {
contentView?.isHidden = true
view.addSubview(animationView)
animationView.startAnimating()
}
func finishLoadData(){
animationView.stopAnimating()
animationView.isHidden = true
contentView?.isHidden = false
}
}
| mit | 1b24fcd4be36aab5df65293b667f6241 | 22.745098 | 117 | 0.628406 | 5.024896 | false | false | false | false |
dogo/AKFloatingLabel | Example/AKFloatingLabel/View/SampleView.swift | 1 | 5546 | //
// SampleView.swift
// AKFloatingLabel_Example
//
// Created by Diogo Autilio on 20/11/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
import SketchKit
import AKFloatingLabel
final class SampleView: UIView {
var firstSeparator = LightGrayView()
var dividerView = LightGrayView()
var secondSeparator = LightGrayView()
let titleField: AKFloatingLabelTextField = {
let textField = AKFloatingLabelTextField(frame: .zero)
textField.font = UIFont.systemFont(ofSize: 16)
textField.attributedPlaceholder = NSAttributedString(string: "Title",
attributes: [.foregroundColor: UIColor.darkGray])
textField.floatingLabelFont = UIFont.boldSystemFont(ofSize: 11)
textField.clearButtonMode = .whileEditing
return textField
}()
let priceField: AKFloatingLabelTextField = {
let textField = AKFloatingLabelTextField(frame: .zero)
textField.font = UIFont.systemFont(ofSize: 16)
textField.attributedPlaceholder = NSAttributedString(string: "Price",
attributes: [.foregroundColor: UIColor.darkGray])
textField.floatingLabelFont = UIFont.boldSystemFont(ofSize: 11)
return textField
}()
let locationField: AKFloatingLabelTextField = {
let textField = AKFloatingLabelTextField(frame: .zero)
textField.font = UIFont.systemFont(ofSize: 16)
textField.attributedPlaceholder = NSAttributedString(string: "Specific Location (optional)",
attributes: [.foregroundColor: UIColor.darkGray])
textField.floatingLabelFont = UIFont.boldSystemFont(ofSize: 11)
return textField
}()
let descriptionField: AKFloatingLabelTextView = {
let textView = AKFloatingLabelTextView(frame: .zero)
textView.font = UIFont.systemFont(ofSize: 16)
textView.placeholder = "Description"
textView.floatingLabelFont = UIFont.boldSystemFont(ofSize: 11)
return textView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.buildViewHierarchy()
self.setupConstraints()
self.configureViews()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension SampleView {
func buildViewHierarchy() {
self.addSubview(titleField)
self.addSubview(firstSeparator)
self.addSubview(priceField)
self.addSubview(dividerView)
self.addSubview(locationField)
self.addSubview(secondSeparator)
self.addSubview(descriptionField)
}
func setupConstraints() {
titleField.layout.applyConstraint { make in
make.topAnchor(equalTo: self.safeTopAnchor)
make.leadingAnchor(equalTo: self.leadingAnchor, constant: 10)
make.trailingAnchor(equalTo: self.trailingAnchor, constant: -10)
make.heightAnchor(greaterThanOrEqualToConstant: 44)
}
firstSeparator.layout.applyConstraint { make in
make.topAnchor(equalTo: self.titleField.bottomAnchor)
make.leadingAnchor(equalTo: self.leadingAnchor)
make.trailingAnchor(equalTo: self.trailingAnchor)
make.heightAnchor(equalToConstant: 1)
}
priceField.layout.applyConstraint { make in
make.topAnchor(equalTo: self.firstSeparator.bottomAnchor)
make.leadingAnchor(equalTo: self.leadingAnchor, constant: 10)
make.heightAnchor(greaterThanOrEqualToConstant: 44)
}
dividerView.layout.applyConstraint { make in
make.leadingAnchor(equalTo: self.priceField.trailingAnchor, constant: 10)
make.centerYAnchor(equalTo: self.priceField.centerYAnchor)
make.widthAnchor(equalToConstant: 1)
make.heightAnchor(equalTo: self.priceField.heightAnchor)
}
locationField.layout.applyConstraint { make in
make.leadingAnchor(equalTo: self.dividerView.trailingAnchor, constant: 10)
make.centerYAnchor(equalTo: self.dividerView.centerYAnchor)
make.trailingAnchor(equalTo: self.trailingAnchor, constant: -10)
make.heightAnchor(equalTo: self.priceField.heightAnchor)
}
secondSeparator.layout.applyConstraint { make in
make.topAnchor(equalTo: self.priceField.bottomAnchor)
make.leadingAnchor(equalTo: self.leadingAnchor)
make.trailingAnchor(equalTo: self.trailingAnchor)
make.heightAnchor(equalToConstant: 1)
}
descriptionField.layout.applyConstraint { make in
make.topAnchor(equalTo: self.secondSeparator.bottomAnchor)
make.leadingAnchor(equalTo: self.leadingAnchor, constant: 10)
make.trailingAnchor(equalTo: self.trailingAnchor, constant: -10)
make.bottomAnchor(equalTo: self.safeBottomAnchor, constant: -10)
}
}
func configureViews() {
self.titleField.floatingLabelTextColor = .brown
self.titleField.clearButtonColor = .red
self.titleField.keepBaseline = true
self.priceField.floatingLabelTextColor = .brown
self.locationField.floatingLabelTextColor = .brown
self.descriptionField.placeholderTextColor = .darkGray
self.descriptionField.floatingLabelTextColor = .brown
}
}
| mit | eb09145c02e50b908bcf975b1f17aaa1 | 37.506944 | 110 | 0.666005 | 5.211466 | false | false | false | false |
easyui/Alamofire | Source/Validation.swift | 4 | 12395 | //
// Validation.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
extension Request {
// MARK: Helper Types
fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
/// Used to represent whether a validation succeeded or failed.
public typealias ValidationResult = Result<Void, Error>
fileprivate struct MIMEType {
let type: String
let subtype: String
var isWildcard: Bool { type == "*" && subtype == "*" }
init?(_ string: String) {
let components: [String] = {
let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
return split.components(separatedBy: "/")
}()
if let type = components.first, let subtype = components.last {
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(_ mime: MIMEType) -> Bool {
switch (type, subtype) {
case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
return true
default:
return false
}
}
}
// MARK: Properties
fileprivate var acceptableStatusCodes: Range<Int> { 200..<300 }
fileprivate var acceptableContentTypes: [String] {
if let accept = request?.value(forHTTPHeaderField: "Accept") {
return accept.components(separatedBy: ",")
}
return ["*/*"]
}
// MARK: Status Code
fileprivate func validate<S: Sequence>(statusCode acceptableStatusCodes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == Int {
if acceptableStatusCodes.contains(response.statusCode) {
return .success(())
} else {
let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
return .failure(AFError.responseValidationFailed(reason: reason))
}
}
// MARK: Content Type
fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
response: HTTPURLResponse,
data: Data?)
-> ValidationResult
where S.Iterator.Element == String {
guard let data = data, !data.isEmpty else { return .success(()) }
return validate(contentType: acceptableContentTypes, response: response)
}
fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
response: HTTPURLResponse)
-> ValidationResult
where S.Iterator.Element == String {
guard
let responseContentType = response.mimeType,
let responseMIMEType = MIMEType(responseContentType)
else {
for contentType in acceptableContentTypes {
if let mimeType = MIMEType(contentType), mimeType.isWildcard {
return .success(())
}
}
let error: AFError = {
let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
return .success(())
}
}
let error: AFError = {
let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes),
responseContentType: responseContentType)
return AFError.responseValidationFailed(reason: reason)
}()
return .failure(error)
}
}
// MARK: -
extension DataRequest {
/// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
/// request was valid.
public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter statusCode: `Sequence` of acceptable response status codes.
///
/// - Returns: The instance.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
validate { [unowned self] _, response, _ in
self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
validate { [unowned self] _, response, data in
self.validate(contentType: acceptableContentTypes(), response: response, data: data)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes: () -> [String] = { [unowned self] in
self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
extension DataStreamRequest {
/// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the
/// request was valid.
public typealias Validation = (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter statusCode: `Sequence` of acceptable response status codes.
///
/// - Returns: The instance.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
validate { [unowned self] _, response in
self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
validate { [unowned self] _, response in
self.validate(contentType: acceptableContentTypes(), response: response)
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Returns: The instance.
@discardableResult
public func validate() -> Self {
let contentTypes: () -> [String] = { [unowned self] in
self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
// MARK: -
extension DownloadRequest {
/// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
/// destination URL, and returns whether the request was valid.
public typealias Validation = (_ request: URLRequest?,
_ response: HTTPURLResponse,
_ fileURL: URL?)
-> ValidationResult
/// Validates that the response has a status code in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter statusCode: `Sequence` of acceptable response status codes.
///
/// - Returns: The instance.
@discardableResult
public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int {
validate { [unowned self] _, response, _ in
self.validate(statusCode: acceptableStatusCodes, response: response)
}
}
/// Validates that the response has a content type in the specified sequence.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
///
/// - returns: The request.
@discardableResult
public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @autoclosure () -> S) -> Self where S.Iterator.Element == String {
validate { [unowned self] _, response, fileURL in
guard let validFileURL = fileURL else {
return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
}
do {
let data = try Data(contentsOf: validFileURL)
return self.validate(contentType: acceptableContentTypes(), response: response, data: data)
} catch {
return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL)))
}
}
}
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
/// type matches any specified in the Accept HTTP header field.
///
/// If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - returns: The request.
@discardableResult
public func validate() -> Self {
let contentTypes = { [unowned self] in
self.acceptableContentTypes
}
return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
}
}
| mit | 40990b2472a1398e4609073dffa47350 | 40.043046 | 150 | 0.637596 | 5.398519 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/UserViewController.swift | 1 | 9929 | //
// MeViewController.swift
// Insapp
//
// Created by Florent THOMAS-MOREL on 9/13/16.
// Copyright © 2016 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import UIKit
let kWhiteEmptyCell = "kWhiteEmptyCell"
class UserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UserEventsDelegate {
@IBOutlet weak var optionButton: UIButton!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIButton!
@IBOutlet weak var creditButton: UIButton!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var promotionLabel: UILabel!
var associations: [String : Association] = [:]
var events: [Event] = []
var user:User!
var initialBrightness: CGFloat!
var isEditable:Bool = true
var canReturn:Bool = false
var user_id:String!
var hasLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.separatorStyle = .none
self.tableView.register(UINib(nibName: "UserEventsCell", bundle: nil), forCellReuseIdentifier: kUserEventsCell)
self.tableView.register(UINib(nibName: "UserBarCodeCell", bundle: nil), forCellReuseIdentifier: kUserBarCodeCell)
self.tableView.register(UINib(nibName: "UserDescriptionCell", bundle: nil), forCellReuseIdentifier: kUserDescriptionCell)
self.tableView.register(UINib(nibName: "LoadingCell", bundle: nil), forCellReuseIdentifier: kLoadingCell)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: kWhiteEmptyCell)
self.avatarImageView.layer.cornerRadius = self.avatarImageView.frame.width/2
self.avatarImageView.layer.borderColor = UIColor.black.cgColor
self.avatarImageView.layer.masksToBounds = true
self.avatarImageView.layer.borderWidth = 1
if self.user_id == nil {
self.user_id = Credentials.fetch()!.userId
}
}
override func viewWillAppear(_ animated: Bool) {
self.notifyGoogleAnalytics()
self.lightStatusBar()
self.hideNavBar()
self.hasLoaded = false
self.initialBrightness = UIScreen.main.brightness
self.editButton.isHidden = !self.isEditable
self.optionButton.isHidden = self.isEditable
self.backButton.isHidden = !self.canReturn
self.creditButton.isHidden = self.canReturn
self.fetchUser(user_id: user_id)
}
func fetchUser(user_id:String){
APIManager.fetch(user_id: user_id, controller: self) { (opt_user) in
guard let user = opt_user else { return }
self.user = user
self.usernameLabel.text = "@" + self.user.username!
self.nameLabel.text = self.user.name!
self.emailLabel.text = self.user.email!
self.promotionLabel.text = self.user.promotion!
self.avatarImageView.image = self.user.avatar()
self.fetchEvents()
self.tableView.reloadData()
}
}
func fetchEvents(){
let group = DispatchGroup()
self.events = []
for eventId in self.user.events! {
group.enter()
APIManager.fetchEvent(event_id: eventId, controller: self, completion: { (opt_event) in
guard let event = opt_event else { return }
self.events.append(event)
group.leave()
})
}
group.notify(queue: DispatchQueue.main) {
self.fetchAssociation()
}
}
func fetchAssociation(){
let group = DispatchGroup()
for event in self.events {
if self.associations[event.association!] == nil {
group.enter()
APIManager.fetchAssociation(association_id: event.association!, controller: self) { (opt_asso) in
guard let association = opt_asso else { return }
self.associations[event.association!] = association
group.leave()
}
}
}
group.notify(queue: DispatchQueue.main) {
self.events = self.events.sorted(by: { (e1, e2) -> Bool in
e1.dateStart!.timeIntervalSince(e2.dateStart! as Date) > 0
})
self.hasLoaded = true
self.tableView.reloadData()
}
}
func setEditable(_ editable:Bool){
self.isEditable = editable
}
func canReturn(_ canReturn: Bool){
self.canReturn = canReturn
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 { return 116 }
let isSelf = self.user?.id == User.userInstance?.id
if indexPath.row == 1 { return (self.hasLoaded ? 0 : 44) }
if indexPath.row == 2 { return UserEventsCell.getHeightForEvents(events: self.events, isSelf: isSelf) }
if indexPath.row == 3 { return UserBarCodeCell.getHeightForUser(user: self.user) }
return UserDescriptionCell.getHeightForUser(self.user, forWidth: self.view.frame.width)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: kLoadingCell, for: indexPath) as! LoadingCell
cell.loadUser()
return cell
}else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: kUserEventsCell, for: indexPath) as! UserEventsCell
let isSelf = self.user?.id == User.userInstance?.id
cell.load(events: self.events, forAssociations: self.associations, isSelf: isSelf)
cell.delegate = self
return cell
}else if indexPath.row == 3 {
let cell = tableView.dequeueReusableCell(withIdentifier: kUserBarCodeCell, for: indexPath) as! UserBarCodeCell
cell.load()
return cell
}else if indexPath.row == 4 {
let cell = tableView.dequeueReusableCell(withIdentifier: kUserDescriptionCell, for: indexPath) as! UserDescriptionCell
cell.load(user: self.user)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: kWhiteEmptyCell, for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 3 {
let brightness: CGFloat = UIScreen.main.brightness
UIScreen.main.brightness = brightness == self.initialBrightness ? 1 : self.initialBrightness
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let value = max(0, scrollView.contentOffset.y)
self.headerView.frame.origin.y = -max(0, value) + 80
self.avatarImageView.bounds = CGRect(x: 0, y: 0, width: 100-value, height: 100-value)
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.width/2
}
func showAllEventAction(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "UserEventListViewController") as! UserEventListViewController
let isSelf = self.user.id! == User.userInstance?.id!
vc.events = ( isSelf ? self.events : Event.filter(events: self.events))
vc.associations = self.associations
self.navigationController?.pushViewController(vc, animated: true)
}
func show(event: Event, forAssociation association: Association){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
vc.event = event
vc.association = association
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func editAction(_ sender: AnyObject) {
if !self.isEditable { return }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "EditUserViewController") as! EditUserViewController
vc.user = self.user
self.present(vc, animated: true, completion: nil)
}
@IBAction func optionAction(_ sender: AnyObject) {
let alertController = Alert.create(alert: .reportUser) { report in
if report {
APIManager.report(user: self.user, controller: self)
let alert = Alert.create(alert: .reportConfirmation)
self.present(alert, animated: true, completion: nil)
}
}
self.present(alertController, animated: true, completion: nil)
}
@IBAction func creditAction(_ sender: AnyObject) {
if self.canReturn { return }
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "CreditViewController")
self.present(vc, animated: true, completion: nil)
}
@IBAction func dismissAction(_ sender: AnyObject) {
self.navigationController!.popViewController(animated: true)
}
}
| mit | df054825e9f83d385d1f82d1468d02a5 | 40.024793 | 132 | 0.643332 | 4.777671 | false | false | false | false |
WEIHOME/SliderExample-Swift | TipCalc/AppDelegate.swift | 1 | 6117 | //
// AppDelegate.swift
// TipCalc
//
// Created by Weihong Chen on 26/03/2015.
// Copyright (c) 2015 Weihong. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.weihong.TipCalc" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TipCalc", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TipCalc.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 53a097ae61f974c6fdcec05d25563eea | 54.108108 | 290 | 0.715383 | 5.732896 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/ModelIO/ModelIO.swift | 10 | 12834 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import ModelIO
import simd
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLMatrix4x4Array {
@nonobjc public var float4x4Array: [float4x4] {
get {
let count = elementCount
var values = [float4x4](repeating: float4x4(), count: Int(count))
__getFloat4x4Array(&values[0], maxCount: count)
return values
}
set(array) {
__setFloat4x4(array, count: array.count)
}
}
@nonobjc public var double4x4Array: [double4x4] {
get {
let count = elementCount
var values = [double4x4](repeating: double4x4(), count: Int(count))
__getDouble4x4Array(&values[0], maxCount: count)
return values
}
set(array) {
__setDouble4x4(array, count: array.count)
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedValue {
@nonobjc public var times: [TimeInterval] {
get {
var times = [TimeInterval](repeating: 0, count: Int(timeSampleCount))
__getTimes(×[0], maxCount: timeSampleCount)
return times
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedScalarArray {
@nonobjc public func set(floatArray array:[Float], atTime time: TimeInterval){
__setFloat(array, count: array.count, atTime: time)
}
@nonobjc public func set(doubleArray array:[Double], atTime time: TimeInterval){
__setDouble(array, count: array.count, atTime: time)
}
@nonobjc public func floatArray(atTime time: TimeInterval) -> [Float] {
var values = [Float](repeating: 0, count: Int(elementCount))
__getFloat(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func doubleArray(atTime time: TimeInterval) -> [Double] {
var values = [Double](repeating: 0, count: Int(elementCount))
__getDouble(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){
__reset(with: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){
__reset(with: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public var floatArray: [Float] {
get {
let count = elementCount * timeSampleCount
var values = [Float](repeating: 0, count: Int(count))
__getFloat(&values[0], maxCount: count)
return values
}
}
@nonobjc public var doubleArray: [Double] {
get {
let count = elementCount * timeSampleCount
var values = [Double](repeating: 0, count: Int(count))
__getDouble(&values[0], maxCount: count)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedVector3Array {
@nonobjc public func set(float3Array array:[float3], atTime time: TimeInterval){
__setFloat3(array, count: array.count, atTime: time)
}
@nonobjc public func set(double3Array array:[double3], atTime time: TimeInterval){
__setDouble3(array, count: array.count, atTime: time)
}
@nonobjc public func float3Array(atTime time: TimeInterval) -> [float3] {
var values = [float3](repeating: float3(), count: Int(elementCount))
__getFloat3Array(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func double3Array(atTime time: TimeInterval) -> [double3] {
var values = [double3](repeating: double3(), count: Int(elementCount))
__getDouble3Array(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func reset(float3Array array:[float3], atTimes times: [TimeInterval]){
__reset(withFloat3Array: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public func reset(double3Array array:[double3], atTimes times: [TimeInterval]){
__reset(withDouble3Array: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public var float3Array: [float3] {
get {
let count = elementCount * timeSampleCount
var values = [float3](repeating: float3(), count: Int(count))
__getFloat3Array(&values[0], maxCount: count)
return values
}
}
@nonobjc public var double3Array: [double3] {
get {
let count = elementCount * timeSampleCount
var values = [double3](repeating: double3(), count: Int(count))
__getDouble3Array(&values[0], maxCount: count)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedQuaternionArray {
@nonobjc public func set(floatQuaternionArray array:[simd_quatf], atTime time: TimeInterval){
__setFloat(array, count: array.count, atTime: time)
}
@nonobjc public func set(doubleQuaternionArray array:[simd_quatd], atTime time: TimeInterval){
__setDouble(array, count: array.count, atTime: time)
}
@nonobjc public func floatQuaternionArray(atTime time: TimeInterval) -> [simd_quatf] {
var values = [simd_quatf](repeating: simd_quatf(), count: Int(elementCount))
__getFloat(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func doubleQuaternionArray(atTime time: TimeInterval) -> [simd_quatd] {
var values = [simd_quatd](repeating: simd_quatd(), count: Int(elementCount))
__getDouble(&values[0], maxCount: elementCount, atTime: time)
return values
}
@nonobjc public func reset(floatQuaternionArray array:[simd_quatf], atTimes times: [TimeInterval]){
__reset(withFloat: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public func reset(doubleQuaternionArray array:[simd_quatd], atTimes times: [TimeInterval]){
__reset(withDouble: array, count: array.count, atTimes: times, count: times.count)
}
@nonobjc public var floatQuaternionArray : [simd_quatf] {
get {
let count = elementCount * timeSampleCount
var values = [simd_quatf](repeating: simd_quatf(), count: Int(count))
__getFloat(&values[0], maxCount: count)
return values
}
}
@nonobjc public var doubleQuaternionArray: [simd_quatd] {
get {
let count = elementCount * timeSampleCount
var values = [simd_quatd](repeating: simd_quatd(), count: Int(count))
__getDouble(&values[0], maxCount: count)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedScalar {
@nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){
__reset(withFloatArray: array, atTimes: times, count: times.count)
}
@nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){
__reset(withDoubleArray: array, atTimes: times, count: times.count)
}
@nonobjc public var floatArray: [Float] {
get {
var values = [Float](repeating: 0, count: Int(timeSampleCount))
__getFloatArray(&values[0], maxCount: timeSampleCount)
return values
}
}
@nonobjc public var doubleArray: [Double] {
get {
var values = [Double](repeating: 0, count: Int(timeSampleCount))
__getDoubleArray(&values[0], maxCount: timeSampleCount)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedVector2 {
@nonobjc public func reset(float2Array array:[float2], atTimes times: [TimeInterval]){
__reset(withFloat2Array: array, atTimes: times, count: times.count)
}
@nonobjc public func reset(double2Array array:[double2], atTimes times: [TimeInterval]){
__reset(withDouble2Array: array, atTimes: times, count: times.count)
}
@nonobjc public var float2Array: [float2] {
get {
var values = [float2](repeating: float2(), count: Int(timeSampleCount))
__getFloat2Array(&values[0], maxCount: timeSampleCount)
return values
}
}
@nonobjc public var double2Array: [double2] {
get {
var values = [double2](repeating: double2(), count: Int(timeSampleCount))
__getDouble2Array(&values[0], maxCount: timeSampleCount)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedVector3 {
@nonobjc public func reset(float3Array array:[float3], atTimes times: [TimeInterval]){
__reset(withFloat3Array: array, atTimes: times, count: times.count)
}
@nonobjc public func reset(double3Array array:[double3], atTimes times: [TimeInterval]){
__reset(withDouble3Array: array, atTimes: times, count: times.count)
}
@nonobjc public var float3Array: [float3] {
get {
var values = [float3](repeating: float3(), count: Int(timeSampleCount))
__getFloat3Array(&values[0], maxCount: timeSampleCount)
return values
}
}
@nonobjc public var double3Array: [double3] {
get {
var values = [double3](repeating: double3(), count: Int(timeSampleCount))
__getDouble3Array(&values[0], maxCount: timeSampleCount)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedVector4 {
@nonobjc public func reset(float4Array array:[float4], atTimes times: [TimeInterval]){
__reset(withFloat4Array: array, atTimes: times, count: times.count)
}
@nonobjc public func reset(double4Array array:[double4], atTimes times: [TimeInterval]){
__reset(withDouble4Array: array, atTimes: times, count: times.count)
}
@nonobjc public var float4Array: [float4] {
get {
var values = [float4](repeating: float4(), count: Int(timeSampleCount))
__getFloat4Array(&values[0], maxCount: timeSampleCount)
return values
}
}
@nonobjc public var double4Array: [double4] {
get {
var values = [double4](repeating: double4(), count: Int(timeSampleCount))
__getDouble4Array(&values[0], maxCount: timeSampleCount)
return values
}
}
}
@available(macOS, introduced: 10.13)
@available(iOS, introduced: 11.0)
@available(tvOS, introduced: 11.0)
extension MDLAnimatedMatrix4x4 {
@nonobjc public func reset(float4x4Array array:[float4x4], atTimes times: [TimeInterval]){
__reset(withFloat4x4Array: array, atTimes: times, count: times.count)
}
@nonobjc public func reset(double4Array array:[double4x4], atTimes times: [TimeInterval]){
__reset(withDouble4x4Array: array, atTimes: times, count: times.count)
}
@nonobjc public var float4x4Array: [float4x4] {
get {
var values = [float4x4](repeating: float4x4(), count: Int(timeSampleCount))
__getFloat4x4Array(&values[0], maxCount: timeSampleCount)
return values
}
}
@nonobjc public var double4x4Array: [double4x4] {
get {
var values = [double4x4](repeating: double4x4(), count: Int(timeSampleCount))
__getDouble4x4Array(&values[0], maxCount: timeSampleCount)
return values
}
}
}
| apache-2.0 | 52af8f05ffbfc9f8035ccac719c92f8e | 34.94958 | 104 | 0.62576 | 4.06654 | false | false | false | false |
cybersamx/Mapper-iOS-Standard | MapperStd/SearchViewController.swift | 1 | 3748 | //
// SearchViewController.swift
// MapperStd
//
// Created by Samuel Chow on 5/15/16.
// Copyright © 2016 Cybersam. All rights reserved.
//
import UIKit
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
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class SearchViewController: UIViewController {
@IBOutlet weak var searchField: UITextField!
@IBOutlet weak var searchButton: UIButton!
var results: [AnyObject]?
@IBAction func searchButtonDidPress(_ sender: AnyObject?) {
fetchAddressResults(searchField.text)
}
override func viewDidLoad() {
super.viewDidLoad()
// Make button pretty with a border
self.searchButton.layer.borderColor = self.searchButton.currentTitleColor.cgColor
self.searchButton.layer.borderWidth = 1.0
self.searchButton.layer.cornerRadius = 4.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "resultsSegue" {
let resultsController = segue.destination as! ResultsViewController
resultsController.results = self.results
} else if segue.identifier == "resultMapSegue" {
let result = self.results?[0] as! JSON
do {
let locationResult = try LocationResult(json: result)
let mapController = segue.destination as! MapViewController
mapController.locationResult = locationResult
} catch {
print("Parse error")
}
}
}
}
// MARK: - Networking
extension SearchViewController {
func fetchAddressResults(_ adddress: String?) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// Encode the address.
let charSet = CharacterSet.urlQueryAllowed
let encodedString: String? = adddress?.addingPercentEncoding(withAllowedCharacters: charSet)
guard let encodedAddressString = encodedString , !(encodedString?.isEmpty)! else {
print("Please supply an address.")
return
}
// Set up the HTTP request.
let queryURL = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=\(encodedAddressString)")
let request = NSMutableURLRequest(url: queryURL!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
// Check for error.
if let responseError = error {
print(responseError)
return
}
// Check HTTP status.
let httpResponse = response as! HTTPURLResponse
if case let errorStatusCode = httpResponse.statusCode , errorStatusCode < 200 || errorStatusCode >= 300 {
print("Error: HTTP status code = \(errorStatusCode)")
return
}
// Parse JSON payload.
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Dictionary<String, AnyObject>
self.results = json?["results"] as? [AnyObject]
DispatchQueue.main.async {
let segueIdentifier = (self.results?.count > 1) ? "resultsSegue" : "resultMapSegue"
self.performSegue(withIdentifier: segueIdentifier, sender: self)
}
} catch let jsonError as NSError {
print(jsonError)
}
})
task.resume()
}
}
| mit | d51aeb3be2139f7978c3e58bbf1f36fa | 28.273438 | 128 | 0.656792 | 4.648883 | false | false | false | false |
soapyigu/Swift30Projects | Project 07 - PokedexGo/PokedexGo/DetailViewController.swift | 1 | 1003 | //
// DetailViewController.swift
// PokedexGo
//
// Created by Yi Gu on 7/13/16.
// Copyright © 2016 yigu. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var nameIDLabel: UILabel!
@IBOutlet weak var pokeImageView: UIImageView!
@IBOutlet weak var pokeInfoLabel: UILabel!
var pokemon: Pokemon! {
didSet (newPokemon) {
self.refreshUI()
}
}
override func viewDidLoad() {
refreshUI()
super.viewDidLoad()
}
func refreshUI() {
nameIDLabel?.text = pokemon.name + (pokemon.id < 10 ? " #00\(pokemon.id)" : pokemon.id < 100 ? " #0\(pokemon.id)" : " #\(pokemon.id)")
pokeImageView?.image = LibraryAPI.sharedInstance.downloadImg(pokemon.pokeImgUrl)
pokeInfoLabel?.text = pokemon.detailInfo
self.title = pokemon.name
}
}
extension DetailViewController: PokemonSelectionDelegate {
func pokemonSelected(_ newPokemon: Pokemon) {
pokemon = newPokemon
}
}
| apache-2.0 | ef68d9b2da30999140ebef16198ee7d5 | 22.857143 | 138 | 0.674651 | 3.97619 | false | false | false | false |
iAladdin/SwiftyFORM | Source/Form/FormViewController.swift | 1 | 1592 | //
// FormViewController.swift
// SwiftyFORM
//
// Created by Simon Strandgaard on 09/11/14.
// Copyright (c) 2014 Simon Strandgaard. All rights reserved.
//
import UIKit
public class FormViewController: UIViewController {
public var dataSource: TableViewSectionArray?
public var keyboardHandler: KeyboardHandler?
public init() {
DLog("super init")
super.init(nibName: nil, bundle: nil)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func loadView() {
DLog("super loadview")
self.view = self.tableView
keyboardHandler = KeyboardHandler(tableView: self.tableView)
self.populate(formBuilder)
self.title = formBuilder.navigationTitle
dataSource = formBuilder.result(self)
self.tableView.dataSource = dataSource
self.tableView.delegate = dataSource
}
public func populate(builder: FormBuilder) {
print("subclass must implement populate()")
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.keyboardHandler?.addObservers()
// Fade out, so that the user can see what row has been updated
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
override public func viewDidDisappear(animated: Bool) {
self.keyboardHandler?.removeObservers()
super.viewDidDisappear(animated)
}
public lazy var formBuilder: FormBuilder = {
return FormBuilder()
}()
public lazy var tableView: FormTableView = {
return FormTableView()
}()
}
| mit | b176ea4982acc13fdbe79addb447d41d | 23.121212 | 65 | 0.73995 | 4.020202 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/Analytics/Analytics+LoginFlow.swift | 1 | 3595 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import FeatureAuthenticationDomain
// TODO: refactor this when secure channel is moved to feature authentication
enum LoginSource {
case secureChannel
case magicLink
}
extension AnalyticsEvents.New {
enum LoginFlow: AnalyticsEvent, Equatable {
case loginClicked(
origin: Origin
)
case loginViewed
case loginIdentifierEntered(
identifierType: IdentifierType
)
case loginIdentifierFailed(
errorMessage: String
)
case loginPasswordEntered
case loginRequestApproved(LoginSource)
case loginRequestDenied(LoginSource)
case loginTwoStepVerificationEntered
case loginTwoStepVerificationDenied
case deviceVerified(
wallet: WalletInfo
)
var type: AnalyticsEventType { .nabu }
var params: [String: Any]? {
switch self {
case .deviceVerified(let info):
let walletInfoDecoded: [String: Any] = [
"guid_first_four": String(info.wallet?.guid.prefix(4) ?? ""),
"has_cloud_backup": info.wallet?.hasCloudBackup ?? false,
"is_mobile_setup": info.wallet?.isMobileSetup ?? false,
"mobile_device_type": Device.iOS.rawValue
]
return ["wallet": walletInfoDecoded]
case .loginPasswordEntered,
.loginTwoStepVerificationEntered,
.loginViewed,
.loginTwoStepVerificationDenied:
return [:]
case .loginRequestApproved(let source),
.loginRequestDenied(let source):
return [
"login_source": String(describing: source)
]
case .loginClicked(let origin):
return [
"origin": origin.rawValue
]
case .loginIdentifierEntered(let identifierType):
return [
"identifier_type": identifierType.rawValue
]
case .loginIdentifierFailed(let errorMessage):
return [
"error_message": errorMessage,
"device": Device.iOS.rawValue,
"platform": Platform.wallet.rawValue
]
}
}
// MARK: Helpers
enum IdentifierType: String, StringRawRepresentable {
case email = "EMAIL"
case walletId = "WALLET-ID"
}
enum Device: String, StringRawRepresentable {
case iOS = "APP-iOS"
}
enum Origin: String, StringRawRepresentable {
case navigation = "NAVIGATION"
}
}
}
extension AnalyticsEvents.New.LoginFlow {
/// - Returns: The case of `.loginClicked` with default parameters
static func loginClicked() -> Self {
.loginClicked(
origin: .navigation
)
}
/// This returns the case `.deviceVerified` with default parameters
/// - Parameter info: The `WalletInfo` as received from the deeplink
static func deviceVerified(info: WalletInfo) -> Self {
.deviceVerified(
wallet: info
)
}
}
extension AnalyticsEventRecorderAPI {
/// Helper method to record `LoginFlow` events
/// - Parameter event: A `LoginFlow` event to be tracked
func record(event: AnalyticsEvents.New.LoginFlow) {
record(event: event)
}
}
| lgpl-3.0 | dace587eceef5cde0e0539b5dd9746ce | 29.717949 | 81 | 0.568169 | 5.285294 | false | false | false | false |
TimothyG/SyndicationKit | Tests/Models/RSS/RSSEnclosureTests.swift | 1 | 2111 | //
// RSSEnclosureTests.swift
// SyndicationKit
//
// Created by Timothy Gonzales on 10/17/16.
// Copyright © 2016 Tim Gonzales. All rights reserved.
//
import XCTest
@testable import SyndicationKit
class RSSEnclosureTests: XCTestCase {
private let href = "http://fake.url/123.mp3"
private let length = "123456789"
private let type = "audio/mpeg"
private var enclosure: RSSEnclosure?
override func setUp() {
enclosure = RSSEnclosure(attributes: ["url": href, "length": length, "type": type])
}
// MARK: Initializers
func testDefaultInitializer() {
let attributesUppercase = ["URL": href, "LENGTH": length, "TYPE": type]
let enclosure2 = RSSEnclosure(attributes: attributesUppercase)
XCTAssertEqual(enclosure?.href, URL(string: href)!)
XCTAssertEqual(enclosure?.length, Int(length)!)
XCTAssertEqual(enclosure?.type, type)
XCTAssertEqual(enclosure2.href, URL(string: href)!)
XCTAssertEqual(enclosure2.length, Int(length)!)
XCTAssertEqual(enclosure2.type, type)
}
// MARK: NSCoding
func testEncodingEnclosure() {
let archived = NSKeyedArchiver.archivedData(withRootObject: enclosure!)
XCTAssertTrue(archived.count > 0)
}
func testDecodingEnclosure() {
let archived = NSKeyedArchiver.archivedData(withRootObject: enclosure!)
let unarchived = NSKeyedUnarchiver.unarchiveObject(with: archived) as? RSSEnclosure
XCTAssertNotNil(unarchived)
if (unarchived != nil) {
XCTAssertEqual(enclosure!, unarchived!)
}
}
// MARK: Equality
func testEquality() {
let enclosureOne = RSSEnclosure(attributes: ["url": href, "length": length, "type": type])
let enclosureTwo = RSSEnclosure(attributes: ["url": href, "length": length, "type": type])
let enclosureThree = RSSEnclosure(attributes: [:])
XCTAssertEqual(enclosureOne, enclosureTwo)
XCTAssertNotEqual(enclosureOne, enclosureThree)
}
}
| mit | 95c132d943cad6bea006448802d8c392 | 30.969697 | 98 | 0.645972 | 4.547414 | false | true | false | false |
bridger/NumberPad | DigitRecognizerSDK/DigitRecognizer.swift | 1 | 27210 | //
// DigitRecognizer.swift
// NumberPad
//
// Created by Bridger Maxwell on 9/2/16.
// Copyright © 2016 Bridger Maxwell. All rights reserved.
//
import Foundation
public struct ImageSize {
public var width: UInt
public var height: UInt
public init(width: UInt, height: UInt) {
self.width = width
self.height = height
}
}
public class DigitRecognizer {
public typealias DigitStrokes = [[CGPoint]]
public typealias DigitLabel = String
public let imageSize = ImageSize(width: 28, height: 28)
public let labelStringToByte: [DigitLabel : UInt8] = [
"0" : 0,
"1" : 1,
"2" : 2,
"3" : 3,
"4" : 4,
"5" : 5,
"6" : 6,
"7" : 7,
"8" : 8,
"9" : 9,
"x" : 10,
"/" : 11,
"+" : 12,
"-" : 13,
"?" : 14,
"^" : 15,
"e" : 16,
]
public lazy var byteToLabelString: [UInt8 : DigitLabel] = {
var computedByteToLabelString: [UInt8 : DigitLabel] = [:]
for (label, byte) in self.labelStringToByte {
computedByteToLabelString[byte] = label
}
return computedByteToLabelString
}()
public typealias Classification = (Label: DigitLabel, Confidence: CGFloat)
public func classifyDigit(digit: DigitStrokes) -> Classification? {
guard let normalizedStroke = DigitRecognizer.normalizeDigit(inputDigit: digit) else {
return nil
}
guard renderToContext(normalizedStrokes: normalizedStroke, size: imageSize, data: dataPointer2) != nil else {
fatalError("Couldn't render image")
}
// Convert the int8 to floats
let intPointer = dataPointer2.assumingMemoryBound(to: UInt8.self)
let imageArray = Array<UInt8>(UnsafeBufferPointer(start: intPointer, count: Int(imageSize.width * imageSize.height)))
for (index, pixel) in imageArray.enumerated() {
dataBuffer1[index] = Float32(pixel) / 255.0
}
BNNSFilterApply(conv1, dataPointer1, dataPointer2)
BNNSFilterApply(pool1, dataPointer2, dataPointer1)
BNNSFilterApply(conv2, dataPointer1, dataPointer2)
BNNSFilterApply(pool2, dataPointer2, dataPointer1)
BNNSFilterApply(fullyConnected1, dataPointer1, dataPointer2)
BNNSFilterApply(fullyConnected2, dataPointer2, dataPointer1)
var highestScore: (Int, Float32)?
for (index, score) in dataBuffer1[0..<labelStringToByte.count].enumerated() {
if highestScore?.1 ?? -1 < score {
highestScore = (index, score)
}
}
if let highestScore = highestScore, let label = byteToLabelString[UInt8(highestScore.0)] {
return (Label: label, Confidence: CGFloat(highestScore.1))
} else {
return nil
}
}
struct StrokeToClassify {
var stroke: [CGPoint]
var min: CGFloat
var max: CGFloat
}
var classificationQueue = [StrokeToClassify]()
var singleStrokeClassifications = [Classification?]()
var doubleStrokeClassifications = [(classification: Classification, overlap: CGFloat)?]()
public func addStrokeToClassificationQueue(stroke: [CGPoint]) {
guard stroke.count > 0 else {
return
}
var minX = stroke[0].x
var maxX = stroke[0].x
for point in stroke {
minX = min(point.x, minX)
maxX = max(point.x, maxX)
}
classificationQueue.append(StrokeToClassify(stroke: stroke, min: minX, max: maxX))
singleStrokeClassifications.append(self.classifyDigit(digit: [stroke]))
if classificationQueue.count > 1 {
var twoStrokeClassification: (Classification, CGFloat)?
let lastStroke = classificationQueue[classificationQueue.count - 2]
// Check to see if this stroke and the last stroke touched
let overlapDistance = min(lastStroke.max, maxX) - max(lastStroke.min, minX)
if overlapDistance >= 0 {
let smallestWidth = min(lastStroke.max - lastStroke.min, maxX - minX)
let overlapPercent = max(overlapDistance, 1) / max(smallestWidth, 1)
if let classification = classifyDigit(digit: [lastStroke.stroke, stroke]) {
twoStrokeClassification = (classification, overlapPercent)
}
}
doubleStrokeClassifications.append(twoStrokeClassification)
}
}
public func clearClassificationQueue() {
classificationQueue.removeAll()
singleStrokeClassifications.removeAll()
doubleStrokeClassifications.removeAll()
}
// This is pretty cheap to call, the work is done upfront in addStrokeToClassificationQueue
public func recognizeStrokesInQueue() -> [DigitLabel]? {
var labels = [DigitLabel]()
// print("Classifying using \nSingle: \(singleStrokeClassifications) \nDouble: \(doubleStrokeClassifications)\n\n")
var index = 0
while index < singleStrokeClassifications.count {
let singleClass = singleStrokeClassifications[index]
var classifyAsDouble: Bool = false
var doubleClass: (classification: Classification, overlap: CGFloat)?
if index + 1 < singleStrokeClassifications.count {
doubleClass = doubleStrokeClassifications[index]
if let doubleClass = doubleClass {
// Decide if we should count both of these strokes as one digit or not
let nextSingle = singleStrokeClassifications[index + 1]
if let singleClass = singleClass, let nextSingle = nextSingle {
// Comparing the confidence score of the two single stroke classifications vs the double stroke
// classificaiton is tricky. I'm not sure the numbers are even on the same scale necessarily.
// The heuristic here is to favor the double stroke if the strokes overlap a lot on the x axis.
let overlapBonus = 0.7 + doubleClass.overlap
if min(singleClass.Confidence, nextSingle.Confidence) < doubleClass.classification.Confidence * overlapBonus {
classifyAsDouble = true
} else if doubleClass.overlap > 0.75
&& ["-", "1"] == [singleClass.Label, nextSingle.Label].sorted() {
// Recognizing "+" as "1-" or "-1" is a common misclassification
classifyAsDouble = true
}
} else {
// Either this stroke or the next couldn't be classified by itself, so we must use the double
classifyAsDouble = true
}
}
}
if classifyAsDouble, let doubleClass = doubleClass {
labels.append(doubleClass.classification.Label)
index += 2
} else if let singleClass = singleClass {
labels.append(singleClass.Label)
index += 1
} else {
return nil
}
}
return labels
}
public class func normalizeDigit(inputDigit: DigitStrokes) -> DigitStrokes? {
let targetPointCount = 32
var newInputDigit: DigitStrokes = []
for stroke in inputDigit {
// First, figure out the total arc length of this stroke
var lastPoint: CGPoint?
var totalDistance: CGFloat = 0
for point in stroke {
if let lastPoint = lastPoint {
totalDistance += lastPoint.distanceTo(point: point)
}
lastPoint = point
}
if totalDistance < 1.0 {
return nil
}
// Now, divide this arc length into 32 segments
let distancePerPoint = totalDistance / CGFloat(targetPointCount)
var newPoints: [CGPoint] = []
lastPoint = nil
var distanceCovered: CGFloat = 0
totalDistance = 0
for point in stroke {
if let lastPoint = lastPoint {
let nextDistance = lastPoint.distanceTo(point: point)
let newTotalDistance = totalDistance + nextDistance
while distanceCovered + distancePerPoint < newTotalDistance {
distanceCovered += distancePerPoint
let ratio: CGFloat = (distanceCovered - totalDistance) / nextDistance
if ratio < 0.0 || ratio > 1.0 {
print("Uh oh! Something went wrong!")
}
let newPointX: CGFloat = point.x * ratio + lastPoint.x * (1.0 - ratio)
let newPointY: CGFloat = point.y * ratio + lastPoint.y * (1.0 - ratio)
newPoints.append(CGPoint(x: newPointX, y: newPointY))
}
totalDistance = newTotalDistance
}
lastPoint = point
}
if newPoints.count > 0 && newPoints.count > 29 {
newInputDigit.append(newPoints)
} else {
print("What happened here????")
}
}
let inputDigit = newInputDigit
var topLeft: CGPoint?
var bottomRight: CGPoint?
for stroke in inputDigit {
for point in stroke {
if let capturedTopLeft = topLeft {
topLeft = CGPoint(x: min(capturedTopLeft.x, point.x), y: min(capturedTopLeft.y, point.y));
} else {
topLeft = point
}
if let capturedBottomRight = bottomRight {
bottomRight = CGPoint(x: max(capturedBottomRight.x, point.x), y: max(capturedBottomRight.y, point.y));
} else {
bottomRight = point
}
}
}
let xDistance = (bottomRight!.x - topLeft!.x)
let yDistance = (bottomRight!.y - topLeft!.y)
let xTranslate = topLeft!.x + xDistance / 2
let yTranslate = topLeft!.y + yDistance / 2
var xScale = 1.0 / xDistance;
var yScale = 1.0 / yDistance;
if !xScale.isFinite {
xScale = 1
}
if !yScale.isFinite {
yScale = 1
}
let scale = min(xScale, yScale)
return inputDigit.map { subPath in
return subPath.map({ point in
let x = (point.x - xTranslate) * scale
let y = (point.y - yTranslate) * scale
return CGPoint(x: x, y: y)
})
}
}
let trainedData: UnsafeMutableRawPointer
let conv1: BNNSFilter
let pool1: BNNSFilter
let conv2: BNNSFilter
let pool2: BNNSFilter
let fullyConnected1: BNNSFilter
let fullyConnected2: BNNSFilter
var dataBuffer1: Array<Float32>
var dataBuffer2: Array<Float32>
let dataPointer1: UnsafeMutableRawPointer
let dataPointer2: UnsafeMutableRawPointer
public init() {
let width = Int(imageSize.width)
let height = Int(imageSize.height)
var filterParams = createEmptyBNNSFilterParameters();
let trainedDataPath = Bundle(for: DigitRecognizer.self).path(forResource: "trainedData", ofType: "dat")
let trainedDataLength = 13127236
// open file descriptors in read-only mode to parameter files
let data_file = open(trainedDataPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(data_file != -1, "Error: failed to open output file at \(trainedDataPath) errno = \(errno)")
// memory map the parameters
trainedData = mmap(nil, trainedDataLength, PROT_READ, MAP_FILE | MAP_SHARED, data_file, 0);
// ****** trained layer data ******** //
let conv1Weights = BNNSLayerData(
data: trainedData + 0,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let conv1Bias = BNNSLayerData(
data: trainedData + 3200,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let conv2Weights = BNNSLayerData(
data: trainedData + 3328,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let conv2Bias = BNNSLayerData(
data: trainedData + 208128,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let fullyConnected1Weights = BNNSLayerData(
data: trainedData + 208384,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let fullyConnected1Bias = BNNSLayerData(
data: trainedData + 13053440,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let fullyConnected2Weights = BNNSLayerData(
data: trainedData + 13057536,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
let fullyConnected2Bias = BNNSLayerData(
data: trainedData + 13127168,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
// ****** conv 1 ******** //
var input = BNNSImageStackDescriptor(
width: width,
height: height,
channels: 1,
row_stride: width,
image_stride: width * height,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var conv1_output = BNNSImageStackDescriptor(
width: width,
height: height,
channels: 32,
row_stride: width,
image_stride: width * height,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var conv1_params = BNNSConvolutionLayerParameters(
x_stride: 1,
y_stride: 1,
x_padding: 2,
y_padding: 2,
k_width: 5,
k_height: 5,
in_channels: input.channels,
out_channels: conv1_output.channels,
weights: conv1Weights,
bias: conv1Bias,
activation: BNNSActivation(
function: BNNSActivationFunctionRectifiedLinear,
alpha: 0,
beta: 0
)
)
conv1 = BNNSFilterCreateConvolutionLayer(&input, &conv1_output, &conv1_params, &filterParams)!
// ****** pool 1 ******** //
let pool1Data = BNNSLayerData(
data: nil,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
var pool1_output = BNNSImageStackDescriptor(
width: width / 2,
height: height / 2,
channels: 32,
row_stride: width / 2,
image_stride: (width / 2) * (height / 2),
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var pool1_parameters = BNNSPoolingLayerParameters(
x_stride: 2,
y_stride: 2,
x_padding: 0,
y_padding: 0,
k_width: 2,
k_height: 2,
in_channels: 32,
out_channels: 32,
pooling_function: BNNSPoolingFunctionMax,
bias: pool1Data,
activation: BNNSActivation(
function: BNNSActivationFunctionIdentity,
alpha: 0,
beta: 0
)
)
pool1 = BNNSFilterCreatePoolingLayer(&conv1_output, &pool1_output, &pool1_parameters, &filterParams)!
// ****** conv 2 ******** //
var conv2_output = BNNSImageStackDescriptor(
width: width / 2,
height: height / 2,
channels: 64,
row_stride: width / 2,
image_stride: (width / 2) * (height / 2),
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var conv2_parameters = BNNSConvolutionLayerParameters(
x_stride: 1,
y_stride: 1,
x_padding: 2,
y_padding: 2,
k_width: 5,
k_height: 5,
in_channels: pool1_output.channels,
out_channels: conv2_output.channels,
weights: conv2Weights,
bias: conv2Bias,
activation: BNNSActivation(
function: BNNSActivationFunctionRectifiedLinear,
alpha: 0,
beta: 0
)
)
conv2 = BNNSFilterCreateConvolutionLayer(&pool1_output, &conv2_output, &conv2_parameters, &filterParams)!
// ****** pool 2 ******** //
let pool2Data = BNNSLayerData(
data: nil,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0,
data_table: nil
)
var pool2_output = BNNSImageStackDescriptor(
width: width / 4,
height: height / 4,
channels: 64,
row_stride: width / 4,
image_stride: (width / 4) * (height / 4),
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var pool2_parameters = BNNSPoolingLayerParameters(
x_stride: 2,
y_stride: 2,
x_padding: 0,
y_padding: 0,
k_width: 2,
k_height: 2,
in_channels: conv2_output.channels,
out_channels: pool2_output.channels,
pooling_function: BNNSPoolingFunctionMax,
bias: pool2Data,
activation: BNNSActivation(
function: BNNSActivationFunctionIdentity,
alpha: 0,
beta: 0
)
)
pool2 = BNNSFilterCreatePoolingLayer(&conv2_output, &pool2_output, &pool2_parameters, &filterParams)!
// ****** fully connected 1 ******** //
var fullyConnected_in = BNNSVectorDescriptor(
size: pool2_output.width * pool2_output.height * pool2_output.channels,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var fullyConnected_out = BNNSVectorDescriptor(
size: 1024,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var fullyConnected1_params = BNNSFullyConnectedLayerParameters(
in_size: fullyConnected_in.size,
out_size: fullyConnected_out.size,
weights: fullyConnected1Weights,
bias: fullyConnected1Bias,
activation: BNNSActivation(
function: BNNSActivationFunctionRectifiedLinear,
alpha: 0,
beta: 0
))
fullyConnected1 = BNNSFilterCreateFullyConnectedLayer(&fullyConnected_in, &fullyConnected_out, &fullyConnected1_params, &filterParams)!
// ****** fully connected 1 ******** //
var output = BNNSVectorDescriptor(
size: self.labelStringToByte.count,
data_type: BNNSDataTypeFloat32,
data_scale: 1,
data_bias: 0)
var fullyConnected2_params = BNNSFullyConnectedLayerParameters(
in_size: fullyConnected_out.size,
out_size: output.size,
weights: fullyConnected2Weights,
bias: fullyConnected2Bias,
activation: BNNSActivation(
function: BNNSActivationFunctionIdentity,
alpha: 0,
beta: 0
))
fullyConnected2 = BNNSFilterCreateFullyConnectedLayer(&fullyConnected_out, &output, &fullyConnected2_params, &filterParams)!
dataBuffer1 = Array<Float32>(repeating: 0, count: 6272)
dataBuffer2 = Array<Float32>(repeating: 0, count: 25088)
dataPointer1 = UnsafeMutableRawPointer(mutating: dataBuffer1)
dataPointer2 = UnsafeMutableRawPointer(mutating: dataBuffer2)
}
public func strokeIsScribble(_ stroke: [CGPoint]) -> Bool {
guard stroke.count > 1 else {
return false
}
// Here are magic values I found by scatter plotting a few samples. This method could
// be improved...
let intersectionThreshold = 32
let lengthToAreaThreshold: CGFloat = 0.055
var lengths = Array<CGFloat>(repeating: 0, count: stroke.count - 1)
var totalLength: CGFloat = 0
var totalArea: CGFloat = 0
func doubleTriangleArea(_ a: CGPoint, _ b: CGPoint, _ c: CGPoint) -> CGFloat {
return abs(a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y))
}
let firstPoint = stroke.first!
var lastPoint: CGPoint?
for (index, point) in stroke.enumerated() {
if let lastPoint = lastPoint {
let distance = lastPoint.distanceTo(point: point)
totalLength += distance
lengths[index - 1] = totalLength
totalArea += doubleTriangleArea(firstPoint, lastPoint, point)
}
lastPoint = point
}
totalArea /= 2
if (totalLength / totalArea) <= lengthToAreaThreshold {
// A scribble should have a relatively large length compared to its area
return false
}
// A, B, C, D, E, F
// 2, 4, 6, 8, 10
struct Arc {
let stroke: ArraySlice<CGPoint>
let lengths: ArraySlice<CGFloat>
let startingLength: CGFloat
}
func split(arc: Arc, midLengthIndex: Int) -> (Arc, Arc) {
let arc1 = Arc(stroke: arc.stroke.prefix(through: midLengthIndex),
lengths: arc.lengths.prefix(upTo: midLengthIndex),
startingLength: arc.startingLength)
let arc1EndLength = arc.lengths[midLengthIndex - 1]
let arc2 = Arc(stroke: arc.stroke.suffix(from: midLengthIndex),
lengths: arc.lengths.suffix(from: midLengthIndex),
startingLength: arc1EndLength)
return (arc1, arc2)
}
func midIndex(_ arc: Arc) -> Int? {
guard arc.stroke.count > 2 else {
return nil
}
// Returns nil if the midpoint is the first point
let arcLength = arc.lengths.last!
let midDistance = (arcLength - arc.startingLength) / 2
let midDistancePlusStarting = midDistance + arc.startingLength
guard let midLengthIndex = arc.lengths.index(where: { $0 > midDistancePlusStarting}),
midLengthIndex > arc.stroke.startIndex else {
return nil
}
return midLengthIndex
}
func averageMidpoint(arc: Arc) -> CGPoint {
let pointSum = arc.stroke.reduce(CGPoint.zero, +)
return pointSum / CGFloat(arc.stroke.count)
}
/* This is based on an intersection-finding algorithm:
1. Chop the curve in half, so you've got two arcs.
2. Draw a circle around the midpoint of each arc. The radius of the circle is L/2, where L is the length of the arc. (So the arc must lie entirely inside the circle).
3. If the circles don't overlap, it is impossible for the two arcs to intersect. Do nothing.
4. If the circles do overlap, it is possible that the arcs intersect. Chop each arc into two pieces, and recurse: for each of the 4 possible pairs, go back to step 1.
In this case, we don't need the actual intersections but how many times the recursion
happens, which is an approximation for how intersection-ey a curve is.
*/
func findRecursiveIntersections(arc1: Arc, midIndex1: Int?, arc2: Arc, midIndex2: Int?) -> Int {
let point1 = midIndex1 != nil ? arc1.stroke[midIndex1!] : averageMidpoint(arc: arc1)
let point2 = midIndex2 != nil ? arc2.stroke[midIndex2!] : averageMidpoint(arc: arc2)
let arc1Length = arc1.lengths.last! - arc1.startingLength
let arc2Length = arc2.lengths.last! - arc2.startingLength
// We imagine that a circle of radius arcLength/2 was drawn around each circle. If those
// circles intersect, then the two arcs might intersect. We divide each up into two more
// arcs and recurse on each combo.
if point1.distanceTo(point: point2) >= (arc1Length + arc2Length) / 2 {
// No intersection
return 0
}
if let midIndex1 = midIndex1, let midIndex2 = midIndex2 {
let (arc1Left, arc1Right) = split(arc: arc1, midLengthIndex: midIndex1)
let arc1LeftMid = midIndex(arc1Left)
let arc1RightMid = midIndex(arc1Right)
let (arc2Left, arc2Right) = split(arc: arc2, midLengthIndex: midIndex2)
let arc2LeftMid = midIndex(arc2Left)
let arc2RightMid = midIndex(arc2Right)
return (1 +
findRecursiveIntersections(arc1: arc1Left, midIndex1: arc1LeftMid, arc2: arc2Left, midIndex2: arc2LeftMid) +
findRecursiveIntersections(arc1: arc1Left, midIndex1: arc1LeftMid, arc2: arc2Right, midIndex2: arc2RightMid) +
findRecursiveIntersections(arc1: arc1Right, midIndex1: arc1RightMid, arc2: arc2Left, midIndex2: arc2LeftMid) +
findRecursiveIntersections(arc1: arc1Right, midIndex1: arc1RightMid, arc2: arc2Right, midIndex2: arc2RightMid)
)
} else {
// If neither can be split we stop recursing
return 1
}
}
let fullArc = Arc(stroke: stroke.suffix(from: 0), lengths: lengths.suffix(from: 0), startingLength: 0)
if let fullArcMiddle = midIndex(fullArc) {
let (fullArcLeft, fullArcRight) = split(arc: fullArc, midLengthIndex: fullArcMiddle)
let intersectionCount = findRecursiveIntersections(arc1: fullArcLeft, midIndex1: midIndex(fullArcLeft), arc2: fullArcRight, midIndex2: midIndex(fullArcRight))
return intersectionCount > intersectionThreshold
}
return false
}
}
| apache-2.0 | cd90dd95e2bc6d7ef1148516d923a1ed | 36.842837 | 177 | 0.556103 | 4.54013 | false | false | false | false |
andrashatvani/bcHealth | bcHealth/Track.swift | 1 | 627 | import Foundation
struct Track {
var date:Date?
var city:String?
var distance:Decimal?
var distanceUnit:String?
var time:Decimal?
var timeUnit:String?
var averageSpeed:Decimal?
var speedUnit:String?
func isComplete() -> Bool {
return (date != nil)
&& ((city != nil) && (city != ""))
&& (distance != nil)
&& ((distanceUnit != nil) && (distanceUnit != ""))
&& (time != nil)
&& ((timeUnit != nil) && (timeUnit != ""))
&& (averageSpeed != nil)
&& ((speedUnit != nil) && (speedUnit != ""))
}
}
| apache-2.0 | 903e72a38dc9e86640a84589944f3c1d | 26.26087 | 62 | 0.483254 | 4.152318 | false | false | false | false |
WalletOne/P2P | P2PUI/Controllers/Refunds/RefundsViewController.swift | 1 | 4408 | //
// RefundsViewController.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 03/08/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import UIKit
import P2PCore
@objc open class RefundsViewController: UIViewController, TableStructuredViewController {
@IBOutlet weak open var tableView: UITableView!
open var refunds: [Refund] = []
open var dealId: String?
lazy var tableController: RefundsTableController = { return .init(vc: self) }()
var isLoading = false
var isLoadMoreInProgress = false
var isAllowLoadMore = false
var pageNumber: Int = 0
var itemsPerPage: Int = 10
convenience public init(dealId: String?) {
self.init(nibName: "RefundsViewController", bundle: .init(for: RefundsViewController.classForCoder()))
self.dealId = dealId
}
override open func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = P2PUILocalizedStrings("Refunds", comment: "")
// Do any additional setup after loading the view.
loadData()
}
func loadData() {
isLoading = true
tableController.buildTableStructure(reloadData: true)
self.pageNumber = 1
P2PCore.refunds.refunds(pageNumber: pageNumber, itemsPerPage: itemsPerPage, dealId: dealId) { (result, error) in
let refunds = result?.refunds ?? []
self.isLoading = false
self.pageNumber += 1
self.refunds = refunds
self.isAllowLoadMore = !refunds.isEmpty
self.tableController.buildTableStructure(reloadData: true)
}
}
func loadMore() {
isLoadMoreInProgress = true
P2PCore.refunds.refunds(pageNumber: pageNumber, itemsPerPage: itemsPerPage, dealId: dealId) { (result, error) in
self.isLoadMoreInProgress = false
let refunds = result?.refunds ?? []
self.refunds.append(contentsOf: refunds)
self.pageNumber += 1
self.isAllowLoadMore = !refunds.isEmpty
self.tableController.buildTableStructure(reloadData: true)
}
}
}
class RefundsTableController: TableStructuredController<RefundsViewController> {
override func configureTableView() {
super.configureTableView()
let nibs = ["RefundTableViewCell", "LoadingTableViewCell", "RefundsEmptyTableViewCell"]
for nibName in nibs {
tableView.register(.init(nibName: nibName, bundle: .init(for: classForCoder)), forCellReuseIdentifier: nibName)
}
}
override func buildTableStructure(reloadData: Bool) {
beginBuilding()
var section = newSection()
if vc.isLoading {
section.append("LoadingTableViewCell")
} else {
if vc.refunds.isEmpty {
section.append("RefundsEmptyTableViewCell")
} else {
section.append(contentsOf: vc.refunds)
if vc.isAllowLoadMore {
section.append("LoadingTableViewCell")
}
}
}
append(section: §ion)
super.buildTableStructure(reloadData: reloadData)
}
override func tableView(_ tableView: UITableView, reuseIdentifierFor object: Any) -> String? {
if object is Refund {
return "RefundTableViewCell"
} else {
return super.tableView(tableView, reuseIdentifierFor: object)
}
}
override func tableView(_ tableView: UITableView, configure cell: UITableViewCell, for object: Any, at indexPath: IndexPath) {
if let cell = cell as? RefundTableViewCell, let refund = object as? Refund {
cell.refund = refund
if vc.isAllowLoadMore && !vc.isLoadMoreInProgress {
vc.loadMore()
}
} else if let cell = cell as? RefundsEmptyTableViewCell {
cell.textLabel?.text = P2PUILocalizedStrings("No Refunds", comment: "")
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, for object: Any) {
if let cell = cell as? LoadingTableViewCell {
cell.startAnimating()
}
}
}
| mit | 98c62f251c309ff72d9f16b0ad4a970e | 29.818182 | 130 | 0.600408 | 5.00227 | false | false | false | false |
shuoli84/RxSwift | RxSwift/RxSwift/Rx.swift | 2 | 1645 | //
// Rx.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if TRACE_RESOURCES
// counts resources
// used to detect resource leaks during unit tests
// it's not perfect, but works well
public var resourceCount: Int32 = 0
#endif
// This is the pipe operator (left associative function application operator)
// a >- b >- c == c(b(a))
// The reason this one is chosen for now is because
// * It's subtle, doesn't add a lot of visual noise
// * It's short
// * It kind of looks like ASCII art horizontal sink to the right
//
infix operator >- { associativity left precedence 91 }
public func >- <In, Out>(lhs: In, @noescape rhs: In -> Out) -> Out {
return rhs(lhs)
}
func contract(@autoclosure condition: () -> Bool) {
if !condition() {
let exception = NSException(name: "ContractError", reason: "Contract failed", userInfo: nil)
exception.raise()
}
}
// Swift doesn't have a concept of abstract metods.
// This function is being used as a runtime check that abstract methods aren't being called.
func abstractMethod<T>() -> T {
rxFatalError("Abstract method")
let dummyValue: T? = nil
return dummyValue!
}
func rxFatalError(lastMessage: String) {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
extension NSObject {
func rx_synchronized<T>(@noescape action: () -> T) -> T {
objc_sync_enter(self)
let result = action()
objc_sync_exit(self)
return result
}
}
| mit | 7afe8ed73f5e83f5bd1c48b4da513893 | 27.362069 | 115 | 0.665046 | 3.772936 | false | false | false | false |
enabledhq/Selfie-Bot | Selfie-Bot/SelfieBotAnalysisViewController.swift | 1 | 2762 | //
// SelfieBotCardViewController.swift
// Selfie-Bot
//
// Created by John Smith on 24/2/17.
// Copyright © 2017 Enabled. All rights reserved.
//
import Foundation
import UIKit
class SelfieBotAnalysisViewController: ViewController {
private let viewModel: SelfieBotAnalysisViewModel
private let analysisView: AnalysisView
init(viewModel: SelfieBotAnalysisViewModel) {
self.viewModel = viewModel
analysisView = AnalysisView(options: viewModel.options)
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
let imageView = UIImageView(image: viewModel.image)
let selfieBotSaysLabel = UILabel()
let qouteLabel = UILabel()
let textColor = UIColor(colorLiteralRed: 140 / 255, green: 140 / 255, blue: 140 / 255, alpha: 1)
//Drop Shadow
imageView.layer.shadowOffset = CGSize(width: -1.0, height: -1.0)
imageView.layer.shadowOpacity = 0.5
imageView.contentMode = .scaleAspectFit
selfieBotSaysLabel.textAlignment = .center
selfieBotSaysLabel.text = "Selfie bot says"
selfieBotSaysLabel.textColor = textColor
qouteLabel.textAlignment = .center
qouteLabel.text = viewModel.qoute
qouteLabel.numberOfLines = 0
qouteLabel.font = UIFont.init(name: "ChalkboardSE-Light", size: 17)
qouteLabel.textColor = textColor
view.backgroundColor = UIColor.white
view.addSubview(imageView)
view.addSubview(selfieBotSaysLabel)
view.addSubview(qouteLabel)
view.addSubview(analysisView)
imageView.snp.makeConstraints {
make in
make.height.equalTo(200)
make.top.equalTo(view).inset(50)
make.centerX.equalTo(view)
}
selfieBotSaysLabel.snp.makeConstraints {
make in
make.left.right.equalTo(view).inset(50)
make.top.equalTo(imageView.snp.bottom).offset(20)
}
qouteLabel.snp.makeConstraints {
make in
make.left.right.equalTo(view).inset(70)
make.top.equalTo(selfieBotSaysLabel.snp.bottom).offset(10)
}
analysisView.snp.makeConstraints {
make in
make.top.equalTo(qouteLabel.snp.bottom).offset(20)
make.left.right.equalTo(view).inset(50)
}
}
override func viewDidAppear(_ animated: Bool) {
analysisView.animateConfidenceBars()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | ef7b21b02607ed7313ebfd7405753013 | 29.340659 | 104 | 0.607026 | 4.563636 | false | false | false | false |
WalletOne/P2P | P2PExample/DataStorage.swift | 1 | 911 | //
// DataStorage.swift
// P2P_iOS
//
// Created by Vitaliy Kuzmenko on 31/07/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import Foundation
class DataStorage: NSObject {
static let `default` = DataStorage()
var deals: [Deal] = []
var employer: Employer!
var freelancer: Freelancer!
var dealRequests: [DealRequest] = []
func dealRequests(for deal: Deal) -> [DealRequest] {
if let payed = dealRequests.filter({ $0.deal == deal && ($0.stateId == .paid || $0.stateId == .paymentProcessing || $0.stateId == .paymentError) }).first {
return [payed]
} else {
return dealRequests.filter({ $0.deal == deal })
}
}
func cancel(request: DealRequest) {
guard let index = dealRequests.index(of: request) else { return }
self.dealRequests.remove(at: index)
}
}
| mit | 0bffc30ba8c10a7c73a158ecf573b4ca | 24.277778 | 163 | 0.585714 | 3.729508 | false | false | false | false |
blinksh/blink | SSH/SFTP.swift | 1 | 22650 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2021 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 BlinkFiles
import LibSSH
public enum FileError: Error {
case Fail(msg: String)
var description: String {
switch self {
case .Fail(let msg):
return msg
}
}
}
extension FileError {
init(in session: ssh_session) {
let msg = SSHError.getErrorDescription(session)
self = .Fail(msg: msg)
}
init(title: String, in session: ssh_session) {
let msg = SSHError.getErrorDescription(session)
self = .Fail(msg: "\(title) - \(msg)")
}
}
public class SFTPClient {
let client: SSHClient
var session: ssh_session { client.session }
let sftp: sftp_session
let rloop: RunLoop
let channel: ssh_channel
var log: SSHLogger { get { client.log } }
init?(on channel: ssh_channel, client: SSHClient) {
self.client = client
self.channel = channel
guard let sftp = sftp_new_channel(client.session, channel) else {
return nil
}
self.sftp = sftp
self.rloop = RunLoop.current
}
func start() throws {
ssh_channel_set_blocking(channel, 1)
defer { ssh_channel_set_blocking(channel, 0) }
let rc = sftp_init(sftp)
if rc != SSH_OK {
throw SSHError(rc, forSession: session)
}
}
deinit {
print("SFTP Out!!")
self.client.closeSFTP(sftp)
}
}
public class SFTPTranslator: BlinkFiles.Translator {
let sftpClient: SFTPClient
var sftp: sftp_session { sftpClient.sftp }
var channel: ssh_channel { sftpClient.channel }
var session: ssh_session { sftpClient.session }
var rloop: RunLoop { sftpClient.rloop }
var log: SSHLogger { get { sftpClient.log } }
var rootPath: String = ""
var path: String = ""
public var current: String { get { path }}
public private(set) var fileType: FileAttributeType = .typeUnknown
public var isDirectory: Bool {
get { return fileType == .typeDirectory }
}
public var isConnected: Bool { ssh_channel_is_closed(sftpClient.channel) != 1 && sftpClient.client.isConnected }
public init(on sftpClient: SFTPClient) throws {
self.sftpClient = sftpClient
let (rootPath, fileType) = try self.canonicalize("")
self.rootPath = rootPath
self.fileType = fileType
self.path = rootPath
}
init(from base: SFTPTranslator) {
self.sftpClient = base.sftpClient
self.rootPath = base.rootPath
self.path = base.path
self.fileType = base.fileType
}
func connection() -> AnyPublisher<sftp_session, Error> {
return .init(Just(sftp).subscribe(on: rloop).setFailureType(to: Error.self))
}
func canonicalize(_ path: String) throws -> (String, FileAttributeType) {
ssh_channel_set_blocking(channel, 1)
defer { ssh_channel_set_blocking(channel, 0) }
guard let canonicalPath = sftp_canonicalize_path(sftp, path.cString(using: .utf8)) else {
throw FileError(title: "Could not canonicalize path", in: session)
}
// Early protocol versions did not stat the item, so we do it ourselves.
// A path like /tmp/notexist would not fail if whatever does not exist.
guard let attrsPtr = sftp_stat(sftp, canonicalPath) else {
throw FileError(title:"\(String(cString:canonicalPath)) No such file or directory.", in: session)
}
let attrs = attrsPtr.pointee
var type: FileAttributeType = .typeUnknown
if attrs.type == SSH_FILEXFER_TYPE_DIRECTORY {
guard let dir = sftp_opendir(sftp, canonicalPath) else {
throw FileError(title: "No permission.", in: session)
}
if sftp_closedir(dir) != 0 {
throw FileError(title: "Could not close directory.", in: session)
}
type = .typeDirectory
} else if attrs.type == SSH_FILEXFER_TYPE_REGULAR {
type = .typeRegular
}
return (String(cString: canonicalPath), type)
}
public func clone() -> Translator {
return SFTPTranslator(from: self)
}
// Resolve to an element in the hierarchy
public func walkTo(_ path: String) -> AnyPublisher<Translator, Error> {
// All paths on SFTP, even Windows ones, must start with a slash (/c:/whatever/)
var absPath = path
// First cleanup the ~, and walk from rootPath
if absPath == "~" {
absPath = String(self.rootPath)
} else if let range = absPath.range(of: "~/", options: [.backwards]) {
absPath.removeSubrange(absPath.startIndex..<range.upperBound)
absPath = NSString(string: self.rootPath).appendingPathComponent(absPath)
}
// For a relative walk, append to current path.
if !absPath.starts(with: "/") {
// NSString performs a cleanup of the path as well.
absPath = NSString(string: self.path).appendingPathComponent(path)
}
return connection().tryMap { sftp -> SFTPTranslator in
let (canonicalPath, type) = try self.canonicalize(absPath)
self.path = canonicalPath
self.fileType = type
return self
}.eraseToAnyPublisher()
}
public func directoryFilesAndAttributes() -> AnyPublisher<[FileAttributes], Error> {
if fileType != .typeDirectory {
return .fail(error: FileError(title: "Not a directory.", in: session))
}
return connection().tryMap { sftp -> [FileAttributes] in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
var contents: [FileAttributes] = []
guard let dir = sftp_opendir(sftp, self.path) else {
throw FileError(in: self.session)
}
while let pointer = sftp_readdir(sftp, dir) {
let sftpAttrs = pointer.pointee
let attrs = self.parseItemAttributes(sftpAttrs)
contents.append(attrs)
sftp_attributes_free(pointer)
}
if sftp_closedir(dir) != 0 {
throw FileError(in: self.session)
}
return contents
}.eraseToAnyPublisher()
}
public func open(flags: Int32) -> AnyPublisher<File, Error> {
if fileType != .typeRegular {
return .fail(error: FileError(title: "Not a file.", in: session))
}
return connection().tryMap { sftp -> SFTPFile in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
guard let file = sftp_open(sftp, self.path, flags, S_IRWXU) else {
throw(FileError(title: "Error opening file", in: self.session))
}
return SFTPFile(file, in: self.sftpClient)
}.eraseToAnyPublisher()
}
public func create(name: String, flags: Int32, mode: mode_t = S_IRWXU) -> AnyPublisher<BlinkFiles.File, Error> {
if fileType != .typeDirectory {
return .fail(error: FileError(title: "Not a directory.", in: session))
}
return connection().tryMap { sftp -> SFTPFile in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let filePath = (self.path as NSString).appendingPathComponent(name)
guard let file = sftp_open(sftp, filePath, flags | O_CREAT, mode) else {
throw FileError(in: self.session)
}
return SFTPFile(file, in: self.sftpClient)
}.eraseToAnyPublisher()
}
public func remove() -> AnyPublisher<Bool, Error> {
return connection().tryMap { sftp -> Bool in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let rc = sftp_unlink(sftp, self.path)
if rc != SSH_OK {
throw FileError(title: "Could not delete file", in: self.session)
}
return true
}.eraseToAnyPublisher()
}
public func rmdir() -> AnyPublisher<Bool, Error> {
return connection().tryMap { sftp -> Bool in
self.log.message("Removing directory \(self.current)", SSH_LOG_INFO)
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let rc = sftp_rmdir(sftp, self.path)
if rc != SSH_OK {
throw FileError(title: "Could not delete directory", in: self.session)
}
return true
}.eraseToAnyPublisher()
}
// Mode uses same default as mkdir
// This is working well for filesystems, but everything else...
public func mkdir(name: String, mode: mode_t = S_IRWXU | S_IRWXG | S_IRWXO) -> AnyPublisher<Translator, Error> {
return connection().tryMap { sftp -> Translator in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let dirPath = (self.path as NSString).appendingPathComponent(name)
let rc = sftp_mkdir(sftp, dirPath, mode)
if rc != SSH_OK {
throw FileError(title: "Could not create directory", in: self.session)
}
self.path = dirPath
return self
}.eraseToAnyPublisher()
}
public func stat() -> AnyPublisher<FileAttributes, Error> {
return connection().tryMap { sftp -> FileAttributes in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let p = sftp_stat(sftp, self.path)
guard let attrs = p?.pointee else {
throw FileError(title: "Could not stat file", in: self.session)
}
return self.parseItemAttributes(attrs)
}.eraseToAnyPublisher()
}
public func wstat(_ attrs: FileAttributes) -> AnyPublisher<Bool, Error> {
// TODO Move -> Rename
return connection().tryMap { sftp -> sftp_session in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
var sftpAttrs = self.buildItemAttributes(attrs)
let rc = sftp_setstat(sftp, self.path, &sftpAttrs)
if rc != SSH_OK {
throw FileError(title: "Could not setstat file", in: self.session)
}
return sftp
}
.tryMap { sftp in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
// Relative path or from root
guard let newName = attrs[.name] as? String else {
return true
}
// We do this 9p style
// https://github.com/kubernetes/minikube/pull/3047/commits/a37faa7c7868ca49b4e8abf92985ab2de3c85cf3
var newPath = ""
if newName.starts(with: "/") {
// Full new path
newPath = newName
} else {
// Relative to CWD
// Change name
newPath = (self.current as NSString).deletingLastPathComponent
newPath = (newPath as NSString).appendingPathComponent(newName)
}
let rc = sftp_rename(sftp, self.path, newPath)
if rc != SSH_OK {
throw FileError(title: "Could not rename file", in: self.session)
}
return true
}
.eraseToAnyPublisher()
}
func parseItemAttributes(_ attrs: sftp_attributes_struct) -> FileAttributes {
var item: FileAttributes = [:]
switch attrs.type {
case UInt8(SSH_FILEXFER_TYPE_REGULAR):
item[.type] = FileAttributeType.typeRegular
case UInt8(SSH_FILEXFER_TYPE_SPECIAL):
item[.type] = FileAttributeType.typeBlockSpecial
case UInt8(SSH_FILEXFER_TYPE_SYMLINK):
item[.type] = FileAttributeType.typeSymbolicLink
case UInt8(SSH_FILEXFER_TYPE_DIRECTORY):
item[.type] = FileAttributeType.typeDirectory
default:
item[.type] = FileAttributeType.typeUnknown
}
item[.name] = attrs.name != nil ? String(cString: attrs.name, encoding: .utf8) : (self.path as NSString).lastPathComponent
if attrs.size >= 0 {
item[.size] = NSNumber(value: attrs.size)
}
// Get rid of the upper 4 bits (which are the file type)
item[.posixPermissions] = Int16(attrs.permissions & 0x0FFF)
if attrs.mtime > 0 {
item[.modificationDate] = NSDate(timeIntervalSince1970: Double(attrs.mtime))
}
if attrs.createtime > 0 {
item[.creationDate] = NSDate(timeIntervalSince1970: Double(attrs.createtime))
}
return item
}
func buildItemAttributes(_ attrs: [FileAttributeKey: Any]) -> sftp_attributes_struct {
var item = sftp_attributes_struct()
if let type = attrs[.type] as? FileAttributeType {
switch type {
case .typeRegular:
item.type = UInt8(SSH_FILEXFER_TYPE_REGULAR)
case .typeDirectory:
item.type = UInt8(SSH_FILEXFER_TYPE_DIRECTORY)
default:
item.type = UInt8(SSH_FILEXFER_TYPE_UNKNOWN)
}
}
if let permissions = attrs[.posixPermissions] as? UInt32 {
item.permissions = permissions
item.flags |= UInt32(SSH_FILEXFER_ATTR_PERMISSIONS)
}
if let mtime = attrs[.modificationDate] as? NSDate {
item.mtime = UInt32(mtime.timeIntervalSince1970)
item.atime = UInt32(mtime.timeIntervalSince1970)
// Both flags need to be set for this to work.
item.flags |= UInt32(SSH_FILEXFER_ATTR_MODIFYTIME) | UInt32(SSH_FILEXFER_ATTR_ACCESSTIME)
}
if let createtime = attrs[.creationDate] as? NSDate {
item.createtime = UInt64(createtime.timeIntervalSince1970)
item.flags |= UInt32(SSH_FILEXFER_ATTR_CREATETIME)
}
return item
}
}
public class SFTPFile : BlinkFiles.File {
var file: sftp_file?
let sftpClient: SFTPClient
var sftp: sftp_session { sftpClient.sftp }
var channel: ssh_channel { sftpClient.channel }
var session: ssh_session { sftpClient.session }
var rloop: RunLoop { sftpClient.rloop }
var log: SSHLogger { get { sftpClient.log } }
var inflightReads: [UInt32] = []
var inflightWrites: [UInt32] = []
let blockSize = 32 * 1024
let maxConcurrentOps = 20
var demand: Subscribers.Demand = .none
var pub: PassthroughSubject<DispatchData, Error>!
init(_ file: sftp_file, in sftpClient: SFTPClient) {
self.sftpClient = sftpClient
self.file = file
sftp_file_set_nonblocking(file)
}
func connection() -> AnyPublisher<sftp_session, Error> {
return .init(Just(sftp).subscribe(on: rloop).setFailureType(to: Error.self))
}
public func close() -> AnyPublisher<Bool, Error> {
return self.connection().tryMap { _ in
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
let rc = sftp_close(self.file)
if rc != SSH_OK {
throw FileError(title: "Error closing file", in: self.session)
}
self.file = nil
return true
}.eraseToAnyPublisher()
}
}
extension SFTPFile: BlinkFiles.Reader, BlinkFiles.WriterTo {
public func read(max length: Int) -> AnyPublisher<DispatchData, Error> {
inflightReads = []
pub = PassthroughSubject<DispatchData, Error>()
return
.demandingSubject(pub,
receiveRequest: receiveRequest,
on: rloop)
}
public func writeTo(_ w: Writer) -> AnyPublisher<Int, Error> {
inflightReads = []
pub = PassthroughSubject<DispatchData, Error>()
return
.demandingSubject(pub,
receiveRequest: receiveRequest(_:),
on: rloop)
.flatMap(maxPublishers: .max(1)) { data -> AnyPublisher<Int, Error> in
return w.write(data, max: data.count)
}.eraseToAnyPublisher()
}
private func receiveRequest(_ req: Subscribers.Demand) {
self.demand = req
self.inflightReadsLoop()
}
// Handle demand. Read scheduled blocks if they are available and push them.
func inflightReadsLoop() {
if file == nil {
pub.send(completion: .failure(FileError(title: "File Closed", in: self.session)))
return
}
var data: DispatchData?
var isComplete = false
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
if inflightReads.count > 0 {
do {
(data, isComplete) = try self.readBlocks()
} catch {
pub.send(completion: .failure(error))
return
}
}
// Schedule more blocks to read. This way data will already be ready when we come back.
while isComplete == false && inflightReads.count < self.maxConcurrentOps {
let asyncRequest = sftp_async_read_begin(self.file, UInt32(self.blockSize))
if asyncRequest < 0 {
pub.send(completion: .failure(FileError(title: "Could not pre-alloc request file", in: session)))
return
}
inflightReads.append(UInt32(asyncRequest))
}
if let data = data, data.count > 0 {
pub.send(data)
// TODO Account for demand here
if self.demand != .unlimited {
self.demand = .none
}
}
if isComplete {
pub.send(completion: .finished)
return
}
// Enqueue again if there is still demand.
if self.demand != .none {
rloop.schedule(after: .init(Date(timeIntervalSinceNow: 0.001))) {
self.inflightReadsLoop()
}
}
}
func readBlocks() throws -> (DispatchData, Bool) {
var data = DispatchData.empty
let newReads: [UInt32] = []
var lastIdx = -1
self.log.message("Reading blocks starting from \(inflightReads[0])", SSH_LOG_DEBUG)
for (idx, block) in inflightReads.enumerated() {
let buf = UnsafeMutableRawPointer.allocate(byteCount: self.blockSize, alignment: MemoryLayout<UInt8>.alignment)
self.log.message("Reading \(block)", SSH_LOG_TRACE)
let nbytes = sftp_async_read(self.file, buf, UInt32(self.blockSize), block)
if nbytes > 0 {
let bb = DispatchData(bytesNoCopy: UnsafeRawBufferPointer(start: buf, count: Int(nbytes)),
deallocator: .custom(nil, { buf.deallocate() }))
data.append(bb)
lastIdx = idx
} else {
buf.deallocate()
if nbytes == SSH_AGAIN {
self.log.message("readBlock AGAIN", SSH_LOG_TRACE)
break
} else if nbytes < 0 {
throw FileError(title: "Error while reading blocks", in: session)
} else if nbytes == 0 {
inflightReads = []
return (data, true)
}
}
}
let blocksRead = lastIdx == -1 ? 0 : lastIdx + 1
self.log.message("Blocks read \(blocksRead), size \(data.count), last block \(lastIdx == -1 ? 0 : inflightReads[lastIdx])", SSH_LOG_DEBUG)
inflightReads = Array(inflightReads[blocksRead...])
inflightReads += newReads
return (data, false)
}
}
extension SFTPFile: BlinkFiles.Writer {
// TODO Take into account length
public func write(_ buf: DispatchData, max length: Int) -> AnyPublisher<Int, Error> {
let pb = PassthroughSubject<Int, Error>()
func writeLoop(_ w: DispatchData, _ wn: DispatchData) {
if self.file == nil {
pb.send(completion: .failure(FileError(title: "File is closed", in: session)))
return
}
var writtenBytes = 0
var write = w
var written = wn
var isFinished = false
if inflightWrites.count > 0 {
// Check scheduled writes
do {
let blocksWritten = try self.checkWrites()
// The last block has the size of whatever is left, and cannot be
// accounted with blocks.
if w.count == 0 && blocksWritten == inflightWrites.count {
writtenBytes = written.count
isFinished = true
} else {
writtenBytes = blocksWritten * blockSize
}
if writtenBytes > 0 {
// Move buffers
inflightWrites = Array(inflightWrites[blocksWritten...])
written = written.subdata(in: writtenBytes..<written.count)
}
} catch {
pb.send(completion: .failure(error))
}
}
ssh_channel_set_blocking(self.channel, 1)
defer { ssh_channel_set_blocking(self.channel, 0) }
// Schedule more writes
while inflightWrites.count < self.maxConcurrentOps && write.count > 0 {
var asyncRequest: UInt32 = 0
let length = write.count < self.blockSize ? write.count : self.blockSize
// Check if we can write, otherwise the async write will fail
if ssh_channel_window_size(self.channel) < length {
break
}
let rc = write.withUnsafeBytes { bytes -> Int32 in
return sftp_async_write(self.file, bytes, length, &asyncRequest)
}
if rc != SSH_OK {
pb.send(completion: .failure(FileError(title: "Could not pre-alloc write request", in: session)))
return
}
inflightWrites.append(asyncRequest)
write = write.subdata(in: length..<write.count)
}
if writtenBytes > 0 {
// Publish bytes written
pb.send(writtenBytes)
}
if isFinished {
pb.send(completion: .finished)
} else {
rloop.schedule { writeLoop(write, written) }
}
}
return
.demandingSubject(pb,
receiveRequest: { _ in writeLoop(buf, buf) },
on: self.rloop)
}
func checkWrites() throws -> Int {
var lastIdx = 0
for block in inflightWrites {
let rc = sftp_async_write_end(self.file, block, 0)
if rc == SSH_AGAIN {
break
} else if rc != SSH_OK {
throw FileError(title: "Error while writing block", in: session)
}
lastIdx += 1
}
return lastIdx
}
}
| gpl-3.0 | 92885351de7c5539468f55a163a8fd28 | 31.082153 | 142 | 0.623841 | 4.000353 | false | false | false | false |
zapdroid/RXWeather | Weather/CoreDataService.swift | 1 | 2130 | //
// LocalDataService.swift
// Weather
//
// Created by Boran ASLAN on 21/05/2017.
// Copyright © 2017 Boran ASLAN. All rights reserved.
//
import Foundation
import CoreData
import UIKit
import CoreLocation
import RxCoreData
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class CoreDataService: CoreDataServiceProtocol {
static let sharedInstance = CoreDataService()
private init() {}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Weather")
container.loadPersistentStores(completionHandler: { _, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var managedObjectContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
func getBookmarks(predicate: NSPredicate?) -> [Bookmark] {
do {
guard let bookmarkList = try self.managedObjectContext.searchObjectsForEntity(entityName: Bookmark.className, predicate: predicate, sortArray: nil) as? [Bookmark] else {
return [Bookmark]()
}
return bookmarkList
} catch {}
return [Bookmark]()
}
func saveBookmark(coordinate: CLLocationCoordinate2D) -> Bookmark? {
guard let bookmark = self.managedObjectContext.insertNewEntity(entityName: Bookmark.className) as? Bookmark else {
return nil
}
bookmark.lat = coordinate.latitude
bookmark.lon = coordinate.longitude
do {
try managedObjectContext.save()
return bookmark
} catch {}
return nil
}
func update() -> Bool {
do {
try managedObjectContext.save()
return true
} catch {}
return false
}
func delete(managedObject _: NSManagedObject) -> Bool {
do {
try managedObjectContext.save()
return true
} catch {}
return false
}
}
| mit | 47704bd69cb556c06dc2ac36185f5b42 | 23.471264 | 181 | 0.615782 | 5.269802 | false | false | false | false |
STShenZhaoliang/STKitSwift | STKitSwiftDemo/STKitSwiftDemo/STAlertController.swift | 1 | 3712 | //
// STAlertController.swift
// STKitSwiftDemo
//
// Created by mac on 2019/7/1.
// Copyright © 2019 沈兆良. All rights reserved.
//
import UIKit
import STKitSwift
class STAlertController: UIViewController {
// MARK: 1.lift cycle
deinit {
print("------------ STAlertController deinit ------------")
}
// MARK: 2.private methods
// MARK: 3.event response
@IBAction func actionButton(_ sender: UIButton) {
let title = "Flutter 与 iOS 原生 WebView 对比"
let message = "在iOS中使用的就是原生的WKWebView,所以总体和 native WKWebView 表现差不多。如果是混编项目中,因为它被包了一层,所以页面加载上存在一定的劣势,所以混编项目中仍然推荐使用 WKWebView。不过如果从多端考虑、以及项目可迁移等,那么使用也未尝不可,就是维护成本要增加一些,需要维护两套 webView。这个就需要根据自己的情况自己取舍了"
STAlertView.show(title: title, message: message, cancelTitle: "取消", otherTitle: "确定") { (item) in
print(item)
}
}
@IBAction func actionNoTitle(_ sender: UIButton) {
let message = "在iOS中使用的就是原生的WKWebView,所以总体和 native WKWebView 表现差不多。如果是混编项目中,因为它被包了一层,所以页面加载上存在一定的劣势,所以混编项目中仍然推荐使用 WKWebView。不过如果从多端考虑、以及项目可迁移等,那么使用也未尝不可,就是维护成本要增加一些,需要维护两套 webView。这个就需要根据自己的情况自己取舍了"
STAlertView.show(title: nil, message: message, cancelTitle: "取消", otherTitle: "确定") { (item) in
print(item)
}
}
@IBAction func actionNoMessage(_ sender: UIButton) {
let title = "Flutter 与 iOS 原生 WebView 对比"
STAlertView.show(title: title, message: nil, cancelTitle: "取消", otherTitle: "确定") { (item) in
print(item)
}
}
@IBAction func actionNoCancel(_ sender: UIButton) {
let title = "Flutter 与 iOS 原生 WebView 对比"
let message = "在iOS中使用的就是原生的WKWebView,所以总体和 native WKWebView 表现差不多。如果是混编项目中,因为它被包了一层,所以页面加载上存在一定的劣势,所以混编项目中仍然推荐使用 WKWebView。不过如果从多端考虑、以及项目可迁移等,那么使用也未尝不可,就是维护成本要增加一些,需要维护两套 webView。这个就需要根据自己的情况自己取舍了"
STAlertView.show(title: title, message: message, cancelTitle: nil, otherTitle: "确定") { (item) in
print(item)
}
}
@IBAction func actionNoButton(_ sender: UIButton) {
let title = "Flutter 与 iOS 原生 WebView 对比"
let message = "在iOS中使用的就是原生的WKWebView,所以总体和 native WKWebView 表现差不多。如果是混编项目中,因为它被包了一层,所以页面加载上存在一定的劣势,所以混编项目中仍然推荐使用 WKWebView。不过如果从多端考虑、以及项目可迁移等,那么使用也未尝不可,就是维护成本要增加一些,需要维护两套 webView。这个就需要根据自己的情况自己取舍了"
STAlertView.show(title: title, message: message, cancelTitle: nil, otherTitle: nil) { (item) in
print(item)
}
}
// MARK: 4.interface
// MARK: 5.getter
}
| mit | d1a09a81c8f5aa489ab9e24582183ca8 | 36.720588 | 206 | 0.654191 | 2.951669 | false | false | false | false |
tjarratt/Xcode-Magic-And-Shit | Fake4SwiftKitSpecs/Fixtures/MySpecialStructEquatableExtension.swift | 3 | 118 |
func ==(a: MySpecialStruct, b: MySpecialStruct) -> Bool {
return a.name == b.name &&
a.age == b.age
}
| mit | 4d40f8ad77e7579d6dc728e604e54075 | 22.6 | 57 | 0.542373 | 3.025641 | false | false | false | false |
mattfenwick/TTT | TTT/TTTViewController.swift | 1 | 4437 | //
// TTTViewController.swift
// TTT
//
// Created by MattF on 12/5/14.
// Copyright (c) 2014 MattF. All rights reserved.
//
import UIKit
class TTTViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet var collectionView : UICollectionView!
var model : TTTModel!
// constructors
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
// don't want rotations
override func shouldAutorotate() -> Bool {
return false
}
// what about supportedInterfaceOrientations
// and preferredInterfaceOrientationForPresentation ?
//
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "TTTCell", bundle: nil)
self.collectionView.registerNib(cellNib, forCellWithReuseIdentifier: "TTTCell")
let width = UIScreen.mainScreen().bounds.width
let height = UIScreen.mainScreen().bounds.height
let length = (width < height) ? width : height
self.setCellSizeAndSpacing(length)
self.model = TTTModel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setCellSizeAndSpacing(length: CGFloat) {
let edge : CGFloat = 10
let middle : CGFloat = 20
let space : CGFloat = length - 2 * edge - 2 * middle
let cellLength = space / 3 // what about rounding?
let layout = self.collectionView.collectionViewLayout as UICollectionViewFlowLayout
layout.itemSize = CGSizeMake(cellLength, cellLength)
// TODO these don't need to be re-set each time
layout.minimumInteritemSpacing = 20
layout.minimumLineSpacing = 20
layout.sectionInset = UIEdgeInsetsMake(30, 10, 0, 10)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator:
UIViewControllerTransitionCoordinator) {
let length = (size.width < size.height) ? size.width : size.height
self.setCellSizeAndSpacing(length)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// collectionview data source
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : TTTCell =
collectionView.dequeueReusableCellWithReuseIdentifier("TTTCell", forIndexPath: indexPath) as TTTCell
func f(path: NSIndexPath) -> () {
// let's just ignore section for now
let row = path.item / 3
let col = path.item % 3
let result : TTTModel.MoveResult = self.model.move(row, column: col)
println("action: \(path)")
switch (result) {
case .SpotTaken:
print("spot taken") // oops, shouldn't have happened
case .GameOver:
let q = self.model.getWinner()
print("GameOver -- \(q!)") // TODO present some new view or something ... or maybe pop the current one from a navigation controller stack
case .Success:
let display : TTTModel.Team = self.model._board[row][col]!
if ( display == TTTModel.Team.Xs ) {
cell.setStatus(TTTCell.Status.X)
} else {
cell.setStatus(TTTCell.Status.O)
}
}
}
cell.action = f
cell.path = indexPath
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9;
}
// collectionview delegate
}
| mit | 46f0450549f0170e634088f4ba1c63b0 | 33.130769 | 153 | 0.626099 | 5.207746 | false | false | false | false |
ngageoint/mage-ios | Mage/Feed/FeedItemSummary.swift | 1 | 3410 | //
// FeedItemSummaryView.swift
// MAGE
//
// Created by Daniel Barela on 6/29/20.
// Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import PureLayout
import Kingfisher
class FeedItemSummary : CommonSummaryView<FeedItem, FeedItemActionsDelegate> {
private var didSetUpConstraints = false;
private lazy var noContentView: UIView = {
let view = UIView(forAutoLayout: ());
let label = UILabel(forAutoLayout: ());
label.text = "No Content";
label.font = UIFont.systemFont(ofSize: 32, weight: .regular);
label.textColor = UIColor.black.withAlphaComponent(0.60);
view.addSubview(label);
label.autoAlignAxis(toSuperviewAxis: .horizontal);
label.autoPinEdge(toSuperviewEdge: .left, withInset: 16);
// label.autoCenterInSuperview();
return view;
}()
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override init(imageOverride: UIImage? = nil, hideImage: Bool = false) {
super.init(imageOverride: imageOverride, hideImage: hideImage);
isUserInteractionEnabled = false;
layoutView();
}
override func populate(item: FeedItem, actionsDelegate: FeedItemActionsDelegate? = nil) {
let processor = DownsamplingImageProcessor(size: CGSize(width: 40, height: 40))
itemImage.tintColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0);
let image = UIImage(named: "observations");
let iconUrl = item.iconURL;
itemImage.kf.indicatorType = .activity
itemImage.kf.setImage(
with: iconUrl,
placeholder: image,
options: [
.requestModifier(ImageCacheProvider.shared.accessTokenModifier),
.processor(processor),
.scaleFactor(UIScreen.main.scale),
.transition(.fade(1)),
.cacheOriginalImage
])
{
result in
switch result {
case .success(_):
self.setNeedsLayout()
case .failure(let error):
print("Job failed: \(error.localizedDescription)")
}
}
if (!item.hasContent()) {
noContentView.isHidden = false;
primaryField.isHidden = true;
secondaryField.isHidden = true;
timestamp.isHidden = true;
return;
}
noContentView.isHidden = true;
primaryField.isHidden = false;
secondaryField.isHidden = false;
primaryField.text = item.primaryValue ?? " ";
secondaryField.text = item.secondaryValue;
if let itemTemporalProperty = item.feed?.itemTemporalProperty {
timestamp.text = item.valueForKey(key: itemTemporalProperty)
timestamp.isHidden = false;
} else {
timestamp.isHidden = true;
}
}
func layoutView() {
self.addSubview(noContentView);
primaryField.numberOfLines = 1;
primaryField.lineBreakMode = .byTruncatingTail
}
override func updateConstraints() {
if (!didSetUpConstraints) {
noContentView.autoPinEdgesToSuperviewEdges();
didSetUpConstraints = true;
}
super.updateConstraints();
}
}
| apache-2.0 | a55e306fc304f930ccbe1bf33323cfb8 | 33.434343 | 93 | 0.603989 | 5.020619 | false | false | false | false |
Esri/tips-and-tricks-ios | DevSummit2015_TipsAndTricksDemos/Tips-And-Tricks/WebTiledLayer/WebTiledLayerVC.swift | 1 | 2466 | // Copyright 2015 Esri
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import ArcGIS
class WebTiledLayerVC: UIViewController {
@IBOutlet weak var mapView: AGSMapView!
var webTiledLayer: AGSWebTiledLayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func toggleWebTiledLayer(sender: UISegmentedControl) {
//
// reset map view
self.mapView.reset()
// load Stamen web tiled layer
if sender.selectedSegmentIndex == 0 {
self.webTiledLayer = AGSWebTiledLayer(templateURL: "http://{subDomain}.tile.stamen.com/watercolor/{level}/{col}/{row}.jpg", tileInfo: nil, spatialReference: nil, fullExtent: nil, subdomains: ["a", "b", "c", "d"])
}
// load Thunderforest web tiled layer
else if sender.selectedSegmentIndex == 1 {
self.webTiledLayer = AGSWebTiledLayer(templateURL: "http://tile.thunderforest.com/transport/{level}/{col}/{row}.png", tileInfo: nil, spatialReference: nil, fullExtent: nil, subdomains: nil)
}
// load Google web tiled layer
else if sender.selectedSegmentIndex == 2 {
self.webTiledLayer = AGSWebTiledLayer(templateURL: "https://{subDomain}.tiles.mapbox.com/v4/examples.map-8ly8i7pv/{level}/{col}/{row}@2x.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IlhHVkZmaW8ifQ.hAMX5hSW-QnTeRCMAy9A8Q", tileInfo: nil, spatialReference: nil, fullExtent: nil, subdomains: ["a", "b", "c", "d"])
}
// add layer to map
self.mapView.addMapLayer(self.webTiledLayer, withName: "Web Tiled Layer")
// zoom to envelope
let envelope = AGSEnvelope.envelopeWithXmin(-14405800.682625, ymin:-1221611.989964, xmax:-7030030.629509, ymax:11870379.854318, spatialReference: AGSSpatialReference.webMercatorSpatialReference()) as AGSEnvelope
self.mapView.zoomToEnvelope(envelope, animated: true)
}
}
| apache-2.0 | 30284adbd4025b2c1411be291d39f694 | 43.836364 | 321 | 0.694242 | 3.871272 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Dynamic Programming/63_Unique Paths II.swift | 1 | 2271 | // 63_Unique Paths II
// https://leetcode.com/problems/unique-paths-ii/
//
// Created by Honghao Zhang on 10/15/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
//
//The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
//
//Now consider if some obstacles are added to the grids. How many unique paths would there be?
//
//
//
//An obstacle and empty space is marked as 1 and 0 respectively in the grid.
//
//Note: m and n will be at most 100.
//
//Example 1:
//
//Input:
//[
// [0,0,0],
// [0,1,0],
// [0,0,0]
//]
//Output: 2
//Explanation:
//There is one obstacle in the middle of the 3x3 grid above.
//There are two ways to reach the bottom-right corner:
//1. Right -> Right -> Down -> Down
//2. Down -> Down -> Right -> Right
//
// 机器人从左上角出发,到右下角。求多少条不同的路径。但是中间有障碍点。
import Foundation
class Num63 {
// MARK: - DP 坐标型
// 需要考虑障碍物的情况
func uniquePathsWithObstacles(_ obstacleGrid: [[Int]]) -> Int {
let m = obstacleGrid.count
guard m > 0 else {
return 0
}
let n = obstacleGrid[0].count
guard n > 0 else {
return 0
}
// the top left corner must be not an obstacle
if obstacleGrid[0][0] == 1 {
return 0
}
// state s[i][j] indicates how many paths reaches s[i][j]
var s: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: m)
// initialize
s[0][0] = 1
// for the first column
for i in 1..<m {
if obstacleGrid[i][0] == 1 {
s[i][0] = 0
}
else {
s[i][0] = s[i - 1][0]
}
}
// for the first row
for j in 1..<n {
if obstacleGrid[0][j] == 1 {
s[0][j] = 0
}
else {
s[0][j] = s[0][j - 1]
}
}
// transition
for i in 1..<m {
for j in 1..<n {
if obstacleGrid[i][j] == 1 {
s[i][j] = 0
}
else {
s[i][j] = s[i - 1][j] + s[i][j - 1]
}
}
}
return s[m - 1][n - 1]
}
}
| mit | 8f78ae896c7c2dfbbb5670f32ce9c6d9 | 21.666667 | 173 | 0.55193 | 3.034868 | false | false | false | false |
gaoleegin/DamaiPlayBusinessnormal | DamaiPlayBusinessPhone/DamaiPlayBusinessPhone/AppDelegate.swift | 1 | 3019 | //
// AppDelegate.swift
// DamaiPlayBusinessPhone
//
// Created by 高李军 on 15/11/3.
// Copyright © 2015年 DamaiPlayBusinessPhone. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds);
window?.backgroundColor = UIColor.redColor()
window!.makeKeyAndVisible()
let sb = UIStoryboard(name: "UserLogin", bundle: nil);
let userLoginVC = sb.instantiateInitialViewController() as! DMUserLoginViewController
let indexSb = UIStoryboard(name: "ActiveList", bundle: nil)
let indexVC = indexSb.instantiateInitialViewController() as! UINavigationController
// 通过判断来控制当前的根控制器是哪一个,通过M值来判断
if DMMValueAndVValue.getMVValue().lengthOfBytesUsingEncoding(NSUTF8StringEncoding)==0{
window!.rootViewController = userLoginVC
} else{
window?.rootViewController = indexVC
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | bf0144c82c9866e62f08e853b71207ab | 41.898551 | 285 | 0.722635 | 5.481481 | false | false | false | false |
kopto/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationBallClipRotate.swift | 1 | 2883 | //
// KRActivityIndicatorBallClipRotate.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class KRActivityIndicatorAnimationBallClipRotate: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let duration: CFTimeInterval = 0.75
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, Float.pi, 2 * Float.pi]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 4735640195b3921b94cc56248ecf3007 | 41.397059 | 137 | 0.686785 | 4.97069 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ReactionsWindowController.swift | 1 | 13480 | //
// ReactionsWindowController.swift
// Telegram
//
// Created by Mike Renoir on 16.08.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import TelegramCore
import SwiftSignalKit
import Postbox
protocol StickerFramesCollector {
func collect() -> [Int : LottiePlayerView]
}
private var reactions: ReactionsWindowController?
final class ReactionsWindowController : NSObject {
private class V : View {
private let visualView: NSVisualEffectView
private let contentView: NSView
private let backgroundView = View()
private let container = View()
private var mask: SimpleShapeLayer?
init(_ content: NSView) {
self.contentView = content
self.visualView = NSVisualEffectView(frame: content.bounds)
super.init(frame: content.bounds)
if #available(macOS 11.0, *) {
container.addSubview(visualView)
backgroundView.backgroundColor = theme.colors.background.withAlphaComponent(0.7)
} else {
backgroundView.backgroundColor = theme.colors.background
}
container.addSubview(backgroundView)
container.addSubview(contentView)
addSubview(container)
self.visualView.wantsLayer = true
self.visualView.state = .active
self.visualView.blendingMode = .behindWindow
self.visualView.autoresizingMask = []
self.autoresizesSubviews = false
self.visualView.material = theme.colors.isDark ? .dark : .light
self.layer?.isOpaque = false
self.layer?.shouldRasterize = true
self.layer?.rasterizationScale = System.backingScale
self.layer?.cornerRadius = 20
contentView.layer?.cornerRadius = 20
self.visualView.layer?.cornerRadius = 20
self.backgroundView.layer?.cornerRadius = 20
self.container.layer?.cornerRadius = 20
contentView.layer?.opacity = 0
}
func appearAnimated(from: NSRect, to: NSRect) {
let shadow = NSShadow()
shadow.shadowBlurRadius = 2
shadow.shadowColor = NSColor.black.withAlphaComponent(0.2)
shadow.shadowOffset = NSMakeSize(0, 0)
self.shadow = shadow
contentView.layer?.opacity = 1
let duration: Double = 0.35
self.container.layer?.mask = nil
self.mask = nil
var offset: NSPoint = .zero
offset.y = to.height - from.height / 2 - from.origin.y - 5
offset.x = 10
self.container.layer?.animateBounds(from: from.size.bounds.offsetBy(dx: offset.x, dy: offset.y), to: to.size.bounds, duration: duration, timingFunction: .spring)
self.container.layer?.animatePosition(from: offset, to: .zero, duration: duration, timingFunction: .spring)
}
func initFake(_ from: NSRect, to: NSRect) {
var offset: NSPoint = .zero
offset.y = to.height - from.height / 2 - from.origin.y - 5
offset.x = 10
var rect = from.size.bounds.offsetBy(dx: offset.x, dy: offset.y)
rect.size.width -= 20
rect.size.height = 40
let mask = SimpleShapeLayer()
self.mask = mask
let path = CGMutablePath()
path.addRoundedRect(in: rect.size.bounds, cornerWidth: rect.height / 2, cornerHeight: rect.height / 2)
mask.path = path
mask.frame = rect
mask.cornerRadius = 20
container.layer?.mask = mask
}
override func layout() {
super.layout()
self.container.frame = bounds
self.contentView.frame = bounds
self.visualView.frame = bounds
self.backgroundView.frame = bounds
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
private let emojies: EmojiesController
private let context: AccountContext
private var panel: Window?
private let overlay = OverlayControl()
private var initialPlayers:[Int: LottiePlayerView] = [:]
private var keyDisposable: Disposable?
private func makeView(_ content: NSView, _ initialView: NSView, _ initialRect: NSRect, animated: Bool) -> (Window, V) {
let v = V(content)
let panel = Window(contentRect: NSMakeRect(initialRect.minX - 21, initialRect.maxY - 320 + (initialRect.height + 20) - 32, 390, 340), styleMask: [.fullSizeContentView], backing: .buffered, defer: false)
panel._canBecomeMain = false
panel._canBecomeKey = false
panel.level = .popUpMenu
panel.backgroundColor = .clear
panel.isOpaque = false
panel.hasShadow = false
let contentView = View(frame: .zero)
panel.contentView = contentView
contentView.backgroundColor = .clear
contentView.flip = false
contentView.layer?.isOpaque = false
v.frame = v.frame.offsetBy(dx: 20, dy: 20)
contentView.addSubview(v)
initialView.frame = NSMakeRect(v.frame.minX + 1, v.frame.maxY - initialView.frame.height - 48, initialView.frame.width, initialView.frame.height)
// initialView.background = .red
// initialView.layer?.opacity = 0.5
contentView.addSubview(initialView)
return (panel, v)
}
init(_ context: AccountContext, message: Message) {
self.context = context
var selectedItems: [EmojiesSectionRowItem.SelectedItem] = []
if let reactions = message.effectiveReactions {
for reaction in reactions {
switch reaction.value {
case let .builtin(emoji):
selectedItems.append(.init(source: .builtin(emoji), type: .transparent))
case let .custom(fileId):
selectedItems.append(.init(source: .custom(fileId), type: .transparent))
}
}
}
self.emojies = .init(context, mode: .reactions, selectedItems: selectedItems)
self.emojies.loadViewIfNeeded()
super.init()
let interactions = EntertainmentInteractions(.emoji, peerId: message.id.peerId)
interactions.sendAnimatedEmoji = { [weak self] sticker, _, _, fromRect in
let value: UpdateMessageReaction
if let bundle = sticker.file.stickerText {
value = .builtin(bundle)
} else {
value = .custom(fileId: sticker.file.fileId.id, file: sticker.file)
}
if case .custom = value, !context.isPremium {
showModalText(for: context.window, text: strings().customReactionPremiumAlert, callback: { _ in
showModal(with: PremiumBoardingController(context: context, source: .premium_stickers), for: context.window)
})
} else {
let updated = message.newReactions(with: value)
context.reactions.react(message.id, values: updated, fromRect: fromRect, storeAsRecentlyUsed: true)
}
self?.close(animated: true)
}
emojies.update(with: interactions, chatInteraction: .init(chatLocation: .peer(message.id.peerId), context: context))
emojies.closeCurrent = { [weak self] in
self?.close(animated: true)
}
emojies.animateAppearance = { [weak self] items in
self?.animateAppearanceItems(items, initialPlayers: self?.initialPlayers ?? [:])
}
}
private func animateAppearanceItems(_ items: [TableRowItem], initialPlayers:[Int: LottiePlayerView]) {
let sections = items.compactMap {
$0 as? EmojiesSectionRowItem
}
let tabs = items.compactMap {
$0 as? StickerPackRowItem
}
let firstTab = items.compactMap {
$0 as? ETabRowItem
}
let duration: Double = 0.35
let itemDelay: Double = duration / Double(sections.count)
var delay: Double = itemDelay
firstTab.first?.animateAppearance(delay: 0.1, duration: duration, ignoreCount: 0)
for tab in tabs {
tab.animateAppearance(delay: 0.1, duration: duration, ignoreCount: 0)
}
for (i, section) in sections.enumerated() {
section.animateAppearance(delay: delay, duration: duration, initialPlayers: i == 0 ? initialPlayers : [:])
delay += itemDelay
}
}
func show(_ initialView: NSView & StickerFramesCollector, animated: Bool = true) {
reactions?.panel?.orderOut(nil)
reactions = self
self.ready(initialView, animated: animated)
}
private func ready(_ initialView: NSView & StickerFramesCollector, animated: Bool) {
let initialScreenRect = initialView.window!.convertToScreen(initialView.convert(initialView.bounds, to: nil))
self.emojies.view.frame = self.emojies.view.bounds
let (panel, view) = makeView(self.emojies.view, initialView, initialScreenRect, animated: animated)
panel.makeKeyAndOrderFront(nil)
panel.order(.below, relativeTo: initialView.window!.windowNumber)
self.panel = panel
panel.set(handler: { [weak self] _ in
self?.close(animated: true)
return .invoked
}, with: self, for: .Escape, priority: .modal)
panel.set(handler: { [weak self] _ in
self?.close(animated: true)
return .invoked
}, with: self, for: .Escape, priority: .modal)
panel.set(mouseHandler: { [weak view, weak self] _ in
if view?.mouseInside() == false {
self?.close(animated: true)
}
return .rejected
}, with: self, for: .leftMouseUp)
context.window.set(handler: { [weak self] _ in
self?.close(animated: true)
return .invoked
}, with: self, for: .Escape, priority: .modal)
var isInteracted: Bool = false
context.window.set(mouseHandler: { event in
isInteracted = true
return .rejected
}, with: self, for: .leftMouseDown, priority: .modal)
context.window.set(mouseHandler: { [weak self] event in
if isInteracted {
self?.close(animated: true)
}
let was = isInteracted
isInteracted = true
return !was ? .rejected : .invoked
}, with: self, for: .leftMouseUp, priority: .modal)
context.window.set(mouseHandler: { event in
isInteracted = true
return .rejected
}, with: self, for: .rightMouseDown, priority: .modal)
context.window.set(mouseHandler: { [weak self] event in
if isInteracted {
self?.close(animated: true)
}
let was = isInteracted
isInteracted = true
return !was ? .rejected : .invoked
}, with: self, for: .rightMouseUp, priority: .modal)
var skippedFirst: Bool = false
self.keyDisposable = context.window.keyWindowUpdater.start(next: { [weak self] value in
if !value && skippedFirst {
self?.close()
}
skippedFirst = true
})
view.initFake(initialView.frame, to: view.frame)
overlay.frame = context.window.bounds
context.window.contentView?.addSubview(overlay)
let ready = emojies.ready.get() |> take(1)
_ = ready.start(next: { [weak view, weak initialView, weak self] _ in
guard let view = view, let initialView = initialView else {
return
}
self?.initialPlayers = initialView.collect()
CATransaction.begin()
view.appearAnimated(from: initialView.frame, to: view.frame)
initialView.removeFromSuperview()
CATransaction.commit()
})
}
private func close(animated: Bool = false) {
self.overlay.removeFromSuperview()
self.context.window.removeAllHandlers(for: self)
self.panel?.removeAllHandlers(for: self)
AppMenu.closeAll()
var panel: Window? = self.panel
if animated {
panel?.contentView?.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { _ in
panel?.orderOut(nil)
panel = nil
})
} else {
self.panel?.orderOut(nil)
}
reactions = nil
}
}
| gpl-2.0 | e5f033aaee19be36d237a89bf431cc39 | 34.193211 | 210 | 0.566437 | 4.869581 | false | false | false | false |
dduan/swift | test/SILGen/objc_blocks_bridging.swift | 1 | 7567 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module %s | FileCheck %s
// REQUIRES: objc_interop
import Foundation
@objc class Foo {
// CHECK-LABEL: sil hidden [thunk] @_TToFC20objc_blocks_bridging3Foo3foo
// CHECK: [[COPY:%.*]] = copy_block %0
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb_dSi_dSi_XFo_dSi_dSi_
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[COPY]])
// CHECK: [[NATIVE:%.*]] = function_ref @_TFC20objc_blocks_bridging3Foo3foo{{.*}} : $@convention(method) (@owned @callee_owned (Int) -> Int, Int, @guaranteed Foo) -> Int
// CHECK: apply [[NATIVE]]([[BRIDGED]], %1, %2)
dynamic func foo(f: Int -> Int, x: Int) -> Int {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC20objc_blocks_bridging3Foo3bar
// CHECK: [[COPY:%.*]] = copy_block %0
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb_dCSo8NSString_aS__XFo_oSS_oSS_
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[COPY]])
// CHECK: [[NATIVE:%.*]] = function_ref @_TFC20objc_blocks_bridging3Foo3bar{{.*}} : $@convention(method) (@owned @callee_owned (@owned String) -> @owned String, @owned String, @guaranteed Foo) -> @owned String
// CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, %2)
dynamic func bar(f: String -> String, x: String) -> String {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC20objc_blocks_bridging3Foo3bas
// CHECK: [[COPY:%.*]] = copy_block %0
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb_dGSqCSo8NSString__aGSqS___XFo_oGSqSS__oGSqSS__
// CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[COPY]])
// CHECK: [[NATIVE:%.*]] = function_ref @_TFC20objc_blocks_bridging3Foo3bas{{.*}} : $@convention(method) (@owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>, @owned Optional<String>, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, %2)
dynamic func bas(f: String? -> String?, x: String?) -> String? {
return f(x)
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC20objc_blocks_bridging3Foo16cFunctionPointer
// CHECK: bb0([[F:%.*]] : $@convention(c) (Int) -> Int, [[X:%.*]] : $Int, [[SELF:%.*]] : $Foo):
// CHECK: [[NATIVE:%.*]] = function_ref @_TFC20objc_blocks_bridging3Foo16cFunctionPointer
// CHECK: apply [[NATIVE]]([[F]], [[X]], [[SELF]])
dynamic func cFunctionPointer(fp: @convention(c) Int -> Int, x: Int) -> Int {
fp(x)
}
// Blocks and C function pointers must not be reabstracted when placed in optionals.
// CHECK-LABEL: sil hidden [thunk] @_TToFC20objc_blocks_bridging3Foo7optFunc
// CHECK: [[COPY:%.*]] = copy_block %0
// CHECK: [[BLOCK:%.*]] = unchecked_enum_data [[COPY]]
// TODO: redundant reabstractions here
// CHECK: [[BLOCK_THUNK:%.*]] = function_ref @_TTRXFdCb_dCSo8NSString_aS__XFo_oSS_oSS_
// CHECK: [[BRIDGED:%.*]] = partial_apply [[BLOCK_THUNK]]([[BLOCK]])
// CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @_TTRXFo_oSS_oSS_XFo_iSS_iSS_
// CHECK: [[REABSTRACT:%.*]] = partial_apply [[REABSTRACT_THUNK]]([[BRIDGED]])
// CHECK: [[NATIVE:%.*]] = function_ref @_TFC20objc_blocks_bridging3Foo7optFunc{{.*}} : $@convention(method) (@owned Optional<String -> String>, @owned String, @guaranteed Foo) -> @owned Optional<String>
// CHECK: apply [[NATIVE]]
dynamic func optFunc(f: (String -> String)?, x: String) -> String? {
return f?(x)
}
// CHECK-LABEL: sil hidden @_TFC20objc_blocks_bridging3Foo19optCFunctionPointer
// CHECK: [[FP_BUF:%.*]] = unchecked_enum_data %0
dynamic func optCFunctionPointer(fp: (@convention(c) String -> String)?, x: String) -> String? {
return fp?(x)
}
}
// CHECK-LABEL: sil hidden @_TF20objc_blocks_bridging10callBlocks
func callBlocks(x: Foo,
f: Int -> Int,
g: String -> String,
h: String? -> String?
) -> (Int, String, String?, String?) {
// CHECK: [[FOO:%.*]] = class_method [volatile] %0 : $Foo, #Foo.foo!1.foreign
// CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]]
// CHECK: store %1 to [[F_BLOCK_CAPTURE]]
// CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @_TTRXFo_dSi_dSi_XFdCb_dSi_dSi_
// CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]]
// CHECK: [[F_BLOCK:%.*]] = copy_block [[F_STACK_BLOCK]]
// CHECK: apply [[FOO]]([[F_BLOCK]]
// CHECK: [[BAR:%.*]] = class_method [volatile] %0 : $Foo, #Foo.bar!1.foreign
// CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @_TTRXFo_oSS_oSS_XFdCb_dCSo8NSString_aS__
// CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]]
// CHECK: [[G_BLOCK:%.*]] = copy_block [[G_STACK_BLOCK]]
// CHECK: apply [[BAR]]([[G_BLOCK]]
// CHECK: [[BAS:%.*]] = class_method [volatile] %0 : $Foo, #Foo.bas!1.foreign
// CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @_TTRXFo_oGSqSS__oGSqSS__XFdCb_dGSqCSo8NSString__aGSqS___
// CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]]
// CHECK: [[H_BLOCK:%.*]] = copy_block [[H_STACK_BLOCK]]
// CHECK: apply [[BAS]]([[H_BLOCK]]
// CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString
// CHECK: enum $Optional<@convention(block) NSString -> NSString>, #Optional.some!enumelt.1, [[G_BLOCK]]
return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three"))
}
class Test: NSObject {
func blockTakesBlock() -> (Int -> Int) -> Int {}
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oXFo_dSi_dSi__dSi_XFdCb_dXFdCb_dSi_dSi__dSi_
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] :
// CHECK: [[CLOSURE:%.*]] = partial_apply {{%.*}}([[BLOCK_COPY]])
// CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CLOSURE]])
// CHECK: return [[RESULT]]
func clearDraggingItemImageComponentsProvider(x: NSDraggingItem) {
x.imageComponentsProvider = {}
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__oGSaPs9AnyObject___XFdCb__aGSqCSo7NSArray__
// CHECK: [[CONVERT:%.*]] = function_ref @_TFE10FoundationSa19_bridgeToObjectiveCfT_CSo7NSArray
// CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]]
// CHECK: return [[OPTIONAL]]
// CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__oSS_XFdCb__aGSqCSo8NSString__
// CHECK: [[CONVERT:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString
// CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]]
// CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]]
// CHECK: return [[OPTIONAL_BRIDGED]]
func bridgeNonnullBlockResult() {
nonnullStringBlockResult { return "test" }
}
// CHECK-LABEL: sil hidden @{{.*}}bridgeNoescapeBlock{{.*}}
func bridgeNoescapeBlock() {
// CHECK: function_ref @_TTRXFo___XFdCb___
noescapeBlockAlias { }
// CHECK: function_ref @_TTRXFo___XFdCb___
noescapeNonnullBlockAlias { }
}
| apache-2.0 | f2c43bffe3979c3920cbf0fb4de93326 | 53.833333 | 259 | 0.602484 | 3.423982 | false | false | false | false |
DrippApp/Dripp-iOS | Dripp/SettingsViewController.swift | 1 | 1299 | //
// SettingsViewController.swift
// Dripp
//
// Created by Henry Saniuk on 1/29/16.
// Copyright © 2016 Henry Saniuk. All rights reserved.
//
import UIKit
enum SettingsTableSection: Int {
case AccountSettings
case Other
case ContactUs
}
class SettingsViewController: UITableViewController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
_ = tableView.indexPathForSelectedRow?.row
if let section = SettingsTableSection(rawValue: indexPath.section) {
switch section {
case .AccountSettings:
AuthenticationManager.sharedManager.logout()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("loginViewController")
self.presentViewController(vc, animated: true, completion: nil)
print("log out")
case .ContactUs:
let email = "[email protected]"
let url = NSURL(string: "mailto:\(email)")
UIApplication.sharedApplication().openURL(url!)
default: break
}
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 1b4316ebbbbe8d534030fcf0e78564d0 | 31.45 | 101 | 0.630971 | 5.255061 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Steps4ImpactTests/LocalizationSpec.swift | 1 | 3111 | /**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import Quick
import Nimble
@testable import Steps4Impact
class LocalizationSpec: QuickSpec {
override func spec() {
describe("Localization") {
var englishLocalization: [String: String]!
var otherLocalizations: [[String: String]]!
let localizations = ["hi"]
beforeEach {
let englishFile = Bundle.main.url(
forResource: "Localizable",
withExtension: "strings",
subdirectory: nil,
localization: "en")! // swiftlint:disable:this force_unwrapping
englishLocalization = NSDictionary(
contentsOf: englishFile) as? [String: String]
otherLocalizations = localizations
.map { Bundle.main.url(
forResource: "Localizable",
withExtension: "strings",
subdirectory: nil,
localization: $0)! } // swiftlint:disable:this force_unwrapping
.compactMap { NSDictionary(contentsOf: $0) as? [String: String] }
}
it("should be able to parse localization file") {
expect(englishLocalization).toNot(beNil())
}
it("should have the right number of other localizations") {
expect(otherLocalizations.count).to(equal(localizations.count))
}
it("should have the same keys for all localizations") {
let englishKeysSet = Set(englishLocalization.keys)
for localization in otherLocalizations {
expect(localization.keys.count).to(equal(englishLocalization.keys.count))
let differenceSet = englishKeysSet.symmetricDifference(localization.keys)
expect(differenceSet).to(equal(Set([])))
}
}
}
}
}
| bsd-3-clause | 5cf3a8b7d1b259dc79cdf46d53fc4819 | 39.921053 | 83 | 0.702251 | 4.755352 | false | false | false | false |
efremidze/Alarm | Alarm/Controllers/ViewController.swift | 1 | 1084 | //
// ViewController.swift
// Alarm
//
// Created by Lasha Efremidze on 1/9/17.
// Copyright © 2017 Lasha Efremidze. All rights reserved.
//
import UIKit
import RevealingSplashView
class ViewController: UIViewController {
lazy var splashView: RevealingSplashView = { [unowned self] in
let image = UIImage(named: "weed")!
let view = RevealingSplashView(iconImage: image, iconInitialSize: image.size, backgroundColor: .weedGreen)
self.view.addSubview(view)
return view
}()
lazy var tableView: TableViewController = { [unowned self] in
let viewController = TableViewController(style: .grouped)
viewController.willMove(toParent: self)
self.addChild(viewController)
self.view.addSubview(viewController.view)
viewController.didMove(toParent: self)
viewController.view.constrainToEdges()
return viewController
}()
override func viewDidLoad() {
super.viewDidLoad()
_ = tableView
splashView.startAnimation()
}
}
| apache-2.0 | 92ee9f7ce1e1657ecacc1e6be78b5582 | 26.769231 | 114 | 0.657433 | 4.729258 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/ClientTests/Wallpaper/WallpaperDataServiceTests.swift | 2 | 6267 | // 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 XCTest
@testable import Client
class WallpaperDataServiceTests: XCTestCase, WallpaperTestDataProvider {
// MARK: - Properties
var networking: NetworkingMock!
// MARK: - Setup & Teardown
override func setUp() {
super.setUp()
networking = NetworkingMock()
}
override func tearDown() {
super.tearDown()
networking = nil
}
// MARK: - Test metadata functions
func testSuccessfullyExtractWallpaperMetadata_WithGoodData() async {
let data = getDataFromJSONFile(named: .goodData)
let expectedMetadata = getExpectedMetadata(for: .goodData)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testSuccessfullyExtractWallpaperMetadata_WithNoURL() async {
let data = getDataFromJSONFile(named: .noLearnMoreURL)
let expectedMetadata = getExpectedMetadata(for: .noLearnMoreURL)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testSuccessfullyExtractWallpaperMetadata_WithNoAvailabilityRange() async {
let data = getDataFromJSONFile(named: .noAvailabilityRange)
let expectedMetadata = getExpectedMetadata(for: .noAvailabilityRange)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testSuccessfullyExtractWallpaperMetadata_WithNoLocales() async {
let data = getDataFromJSONFile(named: .noLocales)
let expectedMetadata = getExpectedMetadata(for: .noLocales)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testSuccessfullyExtractWallpaperMetadata_WithOnlyStartingAvailability() async {
let data = getDataFromJSONFile(named: .availabilityStart)
let expectedMetadata = getExpectedMetadata(for: .availabilityStart)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testSuccessfullyExtractWallpaperMetadata_WithOnlyEndingAvailability() async {
let data = getDataFromJSONFile(named: .availabilityEnd)
let expectedMetadata = getExpectedMetadata(for: .availabilityEnd)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch {
XCTFail("We should not fail the extraction process, but did with error: \(error)")
}
}
func testFailToExtractWallpaperMetadata_WithBadLastUpdatedDate() async {
let data = getDataFromJSONFile(named: .badLastUpdatedDate)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
_ = try await subject.getMetadata()
XCTFail("We should fail the extraction process")
} catch let error {
XCTAssertEqual(error.localizedDescription,
"The data couldn’t be read because it isn’t in the correct format.",
"Unexpected decoding failure")
}
}
func testFailToExtractWallpaperMetadata_WithBadTextColor() async {
let data = getDataFromJSONFile(named: .badTextColor)
let expectedMetadata = getExpectedMetadata(for: .badTextColor)
networking.result = .success(data)
let subject = WallpaperDataService(with: networking)
do {
let actualMetadata = try await subject.getMetadata()
XCTAssertEqual(
actualMetadata,
expectedMetadata,
"The metadata that was decoded from data was not what was expected.")
} catch let error {
XCTFail("We should not fail the extraction process despite bad text color, but did with error: \(error)")
}
}
}
| mpl-2.0 | 32c76e91c71d7728a0f6d8dec58a6304 | 35.841176 | 117 | 0.633562 | 5.298646 | false | true | false | false |
azadibogolubov/InterestDestroyer | iOS Version/Interest Destroyer/Charts/Classes/Renderers/ChartXAxisRenderer.swift | 12 | 13128 | //
// ChartXAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/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
import UIKit
public class ChartXAxisRenderer: ChartAxisRendererBase
{
internal var _xAxis: ChartXAxis!
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer)
_xAxis = xAxis
}
public func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
var a = ""
let max = Int(round(xValAverageLength + Double(_xAxis.spaceBetweenLabels)))
for (var i = 0; i < max; i++)
{
a += "h"
}
let widthText = a as NSString
_xAxis.labelWidth = widthText.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]).width
_xAxis.labelHeight = _xAxis.labelFont.lineHeight
_xAxis.values = xValues
}
public override func renderAxisLabels(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled)
{
return
}
let yoffset = CGFloat(4.0)
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset)
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.5)
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom - _xAxis.labelHeight - yoffset)
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.offsetTop + yoffset)
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.offsetTop - _xAxis.labelHeight - yoffset)
drawLabels(context: context, pos: viewPortHandler.contentBottom + yoffset * 1.6)
}
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, _xAxis.axisLineWidth)
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
/// draws the x-labels on the specified y-position
internal func drawLabels(context context: CGContext?, pos: CGFloat)
{
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let labelAttrs = [NSFontAttributeName: _xAxis.labelFont,
NSForegroundColorAttributeName: _xAxis.labelTextColor,
NSParagraphStyleAttributeName: paraStyle]
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
var labelMaxSize = CGSize()
if (_xAxis.isWordWrapEnabled)
{
labelMaxSize.width = _xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
}
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
let label = _xAxis.values[i]
if (label == nil)
{
continue
}
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (viewPortHandler.isInBoundsX(position.x))
{
let labelns = label! as NSString
if (_xAxis.isAvoidFirstLastClippingEnabled)
{
// avoid clipping of the last
if (i == _xAxis.values.count - 1 && _xAxis.values.count > 1)
{
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
if (width > viewPortHandler.offsetRight * 2.0
&& position.x + width > viewPortHandler.chartWidth)
{
position.x -= width / 2.0
}
}
else if (i == 0)
{ // avoid clipping of the first
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
position.x += width / 2.0
}
}
drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, align: .Center, attributes: labelAttrs, constrainedToSize: labelMaxSize)
}
}
}
internal func drawLabel(context context: CGContext?, label: String, xIndex: Int, x: CGFloat, y: CGFloat, align: NSTextAlignment, attributes: [String: NSObject], constrainedToSize: CGSize)
{
let formattedLabel = _xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label
ChartUtils.drawMultilineText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), align: align, attributes: attributes, constrainedToSize: constrainedToSize)
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext?)
{
if (!_xAxis.isDrawGridLinesEnabled || !_xAxis.isEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, _xAxis.gridLineWidth)
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = _minX; i <= _maxX; i += _xAxis.axisLabelModulus)
{
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (position.x >= viewPortHandler.offsetLeft
&& position.x <= viewPortHandler.chartWidth)
{
_gridLineSegmentsBuffer[0].x = position.x
_gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_gridLineSegmentsBuffer[1].x = position.x
_gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext?)
{
var limitLines = _xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = 0; i < limitLines.count; i++)
{
let l = limitLines[i]
position.x = CGFloat(l.limit)
position.y = 0.0
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = position.x
_limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_limitLineSegmentsBuffer[1].x = position.x
_limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let add = CGFloat(4.0)
let xOffset: CGFloat = l.lineWidth
let yOffset: CGFloat = add / 2.0
if (l.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
CGContextRestoreGState(context)
}
} | apache-2.0 | 35b8b9cb5cb2ef8c7f4a398fb4dab411 | 37.728614 | 191 | 0.557511 | 5.778169 | false | false | false | false |
icylydia/PlayWithLeetCode | 406. Queue Reconstruction by Height/Solution.swift | 1 | 1048 | class Solution {
func reconstructQueue(_ people: [[Int]]) -> [[Int]] {
if people.count == 0 {
return people
}
let sorted = people.sorted {
if $0[0] == $1[0] {
return $0[1] < $1[1]
} else {
return $0[0] < $1[0]
}
}
var bucket = Array<[Int]?>(repeating: nil, count: people.count)
var acc = 0
var min = 0
var lastH = sorted[0][0]
for person in sorted {
if person[0] != lastH {
acc = 0
min = 0
lastH = person[0]
}
for i in min..<bucket.count {
if bucket[i] != nil {
continue
} else if person[1] == acc {
bucket[i] = person
min = i
acc += 1
break
} else {
acc += 1
}
}
}
return bucket.map{$0!}
}
} | mit | ed5f17e89558dc54602b6bd4dfb41312 | 26.605263 | 71 | 0.337786 | 4.440678 | false | false | false | false |
jgonfer/JGFLabRoom | JGFLabRoom/Controller/Security/KeychainViewController.swift | 1 | 8488 | //
// KeychainViewController.swift
// JGFLabRoom
//
// Created by Josep González on 27/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
import UIKit
//////////////////////////////////////////////////
// MARK: IMPORTANT: Stop running app in background
// We can stop running our app in background by setting "Application does not run in background" to "YES" in our Info.plist
// If we have a login view at the beginning of our app, this will be displayed if the user press the Home button
// MARK: IMPORTANT: Keychain Wrapper author
// https://github.com/jrendel/SwiftKeychainWrapper
//////////////////////////////////////////////////
class KeychainViewController: UIViewController {
@IBOutlet weak var userInput: CustomTextField!
@IBOutlet weak var passInput: CustomTextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var cleanLoginButton: UIButton!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var userLabel: UILabel!
@IBOutlet weak var passLabel: UILabel!
let kTagButtonCreateLogin = 10
let kTagButtonLogin = 11
let kTagTextFieldUser = 0
let kTagTextFieldPass = 1
// Old version of KeychainWrapper written in Objective-C
//let kcPassword = MyKeychainWrapper.myObjectForKey("v_Data")
// New version of KeychainWrapper written in Swift
//let kLoginKey = kSecValueData
let kLoginKey = "login"
// Old version of KeychainWrapper
//let MyKeychainWrapper = KeychainWrapper()
override func viewDidLoad() {
super.viewDidLoad()
setupController()
}
private func setupController() {
Utils.cleanBackButtonTitle(navigationController)
userInput.layer.borderColor = kColorPrimaryAlpha.CGColor
userInput.layer.borderWidth = 2
userInput.layer.masksToBounds = true
userInput.layer.cornerRadius = 8.0
userInput.leftTextMargin = 10
userInput.tag = kTagTextFieldUser
passInput.layer.borderColor = kColorPrimaryAlpha.CGColor
passInput.layer.borderWidth = 2
passInput.layer.masksToBounds = true
passInput.layer.cornerRadius = 8.0
passInput.leftTextMargin = 10
passInput.tag = kTagTextFieldPass
loginButton.layer.cornerRadius = 8.0
cleanLoginButton.layer.cornerRadius = 8.0
updateLoginInfo()
let tapGesture = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tapGesture)
}
private func updateLoginInfo() {
// Check if we've created our credentials
let hasLogin = userDefaults.boolForKey("keychainHasLogin")
if hasLogin {
// Setup UI for login state
loginButton.setTitle("Log In", forState: .Normal)
userLabel.text = userDefaults.valueForKey("keychainUsername") as? String
// Old version of KeychainWrapper
//let pass = MyKeychainWrapper.myObjectForKey(kLoginKey) as? String ?? ""
// New version of KeychainWrapper
guard let pass = KeychainWrapper.stringForKey(kLoginKey) else {
cleanLoginInfo(cleanLoginButton)
return
}
var passCoded = ""
if pass.characters.count > 0 {
for _ in 0...pass.characters.count-1 {
passCoded += "•"
}
}
passLabel.text = passCoded
loginButton.tag = kTagButtonLogin
resultLabel.text = "Try to Log In!"
} else {
// Setup UI for create credentials state
loginButton.setTitle("Create", forState: .Normal)
userLabel.text = "---"
passLabel.text = "---"
resultLabel.text = "Create your credentials"
loginButton.tag = kTagButtonCreateLogin
}
userInput.text = ""
passInput.text = ""
}
func dismissKeyboard() {
// Stop focus on both textfields
userInput.resignFirstResponder()
passInput.resignFirstResponder()
}
private func checkLogin() -> Bool {
let kcUsername = userDefaults.valueForKey("keychainUsername")
// Old version of KeychainWrapper
//let kcPassword = MyKeychainWrapper.myObjectForKey("v_Data")
// New version of KeychainWrapper
// Check if there is a Password set in our Keychain
guard let kcPassword = KeychainWrapper.stringForKey(kLoginKey) else {
return false
}
// Check if our credentials match what the user has written in the textfields
guard userInput.text! == kcUsername as? String && passInput.text! == kcPassword else {
return false
}
return true
}
@IBAction func logIn(sender: UIButton) {
dismissKeyboard()
let user = userInput.text!
let pass = passInput.text!
var message = ""
switch (user, pass) {
case ("", ""):
message = "Fill both fields"
case ("", pass):
message = "Fill Username field"
case (user, ""):
message = "Fill Password field"
default:
break
}
// Check if both textfields have text
guard !userInput.text!.isEmpty && !passInput.text!.isEmpty else {
resultLabel.text = message
resultLabel.textColor = kColorWrong
return
}
// Check if we are doing the login process
guard sender.tag == kTagButtonLogin else {
// If not we are creating new credentials to log in later
let hasLogin = userDefaults.boolForKey("keychainHasLogin")
if !hasLogin {
userDefaults.setValue(user, forKey: "keychainUsername")
}
userDefaults.setBool(true, forKey: "keychainHasLogin")
userDefaults.synchronize()
// Old version of KeychainWrapper
//MyKeychainWrapper.mySetObject(pass, forKey: kLoginKey)
//MyKeychainWrapper.writeToKeychain()
// New version of KeychainWrapper
guard KeychainWrapper.setString(pass, forKey: kLoginKey) else {
cleanLoginInfo(cleanLoginButton)
return
}
sender.tag = kTagButtonLogin
updateLoginInfo()
return
}
let success = self.checkLogin()
// Show result of the login process
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.resultLabel.alpha = 0
}, completion: { (Bool) -> Void in
UIView.animateWithDuration(0.75, animations: { () -> Void in
self.resultLabel.text = success ? "Success!" : "Failed"
self.resultLabel.textColor = success ? kColorPrimary : kColorWrong
self.resultLabel.alpha = 1
})
})
}
@IBAction func cleanLoginInfo(sender: UIButton) {
userDefaults.setBool(false, forKey: "keychainHasLogin")
userDefaults.setValue("", forKey: "keychainUsername")
userDefaults.synchronize()
// Old version of KeychainWrapper
//MyKeychainWrapper.mySetObject("", forKey: kLoginKey)
//MyKeychainWrapper.writeToKeychain()
// New version of KeychainWrapper
KeychainWrapper.removeObjectForKey(kLoginKey)
updateLoginInfo()
}
}
// MARK: UITextField Delegate
extension KeychainViewController: UITextFieldDelegate {
// We need to handle when the user press Next button or Done button
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Stop focus the current textfield
textField.resignFirstResponder()
// Check if the current textfield is the Password textfield with the Done button
guard textField.tag == kTagTextFieldPass else {
// If not we focus on the next textfield
if let view = view.viewWithTag(textField.tag + 1) {
view.becomeFirstResponder()
}
return true
}
// If it's the PAssword texfield we start the login process
logIn(loginButton)
return true
}
}
| mit | 294ceac40d2dbfb131015ac1c44c2f2b | 35.25641 | 123 | 0.597595 | 5.309136 | false | false | false | false |
ttlock/iOS_TTLock_Demo | Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUControlPoint.swift | 2 | 23645 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal enum SecureDFUOpCode : UInt8 {
case createObject = 0x01
case setPRNValue = 0x02
case calculateChecksum = 0x03
case execute = 0x04
case readObjectInfo = 0x06
case responseCode = 0x60
var code: UInt8 {
return rawValue
}
}
internal enum SecureDFUExtendedErrorCode : UInt8 {
case noError = 0x00
case wrongCommandFormat = 0x02
case unknownCommand = 0x03
case initCommandInvalid = 0x04
case fwVersionFailure = 0x05
case hwVersionFailure = 0x06
case sdVersionFailure = 0x07
case signatureMissing = 0x08
case wrongHashType = 0x09
case hashFailed = 0x0A
case wrongSignatureType = 0x0B
case verificationFailed = 0x0C
case insufficientSpace = 0x0D
var code: UInt8 {
return rawValue
}
var description: String {
switch self {
case .noError: return "No error"
case .wrongCommandFormat: return "Wrong command format"
case .unknownCommand: return "Unknown command"
case .initCommandInvalid: return "Init command was invalid"
case .fwVersionFailure: return "FW version check failed"
case .hwVersionFailure: return "HW version check failed"
case .sdVersionFailure: return "SD version check failed"
case .signatureMissing: return "Signature missing"
case .wrongHashType: return "Invalid hash type"
case .hashFailed: return "Hashing failed"
case .wrongSignatureType: return "Invalid signature type"
case .verificationFailed: return "Verification failed"
case .insufficientSpace: return "Insufficient space for upgrade"
}
}
}
internal enum SecureDFUProcedureType : UInt8 {
case command = 0x01
case data = 0x02
var description: String{
switch self{
case .command: return "Command"
case .data: return "Data"
}
}
}
internal enum SecureDFURequest {
case createCommandObject(withSize : UInt32)
case createDataObject(withSize : UInt32)
case readCommandObjectInfo
case readDataObjectInfo
case setPacketReceiptNotification(value : UInt16)
case calculateChecksumCommand
case executeCommand
var data : Data {
switch self {
case .createDataObject(let aSize):
var data = Data(bytes: [SecureDFUOpCode.createObject.code, SecureDFUProcedureType.data.rawValue])
data += aSize.littleEndian
return data
case .createCommandObject(let aSize):
var data = Data(bytes: [SecureDFUOpCode.createObject.code, SecureDFUProcedureType.command.rawValue])
data += aSize.littleEndian
return data
case .readCommandObjectInfo:
return Data(bytes: [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.command.rawValue])
case .readDataObjectInfo:
return Data(bytes: [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.data.rawValue])
case .setPacketReceiptNotification(let aSize):
var data = Data(bytes: [SecureDFUOpCode.setPRNValue.code])
data += aSize.littleEndian
return data
case .calculateChecksumCommand:
return Data(bytes: [SecureDFUOpCode.calculateChecksum.code])
case .executeCommand:
return Data(bytes: [SecureDFUOpCode.execute.code])
}
}
var description : String {
switch self {
case .createCommandObject(let size): return "Create Command Object (Op Code = 1, Type = 1, Size: \(size)b)"
case .createDataObject(let size): return "Create Data Object (Op Code = 1, Type = 2, Size: \(size)b)"
case .readCommandObjectInfo: return "Read Command Object Info (Op Code = 6, Type = 1)"
case .readDataObjectInfo: return "Read Data Object Info (Op Code = 6, Type = 2)"
case .setPacketReceiptNotification(let number):
return "Packet Receipt Notif Req (Op Code = 2, Value = \(number))"
case .calculateChecksumCommand: return "Calculate Checksum (Op Code = 3)"
case .executeCommand: return "Execute Object (Op Code = 4)"
}
}
}
internal enum SecureDFUResultCode : UInt8 {
case invalidCode = 0x0
case success = 0x01
case opCodeNotSupported = 0x02
case invalidParameter = 0x03
case insufficientResources = 0x04
case invalidObject = 0x05
case signatureMismatch = 0x06
case unsupportedType = 0x07
case operationNotpermitted = 0x08
case operationFailed = 0x0A
case extendedError = 0x0B
var description: String {
switch self {
case .invalidCode: return "Invalid code"
case .success: return "Success"
case .opCodeNotSupported: return "Operation not supported"
case .invalidParameter: return "Invalid parameter"
case .insufficientResources: return "Insufficient resources"
case .invalidObject: return "Invalid object"
case .signatureMismatch: return "Signature mismatch"
case .operationNotpermitted: return "Operation not permitted"
case .unsupportedType: return "Unsupported type"
case .operationFailed: return "Operation failed"
case .extendedError: return "Extended error"
}
}
var code: UInt8 {
return rawValue
}
}
internal typealias SecureDFUResponseCallback = (_ response : SecureDFUResponse?) -> Void
internal struct SecureDFUResponse {
let opCode : SecureDFUOpCode?
let requestOpCode : SecureDFUOpCode?
let status : SecureDFUResultCode?
let maxSize : UInt32?
let offset : UInt32?
let crc : UInt32?
let error : SecureDFUExtendedErrorCode?
init?(_ data: Data) {
let opCode : UInt8 = data[0]
let requestOpCode : UInt8 = data[1]
let status : UInt8 = data[2]
self.opCode = SecureDFUOpCode(rawValue: opCode)
self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode)
self.status = SecureDFUResultCode(rawValue: status)
// Parse response data in case of a success
if self.status == .success {
switch self.requestOpCode {
case .some(.readObjectInfo):
// The correct reponse for Read Object Info has additional 12 bytes: Max Object Size, Offset and CRC
let maxSize : UInt32 = data.subdata(in: 3 ..< 7).withUnsafeBytes { $0.pointee }
let offset : UInt32 = data.subdata(in: 7 ..< 11).withUnsafeBytes { $0.pointee }
let crc : UInt32 = data.subdata(in: 11 ..< 15).withUnsafeBytes { $0.pointee }
self.maxSize = maxSize
self.offset = offset
self.crc = crc
self.error = nil
case .some(.calculateChecksum):
// The correct reponse for Calculate Checksum has additional 8 bytes: Offset and CRC
let offset : UInt32 = data.subdata(in: 3 ..< 7).withUnsafeBytes { $0.pointee }
let crc : UInt32 = data.subdata(in: 7 ..< 11).withUnsafeBytes { $0.pointee }
self.maxSize = 0
self.offset = offset
self.crc = crc
self.error = nil
default:
self.maxSize = 0
self.offset = 0
self.crc = 0
self.error = nil
}
} else if self.status == .extendedError {
// If extended error was received, parse the extended error code
// The correct response for Read Error request has 4 bytes. The 4th byte is the extended error code
let error : UInt8 = data[3]
self.maxSize = 0
self.offset = 0
self.crc = 0
self.error = SecureDFUExtendedErrorCode(rawValue: error)
} else {
self.maxSize = 0
self.offset = 0
self.crc = 0
self.error = nil
}
if self.opCode != .responseCode || self.requestOpCode == nil || self.status == nil {
return nil
}
}
var description: String {
if status == .success {
switch requestOpCode {
case .some(.readObjectInfo):
// Max size for a command object is usually around 256. Let's say 1024, just to be sure. This is only for logging, so may be wrong.
return String(format: "\(maxSize! > 1024 ? "Data" : "Command") object info (Max size = \(maxSize!), Offset = \(offset!), CRC = %08X)", crc!)
case .some(.calculateChecksum):
return String(format: "Checksum (Offset = \(offset!), CRC = %08X)", crc!)
default:
// Other responses are either not logged, or logged by service or executor, so this 'default' should never be called
break
}
} else if status == .extendedError {
if let error = error {
return "Response (Op Code = \(requestOpCode!.rawValue), Status = \(status!.rawValue), Extended Error \(error.rawValue) = \(error.description))"
} else {
return "Response (Op Code = \(requestOpCode!.rawValue), Status = \(status!.rawValue), Unsupported Extended Error value)"
}
}
return "Response (Op Code = \(requestOpCode!.rawValue), Status = \(status!.rawValue))"
}
}
internal struct SecureDFUPacketReceiptNotification {
let opCode : SecureDFUOpCode?
let requestOpCode : SecureDFUOpCode?
let resultCode : SecureDFUResultCode?
let offset : UInt32
let crc : UInt32
init?(_ data: Data) {
let opCode : UInt8 = data[0]
let requestOpCode : UInt8 = data[1]
let resultCode : UInt8 = data[2]
self.opCode = SecureDFUOpCode(rawValue: opCode)
self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode)
self.resultCode = SecureDFUResultCode(rawValue: resultCode)
if self.opCode != .responseCode {
return nil
}
if self.requestOpCode != .calculateChecksum {
return nil
}
if self.resultCode != .success {
return nil
}
let offset : UInt32 = data.subdata(in: 3 ..< 7).withUnsafeBytes { $0.pointee }
let crc : UInt32 = data.subdata(in: 7 ..< 11).withUnsafeBytes { $0.pointee }
self.offset = offset
self.crc = crc
}
}
internal class SecureDFUControlPoint : NSObject, CBPeripheralDelegate, DFUCharacteristic {
internal var characteristic: CBCharacteristic
internal var logger: LoggerHelper
private var success: Callback?
private var response: SecureDFUResponseCallback?
private var proceed: ProgressCallback?
private var report: ErrorCallback?
internal var valid: Bool {
return characteristic.properties.isSuperset(of: [.write, .notify])
}
// MARK: - Initialization
required init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) {
self.characteristic = characteristic
self.logger = logger
}
func peripheralDidReceiveObject() {
proceed = nil
}
// MARK: - Characteristic API methods
/**
Enables notifications for the DFU Control Point characteristics.
Reports success or an error using callbacks.
- parameter success: Method called when notifications were successfully enabled.
- parameter report: Method called in case of an error.
*/
func enableNotifications(onSuccess success: Callback?, onError report: ErrorCallback?) {
// Save callbacks
self.success = success
self.response = nil
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
let controlPointUUID = characteristic.uuid.uuidString
logger.v("Enabling notifications for \(controlPointUUID)...")
logger.d("peripheral.setNotifyValue(true, for: \(controlPointUUID))")
peripheral.setNotifyValue(true, for: characteristic)
}
/**
Sends given request to the DFU Control Point characteristic. Reports success or an error
using callbacks.
- parameter request: Request to be sent.
- parameter success: Method called when peripheral reported with status success.
- parameter report: Method called in case of an error.
*/
func send(_ request: SecureDFURequest, onSuccess success: Callback?, onError report: ErrorCallback?) {
// Save callbacks and parameter
self.success = success
self.response = nil
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
let controlPointUUID = characteristic.uuid.uuidString
logger.v("Writing to characteristic \(controlPointUUID)...")
logger.d("peripheral.writeValue(0x\(request.data.hexString), for: \(controlPointUUID), type: .withResponse)")
peripheral.writeValue(request.data, for: characteristic, type: .withResponse)
}
/**
Sends given request to the DFU Control Point characteristic. Reports received data or an error
using callbacks.
- parameter request: Request to be sent.
- parameter response: Method called when peripheral sent a notification with requested data and status success.
- parameter report: Method called in case of an error.
*/
func send(_ request: SecureDFURequest, onResponse response: SecureDFUResponseCallback?, onError report: ErrorCallback?) {
// Save callbacks and parameter
self.success = nil
self.response = response
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
let controlPointUUID = characteristic.uuid.uuidString
logger.v("Writing to characteristic \(controlPointUUID)...")
logger.d("peripheral.writeValue(0x\(request.data.hexString), for: \(controlPointUUID), type: .withResponse)")
peripheral.writeValue(request.data, for: characteristic, type: .withResponse)
}
/**
Sets the callbacks used later on when a Packet Receipt Notification is received,
a device reported an error or the whole firmware has been sent.
Sending the firmware is done using DFU Packet characteristic.
- parameter success: Method called when peripheral reported with status success.
- parameter proceed: Method called the a PRN has been received and sending following data can be resumed.
- parameter report: Method called in case of an error.
*/
func waitUntilUploadComplete(onSuccess success: Callback?, onPacketReceiptNofitication proceed: ProgressCallback?, onError report: ErrorCallback?) {
// Save callbacks. The proceed callback will be called periodically whenever a packet receipt notification is received. It resumes uploading.
self.success = success
self.proceed = proceed
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
logger.a("Uploading firmware...")
logger.v("Sending firmware to DFU Packet characteristic...")
}
// MARK: - Peripheral Delegate callbacks
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
logger.e("Enabling notifications failed. Check if Service Changed service is enabled.")
logger.e(error!)
// Note:
// Error 253: Unknown ATT error.
// This most proably is caching issue. Check if your device had Service Changed characteristic (for non-bonded devices)
// in both app and bootloader modes. For bonded devices make sure it sends the Service Changed indication after connecting.
report?(.enablingControlPointFailed, "Enabling notifications failed")
} else {
logger.v("Notifications enabled for \(characteristic.uuid.uuidString)")
logger.a("Secure DFU Control Point notifications enabled")
success?()
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
// This method, according to the iOS documentation, should be called only after writing with response to a characteristic.
// However, on iOS 10 this method is called even after writing without response, which is a bug.
// The DFU Control Point characteristic always writes with response, in oppose to the DFU Packet, which uses write without response.
guard self.characteristic.isEqual(characteristic) else {
return
}
if error != nil {
logger.e("Writing to characteristic failed. Check if Service Changed service is enabled.")
logger.e(error!)
// Note:
// Error 3: Writing is not permitted.
// This most proably is caching issue. Check if your device had Service Changed characteristic (for non-bonded devices)
// in both app and bootloader modes. This is a specially a case in SDK 12.x, where it was disabled by default.
// For bonded devices make sure it sends the Service Changed indication after connecting.
report?(.writingCharacteristicFailed, "Writing to characteristic failed")
} else {
logger.i("Data written to \(characteristic.uuid.uuidString)")
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// Ignore updates received for other characteristics
guard self.characteristic.isEqual(characteristic) else {
return
}
if error != nil {
// This characteristic is never read, the error may only pop up when notification is received
logger.e("Receiving notification failed")
logger.e(error!)
report?(.receivingNotificationFailed, "Receiving notification failed")
} else {
// During the upload we may get either a Packet Receipt Notification, or a Response with status code
if proceed != nil {
if let prn = SecureDFUPacketReceiptNotification(characteristic.value!) {
proceed!(prn.offset) // The CRC is not verified after receiving a PRN, only the offset is
return
}
}
// Otherwise...
logger.i("Notification received from \(characteristic.uuid.uuidString), value (0x): \(characteristic.value!.hexString)")
// Parse response received
let dfuResponse = SecureDFUResponse(characteristic.value!)
if let dfuResponse = dfuResponse {
if dfuResponse.status == .success {
switch dfuResponse.requestOpCode! {
case .readObjectInfo, .calculateChecksum:
logger.a("\(dfuResponse.description) received")
response?(dfuResponse)
case .createObject, .setPRNValue, .execute:
// Don't log, executor or service will do it for us
success?()
default:
logger.a("\(dfuResponse.description) received")
success?()
}
} else if dfuResponse.status == .extendedError {
// An extended error was received
logger.e("Error \(dfuResponse.error!.code): \(dfuResponse.error!.description)")
// The returned errod code is incremented by 20 to match Secure DFU remote codes
report?(DFUError(rawValue: Int(dfuResponse.error!.code) + 20)!, dfuResponse.error!.description)
} else {
logger.e("Error \(dfuResponse.status!.code): \(dfuResponse.status!.description)")
// The returned errod code is incremented by 10 to match Secure DFU remote codes
report?(DFUError(rawValue: Int(dfuResponse.status!.code) + 10)!, dfuResponse.status!.description)
}
} else {
logger.e("Unknown response received: 0x\(characteristic.value!.hexString)")
report?(.unsupportedResponse, "Unsupported response received: 0x\(characteristic.value!.hexString)")
}
}
}
func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
// On iOS 11 and MacOS 10.13 or newer PRS are no longer required. Instead,
// the service checks if it can write write without response before writing
// and it will get this callback if the buffer is ready again.
proceed?(nil) // no offset available
}
}
| mit | b8b3da9d465655a0114062497690b783 | 43.782197 | 159 | 0.624741 | 5.07077 | false | false | false | false |
hejunbinlan/Operations | examples/Permissions/Pods/YapDatabaseExtensions/framework/YapDatabaseExtensions/Common/Write.swift | 1 | 44646 | //
// Created by Daniel Thorpe on 22/04/2015.
//
//
import YapDatabase
// MARK: - YapDatabaseTransaction
extension YapDatabaseReadWriteTransaction {
func writeAtIndex(index: YapDB.Index, object: AnyObject, metadata: AnyObject? = .None) {
if let metadata: AnyObject = metadata {
setObject(object, forKey: index.key, inCollection: index.collection, withMetadata: metadata)
}
else {
setObject(object, forKey: index.key, inCollection: index.collection)
}
}
}
extension YapDatabaseReadWriteTransaction {
/**
Writes a Persistable object conforming to NSCoding to the database inside the read write transaction.
:param: object An Object.
:returns: The Object.
*/
public func write<
Object
where
Object: NSCoding,
Object: Persistable>(object: Object) -> Object {
writeAtIndex(indexForPersistable(object), object: object)
return object
}
/**
Writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: object An ObjectWithObjectMetadata.
:returns: The ObjectWithObjectMetadata.
*/
public func write<
ObjectWithObjectMetadata
where
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata {
writeAtIndex(indexForPersistable(object), object: object, metadata: object.metadata)
return object
}
/**
Writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: object An ObjectWithValueMetadata.
:returns: The ObjectWithValueMetadata.
*/
public func write<
ObjectWithValueMetadata
where
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable,
ObjectWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ObjectWithValueMetadata.MetadataType.ArchiverType.ValueType == ObjectWithValueMetadata.MetadataType>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata {
writeAtIndex(indexForPersistable(object), object: object, metadata: object.metadata.archive)
return object
}
/**
Writes a Persistable value, conforming to Saveable to the database inside the read write transaction.
:param: value A Value.
:returns: The Value.
*/
public func write<
Value
where
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(value: Value) -> Value {
writeAtIndex(indexForPersistable(value), object: value.archive)
return value
}
/**
Writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: value A ValueWithValueMetadata.
:returns: The ValueWithValueMetadata.
*/
public func write<
ValueWithValueMetadata
where
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata {
writeAtIndex(indexForPersistable(value), object: value.archive, metadata: value.metadata.archive)
return value
}
/**
Writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: value A ValueWithObjectMetadata.
:returns: The ValueWithObjectMetadata.
*/
public func write<
ValueWithObjectMetadata
where
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata {
writeAtIndex(indexForPersistable(value), object: value.archive, metadata: value.metadata)
return value
}
}
extension YapDatabaseReadWriteTransaction {
/**
Writes a sequence of Persistable Object instances conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of Object instances.
:returns: An array of Object instances.
*/
public func write<
Objects, Object
where
Objects: SequenceType,
Objects.Generator.Element == Object,
Object: NSCoding,
Object: Persistable>(objects: Objects) -> [Object] {
return objects.map { self.write($0) }
}
/**
Writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: An array of ObjectWithObjectMetadata instances.
*/
public func write<
Objects, ObjectWithObjectMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithObjectMetadata,
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] {
return objects.map { self.write($0) }
}
/**
Writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: An array of ObjectWithValueMetadata instances.
*/
public func write<
Objects, ObjectWithValueMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithValueMetadata,
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] {
return objects.map { self.write($0) }
}
/**
Writes a sequence of Persistable Value instances conforming to Saveable to the database inside the read write transaction.
:param: objects A SequenceType of Value instances.
:returns: An array of Value instances.
*/
public func write<
Values, Value
where
Values: SequenceType,
Values.Generator.Element == Value,
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] {
return values.map { self.write($0) }
}
/**
Writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithValueMetadata instances.
:returns: An array of ValueWithValueMetadata instances.
*/
public func write<
Values, ValueWithValueMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithValueMetadata,
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values) -> [ValueWithValueMetadata] {
return values.map { self.write($0) }
}
/**
Writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithObjectMetadata instances.
:returns: An array of ValueWithObjectMetadata instances.
*/
public func write<
Values, ValueWithObjectMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithObjectMetadata,
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] {
return values.map { self.write($0) }
}
}
// MARK: - YapDatabaseConnection
extension YapDatabaseConnection {
/**
Synchonously writes a Persistable object conforming to NSCoding to the database using the connection.
:param: object An Object.
:returns: The Object.
*/
public func write<
Object
where
Object: NSCoding,
Object: Persistable>(object: Object) -> Object {
return write { $0.write(object) }
}
/**
Synchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: object An ObjectWithObjectMetadata.
:returns: The ObjectWithObjectMetadata.
*/
public func write<
ObjectWithObjectMetadata
where
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata {
return write { $0.write(object) }
}
/**
Synchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: object An ObjectWithValueMetadata.
:returns: The ObjectWithValueMetadata.
*/
public func write<
ObjectWithValueMetadata
where
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata {
return write { $0.write(object) }
}
/**
Synchonously writes a Persistable value conforming to Saveable to the database using the connection.
:param: value A Value.
:returns: The Value.
*/
public func write<
Value
where
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(value: Value) -> Value {
return write { $0.write(value) }
}
/**
Synchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: value A ValueWithValueMetadata.
:returns: The ValueWithValueMetadata.
*/
public func write<
ValueWithValueMetadata
where
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata {
return write { $0.write(value) }
}
/**
Synchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: value A ValueWithObjectMetadata.
:returns: The ValueWithObjectMetadata.
*/
public func write<
ValueWithObjectMetadata
where
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata {
return write { $0.write(value) }
}
}
extension YapDatabaseConnection {
/**
Asynchonously writes a Persistable object conforming to NSCoding to the database using the connection.
:param: object An Object.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the Object.
*/
public func asyncWrite<
Object
where
Object: NSCoding,
Object: Persistable>(object: Object, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object) -> Void) {
asyncWrite({ $0.write(object) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: object An ObjectWithObjectMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ObjectWithObjectMetadata.
*/
public func asyncWrite<
ObjectWithObjectMetadata
where
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithObjectMetadata) -> Void) {
asyncWrite({ $0.write(object) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: object An ObjectWithValueMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ObjectWithValueMetadata.
*/
public func asyncWrite<
ObjectWithValueMetadata
where
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithValueMetadata) -> Void) {
asyncWrite({ $0.write(object) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value conforming to Saveable to the database using the connection.
:param: value A Value.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the Value.
*/
public func asyncWrite<
Value
where
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(value: Value, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value) -> Void) {
asyncWrite({ $0.write(value) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: value An ValueWithValueMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ValueWithValueMetadata.
*/
public func asyncWrite<
ValueWithValueMetadata
where
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithValueMetadata) -> Void) {
asyncWrite({ $0.write(value) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: value An ValueWithObjectMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ValueWithObjectMetadata.
*/
public func asyncWrite<
ValueWithObjectMetadata
where
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithObjectMetadata) -> Void) {
asyncWrite({ $0.write(value) }, queue: queue, completion: completion)
}
}
extension YapDatabaseConnection {
/**
Synchonously writes Persistable objects conforming to NSCoding to the database using the connection.
:param: objects A SequenceType of Object instances.
:returns: An array of Object instances.
*/
public func write<
Objects, Object
where
Objects: SequenceType,
Objects.Generator.Element == Object,
Object: NSCoding,
Object: Persistable>(objects: Objects) -> [Object] {
return write { $0.write(objects) }
}
/**
Synchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: An array of ObjectWithObjectMetadata instances.
*/
public func write<
Objects, ObjectWithObjectMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithObjectMetadata,
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] {
return write { $0.write(objects) }
}
/**
Synchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: An array of ObjectWithValueMetadata instances.
*/
public func write<
Objects, ObjectWithValueMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithValueMetadata,
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] {
return write { $0.write(objects) }
}
/**
Synchonously writes Persistable values conforming to Saveable to the database using the connection.
:param: values A SequenceType of Value instances.
:returns: An array of Object instances.
*/
public func write<
Values, Value
where
Values: SequenceType,
Values.Generator.Element == Value,
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] {
return write { $0.write(values) }
}
/**
Synchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithValueMetadata instances.
:returns: An array of ValueWithValueMetadata instances.
*/
public func write<
Values, ValueWithValueMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithValueMetadata,
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values) -> [ValueWithValueMetadata] {
return write { $0.write(values) }
}
/**
Synchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithObjectMetadata instances.
:returns: An array of ValueWithObjectMetadata instances.
*/
public func write<
Values, ValueWithObjectMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithObjectMetadata,
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] {
return write { $0.write(values) }
}
}
extension YapDatabaseConnection {
/**
Asynchonously writes Persistable objects conforming to NSCoding to the database using the connection.
:param: objects A SequenceType of Object instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of Object instances.
*/
public func asyncWrite<
Objects, Object
where
Objects: SequenceType,
Objects.Generator.Element == Object,
Object: NSCoding,
Object: Persistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) {
asyncWrite({ $0.write(objects) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of ObjectWithObjectMetadata instances.
*/
public func asyncWrite<
Objects, ObjectWithObjectMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithObjectMetadata,
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithObjectMetadata]) -> Void) {
asyncWrite({ $0.write(objects) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of ObjectWithValueMetadata instances.
*/
public func asyncWrite<
Objects, ObjectWithValueMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithValueMetadata,
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithValueMetadata]) -> Void) {
asyncWrite({ $0.write(objects) }, queue: queue, completion: completion)
}
/**
Asynchonously writes Persistable values conforming to Saveable to the database using the connection.
:param: values A SequenceType of Value instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of Value instances.
*/
public func asyncWrite<
Values, Value
where
Values: SequenceType,
Values.Generator.Element == Value,
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) {
asyncWrite({ $0.write(values) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithObjectMetadata instances.
:returns: An array of ValueWithObjectMetadata instances.
*/
public func asyncWrite<
Values, ValueWithObjectMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithObjectMetadata,
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithObjectMetadata]) -> Void) {
asyncWrite({ $0.write(values) }, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithValueMetadata instances.
:returns: An array of ValueWithValueMetadata instances.
*/
public func asyncWrite<
Values, ValueWithValueMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithValueMetadata,
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.MetadataType: NSCoding,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithValueMetadata]) -> Void) {
asyncWrite({ $0.write(values) }, queue: queue, completion: completion)
}
}
// MARK: - YapDatabase
extension YapDatabase {
/**
Synchonously writes a Persistable object conforming to NSCoding to the database using a new connection.
:param: object An Object.
:returns: The Object.
*/
public func write<Object where Object: NSCoding, Object: Persistable>(object: Object) -> Object {
return newConnection().write(object)
}
/**
Synchonously writes a Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: object An ObjectWithObjectMetadata.
:returns: The ObjectWithObjectMetadata.
*/
public func write<
ObjectWithObjectMetadata
where
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata) -> ObjectWithObjectMetadata {
return newConnection().write(object)
}
/**
Synchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: object An ObjectWithValueMetadata.
:returns: The ObjectWithValueMetadata.
*/
public func write<
ObjectWithValueMetadata
where
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata) -> ObjectWithValueMetadata {
return newConnection().write(object)
}
/**
Synchonously writes a Persistable value conforming to Saveable to the database using a new connection.
:param: value A Value.
:returns: The Value.
*/
public func write<
Value
where
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(value: Value) -> Value {
return newConnection().write(value)
}
/**
Synchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: value A ValueWithValueMetadata.
:returns: The ValueWithValueMetadata.
*/
public func write<
ValueWithValueMetadata
where
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata) -> ValueWithValueMetadata {
return newConnection().write(value)
}
/**
Synchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: value A ValueWithObjectMetadata.
:returns: The ValueWithObjectMetadata.
*/
public func write<
ValueWithObjectMetadata
where
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata) -> ValueWithObjectMetadata {
return newConnection().write(value)
}
}
extension YapDatabase {
/**
Asynchonously writes a Persistable object conforming to NSCoding to the database using a new connection.
:param: object An Object.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the Object.
*/
public func asyncWrite<
Object
where
Object: NSCoding,
Object: Persistable>(object: Object, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Object) -> Void) {
newConnection().asyncWrite(object, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable object with metadata, both conforming to NSCoding to the database using a new connection.
:param: object An ObjectWithObjectMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ObjectWithObjectMetadata.
*/
public func asyncWrite<
ObjectWithObjectMetadata
where
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(object: ObjectWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithObjectMetadata) -> Void) {
newConnection().asyncWrite(object, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable object, conforming to NSCoding, with metadata value type to the database using a new connection.
:param: object An ObjectWithValueMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ObjectWithValueMetadata.
*/
public func asyncWrite<
ObjectWithValueMetadata
where
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable>(object: ObjectWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ObjectWithValueMetadata) -> Void) {
newConnection().asyncWrite(object, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value conforming to Saveable to the database using a new connection.
:param: value A Value.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the Value.
*/
public func asyncWrite<
Value
where
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(value: Value, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (Value) -> Void) {
newConnection().asyncWrite(value, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value with a metadata value, both conforming to Saveable, to the database using a new connection.
:param: object An ValueWithValueMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ValueWithValueMetadata.
*/
public func asyncWrite<
ValueWithValueMetadata
where
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.MetadataType.ArchiverType.ValueType == ValueWithValueMetadata.MetadataType>(value: ValueWithValueMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithValueMetadata) -> Void) {
newConnection().asyncWrite(value, queue: queue, completion: completion)
}
/**
Asynchonously writes a Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database using a new connection.
:param: object An ValueWithObjectMetadata.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives the ValueWithObjectMetadata.
*/
public func asyncWrite<
ValueWithObjectMetadata
where
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(value: ValueWithObjectMetadata, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (ValueWithObjectMetadata) -> Void) {
newConnection().asyncWrite(value, queue: queue, completion: completion)
}
}
extension YapDatabase {
/**
Synchonously writes Persistable objects conforming to NSCoding to the database using a new connection.
:param: objects A SequenceType of Object instances.
:returns: An array of Object instances.
*/
public func write<
Objects, Object
where
Objects: SequenceType,
Objects.Generator.Element == Object,
Object: NSCoding,
Object: Persistable>(objects: Objects) -> [Object] {
return newConnection().write(objects)
}
/**
Synchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: An array of ObjectWithObjectMetadata instances.
*/
public func write<
Objects, ObjectWithObjectMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithObjectMetadata,
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects) -> [ObjectWithObjectMetadata] {
return newConnection().write(objects)
}
/**
Synchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: An array of ObjectWithValueMetadata instances.
*/
public func write<
Objects, ObjectWithValueMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithValueMetadata,
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ObjectWithValueMetadata.MetadataType.ArchiverType.ValueType == ObjectWithValueMetadata.MetadataType,
ObjectWithValueMetadata: ValueMetadataPersistable>(objects: Objects) -> [ObjectWithValueMetadata] {
return newConnection().write(objects)
}
/**
Synchonously writes Persistable values conforming to Saveable to the database using a new connection.
:param: values A SequenceType of Value instances.
:returns: An array of Object instances.
*/
public func write<
Values, Value
where
Values: SequenceType,
Values.Generator.Element == Value,
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(values: Values) -> [Value] {
return newConnection().write(values)
}
/**
Synchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithValueMetadata instances.
:returns: An array of ValueWithValueMetadata instances.
*/
public func write<
Values, ValueWithValueMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithValueMetadata,
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.MetadataType.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values) -> [ValueWithValueMetadata] {
return newConnection().write(values)
}
/**
Synchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithObjectMetadata instances.
:returns: An array of ValueWithObjectMetadata instances.
*/
public func write<
Values, ValueWithObjectMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithObjectMetadata,
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values) -> [ValueWithObjectMetadata] {
return newConnection().write(values)
}
}
extension YapDatabase {
/**
Asynchonously writes Persistable objects conforming to NSCoding to the database using a new connection.
:param: values A SequenceType of Object instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of Object instances.
*/
public func asyncWrite<
Objects, Object
where
Objects: SequenceType,
Objects.Generator.Element == Object,
Object: NSCoding,
Object: Persistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Object]) -> Void) {
newConnection().asyncWrite(objects, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable object with metadata, both conforming to NSCoding to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithObjectMetadata instances.
:returns: An array of ObjectWithObjectMetadata instances.
*/
public func asyncWrite<
Objects, ObjectWithObjectMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithObjectMetadata,
ObjectWithObjectMetadata: NSCoding,
ObjectWithObjectMetadata: ObjectMetadataPersistable>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithObjectMetadata]) -> Void) {
newConnection().asyncWrite(objects, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable object, conforming to NSCoding, with metadata value type to the database inside the read write transaction.
:param: objects A SequenceType of ObjectWithValueMetadata instances.
:returns: An array of ObjectWithValueMetadata instances.
*/
public func asyncWrite<
Objects, ObjectWithValueMetadata
where
Objects: SequenceType,
Objects.Generator.Element == ObjectWithValueMetadata,
ObjectWithValueMetadata: NSCoding,
ObjectWithValueMetadata: ValueMetadataPersistable,
ObjectWithValueMetadata.MetadataType: Archiver,
ObjectWithValueMetadata.MetadataType.ArchiverType.ValueType == ObjectWithValueMetadata.MetadataType>(objects: Objects, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ObjectWithValueMetadata]) -> Void) {
newConnection().asyncWrite(objects, queue: queue, completion: completion)
}
/**
Asynchonously writes Persistable values conforming to Saveable to the database using a new connection.
:param: values A SequenceType of Value instances.
:param: queue A dispatch_queue_t, defaults to the main queue.
:param: completion A closure which receives an array of Value instances.
*/
public func asyncWrite<
Values, Value
where
Values: SequenceType,
Values.Generator.Element == Value,
Value: Saveable,
Value: Persistable,
Value.ArchiverType: NSCoding,
Value.ArchiverType.ValueType == Value>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([Value]) -> Void) {
newConnection().asyncWrite(values, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable value with a metadata value, both conforming to Saveable, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithValueMetadata instances.
:returns: An array of ValueWithValueMetadata instances.
*/
public func asyncWrite<
Values, ValueWithValueMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithValueMetadata,
ValueWithValueMetadata: Saveable,
ValueWithValueMetadata: ValueMetadataPersistable,
ValueWithValueMetadata.ArchiverType: NSCoding,
ValueWithValueMetadata.ArchiverType.ValueType == ValueWithValueMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithValueMetadata]) -> Void) {
newConnection().asyncWrite(values, queue: queue, completion: completion)
}
/**
Asynchonously writes a sequence of Persistable value, conforming to Saveable with a metadata object conforming to NSCoding, to the database inside the read write transaction.
:param: objects A SequenceType of ValueWithObjectMetadata instances.
:returns: An array of ValueWithObjectMetadata instances.
*/
public func asyncWrite<
Values, ValueWithObjectMetadata
where
Values: SequenceType,
Values.Generator.Element == ValueWithObjectMetadata,
ValueWithObjectMetadata: Saveable,
ValueWithObjectMetadata: ObjectMetadataPersistable,
ValueWithObjectMetadata.MetadataType: NSCoding,
ValueWithObjectMetadata.ArchiverType: NSCoding,
ValueWithObjectMetadata.ArchiverType.ValueType == ValueWithObjectMetadata>(values: Values, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: ([ValueWithObjectMetadata]) -> Void) {
newConnection().asyncWrite(values, queue: queue, completion: completion)
}
}
| mit | cb579dd69186ebe69d986f2dc7c3a880 | 40.725234 | 238 | 0.710859 | 5.058464 | false | false | false | false |
macc704/iKF | iKF/KFCanvasView.swift | 1 | 5175 | //
// KFCanvasView.swift
// iKF
//
// Created by Yoshiaki Matsuzawa on 2014-07-30.
// Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved.
//
import UIKit
class KFCanvasView: UIView, UIScrollViewDelegate{
private let scrollView = UIScrollView();
private let layerContainerView = UIView();
let draggingLayer = KFLayerView();
let windowsLayer = KFLayerView();
let noteLayer = KFLayerView();
let connectionLayer = KFConnectionLayer();
let drawingLayer = KFLayerView();
var doubleTapHandler:((CGPoint)->())?;
private var halo:KFHalo?;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init(frame: KFAppUtils.DEFAULT_RECT());
//basic structure
self.addSubview(scrollView);
scrollView.addSubview(layerContainerView);
scrollView.delegate = self;
//scrollView.decelerationRate = UIScrollViewDecelerationRateFast; //normal
//scrollView.canCancelContentTouches = false;//important for subview recognition
scrollView.delaysContentTouches = false;//important for subview recognition
//add layers by reversed order
//self.drawingLayer.userInteractionEnabled = true;//not necessary
layerContainerView.addSubview(self.drawingLayer);
//layerContainerView.addSubview(connectionLayer);
self.noteLayer.layer.addSublayer(connectionLayer);
layerContainerView.addSubview(self.noteLayer);
layerContainerView.addSubview(self.windowsLayer);
layerContainerView.addSubview(self.draggingLayer);
//halo disappear
let singleRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:");
singleRecognizer.numberOfTapsRequired = 1;
layerContainerView.addGestureRecognizer(singleRecognizer);
let doubleRecognizer = UITapGestureRecognizer(target: self, action: "handleDoubleTap:");
doubleRecognizer.numberOfTapsRequired = 2;
layerContainerView.addGestureRecognizer(doubleRecognizer);
singleRecognizer.requireGestureRecognizerToFail(doubleRecognizer);
}
func setSize(size:CGSize){
self.frame.size = size;
self.scrollView.frame.size = size;
}
func putToDraggingLayer(view:KFPostRefView){
if(view.superview == noteLayer){
draggingLayer.addSubview(view);
}
}
func pullBackFromDraggingLayer(view:KFPostRefView){
if(view.superview == draggingLayer){
view.removeFromSuperview();
if(view is KFDrawingRefView){
drawingLayer.addSubview(view);
}else{
noteLayer.addSubview(view);
}
}
}
func setCanvasSize(width:CGFloat, height:CGFloat){
layerContainerView.frame = CGRectMake(0, 0, width, height);
drawingLayer.frame = layerContainerView.frame;
connectionLayer.frame = layerContainerView.frame;
noteLayer.frame = layerContainerView.frame;
windowsLayer.frame = layerContainerView.frame;
draggingLayer.frame = layerContainerView.frame;
scrollView.contentSize = layerContainerView.frame.size;
scrollView.maximumZoomScale = 4.0;
scrollView.minimumZoomScale = 0.2;
}
func clearViews(){
self.removeChildren(self.drawingLayer);
self.removeChildren(self.noteLayer);
self.connectionLayer.clearAllConnections();
}
private func removeChildren(view:UIView){
for subview in view.subviews {
subview.removeFromSuperview();
}
}
func findDropTargetWindow(view:UIView) -> KFDropTargetView?{
return windowsLayer.findDropTarget(view);
}
/* halo management */
func handleDoubleTap(recognizer: UIGestureRecognizer){
let loc = recognizer.locationInView(layerContainerView);
self.doubleTapHandler?(loc);
}
func handleSingleTap(recognizer: UIGestureRecognizer){
if(halo != nil){
hideHalo();
}else{
//showhalo
}
}
func showHalo(newHalo:KFHalo){
self.hideHalo();
self.halo = newHalo;
self.halo!.showWithAnimation(self.layerContainerView);
}
func hideHalo(){
if(self.halo != nil){
self.halo!.removeFromSuperview();
self.halo = nil;
}
}
/* Scrollling */
func translateToCanvas(fromViewP:CGPoint) -> CGPoint{
let offset = scrollView.contentOffset;
let scale = scrollView.zoomScale;
return CGPointMake((fromViewP.x + offset.x) / scale, (fromViewP.y + offset.y) / scale);
}
func suppressScroll(){
self.scrollView.canCancelContentTouches = false;
}
func unlockSuppressScroll(){
self.scrollView.canCancelContentTouches = true;
}
/* Scrollling Enabling (only one method) */
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
return layerContainerView;
}
}
| gpl-2.0 | eb1c6050ad23e3a0b1ccbd402c8356c6 | 30.944444 | 96 | 0.644831 | 5.004836 | false | false | false | false |
JPIOS/JDanTang | JDanTang/JDanTang/Class/Tool(工具)/Common/SelectSexVC.swift | 1 | 2714 | //
// SelectSexVC.swift
// JDanTang
//
// Created by 家朋 on 2017/6/13.
// Copyright © 2017年 mac_KY. All rights reserved.
//
import UIKit
/// 使用代理回调数据
protocol SelectSexDelegate :NSObjectProtocol {
func clickSexName(sexName:String)
}
class SelectSexVC: BaseVC,UITableViewDelegate,UITableViewDataSource {
open var sexName:String?
var JTab:UITableView?
var sourceData:NSMutableArray?
var delegate :SelectSexDelegate?
override func viewDidLoad() {
super.viewDidLoad()
loadComment()
loadSubView()
}
func loadComment() {
title = "性别选择"
sourceData = NSMutableArray.init()
let item1:MoreItem = MoreItem()
item1.isArrow = true
item1.title = "男孩"
let item2:MoreItem = MoreItem()
item2.isArrow = true
item2.title = "女孩"
sourceData?.add(item1)
sourceData?.add(item2)
}
func loadSubView() {
JTab = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 64))
view.addSubview(JTab!)
JTab?.delegate = self
JTab?.dataSource = self
JTab?.tableFooterView = UIView()
JTab?.backgroundColor = JGlobalColor()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 2
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cellID:String = "cellID"
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
if cell == nil {
cell = UITableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: cellID)
}
let item :MoreItem = sourceData?.object(at: indexPath.row) as! MoreItem
cell?.textLabel?.text = item.title
cell?.detailTextLabel?.text = item.subTitle
cell?.textLabel?.textColor = RGB(r: 51, g: 51, b: 51)
if item.title == sexName {
//不存在重用 简单处理咯--偷懒一下 😜
cell?.textLabel?.textColor = UIColor.red
}
return cell!
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item :MoreItem = sourceData?.object(at: indexPath.row) as! MoreItem
delegate?.clickSexName(sexName: item.title!)
navigationController?.popViewController(animated: true)
}
}
| apache-2.0 | 32cb05ae90b7d4d627724f3447292fcb | 28.054945 | 112 | 0.613843 | 4.341544 | false | false | false | false |
pardel/PAKeychainService | PAKeychainService.swift | 1 | 2053 | //
// KeychainService.swift
//
// Created by Paul on 07/10/2014.
//
import Foundation
import Security
let kSecClassValue = kSecClass as NSString
let kSecAttrAccountValue = kSecAttrAccount as NSString
let kSecValueDataValue = kSecValueData as NSString
let kSecClassGenericPasswordValue = kSecClassGenericPassword as NSString
let kSecAttrServiceValue = kSecAttrService as NSString
let kSecMatchLimitValue = kSecMatchLimit as NSString
let kSecReturnDataValue = kSecReturnData as NSString
let kSecMatchLimitOneValue = kSecMatchLimitOne as NSString
private let _sharedService = PAKeychainService()
class PAKeychainService: NSObject {
class func sharedService() -> PAKeychainService {
return _sharedService
}
func saveContentsForKey(value: String, key: String) {
let dataFromString = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let keychainQuery = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, serviceString(), key, dataFromString],
forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])
SecItemDelete(keychainQuery as CFDictionaryRef)
SecItemAdd(keychainQuery as CFDictionaryRef, nil)
}
func getContentsOfKey(key: String) -> String? {
let keychainQuery = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, serviceString(), key, kCFBooleanTrue, kSecMatchLimitOneValue],
forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])
// we do the read in Objective-C to work around a Swift compiler optimization bug (as of Xcode 6.2 (6C101) which resulted in no data being returned
return KeychainObjCWrapper.keychainValueForDictionary(keychainQuery)
}
private func serviceString() -> String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleIdentifier") as String
}
}
| mit | 9b8d5e53eab1c1b4ccfaafd1cb8a06f9 | 34.396552 | 178 | 0.74038 | 5.7507 | false | false | false | false |
biohazardlover/ByTrain | ByTrain/NetworkController.swift | 1 | 70495 |
import Foundation
import AFNetworking
typealias NetworkControllerCompletionHandler = (NetworkController?, Any?, NSError?) -> Void
class NetworkController: NSObject, URLSessionDelegate {
private var session: Foundation.URLSession!
private var requestSerializer: AFHTTPRequestSerializer!
override init() {
super.init()
let configuration = URLSessionConfiguration.default
session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
requestSerializer = AFHTTPRequestSerializer()
}
func invalidate() {
session.invalidateAndCancel()
}
// MARK: - Train
/// 获取列车
///
/// :param: fromStation 出发站
/// :param: toStation 到达站
/// :param: departureDate 出发日
/// :param: isStudent 是否是学生
/// :param: completionHandler 回调
func retrieveTrains(fromStation: Station, toStation: Station, departureDate: Date, isStudent: Bool, path: String = "leftTicket/query", completionHandler: NetworkControllerCompletionHandler?) {
let URLString = NSString(format: "https://kyfw.12306.cn/otn/%@?leftTicketDTO.train_date=%@&leftTicketDTO.from_station=%@&leftTicketDTO.to_station=%@&purpose_codes=%@", path, DateFormatter.string(from: departureDate, withFormat: "yyyy-MM-dd"), emptyIfNil(fromStation.stationCode), emptyIfNil(toStation.stationCode), isStudent ? "0X00" : "ADULT") as String
let request = try! requestSerializer.request(withMethod: "GET", urlString: URLString , parameters: nil, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
if let jsonData = data {
let json = try? JSONSerialization.jsonObject(with: jsonData) as? [AnyHashable: Any]
let status = json??["status"] as? NSNumber
if status?.boolValue == false {
if let path = json??["c_url"] as? String {
self?.retrieveTrains(fromStation: fromStation, toStation: toStation, departureDate: departureDate, isStudent: isStudent, path: path, completionHandler: completionHandler)
return
}
}
}
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [[AnyHashable: Any]]
if let trains = self?.trainsWithJSON(json as AnyObject?) {
for var train in trains {
train.fromStation = fromStation
train.toStation = toStation
train.departureDate = departureDate
}
completionHandler?(self, trains, error)
} else {
completionHandler?(self, nil, error)
}
})
task.resume()
}
/// 获取票价
///
/// :param: train 列车
/// :param: departureDate 出发日
/// :param: handler 回调
func retrieveTicketPrice(train: Train, departureDate: Date, completionHandler handler: NetworkControllerCompletionHandler?) {
let URLString = NSString(format: "https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no=%@&from_station_no=%@&to_station_no=%@&seat_types=%@&train_date=%@", emptyIfNil(train.train_no), emptyIfNil(train.from_station_no), emptyIfNil(train.to_station_no), emptyIfNil(train.seat_types), DateFormatter.string(from: departureDate, withFormat: "yyyy-MM-dd")) as String
let request = try! requestSerializer.request(withMethod: "GET", urlString: URLString, parameters: nil, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
if let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any] {
for var seatType in train.allSeatTypes {
if let seatTypeCode2 = seatType.seatTypeCode2 {
seatType.price = json[seatTypeCode2] as? String
}
}
}
handler?(self, train, error)
})
task.resume()
}
func trainsWithJSON(_ json: AnyObject?) -> [Train] {
var trains = [Train]()
if let jsonTrains = json as? [[AnyHashable: Any]] {
for jsonTrain in jsonTrains {
var train = Train()
let queryLeftNewDTO = jsonTrain["queryLeftNewDTO"] as? [AnyHashable: Any]
train.train_no = queryLeftNewDTO?["train_no"] as? String
train.station_train_code = queryLeftNewDTO?["station_train_code"] as? String
train.start_station_telecode = queryLeftNewDTO?["start_station_telecode"] as? String
train.start_station_name = queryLeftNewDTO?["start_station_name"] as? String
train.end_station_telecode = queryLeftNewDTO?["end_station_telecode"] as? String
train.end_station_name = queryLeftNewDTO?["end_station_name"] as? String
train.from_station_telecode = queryLeftNewDTO?["from_station_telecode"] as? String
train.from_station_name = queryLeftNewDTO?["from_station_name"] as? String
train.to_station_telecode = queryLeftNewDTO?["to_station_telecode"] as? String
train.to_station_name = queryLeftNewDTO?["to_station_name"] as? String
train.start_time = queryLeftNewDTO?["start_time"] as? String
train.arrive_time = queryLeftNewDTO?["arrive_time"] as? String
train.day_difference = queryLeftNewDTO?["day_difference"] as? String
train.train_class_name = queryLeftNewDTO?["train_class_name"] as? String
train.lishi = queryLeftNewDTO?["lishi"] as? String
train.canWebBuy = queryLeftNewDTO?["canWebBuy"] as? String
train.lishiValue = queryLeftNewDTO?["lishiValue"] as? String
train.yp_info = queryLeftNewDTO?["yp_info"] as? String
train.control_train_day = queryLeftNewDTO?["control_train_day"] as? String
train.start_train_date = queryLeftNewDTO?["start_train_date"] as? String
train.seat_feature = queryLeftNewDTO?["seat_feature"] as? String
train.yp_ex = queryLeftNewDTO?["yp_ex"] as? String
train.train_seat_feature = queryLeftNewDTO?["train_seat_feature"] as? String
train.seat_types = queryLeftNewDTO?["seat_types"] as? String
train.location_code = queryLeftNewDTO?["location_code"] as? String
train.from_station_no = queryLeftNewDTO?["from_station_no"] as? String
train.to_station_no = queryLeftNewDTO?["to_station_no"] as? String
train.control_day = queryLeftNewDTO?["control_day"] as? String
train.sale_time = queryLeftNewDTO?["sale_time"] as? String
train.is_support_card = queryLeftNewDTO?["is_support_card"] as? String
train.gg_num = queryLeftNewDTO?["gg_num"] as? String
train.gr_num = queryLeftNewDTO?["gr_num"] as? String
train.qt_num = queryLeftNewDTO?["qt_num"] as? String
train.rw_num = queryLeftNewDTO?["rw_num"] as? String
train.rz_num = queryLeftNewDTO?["rz_num"] as? String
train.tz_num = queryLeftNewDTO?["tz_num"] as? String
train.wz_num = queryLeftNewDTO?["wz_num"] as? String
train.yb_num = queryLeftNewDTO?["yb_num"] as? String
train.yw_num = queryLeftNewDTO?["yw_num"] as? String
train.yz_num = queryLeftNewDTO?["yz_num"] as? String
train.ze_num = queryLeftNewDTO?["ze_num"] as? String
train.zy_num = queryLeftNewDTO?["zy_num"] as? String
train.swz_num = queryLeftNewDTO?["swz_num"] as? String
train.secretStr = jsonTrain["secretStr"] as? String
train.buttonTextInfo = jsonTrain["buttonTextInfo"] as? String
train.businessClassSeatType.leftSeats = train.swz_num
train.specialClassSeatType.leftSeats = train.tz_num
train.firstClassSeatType.leftSeats = train.zy_num
train.secondClassSeatType.leftSeats = train.ze_num
train.premiumSoftRoometteType.leftSeats = train.gr_num
train.softRoometteType.leftSeats = train.rw_num
train.hardRoometteType.leftSeats = train.yw_num
train.softSeatType.leftSeats = train.rz_num
train.hardSeatType.leftSeats = train.yz_num
train.noSeatType.leftSeats = train.wz_num
train.otherType.leftSeats = train.qt_num
trains.append(train)
}
}
return trains
}
// MARK: - Book
/// 创建订单
///
/// :param: createOrderForm 订单表单
/// :param: completionHandler 回调
func createOrder(createOrderForm: CreateOrderForm, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForCreateOrderWithForm(createOrderForm)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
/// 准备订票
///
/// :param: order 订单
/// :param: completionHandler 回调
func prepareForBookTickets(order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/confirmPassenger/initDc", parameters: nil, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
if data != nil {
if let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
order.repeat_submit_token = (string as String).substringWithRegex("(?<=var globalRepeatSubmitToken = ').+?(?=';)")
order.key_check_isChange = (string as String).substringWithRegex("(?<='key_check_isChange':').+?(?=',)")
}
}
completionHandler?(self, nil, error as NSError?)
})
task.resume()
}
/// 获取订单用验证码图片
///
/// :param: completionHandler 回调
func retrieveOrderCaptchaImage(completionHandler: NetworkControllerCompletionHandler?) {
let random = Double(arc4random()) / Double(RAND_MAX)
let URLString = NSString(format: "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=passenger&rand=randp&%.18f", random) as String
let request = try! requestSerializer.request(withMethod: "GET", urlString: URLString, parameters: nil, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
let image = data != nil ? UIImage(data: data!) : nil
completionHandler?(self, image, error as NSError?)
})
task.resume()
}
/// 检查订单的验证码
///
/// :param: captcha 验证码
/// :param: order 订单
/// :param: completionHandler 回调
func checkOrderCaptcha(captcha: String, order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"randCode": captcha,
"rand": "randp",
"_json_att": "",
"REPEAT_SUBMIT_TOKEN": emptyIfNil(order.repeat_submit_token)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let result = json?["result"] as? String
completionHandler?(self, result, error)
})
task.resume()
}
/// 检查订单是否合法
///
/// :param: order 订单
/// :param: captcha 验证码
/// :param: completionHandler 回调
func checkOrder(order: Order, captcha: String, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForCheckOrderWithOrder(order, captcha: captcha)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
/// 检查余票
///
/// :param: order 订单
/// :param: completionHandler 回调
func checkLeftTickets(order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForCheckLeftTicketsWithOrder(order)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
/// 提交订单
///
/// :param: order 订单
/// :param: captcha 验证码
/// :param: completionHandler 回调
func submitOrder(order: Order, captcha: String, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForSubmitOrderWithOrder(order, captcha: captcha)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
// MARK: - Passenger
/// 获取乘客列表(已经弃用)
///
/// :param: completionHandler 回调
func retrievePassengers_old(completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"pageIndex": "1",
"pageSize": "99"
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/query", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let passengers = self?.passengersWithJSON(json?["datas"] as AnyObject?)
completionHandler?(self, passengers, error)
})
task.resume()
}
/// 获取乘客列表
///
/// :param: completionHandler 回调
func retrievePassengers(completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"_json_att": ""
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/init", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var passengers = [Passenger]()
if data != nil {
if let htmlString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as? String {
let regex = try? NSRegularExpression(pattern: "(?<=var passengers=).+?(?=;)", options: [])
let range = regex?.rangeOfFirstMatch(in: htmlString, options: [], range: NSRange(location: 0, length: htmlString.characters.count))
if range != nil && range?.location != NSNotFound {
var passengersString = (htmlString as NSString).substring(with: range!)
passengersString = passengersString.replacingOccurrences(of: "'", with: "\"")
if let passengersData = passengersString.data(using: String.Encoding.utf8) {
if let passengersJSON = try? JSONSerialization.jsonObject(with: passengersData, options: []) as? [[AnyHashable: Any]] {
for passengerJSON in passengersJSON ?? [] {
var passenger = Passenger()
passenger.isUserSelf = passengerJSON["isUserSelf"] as? String
passenger.passenger_name = passengerJSON["passenger_name"] as? String
passenger.old_passenger_name = passenger.passenger_name
passenger.passenger_id_type_code = passengerJSON["passenger_id_type_code"] as? String
passenger.old_passenger_id_type_code = passenger.passenger_id_type_code
passenger.passenger_id_type_name = passengerJSON["passenger_id_type_name"] as? String
passenger.passenger_id_no = passengerJSON["passenger_id_no"] as? String
passenger.old_passenger_id_no = passenger.passenger_id_no
passenger.passenger_type = passengerJSON["passenger_type"] as? String
passenger.passenger_type_name = passengerJSON["passenger_type_name"] as? String
passenger.mobile_no = passengerJSON["mobile_no"] as? String
passenger.total_times = passengerJSON["total_times"] as? String
passengers.append(passenger)
}
}
}
}
}
}
completionHandler?(self, passengers, error as NSError?)
})
task.resume()
}
/// 获取乘客详情
///
/// :param: passenger 乘客
/// :param: completionHandler 回调
func retrievePassengerDetails(passenger: Passenger, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"_json_att": "",
"passenger_name": passenger.passenger_name ?? "",
"passenger_id_type_code": passenger.passenger_id_type_code ?? "",
"passenger_id_no": passenger.passenger_id_no ?? "",
"passenger_type": passenger.passenger_type ?? ""
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/show", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
if data != nil {
var passenger = passenger
let doc = TFHpple(htmlData: data)
let passenger_name = doc?.search(withXPathQuery: "//input[@name='passenger_name']").first as? TFHppleElement
let old_passenger_name = doc?.search(withXPathQuery: "//input[@name='old_passenger_name']").first as? TFHppleElement
let sex_code = doc?.search(withXPathQuery: "//input[@name='sex_code' and @checked='checked']").first as? TFHppleElement
let country_code = doc?.search(withXPathQuery: "//input[@name='country_code']").first as? TFHppleElement
let passenger_id_type_code = doc?.search(withXPathQuery: "//input[@name='passenger_id_type_code']").first as? TFHppleElement
let old_passenger_id_type_code = doc?.search(withXPathQuery: "//input[@name='old_passenger_id_type_code']").first as? TFHppleElement
let passenger_id_no = doc?.search(withXPathQuery: "//input[@name='passenger_id_no']").first as? TFHppleElement
let old_passenger_id_no = doc?.search(withXPathQuery: "//input[@name='old_passenger_id_no']").first as? TFHppleElement
let born_date = doc?.search(withXPathQuery: "//input[@name='born_date']").first as? TFHppleElement
passenger.passenger_name = passenger_name?.attributes["value"] as? String
passenger.old_passenger_name = old_passenger_name?.attributes["value"] as? String
passenger.sex_code = sex_code?.attributes["value"] as? String
passenger.country_code = country_code?.attributes["value"] as? String
// passenger.passenger_id_type_code = passenger_id_type_code?.attributes["value"] as? String
// passenger.passenger_id_no = passenger_id_no?.attributes["value"] as? String
passenger.born_date = born_date?.attributes["value"] as? String
let mobile_no = doc?.search(withXPathQuery: "//input[@name='mobile_no']").first as? TFHppleElement
let phone_no = doc?.search(withXPathQuery: "//input[@name='phone_no']").first as? TFHppleElement
let email = doc?.search(withXPathQuery: "//input[@name='email']").first as? TFHppleElement
let address = doc?.search(withXPathQuery: "//input[@name='address']").first as? TFHppleElement
let postalcode = doc?.search(withXPathQuery: "//input[@name='postalcode']").first as? TFHppleElement
passenger.mobile_no = mobile_no?.attributes["value"] as? String
passenger.phone_no = phone_no?.attributes["value"] as? String
passenger.email = email?.attributes["value"] as? String
passenger.address = address?.attributes["value"] as? String
passenger.postalcode = postalcode?.attributes["value"] as? String
let school_name = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.school_name']").first as? TFHppleElement
let school_code = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.school_code']").first as? TFHppleElement
let department = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.department']").first as? TFHppleElement
let school_class = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.school_class']").first as? TFHppleElement
let student_no = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.student_no']").first as? TFHppleElement
let preference_card_no = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.preference_card_no']").first as? TFHppleElement
let preference_from_station_name = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.preference_from_station_name']").first as? TFHppleElement
let preference_from_station_code = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.preference_from_station_code']").first as? TFHppleElement
let preference_to_station_name = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.preference_to_station_name']").first as? TFHppleElement
let preference_to_station_code = doc?.search(withXPathQuery: "//input[@name='studentInfoDTO.preference_to_station_code']").first as? TFHppleElement
var studentInfo = Passenger.StudentInfo()
studentInfo.school_name = school_name?.attributes["value"] as? String
studentInfo.school_code = school_code?.attributes["value"] as? String
studentInfo.department = department?.attributes["value"] as? String
studentInfo.school_class = school_class?.attributes["value"] as? String
studentInfo.student_no = student_no?.attributes["value"] as? String
studentInfo.preference_card_no = preference_card_no?.attributes["value"] as? String
studentInfo.preference_from_station_name = preference_from_station_name?.attributes["value"] as? String
studentInfo.preference_from_station_code = preference_from_station_code?.attributes["value"] as? String
studentInfo.preference_to_station_name = preference_to_station_name?.attributes["value"] as? String
studentInfo.preference_to_station_code = preference_to_station_code?.attributes["value"] as? String
if let province_code = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.province_code']").first as? TFHppleElement {
var optional_province_code_list = Array<Passenger.Option>()
for optionElement in province_code.children as! [TFHppleElement] {
if optionElement.tagName == "option" {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_province_code_list.append(option)
if optionElement.attributes["selected"] as? String == "selected" {
studentInfo.province_code = option
}
}
}
studentInfo.optional_province_code_list = optional_province_code_list
}
if let school_system = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.school_system']").first as? TFHppleElement {
var optional_school_system_list = Array<Passenger.Option>()
for optionElement in school_system.children as! [TFHppleElement] {
if optionElement.tagName == "option" {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_school_system_list.append(option)
if optionElement.attributes["selected"] as? String == "selected" {
studentInfo.school_system = option
}
}
}
studentInfo.optional_school_system_list = optional_school_system_list
}
if let enter_year = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.enter_year']").first as? TFHppleElement {
var optional_enter_year_list = Array<Passenger.Option>()
for optionElement in enter_year.children as! [TFHppleElement] {
if optionElement.tagName == "option" {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_enter_year_list.append(option)
if optionElement.attributes["selected"] as? String == "selected" {
studentInfo.enter_year = option
}
}
}
studentInfo.optional_enter_year_list = optional_enter_year_list
}
passenger.studentInfo = studentInfo
completionHandler?(self, passenger, error as NSError?)
} else {
completionHandler?(self, passenger, error as NSError?)
}
})
task.resume()
}
/// 初始化一个新建的乘客
///
/// :param: completionHandler 回调
func initPassenger(completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"_json_att": ""
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/addInit", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
if data != nil {
var passenger = Passenger()
var studentInfo = Passenger.StudentInfo()
passenger.studentInfo = studentInfo
let doc = TFHpple(htmlData: data)
if let country_code = doc?.search(withXPathQuery: "//select[@name='country_code']").first as? TFHppleElement {
var optional_country_code_list = Array<Passenger.Option>()
for optionElement in country_code.children(withTagName: "option") as! [TFHppleElement] {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_country_code_list.append(option)
}
passenger.optional_country_code_list = optional_country_code_list
}
if let passenger_id_type_code = doc?.search(withXPathQuery: "//select[@name='passenger_id_type_code']").first as? TFHppleElement {
var optional_passenger_id_type_code_list = Array<Passenger.Option>()
for optionElement in passenger_id_type_code.children(withTagName: "option") as! [TFHppleElement] {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_passenger_id_type_code_list.append(option)
}
passenger.optional_passenger_id_type_code_list = optional_passenger_id_type_code_list
}
if let province_code = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.province_code']").first as? TFHppleElement {
var optional_province_code_list = Array<Passenger.Option>()
for optionElement in province_code.children(withTagName: "option") as! [TFHppleElement] {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_province_code_list.append(option)
}
studentInfo.optional_province_code_list = optional_province_code_list
}
if let school_system = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.school_system']").first as? TFHppleElement {
var optional_school_system_list = Array<Passenger.Option>()
for optionElement in school_system.children(withTagName: "option") as! [TFHppleElement] {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_school_system_list.append(option)
}
studentInfo.optional_school_system_list = optional_school_system_list
}
if let enter_year = doc?.search(withXPathQuery: "//select[@name='studentInfoDTO.enter_year']").first as? TFHppleElement {
var optional_enter_year_list = Array<Passenger.Option>()
for optionElement in enter_year.children(withTagName: "option") as! [TFHppleElement] {
var option = Passenger.Option()
option.value = optionElement.attributes["value"] as? String
option.content = optionElement.firstChild?.firstTextChild()?.content
optional_enter_year_list.append(option)
}
studentInfo.optional_enter_year_list = optional_enter_year_list
}
passenger.country_code = passenger.optional_country_code_list?.first?.value
passenger.passenger_id_type_code = passenger.optional_passenger_id_type_code_list?.first?.value
passenger.passenger_id_type_name = passenger.optional_passenger_id_type_code_list?.first?.content
completionHandler?(self, passenger, error as NSError?)
} else {
completionHandler?(self, nil, error as NSError?)
}
})
task.resume()
}
/// 将新建的乘客添加到乘客列表中
///
/// :param: passenger 乘客
/// :param: completionHandler 回调
func addPassenger(passenger: Passenger, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"passenger_name": emptyIfNil(passenger.passenger_name),
"sex_code": emptyIfNil(passenger.sex_code),
"_birthDate": emptyIfNil(passenger.born_date),
"country_code": emptyIfNil(passenger.country_code),
"passenger_id_type_code": emptyIfNil(passenger.passenger_id_type_code),
"passenger_id_no": emptyIfNil(passenger.passenger_id_no),
"mobile_no": emptyIfNil(passenger.mobile_no),
"phone_no": emptyIfNil(passenger.phone_no),
"email": emptyIfNil(passenger.email),
"address": emptyIfNil(passenger.address),
"postalcode": emptyIfNil(passenger.postalcode),
"passenger_type": emptyIfNil(passenger.passenger_type),
"studentInfoDTO.province_code": emptyIfNil(passenger.studentInfo?.province_code?.value),
"studentInfoDTO.school_code": emptyIfNil(passenger.studentInfo?.school_code),
"studentInfoDTO.school_name": emptyIfNil(passenger.studentInfo?.school_name),
"studentInfoDTO.department": emptyIfNil(passenger.studentInfo?.department),
"studentInfoDTO.school_class": emptyIfNil(passenger.studentInfo?.school_class),
"studentInfoDTO.student_no": emptyIfNil(passenger.studentInfo?.student_no),
"studentInfoDTO.school_system": emptyIfNil(passenger.studentInfo?.school_system?.value),
"studentInfoDTO.enter_year": emptyIfNil(passenger.studentInfo?.enter_year?.value),
"studentInfoDTO.preference_card_no": emptyIfNil(passenger.studentInfo?.preference_card_no),
"studentInfoDTO.preference_from_station_name": emptyIfNil(passenger.studentInfo?.preference_from_station_name),
"studentInfoDTO.preference_from_station_code": emptyIfNil(passenger.studentInfo?.preference_from_station_code),
"studentInfoDTO.preference_to_station_name": emptyIfNil(passenger.studentInfo?.preference_to_station_name),
"studentInfoDTO.preference_to_station_code": emptyIfNil(passenger.studentInfo?.preference_to_station_code)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/add", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
let error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: nil) as? [AnyHashable: Any]
let flag = json?["flag"] as? NSNumber
completionHandler?(self, flag?.boolValue, error)
})
task.resume()
}
/// 编辑乘客
///
/// :param: passenger 乘客
/// :param: completionHandler 回调
func editPassenger(passenger: Passenger, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"passenger_name": emptyIfNil(passenger.passenger_name),
"old_passenger_name": emptyIfNil(passenger.old_passenger_name),
"sex_code": emptyIfNil(passenger.sex_code),
"_birthDate": emptyIfNil(passenger.born_date),
"country_code": emptyIfNil(passenger.country_code),
"passenger_id_type_code": emptyIfNil(passenger.passenger_id_type_code),
"old_passenger_id_type_code": emptyIfNil(passenger.old_passenger_id_type_code),
"passenger_id_no": emptyIfNil(passenger.passenger_id_no),
"old_passenger_id_no": emptyIfNil(passenger.old_passenger_id_no),
"mobile_no": emptyIfNil(passenger.mobile_no),
"phone_no": emptyIfNil(passenger.phone_no),
"email": emptyIfNil(passenger.email),
"address": emptyIfNil(passenger.address),
"postalcode": emptyIfNil(passenger.postalcode),
"passenger_type": emptyIfNil(passenger.passenger_type),
"studentInfoDTO.province_code": emptyIfNil(passenger.studentInfo?.province_code?.value),
"studentInfoDTO.school_code": emptyIfNil(passenger.studentInfo?.school_code),
"studentInfoDTO.school_name": emptyIfNil(passenger.studentInfo?.school_name),
"studentInfoDTO.department": emptyIfNil(passenger.studentInfo?.department),
"studentInfoDTO.school_class": emptyIfNil(passenger.studentInfo?.school_class),
"studentInfoDTO.student_no": emptyIfNil(passenger.studentInfo?.student_no),
"studentInfoDTO.school_system": emptyIfNil(passenger.studentInfo?.school_system?.value),
"studentInfoDTO.enter_year": emptyIfNil(passenger.studentInfo?.enter_year?.value),
"studentInfoDTO.preference_card_no": emptyIfNil(passenger.studentInfo?.preference_card_no),
"studentInfoDTO.preference_from_station_name": emptyIfNil(passenger.studentInfo?.preference_from_station_name),
"studentInfoDTO.preference_from_station_code": emptyIfNil(passenger.studentInfo?.preference_from_station_code),
"studentInfoDTO.preference_to_station_name": emptyIfNil(passenger.studentInfo?.preference_to_station_name),
"studentInfoDTO.preference_to_station_code": emptyIfNil(passenger.studentInfo?.preference_to_station_code)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/edit", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let flag = json?["flag"] as? NSNumber
let result = flag?.boolValue
completionHandler?(self, result, error)
})
task.resume()
}
/// 删除乘客
///
/// :param: passenger 乘客
/// :param: completionHandler 回调
func deletePassenger(passenger: Passenger, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"passenger_name": emptyIfNil(passenger.passenger_name),
"passenger_id_type_code": emptyIfNil(passenger.passenger_id_type_code),
"passenger_id_no": emptyIfNil(passenger.passenger_id_no),
"isUserSelf": emptyIfNil(passenger.isUserSelf)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/passengers/delete", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
let error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: nil) as? [AnyHashable: Any]
let flag = json?["flag"] as? NSNumber
completionHandler?(self, flag?.boolValue, error)
})
task.resume()
}
/// 获取大学列表
///
/// :param: provinceCode 大学所在省份的编码(貌似没啥用)
/// :param: completionHandler 回调
func retrieveColleges(provinceCode: String?, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"provinceCode": emptyIfNil(provinceCode)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/userCommon/schoolNames", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
var colleges = [College]()
if let json = self?.JSONForResponseData(data, errorPointer: &error) as? [[AnyHashable: Any]] {
for collegeJSON in json {
var college = College()
college.chineseName = collegeJSON["chineseName"] as? String
college.allPin = collegeJSON["allPin"] as? String
college.simplePin = collegeJSON["simplePin"] as? String
college.stationTelecode = collegeJSON["stationTelecode"] as? String
colleges.append(college)
}
}
completionHandler?(self, colleges, error)
})
task.resume()
}
/// 获取城市列表
///
/// :param: station_name 不知道干啥用的
/// :param: completionHandler 回调
func retrieveCities(station_name: String?, completionHandler: NetworkControllerCompletionHandler?) {
let parameters = [
"station_name": emptyIfNil(station_name)
]
let request = try! requestSerializer.request(withMethod: "POST", urlString: "https://kyfw.12306.cn/otn/userCommon/allCitys", parameters: parameters, error: nil)
let task = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
var cities = [City]()
if let json = self?.JSONForResponseData(data, errorPointer: &error) as? [[AnyHashable: Any]] {
for cityJSON in json {
var city = City()
city.chineseName = cityJSON["chineseName"] as? String
city.allPin = cityJSON["allPin"] as? String
city.simplePin = cityJSON["simplePin"] as? String
city.stationTelecode = cityJSON["stationTelecode"] as? String
cities.append(city)
}
}
completionHandler?(self, cities, error)
})
task.resume()
}
private func passengersWithJSON(_ json: AnyObject?) -> [Passenger] {
var passengers = [Passenger]()
if let jsonPassengers = json as? [[AnyHashable: Any]] {
for jsonPassenger in jsonPassengers {
var passenger = Passenger()
passenger.code = jsonPassenger["code"] as? String
passenger.passenger_name = jsonPassenger["passenger_name"] as? String
passenger.sex_code = jsonPassenger["sex_code"] as? String
passenger.sex_name = jsonPassenger["sex_name"] as? String
passenger.born_date = jsonPassenger["born_date"] as? String
passenger.country_code = jsonPassenger["country_code"] as? String
passenger.passenger_id_type_code = jsonPassenger["passenger_id_type_code"] as? String
passenger.passenger_id_type_name = jsonPassenger["passenger_id_type_name"] as? String
passenger.passenger_id_no = jsonPassenger["passenger_id_no"] as? String
passenger.passenger_type = jsonPassenger["passenger_type"] as? String
passenger.passenger_flag = jsonPassenger["passenger_flag"] as? String
passenger.passenger_type_name = jsonPassenger["passenger_type_name"] as? String
passenger.mobile_no = jsonPassenger["mobile_no"] as? String
passenger.phone_no = jsonPassenger["phone_no"] as? String
passenger.email = jsonPassenger["email"] as? String
passenger.address = jsonPassenger["address"] as? String
passenger.postalcode = jsonPassenger["postalcode"] as? String
passenger.first_letter = jsonPassenger["first_letter"] as? String
passenger.recordCount = jsonPassenger["recordCount"] as? String
passenger.total_times = jsonPassenger["total_times"] as? String
passenger.index_id = jsonPassenger["index_id"] as? String
passengers.append(passenger)
}
}
return passengers
}
// MARK: - Order
/// 获取未完成订单
///
/// :param: completionHandler 回调
func retrieveIncompleteOrders(completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForIncompleteOrders()
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let incompleteOrders = self?.ordersWithJSON(json?["orderDBList"] as AnyObject?)
completionHandler?(self, incompleteOrders, error)
})
task.resume()
}
/// 获取已完成订单
///
/// :param: completionHandler 回调
func retrieveCompleteOrders(completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForCompleteOrders()
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let completeOrders = self?.ordersWithJSON(json?["OrderDTODataList"] as AnyObject?)
completionHandler?(self, completeOrders, error)
})
task.resume()
}
/// 取消订单
///
/// :param: order 订单
/// :param: completionHandler 回调
func cancelOrder(order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForCancelOrder(order)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
/// 获取退票信息
///
/// :param: ticket 车票
/// :param: order 订单
/// :param: completionHandler 回调
func retrieveRefundInfo(ticket: Ticket, order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForRefundInfoWithTicket(ticket, order: order)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let refundInfo = self?.refundInfoWithJSON(json as AnyObject?)
completionHandler?(self, refundInfo, error)
})
task.resume()
}
/// 退票
///
/// :param: completionHandler 回调
func refund(completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForRefund()
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
private func ordersWithJSON(_ json: AnyObject?) -> [Order] {
var orders = [Order]()
if let jsonOrders = json as? [[AnyHashable: Any]] {
for jsonOrder in jsonOrders {
var fromStation = Station()
fromStation.stationName = (jsonOrder["from_station_name_page"] as? [String])?.first
var toStation = Station()
toStation.stationName = (jsonOrder["to_station_name_page"] as? [String])?.first
var train = Train()
train.station_train_code = jsonOrder["train_code_page"] as? String
train.start_time = jsonOrder["start_time_page"] as? String
train.start_train_date = jsonOrder["start_train_date_page"] as? String
train.arrive_time = jsonOrder["arrive_time_page"] as? String
train.fromStation = fromStation
train.toStation = toStation
var tickets = [Ticket]()
if let jsonTickets = jsonOrder["tickets"] as? [[AnyHashable: Any]] {
for jsonTicket in jsonTickets {
var train = Train()
let trainJSON = jsonTicket["stationTrainDTO"] as? [AnyHashable: Any]
train.station_train_code = trainJSON?["station_train_code"] as? String
train.from_station_telecode = trainJSON?["from_station_telecode"] as? String
train.from_station_name = trainJSON?["from_station_name"] as? String
train.start_time = trainJSON?["start_time"] as? String
train.to_station_telecode = trainJSON?["to_station_telecode"] as? String
train.to_station_name = trainJSON?["to_station_name"] as? String
train.arrive_time = trainJSON?["arrive_time"] as? String
train.distance = trainJSON?["distance"] as? String
var passenger = Passenger()
let passengerJSON = jsonTicket["passengerDTO"] as? [AnyHashable: Any]
passenger.passenger_id_type_code = passengerJSON?["passenger_id_type_code"] as? String
passenger.passenger_id_type_name = passengerJSON?["passenger_id_type_name"] as? String
passenger.passenger_id_no = passengerJSON?["passenger_id_no"] as? String
passenger.passenger_name = passengerJSON?["passenger_name"] as? String
passenger.total_times = passengerJSON?["total_times"] as? String
let ticket = Ticket()
ticket.train = train
ticket.passenger = passenger
ticket.ticket_no = jsonTicket["ticket_no"] as? String
ticket.sequence_no = jsonTicket["sequence_no"] as? String
ticket.batch_no = jsonTicket["batch_no"] as? String
ticket.train_date = jsonTicket["train_date"] as? String
ticket.coach_no = jsonTicket["coach_no"] as? String
ticket.coach_name = jsonTicket["coach_name"] as? String
ticket.seat_no = jsonTicket["seat_no"] as? String
ticket.seat_name = jsonTicket["seat_name"] as? String
ticket.seat_flag = jsonTicket["seat_flag"] as? String
ticket.seat_type_code = jsonTicket["seat_type_code"] as? String
ticket.seat_type_name = jsonTicket["seat_type_name"] as? String
ticket.ticket_type_code = jsonTicket["ticket_type_code"] as? String
ticket.ticket_type_name = jsonTicket["ticket_type_name"] as? String
ticket.reserve_time = jsonTicket["reserve_time"] as? String
ticket.limit_time = jsonTicket["limit_time"] as? String
ticket.lose_time = jsonTicket["lose_time"] as? String
ticket.pay_limit_time = jsonTicket["pay_limit_time"] as? String
ticket.ticket_price = jsonTicket["ticket_price"] as? NSNumber
ticket.print_eticket_flag = jsonTicket["print_eticket_flag"] as? String
ticket.resign_flag = jsonTicket["resign_flag"] as? String
ticket.return_flag = jsonTicket["return_flag"] as? String
ticket.confirm_flag = jsonTicket["confirm_flag"] as? String
ticket.pay_mode_code = jsonTicket["pay_mode_code"] as? String
ticket.ticket_status_code = jsonTicket["ticket_status_code"] as? String
ticket.ticket_status_name = jsonTicket["ticket_status_name"] as? String
ticket.cancel_flag = jsonTicket["cancel_flag"] as? String
ticket.amount_char = jsonTicket["amount_char"] as? NSNumber
ticket.trade_mode = jsonTicket["trade_mode"] as? String
ticket.start_train_date_page = jsonTicket["start_train_date_page"] as? String
ticket.str_ticket_price_page = jsonTicket["str_ticket_price_page"] as? String
ticket.come_go_traveller_ticket_page = jsonTicket["come_go_traveller_ticket_page"] as? String
ticket.return_deliver_flag = jsonTicket["return_deliver_flag"] as? String
ticket.deliver_fee_char = jsonTicket["deliver_fee_char"] as? String
ticket.is_need_alert_flag = jsonTicket["is_need_alert_flag"] as? NSNumber
ticket.is_deliver = jsonTicket["is_deliver"] as? String
ticket.dynamicProp = jsonTicket["dynamicProp"] as? String
tickets.append(ticket)
}
}
let order = Order()
order.sequence_no = jsonOrder["sequence_no"] as? String
order.order_date = jsonOrder["order_date"] as? String
order.totalPrice = jsonOrder["ticket_total_price_page"] as? String
order.train = train
order.tickets = tickets
orders.append(order)
}
}
return orders
}
private func refundInfoWithJSON(_ json: AnyObject?) -> RefundInfo {
let refundInfo = RefundInfo()
if let refundJSON = json as? [AnyHashable: Any] {
var train = Train()
let trainJSON = refundJSON["stationTrainDTO"] as? [AnyHashable: Any]
train.station_train_code = trainJSON?["station_train_code"] as? String
train.from_station_name = trainJSON?["from_station_name"] as? String
train.start_time = trainJSON?["start_time"] as? String
train.to_station_name = trainJSON?["to_station_name"] as? String
var passenger = Passenger()
let passengerJSON = refundJSON["passengerDTO"] as? [AnyHashable: Any]
passenger.passenger_name = passengerJSON?["passenger_name"] as? String
passenger.total_times = passengerJSON?["total_times"] as? String
refundInfo.train = train
refundInfo.passenger = passenger
refundInfo.ticket_no = refundJSON["ticket_no"] as? String
refundInfo.sequence_no = refundJSON["sequence_no"] as? String
refundInfo.batch_no = refundJSON["batch_no"] as? String
refundInfo.train_date = refundJSON["train_date"] as? String
refundInfo.coach_no = refundJSON["coach_no"] as? String
refundInfo.coach_name = refundJSON["coach_name"] as? String
refundInfo.seat_no = refundJSON["seat_no"] as? String
refundInfo.seat_name = refundJSON["seat_name"] as? String
refundInfo.seat_type_name = refundJSON["seat_type_name"] as? String
refundInfo.pay_limit_time = refundJSON["pay_limit_time"] as? String
refundInfo.realize_time_char = refundJSON["realize_time_char"] as? String
refundInfo.ticket_price = refundJSON["ticket_price"] as? NSNumber
refundInfo.return_price = refundJSON["return_price"] as? NSNumber
refundInfo.return_cost = refundJSON["return_cost"] as? NSNumber
refundInfo.amount_char = refundJSON["amount_char"] as? NSNumber
refundInfo.start_train_date_page = refundJSON["start_train_date_page"] as? String
refundInfo.str_ticket_price_page = refundJSON["str_ticket_price_page"] as? String
refundInfo.come_go_traveller_ticket_page = refundJSON["come_go_traveller_ticket_page"] as? String
refundInfo.rate = refundJSON["rate"] as? String
refundInfo.return_rate = refundJSON["return_rate"] as? String
refundInfo.return_deliver_flag = refundJSON["return_deliver_flag"] as? String
refundInfo.deliver_fee_char = refundJSON["deliver_fee_char"] as? String
refundInfo.is_need_alert_flag = refundJSON["is_need_alert_flag"] as? NSNumber
refundInfo.is_deliver = refundJSON["is_deliver"] as? String
refundInfo.dynamicProp = refundJSON["dynamicProp"] as? String
}
return refundInfo
}
// MARK: - Payment
func continueToPay(order: Order, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForContinuePaymentWithOrder(order)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
self?.JSONForResponseData(data, errorPointer: &error)
completionHandler?(self, nil, error)
})
task.resume()
}
func retrievePayment(completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForPayment()
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let json = self?.JSONForResponseData(data, errorPointer: &error) as? [AnyHashable: Any]
let paymentForm = json?["payForm"] as? [AnyHashable: Any]
let payment = Payment()
payment.appId = paymentForm?["appId"] as? String
payment.epayurl = paymentForm?["epayurl"] as? String
payment.interfaceName = paymentForm?["interfaceName"] as? String
payment.interfaceVersion = paymentForm?["interfaceVersion"] as? String
payment.merSignMsg = paymentForm?["merSignMsg"] as? String
payment.payOrderId = paymentForm?["payOrderId"] as? String
payment.tranData = paymentForm?["tranData"] as? String
payment.transType = paymentForm?["transType"] as? String
completionHandler?(self, payment, error)
})
task.resume()
}
func retrievePayments(payment: Payment, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForPaymentsWithPayment(payment)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var payments = [Payment]()
let doc = TFHpple(htmlData: data)
let form = doc?.search(withXPathQuery: "//form[@name='myform']").first as? TFHppleElement
if let banks = form?.search(withXPathQuery: "//div[@class='bank3']/div[@class='bank3_5']/img") as? [TFHppleElement] {
for bank in banks {
let payment = Payment()
if let infos = form?.children(withTagName: "input") as? [TFHppleElement] {
for element in infos {
let attributeName = element.attributes["name"] as? String
if attributeName == "tranData" {
payment.tranData = element.attributes["value"] as? String
} else if attributeName == "transType" {
payment.transType = element.attributes["value"] as? String
} else if attributeName == "channelId" {
payment.channelId = element.attributes["value"] as? String
} else if attributeName == "appId" {
payment.appId = element.attributes["value"] as? String
} else if attributeName == "merSignMsg" {
payment.merSignMsg = element.attributes["value"] as? String
} else if attributeName == "merCustomIp" {
payment.merCustomIp = element.attributes["value"] as? String
} else if attributeName == "orderTimeoutDate" {
payment.orderTimeoutDate = element.attributes["value"] as? String
}
}
}
payment.name = bank.attributes["title"] as? String
if let onclick = bank.attributes["onclick"] as? String {
let regex = try? NSRegularExpression(pattern: "(?<=javascript:formsubmit\\(').+?(?='\\);)", options: [])
if let range = regex?.rangeOfFirstMatch(in: onclick, options: [], range: NSRange(location: 0, length: onclick.characters.count)) {
if range.location != NSNotFound {
payment.bankId = (onclick as NSString).substring(with: range)
}
}
}
payments.append(payment)
}
}
completionHandler?(self, payments, error as NSError?)
})
task.resume()
}
func business(payment: Payment, completionHandler: NetworkControllerCompletionHandler?) {
let request = LegacyRequest.requestForBusinessWithPayment(payment)
let task = session.dataTask(with: request.URLRequest as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
var error = error as NSError?
let string = String(data: data!, encoding: String.Encoding.utf8)
let doc = TFHpple(htmlData: data)
let form = doc?.search(withXPathQuery: "//form[@name='myform']").first as? TFHppleElement
if let action = form?.attributes["action"] as? String {
if let url = URL(string: action) {
let request = ASIFormDataRequest(url: url)!
if let infos = form?.children(withTagName: "input") as? [TFHppleElement] {
for element in infos {
let name = element.attributes["name"] as? String
let value = element.attributes["value"] as? String
request.setPostValue(value as NSObjectProtocol!, forKey: name)
}
}
request.startSynchronous()
let yy = request.responseString()
let dd = TFHpple(htmlData: request.responseData())
let qrPayLoopCheckUrl = dd?.search(withXPathQuery: "//input[@name='qrPayLoopCheckUrl']").first as? TFHppleElement
let qrContextId = dd?.search(withXPathQuery: "//input[@name='qrContextId']").first as? TFHppleElement
let qrPayLoopCheckUrlValue = qrPayLoopCheckUrl?.attributes["value"] as? String ?? ""
let qrContextIdValue = qrContextId?.attributes["value"] as? String ?? ""
let url = "\(qrPayLoopCheckUrlValue)?qrContextId=\(qrContextIdValue)"
if let uurrll = URL(string: url) {
let rr = ASIHTTPRequest(url: uurrll)!
rr.startSynchronous()
let sss = rr.responseString().replacingOccurrences(of: "window.qrPayStatus=", with: "")
let dddd = try? JSONSerialization.jsonObject(with: sss.data(using: String.Encoding.utf8)!, options: []) as? [AnyHashable: Any]
if let qrCode = dddd??["qrCode"] as? String {
if let requrl = URL(string: qrCode) {
let req = ASIHTTPRequest(url: requrl)!
req.startSynchronous()
let sss = req.responseString()
let hhh = TFHpple(htmlData: req.responseData())
let iframe = hhh?.search(withXPathQuery: "//iframe").first as? TFHppleElement
if let src = iframe?.attributes["src"] as? String {
if let uuu = URL(string: src) {
if UIApplication.shared.canOpenURL(uuu) {
UIApplication.shared.openURL(uuu)
} else {
error = NSError(domain: ByTrainApplicationDomain, code: ErrorCode.appNotInstalled.hashValue, userInfo: [NSLocalizedDescriptionKey: "对不起,您尚未安装支付宝钱包。"])
}
}
}
}
}
}
}
}
completionHandler?(self, nil, error)
})
task.resume()
}
// MARK: - Parse
private func JSONForResponseData(_ responseData: Data?, errorPointer: NSErrorPointer) -> AnyObject? {
if let jsonData = responseData {
let json = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [AnyHashable: Any]
let data = json??["data"] as? [AnyHashable: Any]
let messages = json??["messages"] as? [String]
if let message = messages?.first {
errorPointer?.pointee = NSError(domain: ByTrainApplicationDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: message])
} else if let errorMessage = data?["errMsg"] as? String {
errorPointer?.pointee = NSError(domain: ByTrainApplicationDomain, code: 0, userInfo: [NSLocalizedDescriptionKey: errorMessage])
}
return json??["data"] as AnyObject?
}
return nil
}
// MARK: - URL Session Delegate
func urlSession(_ session: Foundation.URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
| mit | 0fc40cd569c564d2ee1e4fa6b20eba50 | 55.903987 | 378 | 0.579452 | 4.669493 | false | false | false | false |
OscarSwanros/swift | stdlib/public/SDK/Foundation/NSObject.swift | 13 | 12361 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import ObjectiveC
public protocol _KeyValueCodingAndObserving {}
public struct NSKeyValueObservedChange<Value> {
public typealias Kind = NSKeyValueChange
public let kind: Kind
///newValue and oldValue will only be non-nil if .new/.old is passed to `observe()`. In general, get the most up to date value by accessing it directly on the observed object instead.
public let newValue: Value?
public let oldValue: Value?
///indexes will be nil unless the observed KeyPath refers to an ordered to-many property
public let indexes: IndexSet?
///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()`
public let isPrior:Bool
}
///Conforming to NSKeyValueObservingCustomization is not required to use Key-Value Observing. Provide an implementation of these functions if you need to disable auto-notifying for a key, or add dependent keys
public protocol NSKeyValueObservingCustomization : NSObjectProtocol {
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath>
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool
}
fileprivate extension NSObject {
@objc class func _old_unswizzled_automaticallyNotifiesObservers(forKey key: String?) -> Bool {
fatalError("Should never be reached")
}
@objc class func _old_unswizzled_keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
fatalError("Should never be reached")
}
}
@objc private class _KVOKeyPathBridgeMachinery : NSObject {
@nonobjc static var keyPathTable: [String : AnyKeyPath] = {
/*
Move all our methods into place. We want the following:
_KVOKeyPathBridgeMachinery's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replaces NSObject's versions of them
NSObject's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replace NSObject's _old_unswizzled_* methods
NSObject's _old_unswizzled_* methods replace _KVOKeyPathBridgeMachinery's methods, and are never invoked
*/
let rootClass: AnyClass = NSObject.self
let bridgeClass: AnyClass = _KVOKeyPathBridgeMachinery.self
let dependentSel = #selector(NSObject.keyPathsForValuesAffectingValue(forKey:))
let rootDependentImpl = class_getClassMethod(rootClass, dependentSel)!
let bridgeDependentImpl = class_getClassMethod(bridgeClass, dependentSel)!
method_exchangeImplementations(rootDependentImpl, bridgeDependentImpl) // NSObject <-> Us
let originalDependentImpl = class_getClassMethod(bridgeClass, dependentSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation
let originalDependentSel = #selector(NSObject._old_unswizzled_keyPathsForValuesAffectingValue(forKey:))
let dummyDependentImpl = class_getClassMethod(rootClass, originalDependentSel)!
method_exchangeImplementations(originalDependentImpl, dummyDependentImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version
let autoSel = #selector(NSObject.automaticallyNotifiesObservers(forKey:))
let rootAutoImpl = class_getClassMethod(rootClass, autoSel)!
let bridgeAutoImpl = class_getClassMethod(bridgeClass, autoSel)!
method_exchangeImplementations(rootAutoImpl, bridgeAutoImpl) // NSObject <-> Us
let originalAutoImpl = class_getClassMethod(bridgeClass, autoSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation
let originalAutoSel = #selector(NSObject._old_unswizzled_automaticallyNotifiesObservers(forKey:))
let dummyAutoImpl = class_getClassMethod(rootClass, originalAutoSel)!
method_exchangeImplementations(originalAutoImpl, dummyAutoImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version
return [:]
}()
@nonobjc static var keyPathTableLock = NSLock()
@nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:AnyKeyPath) -> String {
guard let keyPathString = keyPath._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \(keyPath)") }
_KVOKeyPathBridgeMachinery.keyPathTableLock.lock()
defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() }
_KVOKeyPathBridgeMachinery.keyPathTable[keyPathString] = keyPath
return keyPathString
}
@nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:String?) -> AnyKeyPath? {
guard let keyPath = keyPath else { return nil }
_KVOKeyPathBridgeMachinery.keyPathTableLock.lock()
defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() }
let path = _KVOKeyPathBridgeMachinery.keyPathTable[keyPath]
return path
}
@objc override class func automaticallyNotifiesObservers(forKey key: String) -> Bool {
//This is swizzled so that it's -[NSObject automaticallyNotifiesObserversForKey:]
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key) {
return customizingSelf.automaticallyNotifiesObservers(for: path)
} else {
return self._old_unswizzled_automaticallyNotifiesObservers(forKey: key) //swizzled to be NSObject's original implementation
}
}
@objc override class func keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
//This is swizzled so that it's -[NSObject keyPathsForValuesAffectingValueForKey:]
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key!) {
let resultSet = customizingSelf.keyPathsAffectingValue(for: path)
return Set(resultSet.lazy.map {
guard let str = $0._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \($0)") }
return str
})
} else {
return self._old_unswizzled_keyPathsForValuesAffectingValue(forKey: key) //swizzled to be NSObject's original implementation
}
}
}
func _bridgeKeyPathToString(_ keyPath:AnyKeyPath) -> String {
return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath)
}
func _bridgeStringToKeyPath(_ keyPath:String) -> AnyKeyPath? {
return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath)
}
public class NSKeyValueObservation : NSObject {
weak var object : NSObject?
let callback : (NSObject, NSKeyValueObservedChange<Any>) -> Void
let path : String
//workaround for <rdar://problem/31640524> Erroneous (?) error when using bridging in the Foundation overlay
static var swizzler : NSKeyValueObservation? = {
let bridgeClass: AnyClass = NSKeyValueObservation.self
let observeSel = #selector(NSObject.observeValue(forKeyPath:of:change:context:))
let swapSel = #selector(NSKeyValueObservation._swizzle_me_observeValue(forKeyPath:of:change:context:))
let rootObserveImpl = class_getInstanceMethod(bridgeClass, observeSel)
let swapObserveImpl = class_getInstanceMethod(bridgeClass, swapSel)
method_exchangeImplementations(rootObserveImpl, swapObserveImpl)
return nil
}()
fileprivate init(object: NSObject, keyPath: AnyKeyPath, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) {
path = _bridgeKeyPathToString(keyPath)
let _ = NSKeyValueObservation.swizzler
self.object = object
self.callback = callback
}
fileprivate func start(_ options: NSKeyValueObservingOptions) {
object?.addObserver(self, forKeyPath: path, options: options, context: nil)
}
///invalidate() will be called automatically when an NSKeyValueObservation is deinited
public func invalidate() {
object?.removeObserver(self, forKeyPath: path, context: nil)
object = nil
}
@objc func _swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString : Any]?, context: UnsafeMutableRawPointer?) {
guard let ourObject = self.object, object as? NSObject == ourObject, let change = change else { return }
let rawKind:UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt
let kind = NSKeyValueChange(rawValue: rawKind)!
let notification = NSKeyValueObservedChange(kind: kind,
newValue: change[NSKeyValueChangeKey.newKey.rawValue as NSString],
oldValue: change[NSKeyValueChangeKey.oldKey.rawValue as NSString],
indexes: change[NSKeyValueChangeKey.indexesKey.rawValue as NSString] as! IndexSet?,
isPrior: change[NSKeyValueChangeKey.notificationIsPriorKey.rawValue as NSString] as? Bool ?? false)
callback(ourObject, notification)
}
deinit {
object?.removeObserver(self, forKeyPath: path, context: nil)
}
}
public extension _KeyValueCodingAndObserving {
///when the returned NSKeyValueObservation is deinited or invalidated, it will stop observing
public func observe<Value>(
_ keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
-> NSKeyValueObservation {
let result = NSKeyValueObservation(object: self as! NSObject, keyPath: keyPath) { (obj, change) in
let notification = NSKeyValueObservedChange(kind: change.kind,
newValue: change.newValue as? Value,
oldValue: change.oldValue as? Value,
indexes: change.indexes,
isPrior: change.isPrior)
changeHandler(obj as! Self, notification)
}
result.start(options)
return result
}
public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>) {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) {
(self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>) {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) {
(self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
}
extension NSObject : _KeyValueCodingAndObserving {}
| apache-2.0 | ebb309d0122d454fc897069bd086118b | 53.453744 | 209 | 0.689265 | 5.452581 | false | false | false | false |
almazrafi/Metatron | Sources/ID3v2/ID3v2Tag.swift | 1 | 12229 | //
// ID3v2Tag.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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
public class ID3v2Tag {
// MARK: Instance Properties
private let header: ID3v2Header
//MARK:
public var version: ID3v2Version {
get {
return self.header.version
}
set {
self.header.version = newValue
}
}
public var revision: UInt8 {
get {
return self.header.revision
}
set {
self.header.revision = newValue
}
}
public var experimentalIndicator: Bool {
get {
return self.header.experimentalIndicator
}
set {
self.header.experimentalIndicator = newValue
}
}
public var footerPresent: Bool {
get {
return self.header.footerPresent
}
set {
self.header.footerPresent = newValue
}
}
public var fillingLength: Int
// MARK:
private var frameSetKeys: [ID3v2FrameID: Int]
public private(set) var frameSetList: [ID3v2FrameSet]
// MARK:
public var isEmpty: Bool {
return self.frameSetList.isEmpty
}
// MARK: Initializers
private init?(bodyData: [UInt8], header: ID3v2Header, dataLength: Int) {
assert(UInt64(bodyData.count) == UInt64(header.bodyLength), "Invalid data")
self.header = header
var bodyData = bodyData
switch self.header.version {
case ID3v2Version.v2:
if self.header.unsynchronisation {
bodyData = ID3v2Unsynchronisation.decode(bodyData)
}
if self.header.compression {
guard let decompressed = ZLib.inflate(bodyData) else {
return nil
}
bodyData = decompressed
}
case ID3v2Version.v3:
if self.header.unsynchronisation {
bodyData = ID3v2Unsynchronisation.decode(bodyData)
}
case ID3v2Version.v4:
break
}
var offset = 0
if self.header.extHeaderPresent {
guard let extHeader = ID3v2ExtHeader(fromData: bodyData, version: self.header.version) else {
return nil
}
guard UInt64(extHeader.ownDataLength) < UInt64(bodyData.count) else {
return nil
}
offset = Int(extHeader.ownDataLength)
}
self.fillingLength = 0
self.frameSetKeys = [:]
self.frameSetList = []
var frameSets: [ID3v2FrameID: [ID3v2Frame]] = [:]
while offset < bodyData.count {
if let frame = ID3v2Frame(fromBodyData: bodyData, offset: &offset, version: self.header.version) {
if var frames = frameSets[frame.identifier] {
frames.append(frame)
frameSets[frame.identifier] = frames
} else {
frameSets[frame.identifier] = [frame]
}
} else {
self.fillingLength = dataLength
break
}
}
for (identifier, frames) in frameSets {
self.frameSetKeys.updateValue(self.frameSetList.count, forKey: identifier)
self.frameSetList.append(ID3v2FrameSet(frames: frames))
}
}
// MARK:
public init(version: ID3v2Version = ID3v2Version.v4) {
self.header = ID3v2Header(version: version)
self.fillingLength = 0
self.frameSetKeys = [:]
self.frameSetList = []
}
public convenience init?(fromData data: [UInt8]) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
var range = Range<UInt64>(0..<UInt64(data.count))
self.init(fromStream: stream, range: &range)
}
public convenience init?(fromStream stream: Stream, range: inout Range<UInt64>) {
assert(stream.isOpen && stream.isReadable && (stream.length >= range.upperBound), "Invalid stream")
guard range.lowerBound < range.upperBound else {
return nil
}
let anyDataLength = UInt64(ID3v2Header.anyDataLength)
let maxDataLength = UInt64(range.count)
guard anyDataLength <= maxDataLength else {
return nil
}
guard stream.seek(offset: range.lowerBound) else {
return nil
}
if let header = ID3v2Header(fromData: stream.read(maxLength: ID3v2Header.anyDataLength)) {
guard header.position == ID3v2Header.Position.header else {
return nil
}
let dataLength: UInt64
if header.footerPresent {
dataLength = anyDataLength * 2 + UInt64(header.bodyLength)
} else {
dataLength = anyDataLength + UInt64(header.bodyLength)
}
guard (dataLength <= UInt64(Int.max)) && (dataLength <= maxDataLength) else {
return nil
}
guard stream.seek(offset: range.lowerBound + anyDataLength) else {
return nil
}
let bodyData = stream.read(maxLength: Int(header.bodyLength))
guard bodyData.count == Int(header.bodyLength) else {
return nil
}
self.init(bodyData: bodyData, header: header, dataLength: Int(dataLength))
range = range.lowerBound..<(range.lowerBound + dataLength)
} else {
guard stream.seek(offset: range.upperBound - anyDataLength) else {
return nil
}
guard let header = ID3v2Header(fromData: stream.read(maxLength: ID3v2Header.anyDataLength)) else {
return nil
}
guard header.position == ID3v2Header.Position.footer else {
return nil
}
let dataLength = anyDataLength * 2 + UInt64(header.bodyLength)
guard (dataLength <= UInt64(Int.max)) && (dataLength <= maxDataLength) else {
return nil
}
guard stream.seek(offset: range.upperBound - dataLength + anyDataLength) else {
return nil
}
let bodyData = stream.read(maxLength: Int(header.bodyLength))
guard bodyData.count == Int(header.bodyLength) else {
return nil
}
self.init(bodyData: bodyData, header: header, dataLength: Int(dataLength))
range = (range.upperBound - dataLength)..<range.upperBound
}
}
// MARK: Instance Methods
public func toData() -> [UInt8]? {
guard !self.isEmpty else {
return nil
}
self.header.bodyLength = 0
self.header.unsynchronisation = true
self.header.compression = false
self.header.extHeaderPresent = false
guard self.header.isValid else {
return nil
}
var bodyData: [UInt8] = []
for frameSet in self.frameSetList {
for frame in frameSet.frames {
if !frame.unsynchronisation {
self.header.unsynchronisation = false
}
if let frameData = frame.toData(version: self.version) {
if frameData.count <= ID3v2Header.maxBodyLength - bodyData.count {
bodyData.append(contentsOf: frameData)
}
}
}
}
var padding = self.fillingLength - ID3v2Header.anyDataLength - bodyData.count
switch version {
case ID3v2Version.v2, ID3v2Version.v3:
if self.header.unsynchronisation {
bodyData = ID3v2Unsynchronisation.encode(bodyData)
}
case ID3v2Version.v4:
if self.header.footerPresent {
padding -= ID3v2Header.anyDataLength
}
}
guard (bodyData.count > 0) && (bodyData.count <= ID3v2Header.maxBodyLength) else {
return nil
}
padding = min(padding, ID3v2Header.maxBodyLength - bodyData.count)
if padding > 0 {
bodyData.append(contentsOf: Array<UInt8>(repeating: 0, count: padding))
}
guard bodyData.count <= ID3v2Header.maxBodyLength else {
return nil
}
self.header.bodyLength = UInt32(bodyData.count)
guard let headerData = self.header.toData() else {
return nil
}
return headerData.header + bodyData + headerData.footer
}
// MARK:
@discardableResult
public func appendFrameSet(_ identifier: ID3v2FrameID) -> ID3v2FrameSet {
if let index = self.frameSetKeys[identifier] {
return self.frameSetList[index]
} else {
let frameSet = ID3v2FrameSet(identifier: identifier)
self.frameSetKeys.updateValue(self.frameSetList.count, forKey: identifier)
self.frameSetList.append(frameSet)
return frameSet
}
}
@discardableResult
public func resetFrameSet(_ identifier: ID3v2FrameID) -> ID3v2FrameSet {
if let index = self.frameSetKeys[identifier] {
let frameSet = self.frameSetList[index]
frameSet.reset()
return frameSet
} else {
let frameSet = ID3v2FrameSet(identifier: identifier)
self.frameSetKeys.updateValue(self.frameSetList.count, forKey: identifier)
self.frameSetList.append(frameSet)
return frameSet
}
}
@discardableResult
public func removeFrameSet(_ identifier: ID3v2FrameID) -> Bool {
guard let index = self.frameSetKeys.removeValue(forKey: identifier) else {
return false
}
for i in (index + 1)..<self.frameSetList.count {
self.frameSetKeys.updateValue(i - 1, forKey: self.frameSetList[i].identifier)
}
self.frameSetList.remove(at: index)
return true
}
public func revise() {
for frameSet in self.frameSetList {
for frame in frameSet.frames {
if frame.isEmpty {
frameSet.removeFrame(frame)
}
}
if (frameSet.frames.count < 2) && (frameSet.mainFrame.isEmpty) {
if let index = self.frameSetKeys.removeValue(forKey: frameSet.identifier) {
for i in index..<(self.frameSetList.count - 1) {
self.frameSetKeys.updateValue(i, forKey: self.frameSetList[i + 1].identifier)
}
self.frameSetList.remove(at: index)
}
}
}
}
public func clear() {
self.frameSetKeys.removeAll()
self.frameSetList.removeAll()
}
// MARK: Subscripts
public subscript(identifier: ID3v2FrameID) -> ID3v2FrameSet? {
guard let index = self.frameSetKeys[identifier] else {
return nil
}
return self.frameSetList[index]
}
}
| mit | 2f1fd523865e6f50ca360921101da627 | 27.774118 | 110 | 0.578216 | 4.524232 | false | false | false | false |
t-ballz/coopclocker-osx | CoopClocker-osx/Source/ViewModel/MainPopupViewModel.swift | 1 | 3001 | //
// MainPopupViewModel.swift
// StatusBarPomodoro
//
// Created by TaileS Ballz on 23/10/15.
// Copyright (c) 2015 ballz. All rights reserved.
//
import Cocoa
import RxSwift
class MainPopupViewModel : BaseViewModel
{
class WorkListEntry
{
// TODO
}
enum OperationStatus
{
case Ok, Pending, Error
}
enum OperationMode
{
case Offline, Online, Pending
}
let operationStatus = Variable<OperationStatus>(.Pending)
let operationMode = Variable<OperationMode>(.Pending)
let userName = Variable<String>("Unknown user")
let serverName = Variable<String>("No server")
let organizationName = Variable<String>("Unnamed organization")
let projectName = Variable<String>("Unnamed project")
let taskName = Variable<String>("No task")
let timerRunning = Variable<Bool>(false)
let timerProgress = Variable<Float>(0.0)
let timerMinutes = Variable<Int>(0)
let timerSeconds = Variable<Int>(0)
let popupEnabled = Variable<Bool>(true)
private let disposeBag = DisposeBag()
override init()
{
super.init()
let timerDispose = interval(1.0, MainScheduler.sharedInstance) >-
flatMap { next in Observable<NSDate>.rx_return(NSDate()) } >-
subscribeNext { next in
let (minutes, seconds) = next.minutes_seconds()
self.timerMinutes <~ minutes
self.timerSeconds <~ seconds
}
self.disposeBag.addDisposable(timerDispose)
}
func networkPressed(sender: NSView) -> Observable<Void>
{
return create
{ sink in
Logger.log("Status indicator pressed.")
sendCompleted(sink)
return NopDisposable.instance
}
}
func settingsPressed(sender: NSView) -> Observable<Void>
{
return create
{ sink in
Logger.log("Settings button pressed.")
sendCompleted(sink)
return NopDisposable.instance
}
}
func popupPressed(sender: NSView) -> Observable<Void>
{
return create
{ sink in
Logger.log("Popup toggle button pressed.")
sendCompleted(sink)
return NopDisposable.instance
}
}
func newTaskPressed(sender: NSView) -> Observable<Void>
{
return create
{ sink in
Logger.log("Timer restart button pressed.")
sendCompleted(sink)
return NopDisposable.instance
}
}
func timerPressed(sender: NSView) -> Observable<Void>
{
return create
{ sink in
Logger.log("Timer pressed.")
self.timerRunning <~ !self.timerRunning.value
sendCompleted(sink)
return NopDisposable.instance
}
}
}
| bsd-3-clause | d1f0b3ea29608a44b0b7c0bb29b4aa39 | 23.598361 | 73 | 0.565811 | 5.095076 | false | false | false | false |
LoopKit/LoopKit | LoopKit/JSONStreamEncoder.swift | 1 | 1932 | //
// JSONStreamEncoder.swift
// LoopKit
//
// Created by Darin Krauss on 6/25/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import Foundation
public enum JSONStreamEncoderError: Error {
case encoderClosed
}
public class JSONStreamEncoder {
private let stream: OutputStream
private var encoded: Bool
private var closed: Bool
public init(stream: OutputStream) {
self.stream = stream
self.encoded = false
self.closed = false
}
public func close() -> Error? {
guard !closed else {
return nil
}
self.closed = true
do {
try stream.write(encoded ? "\n]" : "[]")
} catch let error {
return error
}
return nil
}
public func encode<T>(_ values: T) throws where T: Collection, T.Element: Encodable {
guard !closed else {
throw JSONStreamEncoderError.encoderClosed
}
for value in values {
try stream.write(encoded ? ",\n" : "[\n")
try stream.write(try Self.encoder.encode(value))
encoded = true
}
}
private static var encoder: JSONEncoder = {
let encoder = JSONEncoder()
if #available(watchOSApplicationExtension 6.0, *) {
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
} else {
encoder.outputFormatting = [.sortedKeys]
}
encoder.dateEncodingStrategy = .custom { (date, encoder) in
var encoder = encoder.singleValueContainer()
try encoder.encode(dateFormatter.string(from: date))
}
return encoder
}()
private static let dateFormatter: ISO8601DateFormatter = {
var dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
return dateFormatter
}()
}
| mit | 1f5f4046b714ca04b83d2f2821965ea4 | 25.452055 | 89 | 0.601243 | 4.815461 | false | false | false | false |
buyiyang/iosstar | iOSStar/General/CustomView/NoDataCell.swift | 4 | 2197 | //
// NoDataCell.swift
// iOSStar
//
// Created by J-bb on 17/6/6.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class NoDataCell: UITableViewCell {
lazy var infoImageView:UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
lazy var infoLabel:UILabel = {
let label = UILabel()
label.textColor = UIColor(hexString: "333333")
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
override func awakeFromNib() {
super.awakeFromNib()
addSubViews()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubViews()
}
func addSubViews() {
selectionStyle = .none
contentView.addSubview(infoImageView)
contentView.addSubview(infoLabel)
contentView.backgroundColor = UIColor(hexString: "fafafa")
infoImageView.snp.makeConstraints({ (make) in
make.top.equalTo(100)
make.centerX.equalTo(self)
})
infoLabel.snp.makeConstraints { (make) in
make.top.equalTo(infoImageView.snp.bottom).offset(35)
make.centerX.equalTo(infoImageView)
}
}
func setImageAndTitle(image:UIImage?,title:String?) {
if title == nil {
remakeConstranints()
}
infoImageView.image = image
infoLabel.text = title
}
func remakeConstranints() {
infoImageView.snp.remakeConstraints { (make) in
make.top.equalTo(30)
make.width.equalTo(kScreenWidth)
make.right.equalTo(0)
make.left.equalTo(0)
}
infoLabel.removeFromSuperview()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | a42958ef3eb027aab8556bd789b75ce2 | 24.511628 | 74 | 0.594804 | 4.769565 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.