repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardPayment/Sources/FeatureCardPaymentData/Client/EveryPayClient.swift
1
2143
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import DIKit import FeatureCardPaymentDomain import Foundation import NetworkKit import ToolKit public final class EveryPayClient: EveryPayClientAPI { // MARK: - Types private enum Path { static let cardDetails = ["api", "v3", "mobile_payments", "card_details"] } private enum Parameter { static let apiUserName = "api_username" static let accessToken = "mobile_access_token" static let tokenConsented = "token_consented" static let cardDetails = "cc_details" static let nonce = "nonce" static let timestamp = "timestamp" static let cardNumber = "cc_number" static let month = "month" static let year = "year" static let cardholderName = "holder_name" static let cvc = "cvc" } // MARK: - Properties private let requestBuilder: RequestBuilder private let networkAdapter: NetworkAdapterAPI // MARK: - Setup public init( networkAdapter: NetworkAdapterAPI = resolve(tag: DIKitContext.everypay), requestBuilder: RequestBuilder = resolve(tag: DIKitContext.everypay) ) { self.networkAdapter = networkAdapter self.requestBuilder = requestBuilder } public func send( cardDetails: CardPartnerPayload.EveryPay.SendCardDetailsRequest.CardDetails, apiUserName: String, token: String ) -> AnyPublisher<CardPartnerPayload.EveryPay.CardDetailsResponse, NetworkError> { let path = Path.cardDetails let headers = [HttpHeaderField.authorization: "Bearer \(token)"] let payload = CardPartnerPayload.EveryPay.SendCardDetailsRequest( apiUserName: apiUserName, nonce: UUID().uuidString, timestamp: DateFormatter.iso8601Format.string(from: Date()), cardDetails: cardDetails ) let request = requestBuilder.post( path: path, body: try? payload.encode(), headers: headers )! return networkAdapter.perform(request: request) } }
lgpl-3.0
9098be4104da3c0ff9cc4b588a282383
30.043478
86
0.656863
4.846154
false
false
false
false
Carthage/ogdl-swift
OGDL/Graph.swift
1
1349
// // Graph.swift // OGDL // // Created by Justin Spahr-Summers on 2015-01-07. // Copyright (c) 2015 Carthage. All rights reserved. // import Foundation /// Represents a node in an OGDL graph. Nodes are not required to be unique. public struct Node: Equatable { /// The value given for this node. public let value: String /// Any children of this node. public let children: [Node] public init(value: String, children: [Node] = []) { self.value = value self.children = children } /// Creates a new node by appending the given children to that of the receiver. public func nodeByAppendingChildren(children: [Node]) -> Node { return Node(value: value, children: self.children + children) } } public func == (lhs: Node, rhs: Node) -> Bool { return lhs.value == rhs.value && lhs.children == rhs.children } extension Node: Hashable { public var hashValue: Int { return value.hashValue ^ children.count.hashValue } } extension Node: Printable { public var description: String { var string = "" if value.rangeOfCharacterFromSet(NSCharacterSet.alphanumericCharacterSet().invertedSet) == nil { string = value } else { string = "\"\(value)\"" } if !children.isEmpty { let childDescriptions = map(children) { $0.description } string += " (" + join(", ", childDescriptions) + ")" } return string } }
mit
9bcea7aa5219310d73790af50e87588b
23.089286
98
0.681245
3.55
false
false
false
false
neonichu/NBMaterialDialogIOS
Pod/Classes/NBMaterialDialog.swift
1
19654
// // NBMaterialDialog.swift // NBMaterialDialogIOS // // Created by Torstein Skulbru on 02/05/15. // Copyright (c) 2015 Torstein Skulbru. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Torstein Skulbru // // 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 BFPaperButton /** Simple material dialog class */ @objc public class NBMaterialDialog : UIViewController { // MARK: - Class variables private var overlay: UIView? private var titleLabel: UILabel? private var containerView: UIView = UIView() private var contentView: UIView = UIView() private var okButton: BFPaperButton? private var cancelButton: BFPaperButton? private var tapGesture: UITapGestureRecognizer! private var backgroundColor: UIColor! private var windowView: UIView! private var isStacked: Bool = false private let kBackgroundTransparency: CGFloat = 0.7 private let kPadding: CGFloat = 16.0 private let kWidthMargin: CGFloat = 40.0 private let kHeightMargin: CGFloat = 24.0 internal var kMinimumHeight: CGFloat { return 120.0 } private var _kMaxHeight: CGFloat? internal var kMaxHeight: CGFloat { if _kMaxHeight == nil { let window = UIScreen.mainScreen().bounds _kMaxHeight = window.height - kHeightMargin - kHeightMargin } return _kMaxHeight! } internal var strongSelf: NBMaterialDialog? internal var userAction: ((isOtherButton: Bool) -> Void)? internal var constraintViews: [String: AnyObject]! // MARK: - Constructors public convenience init() { self.init(color: UIColor.whiteColor()) } public convenience init(color: UIColor) { self.init(nibName: nil, bundle:nil) view.frame = UIScreen.mainScreen().bounds view.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth] view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBackgroundTransparency) backgroundColor = color setupContainerView() view.addSubview(containerView) //Retaining itself strongly so can exist without strong refrence strongSelf = self } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Dialog Lifecycle /** Hides the dialog */ public func hideDialog() { hideDialog(-1) } /** Hides the dialog, sending a callback if provided when dialog was shown :params: buttonIndex The tag index of the button which was clicked */ internal func hideDialog(buttonIndex: Int) { if buttonIndex >= 0 { if let userAction = userAction { userAction(isOtherButton: buttonIndex > 0) } } view.removeGestureRecognizer(tapGesture) for childView in view.subviews { childView.removeFromSuperview() } view.removeFromSuperview() strongSelf = nil } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view */ public func showDialog(windowView: UIView, title: String?, content: UIView) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: nil, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog */ public func showDialog(windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: nil, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). */ public func showDialog(windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: nil, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked */ public func showDialog(windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: nil, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked */ public func showDialog(windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?) -> NBMaterialDialog { return showDialog(windowView, title: title, content: content, dialogHeight: dialogHeight, okButtonTitle: okButtonTitle, action: action, cancelButtonTitle: cancelButtonTitle, stackedButtons: false) } /** Displays a simple dialog using a title and a view with the content you need - parameter windowView: The window which the dialog is to be attached - parameter title: The dialog title - parameter content: A custom content view - parameter dialogHeight: The height of the dialog - parameter okButtonTitle: The title of the last button (far-most right), normally OK, CLOSE or YES (positive response). - parameter action: The action you wish to invoke when a button is clicked - parameter cancelButtonTitle: The title of the first button (the left button), normally CANCEL or NO (negative response) - parameter stackedButtons: Defines if a stackd button view should be used */ public func showDialog(windowView: UIView, title: String?, content: UIView, dialogHeight: CGFloat?, okButtonTitle: String?, action: ((isOtherButton: Bool) -> Void)?, cancelButtonTitle: String?, stackedButtons: Bool) -> NBMaterialDialog { isStacked = stackedButtons var totalButtonTitleLength: CGFloat = 0.0 self.windowView = windowView let windowSize = windowView.bounds windowView.addSubview(view) view.frame = windowView.bounds tapGesture = UITapGestureRecognizer(target: self, action: "tappedBg") view.addGestureRecognizer(tapGesture) setupContainerView() // Add content to contentView contentView = content setupContentView() if let title = title { setupTitleLabelWithTitle(title) } if let okButtonTitle = okButtonTitle { totalButtonTitleLength += (okButtonTitle.uppercaseString as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8 if let cancelButtonTitle = cancelButtonTitle { totalButtonTitleLength += (cancelButtonTitle.uppercaseString as NSString).sizeWithAttributes([NSFontAttributeName: UIFont.robotoMediumOfSize(14)]).width + 8 } // Calculate if the combined button title lengths are longer than max allowed for this dialog, if so use stacked buttons. let buttonTotalMaxLength: CGFloat = (windowSize.width - (kWidthMargin*2)) - 16 - 16 - 8 if totalButtonTitleLength > buttonTotalMaxLength { isStacked = true } } // Always display a close/ok button, but setting a title is optional. if let okButtonTitle = okButtonTitle { setupButtonWithTitle(okButtonTitle, button: &okButton, isStacked: isStacked) if let okButton = okButton { okButton.tag = 0 okButton.addTarget(self, action: "pressedAnyButton:", forControlEvents: UIControlEvents.TouchUpInside) } } if let cancelButtonTitle = cancelButtonTitle { setupButtonWithTitle(cancelButtonTitle, button: &cancelButton, isStacked: isStacked) if let cancelButton = cancelButton { cancelButton.tag = 1 cancelButton.addTarget(self, action: "pressedAnyButton:", forControlEvents: UIControlEvents.TouchUpInside) } } userAction = action setupViewConstraints() // To get dynamic width to work we need to comment this out and uncomment the stuff in setupViewConstraints. But its currently not working.. containerView.frame = CGRectMake(kWidthMargin, (windowSize.height - (dialogHeight ?? kMinimumHeight)) / 2, windowSize.width - (kWidthMargin*2), fmin(kMaxHeight, (dialogHeight ?? kMinimumHeight))) containerView.clipsToBounds = true return self } // MARK: - View lifecycle public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var sz = UIScreen.mainScreen().bounds.size let sver = UIDevice.currentDevice().systemVersion as NSString let ver = sver.floatValue if ver < 8.0 { // iOS versions before 7.0 did not switch the width and height on device roration if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { let ssz = sz sz = CGSize(width:ssz.height, height:ssz.width) } } } // MARK: - User interaction /** Invoked when the user taps the background (anywhere except the dialog) */ internal func tappedBg() { hideDialog(-1) } /** Invoked when a button is pressed - parameter sender: The button clicked */ internal func pressedAnyButton(sender: AnyObject) { self.hideDialog((sender as! UIButton).tag) } // MARK: - View Constraints /** Sets up the constraints which defines the dialog */ internal func setupViewConstraints() { if constraintViews == nil { constraintViews = ["content": contentView, "containerView": containerView, "window": windowView] } containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-24-[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) if let titleLabel = self.titleLabel { constraintViews["title"] = titleLabel containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-24-[title]-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-24-[title]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } else { containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-24-[content]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } if okButton != nil || cancelButton != nil { if isStacked { setupStackedButtonsConstraints() } else { setupButtonConstraints() } } else { containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[content]-24-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } // TODO: Fix constraints for the containerView so we can remove the dialogheight var // // let margins = ["kWidthMargin": kWidthMargin, "kMinimumHeight": kMinimumHeight, "kMaxHeight": kMaxHeight] // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=kWidthMargin)-[containerView(>=80@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews)) // view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=kWidthMargin)-[containerView(>=48@1000)]-(>=kWidthMargin)-|", options: NSLayoutFormatOptions(0), metrics: margins, views: constraintViews)) // view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) // view.addConstraint(NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) } /** Sets up the constraints for normal horizontal styled button layout */ internal func setupButtonConstraints() { if let okButton = self.okButton { constraintViews["okButton"] = okButton containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[content]-24-[okButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) // The cancel button is only shown when the ok button is visible if let cancelButton = self.cancelButton { constraintViews["cancelButton"] = cancelButton containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cancelButton(==36)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[cancelButton(>=64)]-8-[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } else { containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[okButton(>=64)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } } } /** Sets up the constraints for stacked vertical styled button layout */ internal func setupStackedButtonsConstraints() { constraintViews["okButton"] = okButton! constraintViews["cancelButton"] = cancelButton! containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[content]-24-[okButton(==48)]-[cancelButton(==48)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[okButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[cancelButton]-16-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: constraintViews)) } // MARK: Private view helpers / initializers private func setupContainerView() { containerView.backgroundColor = backgroundColor containerView.layer.cornerRadius = 2.0 containerView.layer.masksToBounds = true containerView.layer.borderWidth = 0.5 containerView.layer.borderColor = UIColor(hex: 0xCCCCCC, alpha: 1.0).CGColor view.addSubview(containerView) } private func setupTitleLabelWithTitle(title: String) { titleLabel = UILabel() if let titleLabel = titleLabel { titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.robotoMediumOfSize(20) titleLabel.textColor = UIColor(white: 0.13, alpha: 1.0) titleLabel.numberOfLines = 0 titleLabel.text = title containerView.addSubview(titleLabel) } } private func setupButtonWithTitle(title: String, inout button: BFPaperButton?, isStacked: Bool) { if button == nil { button = BFPaperButton() } if let button = button { button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(title.uppercaseString, forState: .Normal) button.setTitleColor(NBConfig.AccentColor, forState: .Normal) button.isRaised = false button.titleLabel?.font = UIFont.robotoMediumOfSize(14) if isStacked { button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 20) } else { button.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 8) } containerView.addSubview(button) } } private func setupContentView() { contentView.backgroundColor = UIColor.clearColor() contentView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(contentView) } }
mit
004b957e98833984c46df27ce0569831
46.021531
241
0.692734
5.204979
false
false
false
false
pauljohanneskraft/Math
CoreMath/Classes/Functions/Polynomials/Polynomial.swift
1
12616
// // Polynomial.swift // LinearAlgebra // // Created by Paul Kraft on 04.07.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // public struct Polynomial<Number: Numeric>: BasicArithmetic, CustomStringConvertible { public var coefficients: [Number] public init(_ coefficients: [Number] = []) { self.coefficients = coefficients.isEmpty ? [0] : coefficients } } extension Polynomial { public init(_ integerLiteral: Int) { self.init([Number(integerLiteral: integerLiteral)]) } public init(_ floatLiteral: Double) { self.init([Number(floatLiteral: floatLiteral)]) } public init(arrayLiteral: Number...) { self.init(arrayLiteral) } public init() { self.init([]) } public init(_ tuples: (coefficient: Number, exponent: Int)...) { self.coefficients = [0] for t in tuples { self[t.exponent] += t.coefficient } } } extension Polynomial { // calculus, derivative, integral public var derivative: Polynomial<Number> { if self.coefficients.count == 1 { return Polynomial([0]) } let c = self.coefficients.count - 1 var coefficients = [Number](repeating: 0, count: c) for i in coefficients.indices { coefficients[i] = Number(integerLiteral: i + 1) * self.coefficients[i + 1] } return Polynomial(coefficients) } public var integral: Polynomial<Number> { return integral(c: 0) } public func integral(c index0: Number) -> Polynomial<Number> { let c = self.coefficients.count + 1 var coefficients = [Number](repeating: 0, count: c) coefficients[0] = index0 for i in self.coefficients.indices { coefficients[i + 1] = self.coefficients[i] / Number(integerLiteral: i + 1) } return Polynomial(coefficients).reduced } } extension Polynomial { // reducing public var reduced: Polynomial<Number> { return copy { $0.reduce() } } public mutating func reduce() { let d = degree if d != coefficients.count - 1 { self.coefficients = self.coefficients[0...d] + [] } } } extension Polynomial { // descriptions public var latex: String { return descString(latex: true) } public var description: String { return descString(latex: false) } public var reverseDescription: String { let d = degree if d < 0 { return "0" } if d == 0 { return "\(coefficients[0].reducedDescription)" } let c0 = coefficients[0] var res = "" var hasOneInFront = false if c0 != 0 { res += coefficientDescription(first: !hasOneInFront) hasOneInFront = true } for i in 1 ... d { let ci = coefficients[i] if ci != 0 { res += ci.coefficientDescription(first: !hasOneInFront) + "x^\(i)" } } return res } private func descString(latex: Bool) -> String { var d = degree if d <= 0 { return "\(self[0].reducedDescription)" } let ci = coefficients[d] var res = "\(ci.coefficientDescription(first: true))x\(d == 1 ? "" : exp(latex: latex, d))" d -= 1 while d > 0 { let ci = coefficients[d] if ci != 0 { res += " \(ci.coefficientDescription(first: false))x\(d == 1 ? "" : exp(latex: latex, d))" } d -= 1 } let c0 = coefficients[0] if c0 != 0 { res += " \(c0 < 0 ? "-" : "+") \(c0.abs.reducedDescription)" } return res } private func exp(latex: Bool, _ d: Int) -> String { return latex ? "^{\(d)}" : "^\(d)" } } extension Polynomial { public var isZero: Bool { guard degree == 0 else { return false } if let first = coefficients.first as? Double { return Float(first) == 0 } return coefficients[0] == 0 } public var hashValue: Int { return coefficients.indices.reduce(into: 0) { h, i in let hci = Double(coefficients[i].hashValue) let d = Int(bitPattern: UInt(hci.bitPattern)) let r = (h == 0 ? 1 : h) &* (d &+ i) h = h &+ r } } public var degree: Int { return coefficients.indices.reversed().first { coefficients[$0] != 0 } ?? 0 } public subscript(index: Int) -> Number { get { precondition(index >= 0, "precondition(index >= 0)") return index < coefficients.count ? coefficients[index] : 0 } set { precondition(index >= 0, "precondition(index >= 0)") let count = coefficients.count if index >= count { coefficients.append(contentsOf: [Number](repeating: 0, count: index-count+1)) } coefficients[index] = newValue } } public func call(x: Number) -> Number? { var times: Number = 1, res: Number = 0 for i in coefficients.indices { res += times * coefficients[i] times *= x } return res } public var zeros: [Number] { // http://massmatics.de/merkzettel/index.php#!6:Nullstellenberechnung // TODO: still needs implementation, mostly done var cs = reduced.coefficients var zeros = [Number]() while cs.first == 0 { zeros.append(cs.remove(at: 0)) } switch cs.count - 1 { case -1: return [] case 0: return zeros case 1: return zeros + [-(cs[0] / cs[1])] case 2: let det: Number = cs[1]*cs[1] - 4 * cs[0] * cs[2] if !(det is C) { // det = b^2 - 4ac if det < 0 { return zeros } if det == 0 { return zeros + [-cs[1] / ( 2 * cs[2] ) ] } // -b / 2a } let ds = det.sqrt let a = (-cs[1] + ds ) / ( 2 * cs[2] ) let b = (-cs[1] - ds ) / ( 2 * cs[2] ) return zeros + [a, b] default: let factors = Polynomial(cs).factors for f in factors { guard f.degree >= 3 else { zeros += f.zeros continue } var k = false for i in 1...f.degree where f[i] != 0 { guard !k else { return zeros } k = true } let z = (-f[0]/f[f.degree]).power(1 / Double(f.degree)) zeros.append(z) if f.degree % 2 == 0 { zeros.append(-z) } } return zeros } } public var factors: [Polynomial<Number>] { var cs = reduced.coefficients var factors = [Polynomial<Number>]() guard let i = cs.indices.first(where: { cs[$0] != 0 }) else { return [] } if i > 0 { cs.removeFirst(i) factors.append(Polynomial<Number>((1, i))) } var this = Polynomial(cs) if cs.count < 3 { return factors + [this] } if cs.count == 3 { let det: Number = cs[1]*cs[1] - 4 * cs[0] * cs[2] if !(det is C) { // det = b^2 - 4ac if det < 0 { return factors + [this] } if det == 0 { let n = cs[1] / ( 2 * cs[2] ) return factors + [Polynomial<Number>((n, 0), (1, 1)), Polynomial<Number>((n, 0), (1, 1))] } // -b / 2a } let ds = det.sqrt let a = (cs[1] + ds ) / ( 2 * cs[2] ) let b = (cs[1] - ds ) / ( 2 * cs[2] ) return factors + [Polynomial<Number>((a, 0), (1, 1)), Polynomial<Number>((b, 0), (1, 1))] } // source: http://www.math.utah.edu/~wortman/1050-text-fp.pdf guard let last = cs.last else { return factors } for i in cs.indices { cs[i] /= last } if last != 1 { factors.append(Polynomial<Number>((last, 0))) } this = Polynomial(cs) guard let first = cs.first?.abs, first.isInteger else { return factors } let pfactors = first.integer.divisors for i in 1 ..< cs.count - 1 { for pF in pfactors { let p = Number(integerLiteral: pF) // p let poly1 = Polynomial<Number>((p, 0), (1, i)) let div1 = this /% poly1 if div1.remainder.numerator.isZero { // print("agreeing on", div1, poly1, this, Polynomial(div1.numerator)) factors.append(poly1) return factors + div1.result.factors } // -p let poly2 = Polynomial<Number>((-p, 0), (1, i)) let div2 = this /% poly2 if div2.remainder.numerator.isZero { factors.append(poly2) return factors + div2.result.factors } } } return factors + [this] } } infix operator ?= extension Polynomial { public static func == (lhs: Polynomial, rhs: Polynomial) -> Bool { return lhs.reduced.coefficients == rhs.reduced.coefficients } public static func ?= (lhs: Polynomial, rhs: Polynomial) -> [Number] { return (lhs - rhs).zeros } public static func < (lhs: Polynomial, rhs: Polynomial) -> Bool { let r = rhs.coefficients.count let l = lhs.coefficients.count if l != r { return l < r } for i in (0..<l).reversed() { let cmp = lhs.coefficients[i] - rhs.coefficients[i] guard cmp == 0 else { return cmp < 0 } } return false } } extension Polynomial { public static func + (lhs: Polynomial, rhs: Polynomial) -> Polynomial { return lhs.copy { $0 += rhs } } public static func - (lhs: Polynomial, rhs: Polynomial) -> Polynomial { return lhs.copy { $0 -= rhs } } public static func * (lhs: Polynomial, rhs: Polynomial) -> Polynomial { return lhs.copy { $0 *= rhs } } public static func / (lhs: Polynomial, rhs: Polynomial) -> Polynomial { return lhs.copy { $0 /= rhs } } } extension Polynomial { public static func += (lhs: inout Polynomial, rhs: Polynomial) { for i in 0 ... max(lhs.degree, rhs.degree) { lhs[i] += rhs[i] } lhs.reduce() } public static func -= (lhs: inout Polynomial, rhs: Polynomial) { for i in 0 ... max(lhs.degree, rhs.degree) { lhs[i] -= rhs[i] } lhs.reduce() } public static func *= (lhs: inout Polynomial, rhs: Polynomial) { var res = Polynomial([]) for i in 0 ... lhs.degree { let l = lhs[i] if l != 0 { for j in 0 ... rhs.degree { let r = rhs[j] if r != 0 { res[i+j] += r * l } // example: (x^2 - x) * (x - 1) = x^3 - 2x^2 + x } } } res.reduce() lhs = res } public static func /= (lhs: inout Polynomial, rhs: Polynomial) { let ld = lhs.degree let rd = rhs.degree assert(rd != 0 || rhs[0] != 0) guard ld >= rd else { return } let coefficient = lhs[ld] / rhs[rd] let exponent = ld - rd var c = Polynomial([0]) c[exponent] = coefficient lhs = c + ( (lhs - (rhs * c)) / rhs) lhs.reduce() } public static prefix func - (lhs: Polynomial) -> Polynomial { var lhs = lhs for i in 0 ... lhs.degree { lhs[i] = -lhs[i] } return lhs } } infix operator /% extension Polynomial { public static func % (lhs: Polynomial, rhs: Polynomial) -> (numerator: Polynomial, denominator: Polynomial) { // loses accuracy because ignoring rest, maybe adding another stored property to fit in rest? let ld = lhs.degree let rd = rhs.degree assert(rd != 0 || rhs[0] != 0) guard ld >= rd else { return (lhs, rhs) } let coefficient = lhs[ld] / rhs[rd] let exponent = ld - rd var c = Polynomial([0]) c[exponent] = coefficient return (lhs - (rhs * c)) % rhs } public static func /% (lhs: Polynomial, rhs: Polynomial) -> (result: Polynomial, remainder: (numerator: Polynomial, denominator: Polynomial)) { // loses accuracy because ignoring rest, maybe adding another stored property to fit in rest? let ld = lhs.degree let rd = rhs.degree assert(rd != 0 || rhs[0] != 0) guard ld >= rd else { return (0, (lhs, rhs)) } let coefficient = lhs[ld] / rhs[rd] let exponent = ld - rd var c = Polynomial([0]) c[exponent] = coefficient let res = ( (lhs - (rhs * c)) /% rhs) return (res.result + c, res.remainder) } } extension Polynomial: All {}
mit
2262aeba2725fbd95674085d54948f7b
30.616541
113
0.523583
3.754464
false
false
false
false
apple/swift
stdlib/public/core/ContiguousArrayBuffer.swift
5
36680
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED @_silgen_name("swift_COWChecksEnabled") public func _COWChecksEnabled() -> Bool #endif /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. /// /// NOTE: older runtimes called this _EmptyArrayStorage. The two must /// coexist, so it was renamed. The old name must not be used in the new /// runtime. @_fixed_layout @usableFromInline @_objc_non_lazy_realization internal final class __EmptyArrayStorage : __ContiguousArrayStorageBase { @inlinable @nonobjc internal init(_doNotCallMe: ()) { _internalInvariantFailure("creating instance of __EmptyArrayStorage") } #if _runtime(_ObjC) override internal func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { return _BridgingBuffer(0) } #endif @inlinable override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @inlinable override internal var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @inlinable internal var _emptyArrayStorage: __EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_fixed_layout @usableFromInline internal final class _ContiguousArrayStorage< Element >: __ContiguousArrayStorageBase { @inlinable deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) internal final override func withUnsafeBufferOfObjects<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R { _internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self)) let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: elements, count: count)) } @objc(countByEnumeratingWithState:objects:count:) @_effects(releasenone) internal final override func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { var enumerationState = state.pointee if enumerationState.state != 0 { return 0 } return withUnsafeBufferOfObjects { objects in enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr enumerationState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects.baseAddress) enumerationState.state = 1 state.pointee = enumerationState return objects.count } } @inline(__always) @_effects(readonly) @nonobjc private func _objectAt(_ index: Int) -> Unmanaged<AnyObject> { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArraySubscript(index, count: objects.count), "Array index out of range") return Unmanaged.passUnretained(objects[index]) } } @objc(objectAtIndexedSubscript:) @_effects(readonly) final override internal func objectAtSubscript(_ index: Int) -> Unmanaged<AnyObject> { return _objectAt(index) } @objc(objectAtIndex:) @_effects(readonly) final override internal func objectAt(_ index: Int) -> Unmanaged<AnyObject> { return _objectAt(index) } @objc internal override final var count: Int { @_effects(readonly) get { return withUnsafeBufferOfObjects { $0.count } } } @_effects(releasenone) @objc internal override final func getObjects( _ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange ) { return withUnsafeBufferOfObjects { objects in _precondition( _isValidArrayIndex(range.location, count: objects.count), "Array index out of range") _precondition( _isValidArrayIndex( range.location + range.length, count: objects.count), "Array index out of range") if objects.isEmpty { return } // These objects are "returned" at +0, so treat them as pointer values to // avoid retains. Copy bytes via a raw pointer to circumvent reference // counting while correctly aliasing with all other pointer types. UnsafeMutableRawPointer(aBuffer).copyMemory( from: objects.baseAddress! + range.location, byteCount: range.length * MemoryLayout<AnyObject>.stride) } } /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. internal final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer { _internalInvariant( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _BridgingBuffer(count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @inlinable internal override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @inlinable internal override var staticElementType: Any.Type { return Element.self } @inlinable internal final var _elementPointer: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @_alwaysEmitIntoClient @inline(__always) internal func _uncheckedUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } @_alwaysEmitIntoClient @inline(never) @_effects(readonly) @_semantics("array.getContiguousArrayStorageType") func getContiguousArrayStorageType<Element>( for: Element.Type ) -> _ContiguousArrayStorage<Element>.Type { // We can only reset the type metadata to the correct metadata when bridging // on the current OS going forward. if #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) { // SwiftStdlib 5.7 if Element.self is AnyObject.Type { return _uncheckedUnsafeBitCast( _ContiguousArrayStorage<AnyObject>.self, to: _ContiguousArrayStorage<Element>.Type.self) } } return _ContiguousArrayStorage<Element>.self } @usableFromInline @frozen internal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol { @usableFromInline internal var _storage: __ContiguousArrayStorageBase /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @inlinable internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( getContiguousArrayStorageType(for: Element.self), realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) if let allocSize = _mallocSize(ofAllocation: storageAddr) { let endAddr = storageAddr + allocSize let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } else { _initStorageHeader( count: uninitializedCount, capacity: realMinimumCapacity) } } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @inlinable internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @inlinable internal init(_ storage: __ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @inlinable internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } /// A mutable pointer to the first element. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(mutableOrEmptyStorage, Element.self)) } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @inlinable internal init() { _storage = _emptyArrayStorage } @inlinable internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @inlinable internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @inlinable @inline(__always) internal func getElement(_ i: Int) -> Element { _internalInvariant(i >= 0 && i < count, "Array index out of range") let addr = UnsafePointer<Element>( Builtin.projectTailElems(immutableStorage, Element.self)) return addr[i] } /// The storage of an immutable buffer. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient @inline(__always) internal var immutableStorage : __ContiguousArrayStorageBase { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED _internalInvariant(isImmutable, "Array storage is not immutable") #endif return Builtin.COWBufferForReading(_storage) } /// The storage of a mutable buffer. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient @inline(__always) internal var mutableStorage : __ContiguousArrayStorageBase { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED _internalInvariant(isMutable, "Array storage is immutable") #endif return _storage } /// The storage of a mutable or empty buffer. /// /// - Precondition: The buffer must be mutable or the empty array singleton. @_alwaysEmitIntoClient @inline(__always) internal var mutableOrEmptyStorage : __ContiguousArrayStorageBase { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED _internalInvariant(isMutable || _storage.countAndCapacity.capacity == 0, "Array storage is immutable and not empty") #endif return _storage } #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED @_alwaysEmitIntoClient internal var isImmutable: Bool { get { if (_COWChecksEnabled()) { return capacity == 0 || _swift_isImmutableCOWBuffer(_storage) } return true } nonmutating set { if (_COWChecksEnabled()) { // Make sure to not modify the empty array singleton (which has a // capacity of 0). if capacity > 0 { let wasImmutable = _swift_setImmutableCOWBuffer(_storage, newValue) if newValue { _internalInvariant(!wasImmutable, "re-setting immutable array buffer to immutable") } else { _internalInvariant(wasImmutable, "re-setting mutable array buffer to mutable") } } } } } @_alwaysEmitIntoClient internal var isMutable: Bool { if (_COWChecksEnabled()) { return !_swift_isImmutableCOWBuffer(_storage) } return true } #endif /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _internalInvariant(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCount` or `mutableCount` instead. @inlinable internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _internalInvariant(newValue >= 0) _internalInvariant( newValue <= mutableCapacity, "Can't grow an array buffer past its capacity") mutableStorage.countAndCapacity.count = newValue } } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient @inline(__always) internal var immutableCount: Int { return immutableStorage.countAndCapacity.count } /// The number of elements of the buffer. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient internal var mutableCount: Int { @inline(__always) get { return mutableOrEmptyStorage.countAndCapacity.count } @inline(__always) nonmutating set { _internalInvariant(newValue >= 0) _internalInvariant( newValue <= mutableCapacity, "Can't grow an array buffer past its capacity") mutableStorage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be immutable. @inlinable @inline(__always) internal func _checkValidSubscript(_ index: Int) { _precondition( (index >= 0) && (index < immutableCount), "Index out of range" ) } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient @inline(__always) internal func _checkValidSubscriptMutating(_ index: Int) { _precondition( (index >= 0) && (index < mutableCount), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. /// /// This property is obsolete. It's only used for the ArrayBufferProtocol and /// to keep backward compatibility. /// Use `immutableCapacity` or `mutableCapacity` instead. @inlinable internal var capacity: Int { return _storage.countAndCapacity.capacity } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be immutable. @_alwaysEmitIntoClient @inline(__always) internal var immutableCapacity: Int { return immutableStorage.countAndCapacity.capacity } /// The number of elements the buffer can store without reallocation. /// /// - Precondition: The buffer must be mutable. @_alwaysEmitIntoClient @inline(__always) internal var mutableCapacity: Int { return mutableOrEmptyStorage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal __consuming func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _internalInvariant(bounds.lowerBound >= 0) _internalInvariant(bounds.upperBound >= bounds.lowerBound) _internalInvariant(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } @inlinable internal __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) { guard buffer.count > 0 else { return (makeIterator(), 0) } let c = Swift.min(self.count, buffer.count) buffer.baseAddress!.initialize( from: firstElementAddress, count: c) _fixLifetime(owner) return (IndexingIterator(_elements: self, _position: c), c) } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: firstElementAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` if this buffer's storage is uniquely-referenced; /// otherwise, returns `false`. /// /// This function should only be used for internal sanity checks. /// To guard a buffer mutation, use `beginCOWMutation`. @inlinable internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } /// Returns `true` and puts the buffer in a mutable state if the buffer's /// storage is uniquely-referenced; otherwise, performs no action and returns /// `false`. /// /// - Precondition: The buffer must be immutable. /// /// - Warning: It's a requirement to call `beginCOWMutation` before the buffer /// is mutated. @_alwaysEmitIntoClient internal mutating func beginCOWMutation() -> Bool { if Bool(Builtin.beginCOWMutation(&_storage)) { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED isImmutable = false #endif return true } return false; } /// Puts the buffer in an immutable state. /// /// - Precondition: The buffer must be mutable or the empty array singleton. /// /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated /// until the next call of `beginCOWMutation`. @_alwaysEmitIntoClient @inline(__always) internal mutating func endCOWMutation() { #if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED isImmutable = true #endif Builtin.endCOWMutation(&_storage) } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew() -> _ContiguousArrayBuffer { return _consumeAndCreateNew(bufferIsUnique: false, minimumCapacity: count, growForAppend: false) } /// Creates and returns a new uniquely referenced buffer which is a copy of /// this buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced and the elements are moved - instead of copied - to the new /// buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`, but at least kept at `minimumCapacity`. /// /// This buffer is consumed, i.e. it's released. @_alwaysEmitIntoClient @inline(never) @_semantics("optimize.sil.specialize.owned2guarantee.never") internal __consuming func _consumeAndCreateNew( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) -> _ContiguousArrayBuffer { let newCapacity = _growArrayCapacity(oldCapacity: capacity, minimumCapacity: minimumCapacity, growForAppend: growForAppend) let c = count _internalInvariant(newCapacity >= c) let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: c, minimumCapacity: newCapacity) if bufferIsUnique { // As an optimization, if the original buffer is unique, we can just move // the elements instead of copying. let dest = newBuffer.mutableFirstElementAddress dest.moveInitialize(from: firstElementAddress, count: c) mutableCount = 0 } else { _copyContents( subRange: 0..<c, initializing: newBuffer.mutableFirstElementAddress) } return newBuffer } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @usableFromInline internal __consuming func _asCocoaArray() -> AnyObject { // _asCocoaArray was @inlinable in Swift 5.0 and 5.1, which means that there // are existing apps out there that effectively have the old implementation // Be careful with future changes to this function. Here be dragons! // The old implementation was // if count == 0 { // return _emptyArrayStorage // } // if _isBridgedVerbatimToObjectiveC(Element.self) { // return _storage // } // return __SwiftDeferredNSArray(_nativeStorage: _storage) _connectOrphanedFoundationSubclassesIfNeeded() if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { if #available(SwiftStdlib 5.7, *) { // We optimize _ContiguousArrayStorage<Element> where Element is any // class type to use _ContiguousArrayStorage<AnyObject> when we bridge // to objective-c we need to set the correct Element type so that when // we bridge back we can use O(1) bridging i.e we can adopt the storage. _ = _swift_setClassMetadata(_ContiguousArrayStorage<Element>.self, onObject: _storage) } return _storage } return __SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` if we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @inlinable func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @inlinable internal func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _internalInvariant(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } } /// Append the elements of `rhs` to `lhs`. @inlinable internal func += <Element, C: Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C ) where C.Element == Element { let oldCount = lhs.count let newCount = oldCount + rhs.count let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer( start: lhs.firstElementAddress + oldCount, count: rhs.count) lhs.mutableCount = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.mutableCount = 0 (lhs, newLHS) = (newLHS, lhs) buf = UnsafeMutableBufferPointer( start: lhs.firstElementAddress + oldCount, count: rhs.count) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer: RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable internal var endIndex: Int { return count } @usableFromInline internal typealias Indices = Range<Int> } extension Sequence { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copySequenceToContiguousArray(self) } } @inlinable internal func _copySequenceToContiguousArray< S: Sequence >(_ source: S) -> ContiguousArray<S.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @inlinable internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @inlinable internal func _copyCollectionToContiguousArray< C: Collection >(_ source: C) -> ContiguousArray<C.Element> { let count = source.count if count == 0 { return ContiguousArray() } var result = _ContiguousArrayBuffer<C.Element>( _uninitializedCount: count, minimumCapacity: 0) let p = UnsafeMutableBufferPointer( start: result.firstElementAddress, count: count) var (itr, end) = source._copyContents(initializing: p) _debugPrecondition(itr.next() == nil, "invalid Collection: more than 'count' elements in collection") // We also have to check the evil shrink case in release builds, because // it can result in uninitialized array elements and therefore undefined // behavior. _precondition(end == p.endIndex, "invalid Collection: less than 'count' elements in collection") result.endCOWMutation() return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @usableFromInline @frozen internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @usableFromInline internal var result: _ContiguousArrayBuffer<Element> @usableFromInline internal var p: UnsafeMutablePointer<Element> @usableFromInline internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inlinable @inline(__always) // For performance reasons. internal init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inlinable @inline(__always) // For performance reasons. internal mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity if !result.isEmpty { // This check prevents a data race writing to _swiftEmptyArrayStorage // Since count is always 0 there, this code does nothing anyway newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.mutableCount = 0 } (result, newResult) = (newResult, result) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inlinable @inline(__always) // For performance reasons. internal mutating func addWithExistingCapacity(_ element: Element) { _internalInvariant(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. if (result.capacity != 0) { result.mutableCount = result.capacity - remainingCapacity } else { _internalInvariant(remainingCapacity == 0) _internalInvariant(result.count == 0) } return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inlinable @inline(__always) // For performance reasons. internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _internalInvariant(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() (finalResult, result) = (result, finalResult) remainingCapacity = 0 finalResult.endCOWMutation() return ContiguousArray(_buffer: finalResult) } }
apache-2.0
a56ecf73a3a31878e3303130a7ad88bc
31.256816
94
0.689115
4.821349
false
false
false
false
CD1212/Doughnut
Doughnut/Views/PodcastCellView.swift
1
4275
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * 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 Cocoa class PodcastUnplayedCountView: NSView { var value = 0 { didSet { updateState() } } var loading: Bool = false { didSet { updateState() } } // Render in blue on white bg var highlightColor = false { didSet { self.needsDisplay = true } } let loadingIndicator = NSProgressIndicator() required init?(coder decoder: NSCoder) { super.init(coder: decoder) loadingIndicator.isHidden = true loadingIndicator.style = .spinning loadingIndicator.isIndeterminate = true addSubview(loadingIndicator) } func updateState() { if loading { isHidden = false loadingIndicator.isHidden = false loadingIndicator.startAnimation(self) } else if (value >= 1) { isHidden = false loadingIndicator.isHidden = true loadingIndicator.stopAnimation(self) // let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.paragraphSpacing = 0 paragraphStyle.lineSpacing = 0 attrString = NSMutableAttributedString(string: String(value), attributes: [ NSAttributedStringKey.font: NSFont.boldSystemFont(ofSize: 11), NSAttributedStringKey.foregroundColor: NSColor.white, NSAttributedStringKey.paragraphStyle: paragraphStyle ]) } else { isHidden = true } } override func viewDidMoveToWindow() { loadingIndicator.frame = NSRect(x: frame.width - 16 - 3, y: (frame.height - 16) / 2, width: 16.0, height: 16.0) } var attrString = NSMutableAttributedString(string: "") override func draw(_ dirtyRect: NSRect) { if !loading { let bb = attrString.boundingRect(with: CGSize(width: 50, height: 18), options: []) let X_PAD: CGFloat = 7.0 let Y_PAD: CGFloat = 2.0 let bgWidth = bb.width + (X_PAD * CGFloat(2)) let bgHeight = bb.height + (Y_PAD * CGFloat(2)) let bgMidPoint: CGFloat = bgHeight * 0.5 let bgRect = NSRect(x: bounds.width - bgWidth, y: bounds.midY - bgMidPoint, width: bgWidth, height: bgHeight) let bg = NSBezierPath(roundedRect: bgRect, xRadius: 5, yRadius: 5) if highlightColor { let selectedBlue = NSColor(calibratedRed: 0.090, green: 0.433, blue: 0.937, alpha: 1.0) selectedBlue.setFill() } else { NSColor.gray.setFill() } bg.fill() attrString.draw(with: NSRect(x: bgRect.minX + X_PAD, y: bgRect.minY + 3 + Y_PAD, width: bb.width, height: bb.height), options: []) } } } class PodcastCellView: NSTableCellView { @IBOutlet weak var artwork: NSImageView! @IBOutlet weak var title: NSTextField! @IBOutlet weak var author: NSTextField! @IBOutlet weak var episodeCount: NSTextField! @IBOutlet weak var podcastUnplayedCount: PodcastUnplayedCountView! var loading: Bool = false { didSet { needsDisplay = true podcastUnplayedCount.loading = loading } } override var backgroundStyle: NSView.BackgroundStyle { willSet { if newValue == .dark { title.textColor = NSColor.white author.textColor = NSColor.init(white: 0.9, alpha: 1.0) episodeCount.textColor = NSColor.init(white: 0.9, alpha: 1.0) podcastUnplayedCount.highlightColor = true } else { title.textColor = NSColor.labelColor author.textColor = NSColor.secondaryLabelColor episodeCount.textColor = NSColor.secondaryLabelColor podcastUnplayedCount.highlightColor = false } } } }
gpl-3.0
025ea92e1d477418263a2a2d64b8bc7a
29.319149
136
0.660351
4.402678
false
false
false
false
dankogai/swift-json
Sources/JSON/JSON.swift
1
15730
// // json.swift // json // // Created by Dan Kogai on 7/15/14. // Copyright (c) 2014-2018 Dan Kogai. All rights reserved. // import Foundation public enum JSON:Equatable { public enum JSONError : Equatable { case notAJSONObject case notIterable(JSON.ContentType) case notSubscriptable(JSON.ContentType) case indexOutOfRange(JSON.Index) case keyNonexistent(JSON.Key) case nsError(NSError) } public typealias Key = String public typealias Value = JSON public typealias Index = Int case Error(JSONError) case Null case Bool(Bool) case Number(Double) case String(String) case Array([Value]) case Object([Key:Value]) } extension JSON : Hashable { public var hashValue: Int { switch self { case .Error(let m): fatalError("\(m)") case .Null: return NSNull().hashValue case .Bool(let v): return v.hashValue case .Number(let v): return v.hashValue case .String(let v): return v.hashValue case .Array(let v): return "\(v)".hashValue // will be fixed in Swift 4.2 case .Object(let v): return "\(v)".hashValue // will be fixed in Swift 4.2 } } } extension JSON : CustomStringConvertible { public func toString(depth d:Int, separator s:String, terminator t:String, sortedKey:Bool=false)->String { let i = Swift.String(repeating:s, count:d) let g = s == "" ? "" : " " switch self { case .Error(let m): return ".Error(\"\(m)\")" case .Null: return "null" case .Bool(let v): return v.description case .Number(let v): return v.description case .String(let v): return v.debugDescription case .Array(let a): return "[" + t + a.map{ $0.toString(depth:d+1, separator:s, terminator:t, sortedKey:sortedKey) } .map{ i + s + $0 }.joined(separator:","+t) + t + i + "]" + (d == 0 ? t : "") case .Object(let o): let a = sortedKey ? o.map{ $0 }.sorted{ $0.0 < $1.0 } : o.map{ $0 } return "{" + t + a.map { $0.debugDescription + g + ":" + g + $1.toString(depth:d+1, separator:s, terminator:t, sortedKey:sortedKey) } .map{ i + s + $0 }.joined(separator:"," + t) + t + i + "}" + (d == 0 ? t : "") } } public func toString(space:Int=0)->String { return space == 0 ? toString(depth:0, separator:"", terminator:"") : toString(depth:0, separator:Swift.String(repeating:" ", count:space), terminator:"\n", sortedKey:true) } public var description:String { return self.toString() } } // Inits extension JSON : ExpressibleByNilLiteral, ExpressibleByBooleanLiteral, ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { public init() { self = .Null } public init(nilLiteral: ()) { self = .Null } public typealias BooleanLiteralType = Bool public init(_ value:Bool) { self = .Bool(value) } public init(booleanLiteral value: Bool) { self = .Bool(value) } public typealias FloatLiteralType = Double public init(_ value:Double) { self = .Number(value) } public init(floatLiteral value:Double) { self = .Number(value) } public typealias IntegerLiteralType = Int public init(_ value:Int) { self = .Number(Double(value)) } public init(integerLiteral value: Int) { self = .Number(Double(value)) } public typealias StringLiteralType = String public init(_ value:String) { self = .String(value) } public init(stringLiteral value:String) { self = .String(value) } public typealias ArrayLiteralElement = Value public init(_ value:[Value]) { self = .Array(value) } public init(arrayLiteral value:JSON...) { self = .Array(value) } public init(_ value:[Key:Value]) { self = .Object(value) } public init(dictionaryLiteral value:(Key,Value)...) { var o = [Key:Value]() value.forEach { o[$0.0] = $0.1 } self = .Object(o) } } extension JSON { public init(jsonObject:Any?) { switch jsonObject { // Be careful! JSONSerialization renders bool as NSNumber use .objcType to tell the difference case let a as NSNumber: switch Swift.String(cString:a.objCType) { case "c", "C": self = .Bool(a as! Bool) default: self = .Number(a as! Double) } case nil: self = .Null case let a as String: self = .String(a) case let a as [Any?]: self = .Array(a.map{ JSON(jsonObject:$0) }) case let a as [Key:Any?]: var o = [Key:Value]() a.forEach{ o[$0.0] = JSON(jsonObject:$0.1) } self = .Object(o) default: self = .Error(.notAJSONObject) } } public init(data:Data) { do { let jo = try JSONSerialization.jsonObject(with:data, options:[.allowFragments]) self.init(jsonObject:jo) } catch { self = .Error(.nsError(error as NSError)) } } public init(string:String) { self.init(data:string.data(using:.utf8)!) } public init(urlString:String) { if let url = URL(string: urlString) { self = JSON(url:url) } else { self = JSON.Null } } public init(url:URL) { do { let str = try Swift.String(contentsOf: url) self = JSON(string:str) } catch { self = .Error(.nsError(error as NSError)) } } public var data:Data { return self.description.data(using:.utf8)! } public var jsonObject:Any { return try! JSONSerialization.jsonObject(with:self.data, options:[.allowFragments]) } } extension JSON { public enum ContentType { case error, null, bool, number, string, array, object } public var type:ContentType { switch self { case .Error(_): return .error case .Null: return .null case .Bool(_): return .bool case .Number(_): return .number case .String(_): return .string case .Array(_): return .array case .Object(_): return .object } } public var isNull:Bool { return type == .null } public var error:JSONError? { switch self { case .Error(let v): return v default: return nil } } public var bool:Bool? { get { switch self { case .Bool(let v): return v default: return nil } } set { self = .Bool(newValue!) } } public var number:Double? { get { switch self { case .Number(let v):return v default: return nil } } set { self = .Number(newValue!) } } public var string:String? { get { switch self { case .String(let v):return v default: return nil } } set { self = .String(newValue!) } } public var array:[Value]? { get { switch self { case .Array(let v): return v default: return nil } } set { self = .Array(newValue!) } } public var object:[Key:Value]? { get { switch self { case .Object(let v):return v default: return nil } } set { self = .Object(newValue!) } } public var isIterable:Bool { return type == .array || type == .object } } extension JSON { public subscript(_ idx:Index)->JSON { get { switch self { case .Error(_): return self case .Array(let a): guard idx < a.count else { return .Error(.indexOutOfRange(idx)) } return a[idx] default: return .Error(.notSubscriptable(self.type)) } } set { switch self { case .Array(var a): if idx < a.count { a[idx] = newValue } else { for _ in a.count ..< idx { a.append(.Null) } a.append(newValue) } self = .Array(a) default: fatalError("\"\(self)\" is not an array") } } } public subscript(_ key:Key)->JSON { get { switch self { case .Error(_): return self case .Object(let o): return o[key] ?? .Error(.keyNonexistent(key)) default: return .Error(.notSubscriptable(self.type)) } } set { switch self { case .Object(var o): o[key] = newValue self = .Object(o) default: fatalError("\"\(self)\" is not an object") } } } } extension JSON : Sequence { public enum IteratorKey { case None case Index(Int) case Key(String) public var index:Int? { switch self { case .Index(let v): return v default: return nil } } public var key:String? { switch self { case .Key(let v): return v default: return nil } } } public typealias Element = (key:IteratorKey,value:JSON) // for Sequence conformance public typealias Iterator = AnyIterator<Element> public func makeIterator() -> AnyIterator<JSON.Element> { switch self { case .Array(let a): var i = -1 return AnyIterator { i += 1 return a.count <= i ? nil : (IteratorKey.Index(i), a[i]) } case .Object(let o): var kv = o.map{ $0 } var i = -1 return AnyIterator { i += 1 return kv.count <= i ? nil : (IteratorKey.Key(kv[i].0), kv[i].1) } default: return AnyIterator { nil } } } public func walk<R>(depth:Int=0, collect:(JSON, [(IteratorKey, R)], Int)->R, visit:(JSON)->R)->R { return collect(self, self.map { let value = $0.1.isIterable ? $0.1.walk(depth:depth+1, collect:collect, visit:visit) : visit($0.1) return ($0.0, value) }, depth) } public func walk(depth:Int=0, visit:(JSON)->JSON)->JSON { return self.walk(depth:depth, collect:{ node,pairs,depth in switch node.type { case .array: return .Array(pairs.map{ $0.1 }) case .object: var o = [Key:Value]() pairs.forEach{ o[$0.0.key!] = $0.1 } return .Object(o) default: return .Error(.notIterable(node.type)) } }, visit:visit) } public func walk(depth:Int=0, collect:(JSON, [Element], Int)->JSON)->JSON { return self.walk(depth:depth, collect:collect, visit:{ $0 }) } public func pick(picker:(JSON)->Bool)->JSON { return self.walk{ node, pairs, depth in switch node.type { case .array: return .Array(pairs.map{ $0.1 }.filter({ picker($0) }) ) case .object: var o = [Key:Value]() pairs.filter{ picker($0.1) }.forEach{ o[$0.0.key!] = $0.1 } return .Object(o) default: return .Error(.notIterable(node.type)) } } } } extension JSON : Codable { private static let codableTypes:[Codable.Type] = [ [Key:Value].self, [Value].self, Swift.String.self, Swift.Bool.self, UInt.self, Int.self, Double.self, Float.self, UInt64.self, UInt32.self, UInt16.self, UInt8.self, Int64.self, Int32.self, Int16.self, Int8.self, ] public init(from decoder: Decoder) throws { if let c = try? decoder.singleValueContainer(), !c.decodeNil() { for type in JSON.codableTypes { switch type { case let t as Swift.Bool.Type: if let v = try? c.decode(t) { self = .Bool(v); return } case let t as Int.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as Int8.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as Int32.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as Int64.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as UInt.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as UInt8.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as UInt16.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as UInt32.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as UInt64.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as Float.Type: if let v = try? c.decode(t) { self = .Number(Double(v)); return } case let t as Double.Type: if let v = try? c.decode(t) { self = .Number(v); return } case let t as Swift.String.Type:if let v = try? c.decode(t) { self = .String(v); return } case let t as [Value].Type: if let v = try? c.decode(t) { self = .Array(v); return } case let t as [Key:Value].Type: if let v = try? c.decode(t) { self = .Object(v); return } default: break } } } self = JSON.Null } public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() if self.isNull { try c.encodeNil() return } switch self { case .Bool(let v): try c.encode(v) case .Number(let v): try c.encode(v) case .String(let v): try c.encode(v) case .Array(let v): try c.encode(v) case .Object(let v): try c.encode(v) default: break } } } extension JSON.JSONError : CustomStringConvertible { public enum ErrorType { case notAJSONObject, notIterable, notSubscriptable, indexOutOfRange, keyNonexistent, nsError } public var type:ErrorType { switch self { case .notAJSONObject: return .notAJSONObject case .notIterable: return .notIterable case .notSubscriptable(_): return .notSubscriptable case .indexOutOfRange(_): return .indexOutOfRange case .keyNonexistent(_): return .keyNonexistent case .nsError(_): return .nsError } } public var nsError:NSError? { switch self { case .nsError(let v) : return v default : return nil } } public var description:String { switch self { case .notAJSONObject: return "not an jsonObject" case .notIterable(let t): return "\(t) is not iterable" case .notSubscriptable(let t): return "\(t) cannot be subscripted" case .indexOutOfRange(let i): return "index \(i) is out of range" case .keyNonexistent(let k): return "key \"\(k)\" does not exist" case .nsError(let e): return "\(e)" } } }
mit
fba1d22302784e387f4f4a4eaba4be19
38.722222
134
0.528163
4.018906
false
false
false
false
IrenaChou/IRDouYuZB
IRDouYuZBSwift/IRDouYuZBSwift/Classes/Tools/Extension/UIBarButtonItem_Extension.swift
1
965
// // UIBarButtonItem_Extension.swift // IRDouYuZBSwift // // Created by zhongdai on 2017/1/5. // Copyright © 2017年 ir. All rights reserved. // import UIKit extension UIBarButtonItem { /// 便利构造函数 /// /// - Parameters: /// - imageName: 显示normal图片名 /// - highImageName: 显示high图片名【非必传】 /// - size: 按钮大小【非必传】 convenience init(imageName: String,highImageName: String = "",size:CGSize = CGSize.zero ) { let btn = UIButton() btn.setImage(UIImage.init(named: imageName), for: UIControlState.normal) if highImageName != "" { btn.setImage(UIImage.init(named: highImageName), for: UIControlState.highlighted) } if size != CGSize.zero { btn.frame = CGRect(origin: CGPoint.zero, size: size) }else{ btn.sizeToFit() } self.init(customView: btn) } }
mit
6a795da29893633b955763f3cfdcea95
24.055556
94
0.58204
3.921739
false
false
false
false
nalexn/ViewInspector
Sources/ViewInspector/Modifiers/NavigationBarModifiers.swift
1
5954
import SwiftUI #if os(macOS) && !MAC_OS_VERSION_13_0 struct ToolbarPlacement { static var navigationBar: ToolbarPlacement { .init() } } #endif @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView { @available(iOS 13.0, tvOS 13.0, *) @available(macOS, unavailable) func navigationBarHidden() throws -> Bool { if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { let value = try modifierAttribute(modifierLookup: { modifier -> Bool in guard modifier.modifierType.contains("ToolbarAppearanceModifier"), let bars = try? Inspector.attribute( path: "modifier|bars", value: modifier, type: [ToolbarPlacement].self) else { return false } return bars.contains(.navigationBar) }, path: "modifier|visibility|some", type: Any.self, call: "navigationBarHidden") return String(describing: value) != "visible" } let value = try modifierAttribute( modifierName: "_PreferenceWritingModifier<NavigationBarHiddenKey>", path: "modifier|value", type: Any.self, call: "navigationBarHidden") if let bool = value as? Bool?, let value = bool { return value } return try Inspector.cast(value: value, type: Bool.self) } @available(iOS 13.0, tvOS 13.0, *) @available(macOS, unavailable) func navigationBarBackButtonHidden() throws -> Bool { return try modifierAttribute( modifierName: "_PreferenceWritingModifier<NavigationBarBackButtonHiddenKey>", path: "modifier|value", type: Bool.self, call: "navigationBarBackButtonHidden") } @available(iOS 13.0, *) @available(macOS, unavailable) @available(tvOS, unavailable) @available(watchOS, unavailable) func statusBarHidden() throws -> Bool { return try modifierAttribute( modifierName: "TransactionalPreferenceModifier<Bool, StatusBarKey>", path: "modifier|value", type: Bool.self, call: "statusBar(hidden:)") } } @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) extension ToolbarPlacement: BinaryEquatable { } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension ViewType { struct EnvironmentReaderView { } } // MARK: - Content Extraction @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.EnvironmentReaderView: SingleViewContent { static func child(_ content: Content) throws -> Content { return content } } // MARK: - Extraction from SingleViewContent parent @available(iOS 13.0, tvOS 13.0, *) @available(macOS, unavailable) @available(watchOS, unavailable) public extension InspectableView where View: SingleViewContent { func navigationBarItems() throws -> InspectableView<ViewType.ClassifiedView> { return try navigationBarItems(AnyView.self) } func navigationBarItems<V>(_ viewType: V.Type) throws -> InspectableView<ViewType.ClassifiedView> where V: SwiftUI.View { return try navigationBarItems(viewType: viewType, content: try child()) } } // MARK: - Extraction from MultipleViewContent parent @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View: MultipleViewContent { func navigationBarItems(_ index: Int = 0) throws -> InspectableView<ViewType.ClassifiedView> { return try navigationBarItems(AnyView.self, index) } func navigationBarItems<V>(_ viewType: V.Type, _ index: Int = 0) throws -> InspectableView<ViewType.ClassifiedView> where V: SwiftUI.View { return try navigationBarItems(viewType: viewType, content: try child(at: index)) } } // MARK: - Unwrapping the EnvironmentReaderView @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension InspectableView { func navigationBarItems<V>(viewType: V.Type, content: Content) throws -> InspectableView<ViewType.ClassifiedView> where V: SwiftUI.View { typealias Closure = (EnvironmentValues) -> ModifiedContent<V, _PreferenceWritingModifier<FakeNavigationBarItemsKey>> guard let closure = try? Inspector.attribute(label: "content", value: content.view), let closureDesc = Inspector.typeName(value: closure) as String?, closureDesc.contains("_PreferenceWritingModifier<NavigationBarItemsKey>>") else { throw InspectionError.modifierNotFound(parent: Inspector.typeName(value: content.view), modifier: "navigationBarItems", index: 0) } let expectedViewType = closureDesc.navigationBarItemsWrappedViewType guard Inspector.typeName(type: viewType) == expectedViewType else { // swiftlint:disable line_length throw InspectionError.notSupported( "Please substitute '\(expectedViewType).self' as the parameter for 'navigationBarItems()' inspection call") // swiftlint:enable line_length } guard let typedClosure = withUnsafeBytes(of: closure, { $0.bindMemory(to: Closure.self).first }) else { throw InspectionError.typeMismatch(closure, Closure.self) } let view = typedClosure(EnvironmentValues()) return try .init(try Inspector.unwrap(view: view, medium: content.medium), parent: self) } } private extension String { var navigationBarItemsWrappedViewType: String { let prefix = "(EnvironmentValues) -> ModifiedContent<" let suffix = ", _PreferenceWritingModifier<NavigationBarItemsKey>>" return components(separatedBy: prefix).last? .components(separatedBy: suffix).first ?? self } } private struct FakeNavigationBarItemsKey: PreferenceKey { static var defaultValue: String = "" static func reduce(value: inout String, nextValue: () -> String) { } }
mit
ffbae479d1e4874a4f016070184db1d4
39.22973
123
0.67081
4.572965
false
false
false
false
crazypoo/PTools
Pods/JXSegmentedView/Sources/Core/JXSegmentedView.swift
1
36040
// // JXSegmentedView.swift // JXSegmentedView // // Created by jiaxin on 2018/12/26. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit public let JXSegmentedViewAutomaticDimension: CGFloat = -1 /// 选中item时的类型 /// /// - unknown: 不是选中 /// - code: 通过代码调用方法`func selectItemAt(index: Int)`选中 /// - click: 通过点击item选中 /// - scroll: 通过滚动到item选中 public enum JXSegmentedViewItemSelectedType { case unknown case code case click case scroll } public protocol JXSegmentedViewListContainer { var defaultSelectedIndex: Int { set get } func contentScrollView() -> UIScrollView func reloadData() func didClickSelectedItem(at index: Int) } public protocol JXSegmentedViewDataSource: AnyObject { var isItemWidthZoomEnabled: Bool { get } var selectedAnimationDuration: TimeInterval { get } var itemSpacing: CGFloat { get } var isItemSpacingAverageEnabled: Bool { get } func reloadData(selectedIndex: Int) /// 返回数据源数组,数组元素必须是JXSegmentedBaseItemModel及其子类 /// /// - Parameter segmentedView: JXSegmentedView /// - Returns: 数据源数组 func itemDataSource(in segmentedView: JXSegmentedView) -> [JXSegmentedBaseItemModel] /// 返回index对应item的宽度,等同于cell的宽度。 /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 目标index /// - Returns: item的宽度 func segmentedView(_ segmentedView: JXSegmentedView, widthForItemAt index: Int) -> CGFloat /// 返回index对应item的content宽度,等同于cell上面内容的宽度。与上面的代理方法不同,需要注意辨别。部分使用场景下,cell的宽度比较大,但是内容的宽度比较小。这个时候指示器又需要和item的content等宽。所以,添加了此代理方法。 /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 目标index func segmentedView(_ segmentedView: JXSegmentedView, widthForItemContentAt index: Int) -> CGFloat /// 注册cell class /// /// - Parameter segmentedView: JXSegmentedView func registerCellClass(in segmentedView: JXSegmentedView) /// 返回index对应的cell /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 目标index /// - Returns: JXSegmentedBaseCell及其子类 func segmentedView(_ segmentedView: JXSegmentedView, cellForItemAt index: Int) -> JXSegmentedBaseCell /// 根据当前选中的selectedIndex,刷新目标index的itemModel /// /// - Parameters: /// - itemModel: JXSegmentedBaseItemModel /// - index: 目标index /// - selectedIndex: 当前选中的index func refreshItemModel(_ segmentedView: JXSegmentedView, _ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int) /// item选中的时候调用。当前选中的currentSelectedItemModel状态需要更新为未选中;将要选中的willSelectedItemModel状态需要更新为选中。 /// /// - Parameters: /// - currentSelectedItemModel: 当前选中的itemModel /// - willSelectedItemModel: 将要选中的itemModel /// - selectedType: 选中的类型 func refreshItemModel(_ segmentedView: JXSegmentedView, currentSelectedItemModel: JXSegmentedBaseItemModel, willSelectedItemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) /// 左右滚动过渡时调用。根据当前的从左到右的百分比,刷新leftItemModel和rightItemModel /// /// - Parameters: /// - leftItemModel: 相对位置在左边的itemModel /// - rightItemModel: 相对位置在右边的itemModel /// - percent: 从左到右的百分比 func refreshItemModel(_ segmentedView: JXSegmentedView, leftItemModel: JXSegmentedBaseItemModel, rightItemModel: JXSegmentedBaseItemModel, percent: CGFloat) } /// 为什么会把选中代理分为三个,因为有时候只关心点击选中的,有时候只关心滚动选中的,有时候只关心选中。所以具体情况,使用对应方法。 public protocol JXSegmentedViewDelegate: AnyObject { /// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件,而不关心具体是点击还是滚动选中的情况。 /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 选中的index func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) /// 点击选中的情况才会调用该方法 /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 选中的index func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) /// 滚动选中的情况才会调用该方法 /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 选中的index func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) /// 正在滚动中的回调 /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - leftIndex: 正在滚动中,相对位置处于左边的index /// - rightIndex: 正在滚动中,相对位置处于右边的index /// - percent: 从左往右计算的百分比 func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) /// 是否允许点击选中目标index的item /// /// - Parameters: /// - segmentedView: JXSegmentedView /// - index: 目标index func segmentedView(_ segmentedView: JXSegmentedView, canClickItemAt index: Int) -> Bool } /// 提供JXSegmentedViewDelegate的默认实现,这样对于遵从JXSegmentedViewDelegate的类来说,所有代理方法都是可选实现的。 public extension JXSegmentedViewDelegate { func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) { } func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) { } func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) { } func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) { } func segmentedView(_ segmentedView: JXSegmentedView, canClickItemAt index: Int) -> Bool { return true } } /// 内部会自己找到父UIViewController,然后将其automaticallyAdjustsScrollViewInsets设置为false,这一点请知晓。 open class JXSegmentedView: UIView, JXSegmentedViewRTLCompatible { open weak var dataSource: JXSegmentedViewDataSource? { didSet { dataSource?.reloadData(selectedIndex: selectedIndex) } } open weak var delegate: JXSegmentedViewDelegate? open private(set) var collectionView: JXSegmentedCollectionView! open var contentScrollView: UIScrollView? { willSet { contentScrollView?.removeObserver(self, forKeyPath: "contentOffset") } didSet { contentScrollView?.scrollsToTop = false contentScrollView?.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) } } public var listContainer: JXSegmentedViewListContainer? = nil { didSet { listContainer?.defaultSelectedIndex = defaultSelectedIndex contentScrollView = listContainer?.contentScrollView() } } /// indicators的元素必须是遵从JXSegmentedIndicatorProtocol协议的UIView及其子类 open var indicators = [JXSegmentedIndicatorProtocol & UIView]() { didSet { collectionView.indicators = indicators } } /// 初始化或者reloadData之前设置,用于指定默认的index open var defaultSelectedIndex: Int = 0 { didSet { selectedIndex = defaultSelectedIndex if listContainer != nil { listContainer?.defaultSelectedIndex = defaultSelectedIndex } } } open private(set) var selectedIndex: Int = 0 /// 整体内容的左边距,默认JXSegmentedViewAutomaticDimension(等于itemSpacing) open var contentEdgeInsetLeft: CGFloat = JXSegmentedViewAutomaticDimension /// 整体内容的右边距,默认JXSegmentedViewAutomaticDimension(等于itemSpacing) open var contentEdgeInsetRight: CGFloat = JXSegmentedViewAutomaticDimension /// 点击切换的时候,contentScrollView的切换是否需要动画 open var isContentScrollViewClickTransitionAnimationEnabled: Bool = true private var itemDataSource = [JXSegmentedBaseItemModel]() private var innerItemSpacing: CGFloat = 0 private var lastContentOffset: CGPoint = CGPoint.zero /// 正在滚动中的目标index。用于处理正在滚动列表的时候,立即点击item,会导致界面显示异常。 private var scrollingTargetIndex: Int = -1 private var isFirstLayoutSubviews = true deinit { contentScrollView?.removeObserver(self, forKeyPath: "contentOffset") } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal collectionView = JXSegmentedCollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.backgroundColor = .clear collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.scrollsToTop = false collectionView.dataSource = self collectionView.delegate = self if #available(iOS 10.0, *) { collectionView.isPrefetchingEnabled = false } if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } if segmentedViewShouldRTLLayout() { collectionView.semanticContentAttribute = .forceLeftToRight segmentedView(horizontalFlipForView: collectionView) } addSubview(collectionView) } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) var nextResponder: UIResponder? = newSuperview while nextResponder != nil { if let parentVC = nextResponder as? UIViewController { parentVC.automaticallyAdjustsScrollViewInsets = false break } nextResponder = nextResponder?.next } } open override func layoutSubviews() { super.layoutSubviews() //部分使用者为了适配不同的手机屏幕尺寸,JXSegmentedView的宽高比要求保持一样。所以它的高度就会因为不同宽度的屏幕而不一样。计算出来的高度,有时候会是位数很长的浮点数,如果把这个高度设置给UICollectionView就会触发内部的一个错误。所以,为了规避这个问题,在这里对高度统一向下取整。 //如果向下取整导致了你的页面异常,请自己重新设置JXSegmentedView的高度,保证为整数即可。 let targetFrame = CGRect(x: 0, y: 0, width: bounds.size.width, height: floor(bounds.size.height)) if isFirstLayoutSubviews { isFirstLayoutSubviews = false collectionView.frame = targetFrame reloadDataWithoutListContainer() }else { if collectionView.frame != targetFrame { collectionView.frame = targetFrame collectionView.collectionViewLayout.invalidateLayout() collectionView.reloadData() } } } //MARK: - Public public final func dequeueReusableCell(withReuseIdentifier identifier: String, at index: Int) -> JXSegmentedBaseCell { let indexPath = IndexPath(item: index, section: 0) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) guard cell.isKind(of: JXSegmentedBaseCell.self) else { fatalError("Cell class must be subclass of JXSegmentedBaseCell") } return cell as! JXSegmentedBaseCell } open func reloadData() { reloadDataWithoutListContainer() listContainer?.reloadData() } open func reloadDataWithoutListContainer() { dataSource?.reloadData(selectedIndex: selectedIndex) dataSource?.registerCellClass(in: self) if let itemSource = dataSource?.itemDataSource(in: self) { itemDataSource = itemSource } if selectedIndex < 0 || selectedIndex >= itemDataSource.count { defaultSelectedIndex = 0 selectedIndex = 0 } innerItemSpacing = dataSource?.itemSpacing ?? 0 var totalItemWidth: CGFloat = 0 var totalContentWidth: CGFloat = getContentEdgeInsetLeft() for (index, itemModel) in itemDataSource.enumerated() { itemModel.index = index itemModel.itemWidth = (dataSource?.segmentedView(self, widthForItemAt: index) ?? 0) if dataSource?.isItemWidthZoomEnabled == true { itemModel.itemWidth *= itemModel.itemWidthCurrentZoomScale } itemModel.isSelected = (index == selectedIndex) totalItemWidth += itemModel.itemWidth if index == itemDataSource.count - 1 { totalContentWidth += itemModel.itemWidth + getContentEdgeInsetRight() }else { totalContentWidth += itemModel.itemWidth + innerItemSpacing } } if dataSource?.isItemSpacingAverageEnabled == true && totalContentWidth < bounds.size.width { var itemSpacingCount = itemDataSource.count - 1 var totalItemSpacingWidth = bounds.size.width - totalItemWidth if contentEdgeInsetLeft == JXSegmentedViewAutomaticDimension { itemSpacingCount += 1 }else { totalItemSpacingWidth -= contentEdgeInsetLeft } if contentEdgeInsetRight == JXSegmentedViewAutomaticDimension { itemSpacingCount += 1 }else { totalItemSpacingWidth -= contentEdgeInsetRight } if itemSpacingCount > 0 { innerItemSpacing = totalItemSpacingWidth / CGFloat(itemSpacingCount) } } var selectedItemFrameX = innerItemSpacing var selectedItemWidth: CGFloat = 0 totalContentWidth = getContentEdgeInsetLeft() for (index, itemModel) in itemDataSource.enumerated() { if index < selectedIndex { selectedItemFrameX += itemModel.itemWidth + innerItemSpacing }else if index == selectedIndex { selectedItemWidth = itemModel.itemWidth } if index == itemDataSource.count - 1 { totalContentWidth += itemModel.itemWidth + getContentEdgeInsetRight() }else { totalContentWidth += itemModel.itemWidth + innerItemSpacing } } let minX: CGFloat = 0 let maxX = totalContentWidth - bounds.size.width let targetX = selectedItemFrameX - bounds.size.width/2 + selectedItemWidth/2 collectionView.setContentOffset(CGPoint(x: max(min(maxX, targetX), minX), y: 0), animated: false) if contentScrollView != nil { if contentScrollView!.frame.equalTo(CGRect.zero) && contentScrollView!.superview != nil { //某些情况系统会出现JXSegmentedView先布局,contentScrollView后布局。就会导致下面指定defaultSelectedIndex失效,所以发现contentScrollView的frame为zero时,强行触发其父视图链里面已经有frame的一个父视图的layoutSubviews方法。 //比如JXSegmentedListContainerView会将contentScrollView包裹起来使用,该情况需要JXSegmentedListContainerView.superView触发布局更新 var parentView = contentScrollView?.superview while parentView != nil && parentView?.frame.equalTo(CGRect.zero) == true { parentView = parentView?.superview } parentView?.setNeedsLayout() parentView?.layoutIfNeeded() } contentScrollView!.setContentOffset(CGPoint(x: CGFloat(selectedIndex) * contentScrollView!.bounds.size.width , y: 0), animated: false) } for indicator in indicators { if itemDataSource.isEmpty { indicator.isHidden = true }else { indicator.isHidden = false let selectedItemFrame = getItemFrameAt(index: selectedIndex) let indicatorParams = JXSegmentedIndicatorSelectedParams(currentSelectedIndex: selectedIndex, currentSelectedItemFrame: selectedItemFrame, selectedType: .unknown, currentItemContentWidth: dataSource?.segmentedView(self, widthForItemContentAt: selectedIndex) ?? 0, collectionViewContentSize: CGSize(width: totalContentWidth, height: bounds.size.height)) indicator.refreshIndicatorState(model: indicatorParams) if indicator.isIndicatorConvertToItemFrameEnabled { var indicatorConvertToItemFrame = indicator.frame indicatorConvertToItemFrame.origin.x -= selectedItemFrame.origin.x itemDataSource[selectedIndex].indicatorConvertToItemFrame = indicatorConvertToItemFrame } } } collectionView.reloadData() collectionView.collectionViewLayout.invalidateLayout() } open func reloadItem(at index: Int) { guard index >= 0 && index < itemDataSource.count else { return } dataSource?.refreshItemModel(self, itemDataSource[index], at: index, selectedIndex: selectedIndex) let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? JXSegmentedBaseCell cell?.reloadData(itemModel: itemDataSource[index], selectedType: .unknown) } /// 代码选中指定index /// 如果要同时触发列表容器对应index的列表加载,请再调用`listContainerView.didClickSelectedItem(at: index)`方法 /// /// - Parameter index: 目标index open func selectItemAt(index: Int) { selectItemAt(index: index, selectedType: .code) } //MARK: - KVO open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "contentOffset" { let contentOffset = change?[NSKeyValueChangeKey.newKey] as! CGPoint if contentScrollView?.isTracking == true || contentScrollView?.isDecelerating == true { //用户滚动引起的contentOffset变化,才处理。 if contentScrollView?.bounds.size.width == 0 { // 如果contentScrollView Frame为零,直接忽略 return } var progress = contentOffset.x/contentScrollView!.bounds.size.width if Int(progress) > itemDataSource.count - 1 || progress < 0 { //超过了边界,不需要处理 return } if contentOffset.x == 0 && selectedIndex == 0 && lastContentOffset.x == 0 { //滚动到了最左边,且已经选中了第一个,且之前的contentOffset.x为0 return } let maxContentOffsetX = contentScrollView!.contentSize.width - contentScrollView!.bounds.size.width if contentOffset.x == maxContentOffsetX && selectedIndex == itemDataSource.count - 1 && lastContentOffset.x == maxContentOffsetX { //滚动到了最右边,且已经选中了最后一个,且之前的contentOffset.x为maxContentOffsetX return } progress = max(0, min(CGFloat(itemDataSource.count - 1), progress)) let baseIndex = Int(floor(progress)) let remainderProgress = progress - CGFloat(baseIndex) let leftItemFrame = getItemFrameAt(index: baseIndex) let rightItemFrame = getItemFrameAt(index: baseIndex + 1) var rightItemContentWidth: CGFloat = 0 if baseIndex + 1 < itemDataSource.count { rightItemContentWidth = dataSource?.segmentedView(self, widthForItemContentAt: baseIndex + 1) ?? 0 } let indicatorParams = JXSegmentedIndicatorTransitionParams(currentSelectedIndex: selectedIndex, leftIndex: baseIndex, leftItemFrame: leftItemFrame, leftItemContentWidth: dataSource?.segmentedView(self, widthForItemContentAt: baseIndex) ?? 0, rightIndex: baseIndex + 1, rightItemFrame: rightItemFrame, rightItemContentWidth: rightItemContentWidth, percent: remainderProgress) if remainderProgress == 0 { //滑动翻页,需要更新选中状态 //滑动一小段距离,然后放开回到原位,contentOffset同样的值会回调多次。例如在index为1的情况,滑动放开回到原位,contentOffset会多次回调CGPoint(width, 0) if !(lastContentOffset.x == contentOffset.x && selectedIndex == baseIndex) { scrollSelectItemAt(index: baseIndex) } }else { //快速滑动翻页,当remainderRatio没有变成0,但是已经翻页了,需要通过下面的判断,触发选中 if abs(progress - CGFloat(selectedIndex)) > 1 { var targetIndex = baseIndex if progress < CGFloat(selectedIndex) { targetIndex = baseIndex + 1 } scrollSelectItemAt(index: targetIndex) } if selectedIndex == baseIndex { scrollingTargetIndex = baseIndex + 1 }else { scrollingTargetIndex = baseIndex } dataSource?.refreshItemModel(self, leftItemModel: itemDataSource[baseIndex], rightItemModel: itemDataSource[baseIndex + 1], percent: remainderProgress) for indicator in indicators { indicator.contentScrollViewDidScroll(model: indicatorParams) if indicator.isIndicatorConvertToItemFrameEnabled { var leftIndicatorConvertToItemFrame = indicator.frame leftIndicatorConvertToItemFrame.origin.x -= leftItemFrame.origin.x itemDataSource[baseIndex].indicatorConvertToItemFrame = leftIndicatorConvertToItemFrame var rightIndicatorConvertToItemFrame = indicator.frame rightIndicatorConvertToItemFrame.origin.x -= rightItemFrame.origin.x itemDataSource[baseIndex + 1].indicatorConvertToItemFrame = rightIndicatorConvertToItemFrame } } let leftCell = collectionView.cellForItem(at: IndexPath(item: baseIndex, section: 0)) as? JXSegmentedBaseCell leftCell?.reloadData(itemModel: itemDataSource[baseIndex], selectedType: .unknown) let rightCell = collectionView.cellForItem(at: IndexPath(item: baseIndex + 1, section: 0)) as? JXSegmentedBaseCell rightCell?.reloadData(itemModel: itemDataSource[baseIndex + 1], selectedType: .unknown) delegate?.segmentedView(self, scrollingFrom: baseIndex, to: baseIndex + 1, percent: remainderProgress) } } lastContentOffset = contentOffset } } //MARK: - Private private func clickSelectItemAt(index: Int) { guard delegate?.segmentedView(self, canClickItemAt: index) != false else { return } selectItemAt(index: index, selectedType: .click) } private func scrollSelectItemAt(index: Int) { selectItemAt(index: index, selectedType: .scroll) } private func selectItemAt(index: Int, selectedType: JXSegmentedViewItemSelectedType) { guard index >= 0 && index < itemDataSource.count else { return } if index == selectedIndex { if selectedType == .code { listContainer?.didClickSelectedItem(at: index) }else if selectedType == .click { delegate?.segmentedView(self, didClickSelectedItemAt: index) listContainer?.didClickSelectedItem(at: index) }else if selectedType == .scroll { delegate?.segmentedView(self, didScrollSelectedItemAt: index) } delegate?.segmentedView(self, didSelectedItemAt: index) scrollingTargetIndex = -1 return } let currentSelectedItemModel = itemDataSource[selectedIndex] let willSelectedItemModel = itemDataSource[index] dataSource?.refreshItemModel(self, currentSelectedItemModel: currentSelectedItemModel, willSelectedItemModel: willSelectedItemModel, selectedType: selectedType) let currentSelectedCell = collectionView.cellForItem(at: IndexPath(item: selectedIndex, section: 0)) as? JXSegmentedBaseCell currentSelectedCell?.reloadData(itemModel: currentSelectedItemModel, selectedType: selectedType) let willSelectedCell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) as? JXSegmentedBaseCell willSelectedCell?.reloadData(itemModel: willSelectedItemModel, selectedType: selectedType) if scrollingTargetIndex != -1 && scrollingTargetIndex != index { let scrollingTargetItemModel = itemDataSource[scrollingTargetIndex] scrollingTargetItemModel.isSelected = false dataSource?.refreshItemModel(self, currentSelectedItemModel: scrollingTargetItemModel, willSelectedItemModel: willSelectedItemModel, selectedType: selectedType) let scrollingTargetCell = collectionView.cellForItem(at: IndexPath(item: scrollingTargetIndex, section: 0)) as? JXSegmentedBaseCell scrollingTargetCell?.reloadData(itemModel: scrollingTargetItemModel, selectedType: selectedType) } if dataSource?.isItemWidthZoomEnabled == true { if selectedType == .click || selectedType == .code { //延时为了解决cellwidth变化,点击最后几个cell,scrollToItem会出现位置偏移bu。需要等cellWidth动画渐变结束后再滚动到index的cell位置。 let selectedAnimationDurationInMilliseconds = Int((dataSource?.selectedAnimationDuration ?? 0)*1000) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(selectedAnimationDurationInMilliseconds)) { self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true) } }else if selectedType == .scroll { //滚动选中的直接处理 collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true) } }else { collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: true) } if contentScrollView != nil && (selectedType == .click || selectedType == .code) { contentScrollView!.setContentOffset(CGPoint(x: contentScrollView!.bounds.size.width*CGFloat(index), y: 0), animated: isContentScrollViewClickTransitionAnimationEnabled) } selectedIndex = index let currentSelectedItemFrame = getSelectedItemFrameAt(index: selectedIndex) for indicator in indicators { let indicatorParams = JXSegmentedIndicatorSelectedParams(currentSelectedIndex: selectedIndex, currentSelectedItemFrame: currentSelectedItemFrame, selectedType: selectedType, currentItemContentWidth: dataSource?.segmentedView(self, widthForItemContentAt: selectedIndex) ?? 0, collectionViewContentSize: nil) indicator.selectItem(model: indicatorParams) if indicator.isIndicatorConvertToItemFrameEnabled { var indicatorConvertToItemFrame = indicator.frame indicatorConvertToItemFrame.origin.x -= currentSelectedItemFrame.origin.x itemDataSource[selectedIndex].indicatorConvertToItemFrame = indicatorConvertToItemFrame willSelectedCell?.reloadData(itemModel: willSelectedItemModel, selectedType: selectedType) } } scrollingTargetIndex = -1 if selectedType == .code { listContainer?.didClickSelectedItem(at: index) }else if selectedType == .click { delegate?.segmentedView(self, didClickSelectedItemAt: index) listContainer?.didClickSelectedItem(at: index) }else if selectedType == .scroll { delegate?.segmentedView(self, didScrollSelectedItemAt: index) } delegate?.segmentedView(self, didSelectedItemAt: index) } private func getItemFrameAt(index: Int) -> CGRect { guard index < itemDataSource.count else { return CGRect.zero } var x = getContentEdgeInsetLeft() for i in 0..<index { let itemModel = itemDataSource[i] var itemWidth: CGFloat = 0 if itemModel.isTransitionAnimating && itemModel.isItemWidthZoomEnabled { //正在进行动画的时候,itemWidthCurrentZoomScale是随着动画渐变的,而没有立即更新到目标值 if itemModel.isSelected { itemWidth = (dataSource?.segmentedView(self, widthForItemAt: itemModel.index) ?? 0) * itemModel.itemWidthSelectedZoomScale }else { itemWidth = (dataSource?.segmentedView(self, widthForItemAt: itemModel.index) ?? 0) * itemModel.itemWidthNormalZoomScale } }else { itemWidth = itemModel.itemWidth } x += itemWidth + innerItemSpacing } var width: CGFloat = 0 let selectedItemModel = itemDataSource[index] if selectedItemModel.isTransitionAnimating && selectedItemModel.isItemWidthZoomEnabled { width = (dataSource?.segmentedView(self, widthForItemAt: selectedItemModel.index) ?? 0) * selectedItemModel.itemWidthSelectedZoomScale }else { width = selectedItemModel.itemWidth } return CGRect(x: x, y: 0, width: width, height: bounds.size.height) } private func getSelectedItemFrameAt(index: Int) -> CGRect { guard index < itemDataSource.count else { return CGRect.zero } var x = getContentEdgeInsetLeft() for i in 0..<index { let itemWidth = (dataSource?.segmentedView(self, widthForItemAt: i) ?? 0) x += itemWidth + innerItemSpacing } var width: CGFloat = 0 let selectedItemModel = itemDataSource[index] if selectedItemModel.isItemWidthZoomEnabled { width = (dataSource?.segmentedView(self, widthForItemAt: selectedItemModel.index) ?? 0) * selectedItemModel.itemWidthSelectedZoomScale }else { width = selectedItemModel.itemWidth } return CGRect(x: x, y: 0, width: width, height: bounds.size.height) } private func getContentEdgeInsetLeft() -> CGFloat { if contentEdgeInsetLeft == JXSegmentedViewAutomaticDimension { return innerItemSpacing }else { return contentEdgeInsetLeft } } private func getContentEdgeInsetRight() -> CGFloat { if contentEdgeInsetRight == JXSegmentedViewAutomaticDimension { return innerItemSpacing }else { return contentEdgeInsetRight } } } extension JXSegmentedView: UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemDataSource.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = dataSource?.segmentedView(self, cellForItemAt: indexPath.item) { cell.reloadData(itemModel: itemDataSource[indexPath.item], selectedType: .unknown) return cell }else { return UICollectionViewCell(frame: CGRect.zero) } } } extension JXSegmentedView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var isTransitionAnimating = false for itemModel in itemDataSource { if itemModel.isTransitionAnimating { isTransitionAnimating = true break } } if !isTransitionAnimating { //当前没有正在过渡的item,才允许点击选中 clickSelectItemAt(index: indexPath.item) } } } extension JXSegmentedView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: getContentEdgeInsetLeft(), bottom: 0, right: getContentEdgeInsetRight()) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: itemDataSource[indexPath.item].itemWidth, height: collectionView.bounds.size.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return innerItemSpacing } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return innerItemSpacing } }
mit
e7d28366e61d30b4f9ba6467e353e8c4
45.296552
207
0.642812
5.521467
false
false
false
false
eljeff/AudioKit
Sources/AudioKit/Nodes/Generators/Physical Models/RhodesPianoKey.swift
1
2392
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit #if !os(tvOS) /// STK RhodesPiano /// public class RhodesPianoKey: Node, AudioUnitContainer, Tappable, Toggleable { /// Unique four-letter identifier "rhds" public static let ComponentDescription = AudioComponentDescription(instrument: "rhds") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? /// Internal audio unit for Rhodes piano key public class InternalAU: AudioUnitBase { /// Create Rhodes Piano Key DSP /// - Returns: DSP Reference public override func createDSP() -> DSPRef { return akCreateDSP("RhodesPianoKeyDSP") } /// Trigger a rhoes piano key note /// - Parameters: /// - note: MIDI Note Number /// - velocity: MIDI Velocity public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity) { if let midiBlock = scheduleMIDIEventBlock { let event = MIDIEvent(noteOn: note, velocity: velocity, channel: 0) event.data.withUnsafeBufferPointer { ptr in guard let ptr = ptr.baseAddress else { return } midiBlock(AUEventSampleTimeImmediate, 0, event.data.count, ptr) } } } } // MARK: - Initialization /// Initialize the STK Rhdoes Piano model /// /// - Parameters: /// - note: MIDI note number /// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127 /// public init() { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType } } /// Trigger the sound with a set of parameters /// /// - Parameters: /// - note: MIDI note number /// - velocity: Amplitude or volume expressed as a MIDI Velocity 0-127 /// public func trigger(note: MIDINoteNumber, velocity: MIDIVelocity = 127) { internalAU?.start() internalAU?.trigger(note: note, velocity: velocity) } } #endif
mit
0253d04c3d371d0f2e2be8b7ea5fd84b
30.064935
100
0.625
4.962656
false
false
false
false
cornerstonecollege/402
Jorge_Juri/CustomViews/CustomViews/CircleView.swift
1
2590
// // CircleView.swift // CustomViews // // Created by Luiz on 2016-10-13. // Copyright © 2016 Ideia do Luiz. All rights reserved. // import UIKit extension UIBezierPath { // create a custom method for the pen func setStrokeColor(color:UIColor) { color.setStroke() } func setFillColor(color:UIColor) { color.setFill() } } class CircleView: UIView { override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { self.center = touches.first!.location(in: self.superview) //es porque se debe invocar al padre no a si mismo } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // the code below is in case that you will need an initial point // let initialPoint: CGPoint // // init(frame: CGRect, point: CGPoint) { // super.init(frame:frame) // self.initialPoint = point // } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { let pen = UIBezierPath() let center = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2) // make the circle let twoPi = CGFloat(M_PI) * 2 pen.addArc(withCenter: center, radius: rect.size.width / 2 - 5, startAngle: 0.0, endAngle: twoPi, clockwise: true) // configure and paint it //pen.lineWidth = 10.0 //pen.setStrokeColor(color: UIColor.clear) //pen.stroke() pen.setFillColor(color: UIColor.blue) pen.fill() //make the triangle let lastPoint = CGPoint(x: rect.size.width, y: rect.size.height) pen.move(to: lastPoint) pen.addLine(to: center) pen.addLine(to: CGPoint(x: center.x, y: center.y + 20)) pen.addLine(to: lastPoint) pen.close() // configure and paint it //pen.lineWidth = 10.0 //pen.setStrokeColor(color: UIColor.clear) //pen.stroke() pen.setFillColor(color: UIColor.blue) pen.fill() // pen.move(to: rect.origin) // pen.addLine(to: CGPoint(x: rect.width, y: rect.height)) // pen.lineWidth = 10.0 // // We are avoiding to do UIColor.black.setStroke() // pen.setStrokeColor(color: UIColor.black) // pen.stroke() } }
gpl-3.0
fe7095dc8f84a9b5d876b73d9ca7d44d
28.089888
122
0.587486
3.940639
false
false
false
false
wzw5566/WDYZB
WDYZB/WDYZB/Classes/UIBarButtonItem-Extension.swift
1
899
// // File.swift // WDYZB // // Created by vincentwen on 17/5/2. // Copyright © 2017年 vincentwen. All rights reserved. // import UIKit extension UIBarButtonItem{ convenience init(imageName:String, highImageName : String = "", size :CGSize = CGSize.zero) { //1.定义按钮 let btn = UIButton() //2.设置按钮图片 btn.setImage(UIImage(named: imageName), for: UIControlState()) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } //3.设置按钮的尺寸 if size == CGSize.zero{ btn.sizeToFit() }else{ btn.frame = CGRect(origin: CGPoint.zero, size: size) } //4.创建UUIBarButtonItem self.init(customView : btn) } }
mit
42cefb06e89d6308895b3ef586af56a5
19.428571
97
0.516317
4.333333
false
false
false
false
drewcrawford/DCAKit
DCAKit/Foundation Additions/KVOHelp2.swift
1
3166
// // KVOHelp2.swift // DCAKit // // Created by Drew Crawford on 7/27/15. // Copyright (c) 2015 DrewCrawfordApps. All rights reserved. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. /* KVOHelp had certain design issues. It's hard to make the nillable observers actually work in practice, not the least bit because KVOed objects can't be deallocated with observers still attached in recent versions of Foundation. It's a design principle that there are deterministic crashes if you do something suspicious with memory in this library. */ import Foundation public typealias KVOHelp2ClosureType = (keyPath: String, object: AnyObject, change: [NSObject: AnyObject], context: Any?) -> () public protocol KVOHandle { func stopObserving() } private final class Observer : NSObject { init(keyPath: String, observing: AnyObject, context: Any?, closure: KVOHelp2ClosureType) { self.context = context self.observing = observing self.keyPath = keyPath self.closure = closure } private let context : Any? private let closure : KVOHelp2ClosureType private let keyPath: String private weak var observing : AnyObject? var dead = false private override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { self.closure(keyPath: keyPath, object: object, change: change, context: context) } deinit { precondition(dead, "Discarding a KVOHandle while it is live. Call stopObserving() on it first.") } } extension Observer : KVOHandle { /**Stop observing for this KVO path. */ private func stopObserving() { precondition(observing != nil, "Deallocated an object with observers still attached. Remove those observers first.") observing!.removeObserver(self, forKeyPath:keyPath) dead = true } } extension NSObject { /**A saner blocks-based KVO, based on the pattern in Nitrogen. - parameters: - keyPath: The key path to observe. - options: The options to observe. - context: Any object you'd like to receive in callbacks. - closure: The callback that will be called. Note that you probably want a `[unowned self]` here. - returns: A handle. You must keep a strong reference to this handle for the duration of the observation. (Failing to do so will cause a deterministic crash.) To stop observing, use the function on the handle. */ public func beginObservingValue(forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: Any? = nil, closure: KVOHelp2ClosureType) -> KVOHandle { let o = Observer(keyPath: keyPath, observing: self, context: context, closure: closure) self.addObserver(o, forKeyPath: keyPath, options: options, context: nil) return o } }
mit
d8a83535acc4ba3ce5fd4d45aa4aaebc
44.884058
231
0.721415
4.354883
false
false
false
false
natecook1000/swift
test/SourceKit/CodeComplete/complete_moduleimportdepth.swift
4
5096
import ImportsImportsFoo import FooHelper.FooHelperExplicit func test() { let x = 1 #^A^# } // XFAIL: broken_std_regex // REQUIRES: objc_interop // RUN: %complete-test -hide-none -group=none -tok=A %s -raw -- -I %S/Inputs -F %S/../Inputs/libIDE-mock-sdk > %t // RUN: %FileCheck %s < %t // Swift == 1 // CHECK-LABEL: key.name: "abs(:)", // CHECK-NEXT: key.sourcetext: "abs(<#T##x: Comparable & SignedNumeric##Comparable & SignedNumeric#>)", // CHECK-NEXT: key.description: "abs(x: Comparable & SignedNumeric)", // CHECK-NEXT: key.typename: "Comparable & SignedNumeric", // CHECK-NEXT: key.doc.brief: "Returns the absolute value of the given number.", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Swift" // CHECK-NEXT: }, // CHECK-LABEL: key.name: "abs(:)", // CHECK-NEXT: key.sourcetext: "abs(<#T##x: Comparable & SignedNumeric##Comparable & SignedNumeric#>)", // CHECK-NEXT: key.description: "abs(x: Comparable & SignedNumeric)", // CHECK-NEXT: key.typename: "Comparable & SignedNumeric", // CHECK-NEXT: key.doc.brief: "Returns the absolute value of the given number.", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Swift" // CHECK-NEXT: }, // FooHelper.FooHelperExplicit == 1 // CHECK-LABEL: key.name: "fooHelperExplicitFrameworkFunc1(:)", // CHECK-NEXT: key.sourcetext: "fooHelperExplicitFrameworkFunc1(<#T##a: Int32##Int32#>)", // CHECK-NEXT: key.description: "fooHelperExplicitFrameworkFunc1(a: Int32)", // CHECK-NEXT: key.typename: "Int32", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "FooHelper.FooHelperExplicit" // CHECK-NEXT: }, // ImportsImportsFoo == 1 // CHECK-LABEL: key.name: "importsImportsFoo()", // CHECK-NEXT: key.sourcetext: "importsImportsFoo()", // CHECK-NEXT: key.description: "importsImportsFoo()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 1, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "ImportsImportsFoo" // CHECK-NEXT: }, // Bar == 2 // CHECK-LABEL: key.name: "BarForwardDeclaredClass", // CHECK-NEXT: key.sourcetext: "BarForwardDeclaredClass", // CHECK-NEXT: key.description: "BarForwardDeclaredClass", // CHECK-NEXT: key.typename: "BarForwardDeclaredClass", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 2, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Bar" // CHECK-NEXT: }, // ImportsFoo == 2 // CHECK-LABEL: key.name: "importsFoo()", // CHECK-NEXT: key.sourcetext: "importsFoo()", // CHECK-NEXT: key.description: "importsFoo()", // CHECK-NEXT: key.typename: "Void", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 2, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "ImportsFoo" // CHECK-NEXT: }, // Foo == FooSub == 3 // CHECK-LABEL: key.name: "FooClassBase", // CHECK-NEXT: key.sourcetext: "FooClassBase", // CHECK-NEXT: key.description: "FooClassBase", // CHECK-NEXT: key.typename: "FooClassBase", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 3, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Foo" // CHECK-NEXT: }, // CHECK-LABEL: key.name: "FooSubEnum1", // CHECK-NEXT: key.sourcetext: "FooSubEnum1", // CHECK-NEXT: key.description: "FooSubEnum1", // CHECK-NEXT: key.typename: "FooSubEnum1", // CHECK-NEXT: key.context: source.codecompletion.context.othermodule, // CHECK-NEXT: key.moduleimportdepth: 3, // CHECK-NEXT: key.num_bytes_to_erase: 0, // CHECK-NOT: key.modulename // CHECK: key.modulename: "Foo.FooSub" // CHECK-NEXT: }, // FooHelper == 4 // FIXME: rdar://problem/20230030 // We're picking up the implicit import of FooHelper used to attach FooHelperExplicit to. // xCHECK-LABEL: key.name: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.sourcetext: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.description: "FooHelperUnnamedEnumeratorA2", // xCHECK-NEXT: key.typename: "Int", // xCHECK-NEXT: key.context: source.codecompletion.context.othermodule, // xCHECK-NEXT: key.moduleimportdepth: 4, // xCHECK-NEXT: key.num_bytes_to_erase: 0, // xCHECK-NOT: key.modulename // xCHECK: key.modulename: "FooHelper" // xCHECK-NEXT: },
apache-2.0
a74ef7518e5f62dce31430cc823226bf
41.115702
113
0.6823
3.167185
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/BarShadowViewController.swift
1
3628
// // BarShadowViewController.swift // ApiDemo-Swift // // Created by Jacob su on 8/6/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class BarShadowViewController: UIViewController, UIBarPositioningDelegate { var navBar : UINavigationBar! var toolBar : UIToolbar! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let navBar = UINavigationBar() //navBar.backgroundColor = UIColor.yellowColor() self.navBar = navBar let toolBar = UIToolbar() //toolBar.backgroundColor = UIColor.blueColor() self.toolBar = toolBar self.view.addSubview(navBar) self.view.addSubview(toolBar) navBar.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ navBar.widthAnchor.constraint(equalTo: self.view.widthAnchor), navBar.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor), toolBar.widthAnchor.constraint(equalTo: self.view.widthAnchor), toolBar.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.bottomAnchor) ]) let sz = CGSize(width: 20,height: 20) navBar.setBackgroundImage(imageOfSize(sz, false) { UIColor(white:0.95, alpha:0.85).setFill() //UIColor(red: 1, green: 0, blue: 0, alpha: 1).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 0,width: 20,height: 20)) }, for:.any, barMetrics: .default) toolBar.setBackgroundImage(imageOfSize(sz) { UIColor(white:0.95, alpha:0.85).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 0,width: 20,height: 20)) }, forToolbarPosition:.any, barMetrics: .default) let shadowsz = CGSize(width: 4,height: 4) navBar.shadowImage = imageOfSize(shadowsz) { UIColor.gray.withAlphaComponent(0.3).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 0,width: 4,height: 2)) UIColor.gray.withAlphaComponent(0.15).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 2,width: 4,height: 2)) } toolBar.setShadowImage(imageOfSize(shadowsz) { UIColor.gray.withAlphaComponent(0.3).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 2,width: 4,height: 2)) UIColor.gray.withAlphaComponent(0.15).setFill() UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0,y: 0,width: 4,height: 2)) }, forToolbarPosition:.any ) navBar.isTranslucent = true toolBar.isTranslucent = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func imageOfSize(_ size:CGSize, _ opaque:Bool = false, _ closure:() -> ()) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, opaque, 0) closure() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } func position(for bar: UIBarPositioning) -> UIBarPosition { switch true { // another (old) trick for special switch situations case bar === self.navBar: return .topAttached case bar === self.toolBar: return .bottom default: return .any } } }
apache-2.0
af055d93e23d855cf27d6ea5505b3122
37.178947
103
0.62917
4.836
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/Advanced Settings/InsertMediaImagePositionSettingsViewController.swift
3
4238
final class InsertMediaImagePositionSettingsViewController: ViewController { private let tableView = UITableView() private var selectedIndexPath: IndexPath? typealias ImagePosition = InsertMediaSettings.Advanced.ImagePosition func selectedImagePosition(isTextWrappingEnabled: Bool) -> ImagePosition { guard isTextWrappingEnabled else { return .none } guard let selectedIndexPath = selectedIndexPath else { return .right } return viewModels[selectedIndexPath.row].imagePosition } struct ViewModel { let imagePosition: ImagePosition let title: String let isSelected: Bool init(imagePosition: ImagePosition, isSelected: Bool = false) { self.imagePosition = imagePosition self.title = imagePosition.displayTitle self.isSelected = isSelected } } private lazy var viewModels: [ViewModel] = { let rightViewModel = ViewModel(imagePosition: .right, isSelected: true) let leftViewModel = ViewModel(imagePosition: .left) let centerViewModel = ViewModel(imagePosition: .center) return [rightViewModel, leftViewModel, centerViewModel] }() override func viewDidLoad() { scrollView = tableView super.viewDidLoad() navigationBar.isBarHidingEnabled = false tableView.dataSource = self tableView.delegate = self view.wmf_addSubviewWithConstraintsToEdges(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.identifier) tableView.separatorInset = .zero tableView.tableFooterView = UIView() title = ImagePosition.displayTitle apply(theme: theme) } private func apply(theme: Theme, to cell: UITableViewCell) { cell.backgroundColor = theme.colors.paperBackground cell.contentView.backgroundColor = theme.colors.paperBackground cell.textLabel?.textColor = theme.colors.primaryText let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = theme.colors.midBackground cell.selectedBackgroundView = selectedBackgroundView } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground tableView.backgroundColor = view.backgroundColor tableView.separatorColor = theme.colors.border tableView.reloadData() } } extension InsertMediaImagePositionSettingsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModels.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier, for: indexPath) let viewModel = viewModels[indexPath.row] cell.textLabel?.text = viewModel.title cell.accessoryType = viewModel.isSelected ? .checkmark : .none if viewModel.isSelected { cell.accessoryType = .checkmark selectedIndexPath = indexPath } else { cell.accessoryType = .none } apply(theme: theme, to: cell) return cell } } extension InsertMediaImagePositionSettingsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard let selectedIndexPath = selectedIndexPath, let selectedCell = tableView.cellForRow(at: selectedIndexPath) else { return indexPath } selectedCell.accessoryType = .none return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath) selectedCell?.accessoryType = .checkmark selectedIndexPath = indexPath } }
mit
8dbcb00d02aab309fb9c07e1148df35d
35.852174
108
0.680982
5.837466
false
false
false
false
lucasharding/antenna
tvOS/Controllers/GuideTimeCollectionViewHeader.swift
1
1201
// // GuideTimeCollectionViewHeader.swift // ustvnow-tvos // // Created by Lucas Harding on 2015-09-12. // Copyright © 2015 Lucas Harding. All rights reserved. // import UIKit open class GuideTimeCollectionViewHeader : UICollectionReusableView { var titleLabel: UILabel! public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { let titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 38, weight: UIFontWeightLight) titleLabel.textColor = UIColor.white titleLabel.translatesAutoresizingMaskIntoConstraints = false self.addSubview(titleLabel) self.titleLabel = titleLabel addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[titleLabel]-30-|", options: [], metrics: nil, views: ["titleLabel": titleLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[titleLabel]-|", options: [], metrics: nil, views: ["titleLabel": titleLabel])) } }
gpl-3.0
5e894488808f70750ab03317d4848879
31.432432
162
0.673333
4.918033
false
false
false
false
huankong/Weibo
Weibo/Weibo/Main/Base/VisitorView.swift
1
7953
// // VisitorView.swift // Weibo // // Created by ldy on 16/6/23. // Copyright © 2016年 ldy. All rights reserved. // import UIKit import SnapKit protocol VisitorViewDelegate: NSObjectProtocol{ //登录回调 func loginBtnDidAction() //注册回调 func registBtnDidAction() //去关注回调 func attenBtnDidAction() } class VisitorView: UIView { enum VisitorType { case IsHome case IsMessage case IsDiscover case IsProfile } deinit { print("销毁") } //定义一个属性保存代理对象 weak var delegate: VisitorViewDelegate? override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { addSubview(bgIconImage) addSubview(maskIconImage) addSubview(whithV) addSubview(iconImage) addSubview(messageLabel) addSubview(attenBtn) addSubview(registBtn) addSubview(loginBtn) maskIconImage.snp_makeConstraints { (make) in make.edges.equalTo(self) } bgIconImage.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-100) make.size.equalTo(CGSize(width: 200, height: 200)) } whithV.snp_makeConstraints(closure: { (make) in make.size.equalTo(CGSize(width: 200, height: 100)) make.top.equalTo(bgIconImage.snp_top).offset(100) make.right.equalTo(bgIconImage.snp_right) }) iconImage.snp_makeConstraints { (make) in make.size.equalTo(CGSize(width: 100, height: 100)) make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-100) } messageLabel.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.size.equalTo(CGSize(width: 300, height: 50)) make.top.equalTo(iconImage.snp_bottom).offset(50) } attenBtn.snp_makeConstraints { (make) in make.centerX.equalTo(self) make.size.equalTo(CGSize(width: 100, height: 35)) make.top.equalTo(messageLabel.snp_bottom).offset(20) } registBtn.snp_makeConstraints { (make) in make.centerX.equalTo(self).offset(-60) make.size.equalTo(CGSize(width: 100, height: 35)) make.top.equalTo(messageLabel.snp_bottom).offset(20) } loginBtn.snp_makeConstraints { (make) in make.centerX.equalTo(self).offset(60) make.size.equalTo(CGSize(width: 100, height: 35)) make.top.equalTo(messageLabel.snp_bottom).offset(20) } } func visitorInfo(visitorType: VisitorType) { switch visitorType { case .IsHome: //动画 animationBgIcon() registBtn.hidden = true loginBtn.hidden = true attenBtn.hidden = false bgIconImage.hidden = false case .IsMessage: hidenView() iconImage.image = self.getbtnImage("visitordiscover_image_message") messageLabel.text = "登录后,别人评论你的微博,给你发消息,都会在这里收到通知" case .IsDiscover: hidenView() iconImage.image = self.getbtnImage("visitordiscover_image_message") messageLabel.text = "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过" case .IsProfile: hidenView() iconImage.image = UIImage(named: "visitordiscover_image_profile") messageLabel.text = "登录后,你的微博、相册、个人资料会显示在这里,展示给别人" } } func hidenView() { bgIconImage.hidden = true attenBtn.hidden = true registBtn.hidden = false loginBtn.hidden = false } /** 主页背景图标动画 */ func animationBgIcon() { let anima = CABasicAnimation(keyPath: "transform.rotation") anima.fromValue = 0 anima.toValue = M_PI * 2 anima.repeatCount = MAXFLOAT anima.duration = 20 anima.removedOnCompletion = false bgIconImage.layer.addAnimation(anima, forKey: nil) } //MARK: -懒加载视图 /// 背景图标 private lazy var bgIconImage: UIImageView = { let img = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) return img }() /// 大背景视图 private lazy var maskIconImage: UIImageView = { let img = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) return img }() private lazy var whithV: UIView = { let whiV = UIView() whiV.backgroundColor = UIColor.whiteColor() return whiV }() /// 房子 private lazy var iconImage: UIImageView = { let img = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) return img }() /// 消息文字 private lazy var messageLabel: UILabel = { let label = UILabel() label.text = "关注一些人,回这里看看有什么惊喜" label.textColor = UIColor.darkGrayColor() label.font = UIFont.systemFontOfSize(14) label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center return label }() /// 关注按钮 private lazy var attenBtn: UIButton = { let btn = UIButton(type: UIButtonType.Custom) btn.setTitle("去关注", forState: UIControlState.Normal) btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.setBackgroundImage(self.getbtnImage("common_button_white_disable"), forState: UIControlState.Normal) //添加监听 btn.addTarget(self, action: #selector(attenBtnAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() /// 注册按钮 private lazy var registBtn: UIButton = { let btn = UIButton(type: UIButtonType.Custom) btn.setTitle("注册", forState: UIControlState.Normal) btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) btn.setBackgroundImage(self.getbtnImage("common_button_white_disable"), forState: UIControlState.Normal) //添加监听 btn.addTarget(self, action: #selector(registBtnAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() /// 登录按钮 private lazy var loginBtn: UIButton = { let btn = UIButton(type: UIButtonType.Custom) btn.setTitle("登录", forState: UIControlState.Normal) btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) btn.setBackgroundImage(self.getbtnImage("common_button_white_disable"), forState: UIControlState.Normal) //添加监听 btn.addTarget(self, action: #selector(loginBtnAction), forControlEvents: UIControlEvents.TouchUpInside) return btn }() //设置btn图片 func getbtnImage(imageName: String) -> UIImage { var btnImage = UIImage(named: imageName) btnImage = btnImage?.stretchableImageWithLeftCapWidth(Int((btnImage?.size.width)!/2.0), topCapHeight: Int((btnImage?.size.height)!/2.0)) return btnImage! } //MARK: -按钮点击事件 /** 关注按钮点击事件 */ func attenBtnAction() { delegate?.attenBtnDidAction() } /** 注册按钮点击事件 */ func registBtnAction() { delegate?.registBtnDidAction() } /** 登录按钮点击事件 */ func loginBtnAction() { delegate?.loginBtnDidAction() } }
apache-2.0
b91a9156e296236298815f84d96c9ada
31.921053
144
0.610711
4.37923
false
false
false
false
kevintavog/Radish
src/Radish/Controllers/SingleViewWindowController-MenuHandling.swift
1
10447
// // Radish // import AppKit import RangicCore // Menu handlers for SingleViewWindowController extension SingleViewWindowController { @IBAction func onShowWikipediaOnMap(_ sender: Any) { var val = false if menuShowWikipediaOnMap.state == NSControl.StateValue.off { menuShowWikipediaOnMap.state = NSControl.StateValue.on val = true } else { menuShowWikipediaOnMap.state = NSControl.StateValue.off val = false } Notifications.postNotification(Notifications.SingleView.ShowWikipediaOnMap, object: self, userInfo: ["ShowWikipediaOnMap": val]) } @IBAction func onShowPlacenameDetails(_ sender: Any) { var val = false if menuShowPlacenameDetails.state == NSControl.StateValue.off { menuShowPlacenameDetails.state = NSControl.StateValue.on val = true } else { menuShowPlacenameDetails.state = NSControl.StateValue.off val = false } Notifications.postNotification(Notifications.SingleView.ShowPlacenameDetails, object: self, userInfo: ["ShowPlacenameDetails": val]) } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { switch MenuItemTag(rawValue: menuItem.tag)! { case .alwaysEnable: return true case .requiresFile: return (mediaProvider?.mediaCount)! > 0 } } func tryToMoveTo(_ calculate: (_ index: Int, _ maxIndex: Int) -> Int) { if let provider = mediaProvider { let count = provider.mediaCount if count > 0 { displayFileByIndex(calculate(currentFileIndex, count - 1)) } } } @objc override func pageUp(_ sender: Any?) { tryToMoveTo({ index, maxIndex in max(0, index - Preferences.pageSize) }) } @objc override func pageDown(_ sender: Any?) { tryToMoveTo({ index, maxIndex in min(maxIndex, index + Preferences.pageSize) }) } @objc func moveToFirstItem(_ sender: AnyObject?) { tryToMoveTo({ index, maxIndex in 0 }) } @objc func moveToLastItem(_ sender: AnyObject?) { tryToMoveTo({ index, maxIndex in maxIndex }) } @objc func moveToPercent(_ percent: Int) { tryToMoveTo({ index, maxIndex in (maxIndex * percent) / 100 }) } @objc func moveToTenPercent(_ sender: AnyObject?) { moveToPercent(10) } @objc func moveToTwentyPercent(_ sender: AnyObject?) { moveToPercent(20) } @objc func moveToThirtyPercent(_ sender: AnyObject?) { moveToPercent(30) } @objc func moveToFortyPercent(_ sender: AnyObject?) { moveToPercent(40) } @objc func moveToFiftyPercent(_ sender: AnyObject?) { moveToPercent(50) } @objc func moveToSixtyPercent(_ sender: AnyObject?) { moveToPercent(60) } @objc func moveToSeventyPercent(_ sender: AnyObject?) { moveToPercent(70) } @objc func moveToEightyPercent(_ sender: AnyObject?) { moveToPercent(80) } @objc func moveToNinetyPercent(_ sender: AnyObject?) { moveToPercent(90) } @objc override func keyDown(with theEvent: NSEvent) { if let chars = theEvent.charactersIgnoringModifiers { let modFlags = NSEvent.ModifierFlags(rawValue: theEvent.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) let keySequence = KeySequence(modifierFlags: modFlags, chars: chars) if let selector = keyMappings[keySequence] { self.performSelector(onMainThread: selector, with: theEvent.window, waitUntilDone: true) return } else { // Logger.debug("Unable to find match for \(keySequence)") } } super.keyDown(with: theEvent) } @IBAction func openFolder(_ sender: AnyObject) { let folders = selectFoldersToAdd() if (folders.urls == nil) { return } currentMediaData = nil currentFileIndex = 0; mediaProvider!.clear() mediaProvider!.setRepository(FileMediaRepository()) addFolders(folders.urls!, selected: folders.selected) } @IBAction func addFolder(_ sender: AnyObject) { if (mediaProvider?.mediaCount)! < 1 { openFolder(sender) return } let folders = selectFoldersToAdd() if (folders.urls == nil) { return } addFolders(folders.urls!, selected: currentMediaData!.url) updateStatusView() } @IBAction func refreshFiles(_ sender: AnyObject) { mediaProvider!.refresh() } @IBAction func nextFile(_ sender: AnyObject) { displayFileByIndex(currentFileIndex + 1) } @IBAction func previousFile(_ sender: AnyObject) { displayFileByIndex(currentFileIndex - 1) } @IBAction func firstFile(_ sender: AnyObject) { displayFileByIndex(0) } @IBAction func lastFile(_ sender: AnyObject) { displayFileByIndex(mediaProvider!.mediaCount - 1) } @IBAction func revealInFinder(_ sender: AnyObject) { if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can be revealed in the finder.", information: "\(currentMediaData!.url!)") { return } NSWorkspace.shared.selectFile(currentMediaData!.url!.path, inFileViewerRootedAtPath: "") } @IBAction func setFileDateFromExifDate(_ sender: AnyObject) { if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can change dates.", information: "\(currentMediaData!.url!)") { return } let filename = currentMediaData!.url.path Logger.info("setFileDateFromExifDate: \(filename)") let result = mediaProvider?.setFileDatesToExifDates([currentMediaData!]) if !result!.allSucceeded { let alert = NSAlert() alert.messageText = "Set file date of '\(filename)' failed: \(result!.errorMessage)." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() } } @IBAction func autoRotate(_ sender: AnyObject) { if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can be rotated.", information: "\(currentMediaData!.url!)") { return } let filename = currentMediaData!.url.path Logger.info("autoRotate: \(filename)") let jheadInvoker = JheadInvoker.autoRotate([filename]) if jheadInvoker.processInvoker.exitCode != 0 { let alert = NSAlert() alert.messageText = "Auto rotate of '\(filename)' failed: \(jheadInvoker.processInvoker.error)." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() } } @IBAction func moveToTrash(_ sender: AnyObject) { let url = currentMediaData!.url if !onlyIfLocalFile(url, message: "Only local files can be moved to the trash.", information: "\(url!)") { return } Logger.info("moveToTrash: \((url?.path)!)") let filename = (url?.lastPathComponent)! NSWorkspace.shared.recycle([url!]) { newUrls, error in if error != nil { let alert = NSAlert() alert.messageText = "Failed moving '\(filename)' to trash." alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() } else { NSSound(contentsOfFile: self.trashSoundPath, byReference: false)?.play() } } } @IBAction func showOnMap(_ sender: AnyObject) { Logger.info("showOnMap '\((currentMediaData?.locationString())!)'") if let location = currentMediaData?.location { var url = "" switch Preferences.showOnMap { case .bing: url = "http://www.bing.com/maps/default.aspx?cp=\(location.latitude)~\(location.longitude)&lvl=17&rtp=pos.\(location.latitude)_\(location.longitude)" case .google: url = "http://maps.google.com/maps?q=\(location.latitude),\(location.longitude)" case .openStreetMap: url = "http://www.openstreetmap.org/?&mlat=\(location.latitude)&mlon=\(location.longitude)#map=18/\(location.latitude)/\(location.longitude)" } if url.count > 0 { NSWorkspace.shared.open(URL(string: url)!) } } } @IBAction func showOpenStreetMapFeatures(_ sender: Any) { Logger.info("showOpenStreetMapFeatures '\((currentMediaData?.locationString())!)'") if let location = currentMediaData?.location { let url = "https://www.openstreetmap.org/query?lat=\(location.latitude)&lon=\(location.longitude)&mlat=\(location.latitude)&mlon=\(location.longitude)" NSWorkspace.shared.open(URL(string: url)!) } } @IBAction func copyLatLon(_ sender: Any) { if let location = currentMediaData?.location { NSPasteboard.general.clearContents() NSPasteboard.general.writeObjects(["\(location.latitude),\(location.longitude)" as NSString]) } } @IBAction func zoomIn(_ sender: Any) { zoomView?.zoomIn() } @IBAction func zoomOut(_ sender: Any) { zoomView?.zoomOut() } @IBAction func zoomToActualSize(_ sender: Any) { zoomView?.zoomToActualSize(imageSize: imageViewer.image!.size) } @IBAction func zoomToFit(_ sender: Any) { zoomView?.zoomToFit() } func onlyIfLocalFile(_ url: URL?, message: String, information: String?) -> Bool { if !(url?.isFileURL)! { let alert = NSAlert() alert.messageText = message if information != nil { alert.informativeText = information! } alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "Close") alert.runModal() return false } return true } }
mit
e2da0143273a1d322f2035586d161838
28.763533
165
0.597396
4.632816
false
false
false
false
gerardogrisolini/iWebretail
iWebretail/PrinterBLEController.swift
1
4349
// // PrinterBLE.swift // iWebretail // // Created by Gerardo Grisolini on 13/06/17. // Copyright © 2017 Gerardo Grisolini. All rights reserved. // import UIKit import CoreBluetooth class PrinterBLEController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate { @IBOutlet weak var deviceView: UILabel! @IBOutlet weak var activityView: UIActivityIndicatorView! @IBOutlet weak var messageView: UILabel! var manager:CBCentralManager! var peripheral:CBPeripheral! var txCharacteristic:CBCharacteristic! let BEAN_NAME = "BlueTooth Printer" override func viewDidLoad() { super.viewDidLoad() activityView.startAnimating() manager = CBCentralManager(delegate: self, queue: nil) } func printReceipt(id: Int32) { let helloWorld = "Hello World! - \(id)".data(using: String.Encoding.utf8) var value : [UInt8] = [0x1b, 0x21, 0x00] value[2] |= 0x10 var data = NSData(bytes: value, length: value.count) peripheral.writeValue(data as Data, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse) peripheral.writeValue(helloWorld!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse) value[2] &= 0xEF data = NSData(bytes: value, length: value.count) peripheral.writeValue(data as Data, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse) peripheral.writeValue(helloWorld!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse) activityView.stopAnimating() activityView.isHidden = true } // MARK: CBCentralManagerDelegate Methods func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { let device = (advertisementData as NSDictionary) .object(forKey: CBAdvertisementDataLocalNameKey) as? NSString if device?.contains(BEAN_NAME) == true { self.manager.stopScan() self.peripheral = peripheral self.peripheral.delegate = self manager.connect(peripheral, options: nil) messageView.text = "Discovered \(BEAN_NAME)" } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { deviceView.text = "Connected to \(BEAN_NAME)" peripheral.discoverServices(nil) guard let services = peripheral.services else { activityView.stopAnimating() messageView.text = "No characteristics for \(BEAN_NAME)" return } for service in services { peripheral.discoverCharacteristics(nil, for: service) } } func centralManagerDidUpdateState(_ central: CBCentralManager) { switch (central.state) { case CBManagerState.poweredOff: messageView.text = "Bluetooth: PoweredOff" case CBManagerState.unauthorized: messageView.text = "Bluetooth: Unauthorized" break case CBManagerState.unknown: messageView.text = "Bluetooth: Unknown" break case CBManagerState.poweredOn: messageView.text = "Bluetooth: PoweredOn" manager.scanForPeripherals(withServices: nil, options: nil) return case CBManagerState.resetting: messageView.text = "Bluetooth: Resetting" break case CBManagerState.unsupported: messageView.text = "Bluetooth: Unsupported" break } activityView.stopAnimating() } // MARK: CBPeripheralDelegate Methods func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for characteristic in service.characteristics! { txCharacteristic = characteristic print(characteristic.descriptors!.first.debugDescription) printReceipt(id: 0) } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { print("Sent") } }
apache-2.0
4f27e59f11889593e634e4aca069bb7d
34.064516
148
0.639834
5.348093
false
false
false
false
mluisbrown/iCalendar
Sources/iCalendar/Event.swift
1
1647
// // Event.swift // iCalendar // // Created by Michael Brown on 20/05/2017. // Copyright © 2017 iCalendar. All rights reserved. // import Foundation struct Event { let uid: String let startDate: Date let endDate: Date let description: String? let summary: String? let location: String? init?(with encoded: [String:EventValueRepresentable]) { guard let startDate = encoded[Keys.startDate]?.dateValue, let endDate = encoded[Keys.endDate]?.dateValue else { return nil } self.uid = encoded[Keys.uid]?.textValue ?? UUID().uuidString self.startDate = startDate self.endDate = endDate description = encoded[Keys.description]?.textValue summary = encoded[Keys.summary]?.textValue location = encoded[Keys.location]?.textValue } var encoded: [String:EventValueRepresentable] { var dict: [String: EventValueRepresentable] = [:] dict[Keys.uid] = EventValue(value: uid) dict[Keys.startDate] = EventValue(value: startDate) dict[Keys.endDate] = EventValue(value: endDate) dict[Keys.description] = description.map { EventValue(value: $0) } dict[Keys.summary] = summary.map { EventValue(value: $0) } dict[Keys.location] = location.map { EventValue(value: $0) } return dict } } extension Event { enum Keys: String { case uid = "UID" case startDate = "DTSTART" case endDate = "DTEND" case description = "DESCRIPTION" case summary = "SUMMARY" case location = "LOCATION" } }
mit
f7021152ff763438389c089474f4ea66
28.927273
74
0.613609
4.209719
false
false
false
false
huahuasj/ios-charts
Charts/Classes/Components/ChartYAxis.swift
3
6976
// // ChartYAxis.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// Class representing the y-axis labels settings and its entries. /// Be aware that not all features the YLabels class provides are suitable for the RadarChart. /// Customizations that affect the value range of the axis need to be applied before setting data for the chart. public class ChartYAxis: ChartAxisBase { @objc public enum YAxisLabelPosition: Int { case OutsideChart case InsideChart } /// Enum that specifies the axis a DataSet should be plotted against, either Left or Right. @objc public enum AxisDependency: Int { case Left case Right } public var entries = [Float]() public var entryCount: Int { return entries.count; } /// the number of y-label entries the y-labels should have, default 6 private var _labelCount = Int(6) /// indicates if the top y-label entry is drawn or not public var drawTopYLabelEntryEnabled = true /// if true, the y-labels show only the minimum and maximum value public var showOnlyMinMaxEnabled = false /// flag that indicates if the axis is inverted or not public var inverted = false /// if true, the y-label entries will always start at zero public var startAtZeroEnabled = true /// the formatter used to customly format the y-labels public var valueFormatter: NSNumberFormatter? /// the formatter used to customly format the y-labels internal var _defaultValueFormatter = NSNumberFormatter() /// A custom minimum value for this axis. /// If set, this value will not be calculated automatically depending on the provided data. /// Use resetcustomAxisMin() to undo this. /// Do not forget to set startAtZeroEnabled = false if you use this method. /// Otherwise, the axis-minimum value will still be forced to 0. public var customAxisMin = Float.NaN /// Set a custom maximum value for this axis. /// If set, this value will not be calculated automatically depending on the provided data. /// Use resetcustomAxisMax() to undo this. public var customAxisMax = Float.NaN /// axis space from the largest value to the top in percent of the total axis range public var spaceTop = CGFloat(0.1) /// axis space from the smallest value to the bottom in percent of the total axis range public var spaceBottom = CGFloat(0.1) public var axisMaximum = Float(0) public var axisMinimum = Float(0) /// the total range of values this axis covers public var axisRange = Float(0) /// the position of the y-labels relative to the chart public var labelPosition = YAxisLabelPosition.OutsideChart /// the side this axis object represents private var _axisDependency = AxisDependency.Left /// the minimum width that the axis should take /// :default 0.0 public var minWidth = CGFloat(0) /// the maximum width that the axis can take. /// use zero for disabling the maximum /// :default 0.0 (no maximum specified) public var maxWidth = CGFloat(0) public override init() { super.init(); _defaultValueFormatter.maximumFractionDigits = 1; _defaultValueFormatter.minimumFractionDigits = 1; _defaultValueFormatter.usesGroupingSeparator = true; } public init(position: AxisDependency) { super.init(); _axisDependency = position; _defaultValueFormatter.maximumFractionDigits = 1; _defaultValueFormatter.minimumFractionDigits = 1; _defaultValueFormatter.usesGroupingSeparator = true; } public var axisDependency: AxisDependency { return _axisDependency; } /// the number of label entries the y-axis should have /// max = 25, /// min = 2, /// default = 6, /// be aware that this number is not fixed and can only be approximated public var labelCount: Int { get { return _labelCount; } set { _labelCount = newValue; if (_labelCount > 25) { _labelCount = 25; } if (_labelCount < 2) { _labelCount = 2; } } } /// By calling this method, any custom minimum value that has been previously set is reseted, and the calculation is done automatically. public func resetcustomAxisMin() { customAxisMin = Float.NaN; } /// By calling this method, any custom maximum value that has been previously set is reseted, and the calculation is done automatically. public func resetcustomAxisMax() { customAxisMax = Float.NaN; } public func requiredSize() -> CGSize { var label = getLongestLabel() as NSString; var size = label.sizeWithAttributes([NSFontAttributeName: labelFont]); size.width += xOffset * 2.0; size.height += yOffset * 2.0; size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width)); return size; } public override func getLongestLabel() -> String { var longest = ""; for (var i = 0; i < entries.count; i++) { var text = getFormattedLabel(i); if (longest.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) < text.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)) { longest = text; } } return longest; } /// Returns the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set). public func getFormattedLabel(index: Int) -> String { if (index < 0 || index >= entries.count) { return ""; } return (valueFormatter ?? _defaultValueFormatter).stringFromNumber(entries[index])!; } /// Returns true if this axis needs horizontal offset, false if no offset is needed. public var needsOffset: Bool { if (isEnabled && isDrawLabelsEnabled && labelPosition == .OutsideChart) { return true; } else { return false; } } public var isInverted: Bool { return inverted; } public var isStartAtZeroEnabled: Bool { return startAtZeroEnabled; } public var isShowOnlyMinMaxEnabled: Bool { return showOnlyMinMaxEnabled; } public var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled; } }
apache-2.0
7b88d90b2fca0961857b0a29cfcd7739
30.427928
142
0.628727
5.044107
false
false
false
false
L550312242/SinaWeiBo-Switf
weibo 1/Class/Module(模块)/Home(首页)/Controller/CZHomeTabbleViewController.swift
1
3232
// // CZHomeTabbleViewController.swift // weibo 1 // // Created by sa on 15/10/28. // Copyright © 2015年 sa. All rights reserved. // import UIKit class CZHomeTabbleViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
b61fd2ae8bf321d7ee25058204364be9
32.989474
157
0.68659
5.519658
false
false
false
false
developerY/Active-Learning-Swift-2.0_OLD
ActiveLearningSwift2.playground/Pages/Extensions.xcplaygroundpage/Contents.swift
3
5727
//: [Previous](@previous) // ------------------------------------------------------------------------------------------------ // Things to know: // // * Similar to Objective-C categories, extensions allow you to add functionality to an existing // type (class, struct, enumeration.) // // * You do not need access to the original source code to extend a type. // // * Extensions can be applied to built-in types as well, including String, Int, Double, etc. // // * With extensions, you can: // // o Add computed properties (including static) // o Define instance methods and type methods // o Provide new convenience initializers // o Define subscripts // o Define and use new nested types // o Make an existing type conform to a protocol // // * Extensions do not support adding stored properties or property observers to a type. // // * Extensions apply all instances of a type, even if they were created before the extension was // defined. // ------------------------------------------------------------------------------------------------ // Let's take a look at how extensions are declared. Note that, unlike Objective-C categories, // extensions are not named: extension Int { // ... code here } // ------------------------------------------------------------------------------------------------ // Computed properties // // Computed properties are a poweful use of extensions. Below, we'll add native conversion from // various measurements (Km, mm, feet, etc.) to the Double class. extension Double { var kmToMeters: Double { return self * 1_000.0 } var cmToMeters: Double { return self / 100.0 } var mmToMeters: Double { return self / 1_000.0 } var inchToMeters: Double { return self / 39.3701 } var ftToMeters: Double { return self / 3.28084 } } // We can call upon Double's new computed property to convert inches to meters let oneInchInMeters = 1.inchToMeters // Similarly, we'll convert three feet to meters let threeFeetInMeters = 3.ftToMeters // ------------------------------------------------------------------------------------------------ // Initializers // // Extensions can be used to add new convenience initializers to a class, but they cannot add // new designated initializers. // // Let's see this in action: struct Size { var width = 0.0 var height = 0.0 } struct Point { var x = 0.0 var y = 0.0 } struct Rect { var origin = Point() var size = Size() } // Since we didn't provide any initializers, we can use Swift's default memberwise initializer for // the Rect. var memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) // Let's extend Rect to add a new convenience initializer. Note that we're still responsible for // ensuring that the instance is fully initialized. extension Rect { init (center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } // Let's try out our new initializer: let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // Remember that if a class has an initializer, Swift will not provide the default memberwise // initializer. However, since we added an initializer via an Extension, we still have access // to Swift's memberwise initializer: var anotherRect = Rect(origin: Point(x: 1.0, y: 1.0), size: Size(width: 3.0, height: 2.0)) // ------------------------------------------------------------------------------------------------ // Methods // // As you might expect, we can add methods to an existing type as well. Here's a clever little // extention to perform a task (a closure) multiple times, equal to the value stored in the Int. // // Note that the integer value is stored in 'self'. extension Int { func repititions(task: () -> ()) { for i in 0..<self { task() } } } // Let's call our new member using the shorthand syntax for trailing closures: 3.repititions { println("hello") } // Instance methods can mutate the instance itself. // // Note the use of the 'mutating' keyword. extension Int { mutating func square() { self = self * self } } var someInt = 3 someInt.square() // someInt is now 9 // ------------------------------------------------------------------------------------------------ // Subscripts // // Let's add a subscript to Int: extension Int { subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0 ..< digitIndex { decimalBase *= 10 } return self / decimalBase % 10 } } // And we can call our subscript directly on an Int, including a literal Int type: 123456789[0] 123456789[1] 123456789[2] 123456789[3] 123456789[4] 123456789[5] 123456789[6] // ------------------------------------------------------------------------------------------------ // Nested types // // We can also add nested types to an existing type: extension Character { enum Kind { case Vowel, Consonant, Other } var kind: Kind { switch String(self) { case "a", "e", "i", "o", "u": return .Vowel case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": return .Consonant default: return .Other } } } // Let's test out our new extension with nested types: Character("a").kind == .Vowel Character("h").kind == .Consonant Character("+").kind == .Other //: [Next](@next)
apache-2.0
c343270703326903047a60b8f0c16007
28.673575
99
0.559979
4.114224
false
false
false
false
Monnoroch/Cuckoo
Generator/Tests/SourceFiles/Expected/NoHeader.swift
1
1176
import Cuckoo import Foundation class MockEmptyClass: EmptyClass, Cuckoo.Mock { typealias MocksType = EmptyClass typealias Stubbing = __StubbingProxy_EmptyClass typealias Verification = __VerificationProxy_EmptyClass let manager = Cuckoo.MockManager() private var observed: EmptyClass? func spy(on victim: EmptyClass) -> Self { observed = victim return self } struct __StubbingProxy_EmptyClass: Cuckoo.StubbingProxy { private let manager: Cuckoo.MockManager init(manager: Cuckoo.MockManager) { self.manager = manager } } struct __VerificationProxy_EmptyClass: Cuckoo.VerificationProxy { private let manager: Cuckoo.MockManager private let callMatcher: Cuckoo.CallMatcher private let sourceLocation: Cuckoo.SourceLocation init(manager: Cuckoo.MockManager, callMatcher: Cuckoo.CallMatcher, sourceLocation: Cuckoo.SourceLocation) { self.manager = manager self.callMatcher = callMatcher self.sourceLocation = sourceLocation } } } class EmptyClassStub: EmptyClass { }
mit
a40d3753b3f6613bed7958a143f109eb
28.4
115
0.668367
5.521127
false
false
false
false
ijoshsmith/json2swift
json2swift/command-line-interface.swift
1
4448
// // command-line-interface.swift // json2swift // // Created by Joshua Smith on 10/28/16. // Copyright © 2016 iJoshSmith. All rights reserved. // import Foundation typealias ErrorMessage = String func run(with arguments: [String]) -> ErrorMessage? { guard arguments.isEmpty == false else { return "Please provide a JSON file path or directory path." } let path = (arguments[0] as NSString).resolvingSymlinksInPath var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) else { return "No such file or directory exists." } let jsonFilePaths: [String] if isDirectory.boolValue { guard let filePaths = findJSONFilePaths(in: path) else { return "Unable to read contents of directory." } guard filePaths.isEmpty == false else { return "The directory does not contain any JSON files." } jsonFilePaths = filePaths } else { jsonFilePaths = [path] } let jsonUtilitiesFilePath: String? = jsonFilePaths.count > 1 ? (path as NSString).appendingPathComponent("JSONUtilities.swift") : nil let shouldIncludeUtils = jsonUtilitiesFilePath == nil let rootType = arguments.count >= 2 ? arguments[1] : "root-type" for jsonFilePath in jsonFilePaths { if let errorMessage = generateSwiftFileBasedOnJSON(inFile: jsonFilePath, includeJSONUtilities: shouldIncludeUtils, rootTypeName: rootType) { return errorMessage } } if let jsonUtilitiesFilePath = jsonUtilitiesFilePath { guard writeJSONUtilitiesFile(to: jsonUtilitiesFilePath) else { return "Unable to write JSON utilities file to \(jsonUtilitiesFilePath)" } } return nil } // MARK: - Finding JSON files in directory private func findJSONFilePaths(in directory: String) -> [String]? { guard let jsonFileNames = findJSONFileNames(in: directory) else { return nil } return resolveAbsolutePaths(for: jsonFileNames, inDirectory: directory) } private func findJSONFileNames(in directory: String) -> [String]? { let isJSONFile: (String) -> Bool = { $0.lowercased().hasSuffix(".json") } do { return try FileManager.default.contentsOfDirectory(atPath: directory).filter(isJSONFile) } catch { return nil } } private func resolveAbsolutePaths(for jsonFileNames: [String], inDirectory directory: String) -> [String] { return jsonFileNames.map { (directory as NSString).appendingPathComponent($0) } } // MARK: - Generating Swift file based on JSON private func generateSwiftFileBasedOnJSON(inFile jsonFilePath: String, includeJSONUtilities: Bool, rootTypeName: String) -> ErrorMessage? { let url = URL(fileURLWithPath: jsonFilePath) let data: Data do { data = try Data(contentsOf: url) } catch { return "Unable to read file: \(jsonFilePath)" } let jsonObject: Any do { jsonObject = try JSONSerialization.jsonObject(with: data, options: []) } catch { return "File does not contain valid JSON: \(jsonFilePath)" } let jsonSchema: JSONElementSchema if let jsonElement = jsonObject as? JSONElement { jsonSchema = JSONElementSchema.inferred(from: jsonElement, named: rootTypeName) } else if let jsonArray = jsonObject as? [JSONElement] { jsonSchema = JSONElementSchema.inferred(from: jsonArray, named: rootTypeName) } else { return "Unsupported JSON format: must be a dictionary or array of dictionaries." } let swiftStruct = SwiftStruct.create(from: jsonSchema) let swiftCode = includeJSONUtilities ? SwiftCodeGenerator.generateCodeWithJSONUtilities(for: swiftStruct) : SwiftCodeGenerator.generateCode(for: swiftStruct) let swiftFilePath = (jsonFilePath as NSString).deletingPathExtension + ".swift" guard write(swiftCode: swiftCode, toFile: swiftFilePath) else { return "Unable to write to file: \(swiftFilePath)" } return nil } private func writeJSONUtilitiesFile(to filePath: String) -> Bool { let jsonUtilitiesCode = SwiftCodeGenerator.generateJSONUtilities() return write(swiftCode: jsonUtilitiesCode, toFile: filePath) } private func write(swiftCode: String, toFile filePath: String) -> Bool { do { try swiftCode.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8) return true } catch { return false } }
mit
a03c65d83190baa02d821c124a696d23
40.175926
148
0.701372
4.487386
false
false
false
false
k3zi/KZSwipeTableViewCell
KZSwipeTableViewCell/KZSwipeTableViewCell.swift
1
20293
// // KZSwipeTableViewCell.swift // Convenient UITableViewCell subclass that implements a swippable content to trigger actions // Swift Port of MCSwipeTableViewCell // // Created by Kesi Maduka on 2/7/16. // LICENSE: MIT // import UIKit enum KZSwipeTableViewCellDirection { case Left case Right case Center } public enum KZSwipeTableViewCellState { case None case State1 case State2 case State3 case State4 } public enum KZSwipeTableViewCellMode { case None case Exit case Switch } public struct KZSwipeTableViewCellSettings { public var damping, velocity, firstTrigger, secondTrigger: CGFloat public var animationDuration: NSTimeInterval public var startImmediately, shouldAnimateIcons: Bool public var defaultColor: UIColor init(damping: CGFloat = 0.6, velocity: CGFloat = 0.9, animationDuration: NSTimeInterval = 0.4, firstTrigger: CGFloat = 0.15, secondTrigger: CGFloat = 0.47, startImmediately: Bool = false, shouldAnimateIcons: Bool = true, defaultColor: UIColor = UIColor.whiteColor()) { self.damping = damping self.velocity = velocity self.animationDuration = animationDuration self.firstTrigger = firstTrigger self.secondTrigger = secondTrigger self.startImmediately = startImmediately self.defaultColor = defaultColor self.shouldAnimateIcons = shouldAnimateIcons } } public typealias KZSwipeCompletionBlock = (cell: KZSwipeTableViewCell, state: KZSwipeTableViewCellState, mode: KZSwipeTableViewCellMode) -> Void public class KZSwipeTableViewCell: UITableViewCell { let _panGestureRecognizer = UIPanGestureRecognizer() var _contentScreenshotView: UIImageView? var _colorIndicatorView: UIView? var _slidingView: UIView? var _direction = KZSwipeTableViewCellDirection.Center var _isExited = false public var settings = KZSwipeTableViewCellSettings() var currentPercentage = CGFloat(0) var _view1: UIView? var _view2: UIView? var _view3: UIView? var _view4: UIView? var _color1: UIColor? var _color2: UIColor? var _color3: UIColor? var _color4: UIColor? var _modeForState1 = KZSwipeTableViewCellMode.None var _modeForState2 = KZSwipeTableViewCellMode.None var _modeForState3 = KZSwipeTableViewCellMode.None var _modeForState4 = KZSwipeTableViewCellMode.None var completionBlock1: KZSwipeCompletionBlock? var completionBlock2: KZSwipeCompletionBlock? var completionBlock3: KZSwipeCompletionBlock? var completionBlock4: KZSwipeCompletionBlock? var _activeView: UIView? required override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) _panGestureRecognizer.addTarget(self, action: Selector("handlePanGestureRecognizer:")) self.addGestureRecognizer(_panGestureRecognizer) _panGestureRecognizer.delegate = self } //MARK: Init //MARK: Prepare For Reuse override public func prepareForReuse() { super.prepareForReuse() uninstallSwipingView() _isExited = false _view1 = nil _view2 = nil _view3 = nil _view4 = nil _color1 = nil _color2 = nil _color3 = nil _color4 = nil _modeForState1 = .None _modeForState2 = .None _modeForState3 = .None _modeForState4 = .None completionBlock1 = nil completionBlock2 = nil completionBlock3 = nil completionBlock4 = nil settings = KZSwipeTableViewCellSettings() } //MARK: View Manipulation func setupSwipingView() { if _contentScreenshotView != nil { return } let contentViewScreenshotImage = imageWithView(self) let colorIndicatorView = UIView(frame: self.bounds) colorIndicatorView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] colorIndicatorView.backgroundColor = settings.defaultColor self.addSubview(colorIndicatorView) let slidingView = UIView() slidingView.contentMode = .Center colorIndicatorView.addSubview(slidingView) let contentScreenshotView = UIImageView(image: contentViewScreenshotImage) self.addSubview(contentScreenshotView) _slidingView = slidingView _colorIndicatorView = colorIndicatorView _contentScreenshotView = contentScreenshotView } func uninstallSwipingView() { if let contentScreenshotView = _contentScreenshotView { if let slidingView = _slidingView { slidingView.removeFromSuperview() _slidingView = nil } if let colorIndicatorView = _colorIndicatorView { colorIndicatorView.removeFromSuperview() _colorIndicatorView = nil } contentScreenshotView.removeFromSuperview() _contentScreenshotView = nil } } func setViewOfSlidingView(slidingView: UIView) { if let parentSlidingView = _slidingView { parentSlidingView.subviews.forEach({ $0.removeFromSuperview() }) parentSlidingView.addSubview(slidingView) } } //MARK: Swipe Config public func setSwipeGestureWith(view: UIView, color: UIColor, mode: KZSwipeTableViewCellMode = .None, state: KZSwipeTableViewCellState = .State1, completionBlock: KZSwipeCompletionBlock) { if state == .State1 { completionBlock1 = completionBlock _color1 = color _view1 = view _modeForState1 = mode } if state == .State2 { completionBlock2 = completionBlock _color2 = color _view2 = view _modeForState2 = mode } if state == .State3 { completionBlock3 = completionBlock _color3 = color _view3 = view _modeForState3 = mode } if state == .State4 { completionBlock4 = completionBlock _color4 = color _view4 = view _modeForState4 = mode } } //MARK: Gestures func handlePanGestureRecognizer(gesture: UIPanGestureRecognizer) { if _isExited { return } let translation = gesture.translationInView(self) let velocity = gesture.velocityInView(self) let animationDuration = animationDurationWithVelocity(velocity) var percentage = CGFloat(0) if let contentScreenshotView = _contentScreenshotView { percentage = percentageWithOffset(CGRectGetMinX(contentScreenshotView.frame), relativeToWidth: CGRectGetWidth(self.bounds)) _direction = directionWithPercentage(percentage) } //------------------ ----------------\\ if gesture.state == .Began || gesture.state == .Changed { setupSwipingView() if let contentScreenshotView = _contentScreenshotView { if (canTravelTo(percentage)) { contentScreenshotView.center = CGPoint(x: contentScreenshotView.center.x + translation.x, y: contentScreenshotView.center.y) animateWithOffset(CGRectGetMinX(contentScreenshotView.frame)) gesture.setTranslation(CGPoint.zero, inView: self) } } } else if gesture.state == .Ended || gesture.state == .Cancelled { _activeView = self.viewWithPercentage(percentage) currentPercentage = percentage let state = stateWithPercentage(percentage) var mode = KZSwipeTableViewCellMode.None if state == .State1 { mode = _modeForState1 } else if state == .State2 { mode = _modeForState2 } else if state == .State2 { mode = _modeForState3 } else if state == .State4 { mode = _modeForState4 } if mode == .Exit && _direction != .Center { self.moveWithDuration(animationDuration, direction: _direction) } else { self.swipeToOriginWithCompletion({ () -> Void in self.executeCompletionBlock() }) } } } override public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let gesture = gestureRecognizer as? UIPanGestureRecognizer { let point = gesture.velocityInView(self) if fabs(point.x) > fabs(point.y) { if point.x > 0 && _modeForState1 == .None && _modeForState2 == .None { return false } return true } } return false } //MARK: Movement func animateWithOffset(offset: CGFloat) { let percentage = percentageWithOffset(offset, relativeToWidth: CGRectGetWidth(self.bounds)) if let view = viewWithPercentage(percentage) { setViewOfSlidingView(view) if let slidingView = _slidingView { slidingView.alpha = alphaWithPercentage(percentage) } slideViewWithPercentage(percentage, view: view, isDragging: self.settings.shouldAnimateIcons) } let color = colorWithPercentage(percentage) if let colorIndicatorView = _colorIndicatorView { colorIndicatorView.backgroundColor = color } } func slideViewWithPercentage(percentage: CGFloat, view: UIView?, isDragging: Bool) { guard let view = view else { return } var position = CGPoint.zero position.y = CGRectGetHeight(self.bounds) / 2.0 if isDragging { if percentage >= 0 && percentage < settings.firstTrigger { position.x = offsetWithPercentage(settings.firstTrigger/2, relativeToWidth: CGRectGetWidth(self.bounds)) } else if percentage >= settings.firstTrigger { position.x = offsetWithPercentage(percentage - (settings.firstTrigger/2), relativeToWidth: CGRectGetWidth(self.bounds)) } else if percentage < 0 && percentage >= -settings.firstTrigger { position.x = CGRectGetWidth(self.bounds) - offsetWithPercentage(settings.firstTrigger/2, relativeToWidth: CGRectGetWidth(self.bounds)) } else if percentage < -settings.firstTrigger { position.x = CGRectGetWidth(self.bounds) + offsetWithPercentage(percentage + (settings.firstTrigger/2), relativeToWidth: CGRectGetWidth(self.bounds)) } } else { if _direction == .Right { position.x = offsetWithPercentage(settings.firstTrigger/2, relativeToWidth: CGRectGetWidth(self.bounds)) } else if _direction == .Left { position.x = CGRectGetWidth(self.bounds) - offsetWithPercentage(settings.firstTrigger/2, relativeToWidth: CGRectGetWidth(self.bounds)) } else { return } } let activeViewSize = view.bounds.size var activeViewFrame = CGRect(x: position.x - activeViewSize.width / 2.0, y: position.y - activeViewSize.height / 2.0, width: activeViewSize.width, height: activeViewSize.height) activeViewFrame = CGRectIntegral(activeViewFrame) if let slidingView = _slidingView { slidingView.frame = activeViewFrame } } func moveWithDuration(duration: NSTimeInterval, direction: KZSwipeTableViewCellDirection) { _isExited = true var origin = CGFloat(0) if direction == .Left { origin = -CGRectGetWidth(self.bounds) } else if direction == .Right { origin = CGRectGetWidth(self.bounds) } guard let contentScreenshotView = _contentScreenshotView else { return } guard let slidingView = _slidingView else { return } let percentage = percentageWithOffset(origin, relativeToWidth: CGRectGetWidth(self.bounds)) var frame = contentScreenshotView.frame frame.origin.x = origin UIView.animateWithDuration(duration, delay: 0, options: [.CurveEaseOut, .AllowUserInteraction], animations: { () -> Void in contentScreenshotView.frame = frame slidingView.alpha = 0 self.slideViewWithPercentage(percentage, view: self._activeView, isDragging: self.settings.shouldAnimateIcons) }) { (finished) -> Void in self.executeCompletionBlock() } } public func swipeToOriginWithCompletion(completion: (()->Void)?) { UIView.animateWithDuration(settings.animationDuration, delay: 0.0, usingSpringWithDamping: settings.damping, initialSpringVelocity: settings.velocity, options: [.CurveEaseInOut], animations: { () -> Void in if let contentScreenshotView = self._contentScreenshotView { contentScreenshotView.frame.origin.x = 0 } if let colorIndicatorView = self._colorIndicatorView { colorIndicatorView.backgroundColor = self.settings.defaultColor } if let slidingView = self._slidingView { slidingView.alpha = 0.0 } self.slideViewWithPercentage(0, view: self._activeView, isDragging: false) }) { (finished) -> Void in self._isExited = false self.uninstallSwipingView() if let completion = completion { completion() } } } func imageWithView(view: UIView) -> UIImage { let scale = UIScreen.mainScreen().scale UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale) if let context = UIGraphicsGetCurrentContext() { view.layer.renderInContext(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } return UIImage() } func canTravelTo(percentage: CGFloat) -> Bool { if _modeForState1 == .None && _modeForState2 == .None { if percentage > 0.0 { return false } } if _modeForState3 == .None && _modeForState4 == .None { if percentage < 0.0 { return false } } return true } //MARK: Percentage func offsetWithPercentage(percentage: CGFloat, relativeToWidth width: CGFloat) -> CGFloat{ var offset = percentage * width if offset < -width { offset = -width } else if offset > width { offset = width } return offset } func percentageWithOffset(offset: CGFloat, relativeToWidth width: CGFloat) -> CGFloat { var percentage = offset/width if percentage < -1.0 { percentage = -1.0 } else if percentage > 1.0 { percentage = 1.0 } return percentage } func animationDurationWithVelocity(velocity: CGPoint) -> NSTimeInterval { let width = CGRectGetWidth(self.bounds) let animationDurationDiff = CGFloat(0.1 - 0.25) var horizontalVelocity = velocity.x if horizontalVelocity < -width { horizontalVelocity = -width } else if horizontalVelocity > width { horizontalVelocity = width } return (0.1 + 0.25) - NSTimeInterval(((horizontalVelocity / width) * animationDurationDiff)); } func directionWithPercentage(percentage: CGFloat) -> KZSwipeTableViewCellDirection { if percentage < 0 { return .Left } else if percentage > 0 { return .Right } return .Center } func viewWithPercentage(percentage: CGFloat) -> UIView? { var view: UIView? if percentage >= 0 && _modeForState1 != .None { view = _view1 } if percentage >= settings.secondTrigger && _modeForState2 != .None { view = _view2 } if percentage < 0 && _modeForState3 != .None { view = _view3 } if percentage <= -settings.secondTrigger && _modeForState4 != .None { view = _view4 } return view } func alphaWithPercentage(percentage: CGFloat) -> CGFloat { var alpha = CGFloat(1.0) if percentage >= 0 && percentage < settings.firstTrigger { alpha = percentage / settings.firstTrigger } else if percentage < 0 && percentage > -settings.firstTrigger { alpha = fabs(percentage / settings.firstTrigger) } else { alpha = 1.0 } return alpha; } func colorWithPercentage(percentage: CGFloat) -> UIColor { var color = settings.defaultColor if (percentage > settings.firstTrigger || (settings.startImmediately && percentage > 0)) && _modeForState1 != .None { color = _color1 ?? color } if percentage > settings.secondTrigger && _modeForState2 != .None { color = _color2 ?? color } if (percentage < -settings.firstTrigger || (settings.startImmediately && percentage < 0)) && _modeForState3 != .None { color = _color3 ?? color } if percentage <= -settings.secondTrigger && _modeForState4 != .None { color = _color4 ?? color } return color } func stateWithPercentage(percentage: CGFloat) -> KZSwipeTableViewCellState { var state = KZSwipeTableViewCellState.None if percentage > settings.firstTrigger && _modeForState1 != .None { state = .State1 } if percentage >= settings.secondTrigger && _modeForState2 != .None { state = .State2 } if percentage <= -settings.firstTrigger && _modeForState3 != .None { state = .State3 } if percentage <= -settings.secondTrigger && _modeForState4 != .None { state = .State4 } return state } public class func viewWithImageName(name: String) -> UIView { let image = UIImage(named: name) let imageView = UIImageView(image: image) imageView.contentMode = UIViewContentMode.Center return imageView } func executeCompletionBlock(){ let state = stateWithPercentage(currentPercentage) var mode = KZSwipeTableViewCellMode.None var completionBlock: KZSwipeCompletionBlock? switch state { case .State1: mode = _modeForState1 completionBlock = completionBlock1 break; case .State2: mode = _modeForState2 completionBlock = completionBlock2 break; case .State3: mode = _modeForState3 completionBlock = completionBlock3 break; case .State4: mode = _modeForState4 completionBlock = completionBlock4 break; default: break; } if let completionBlock = completionBlock { completionBlock(cell: self, state: state, mode: mode) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
adef6dcf793050c57e80c49e0b0140cb
33.336717
272
0.590006
5.218051
false
false
false
false
jfcontart/TestGit
TestGit/TestGit/ViewController.swift
1
4846
// // ViewController.swift // TestGit // // Created by Jean-François CONTART on 21/03/2017. // Copyright © 2017 idemobi. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet var mTitleLabel : UILabel? @IBOutlet var mSegmentedBar : UISegmentedControl? @IBOutlet var mSegmentedBarB : UISegmentedControl? @IBOutlet var mTableView : UITableView? var mData : MyDataModel = MyDataModel() public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let tGroup : MyGroupModel = mData.mList[section] as! MyGroupModel return tGroup.mList.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tCell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) let tGroup : MyGroupModel = mData.mList[indexPath.section] as! MyGroupModel let tCellData : MyCellModel = tGroup.mList [indexPath.row] as! MyCellModel tCell.textLabel?.text = tCellData.mTitle tCell.detailTextLabel?.text = tCellData.mSubTitle tCell.imageView?.image = tGroup.mImage // tCell.textLabel?.text = "Mon titre n° \(indexPath.section) - \(indexPath.row)" return tCell } public func numberOfSections(in tableView: UITableView) -> Int { return mData.mList.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let tGroup : MyGroupModel = mData.mList[section] as! MyGroupModel return tGroup.mTitle } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mTitleLabel?.text = "Jean-François CONTART" ChangeColor(sSender: mSegmentedBar!) mData.addGroup(sGroup: MyGroupModel.createWithTitle(sTitleLocalizationKey: "CoconutsTreeTitleKey", withAssetName: "Cocotier", withCellNumber: 10)) mData.addGroup(sGroup: MyGroupModel.createWithTitle(sTitleLocalizationKey: "ChickenTitleKey", withAssetName: "Poule", withCellNumber: 10)) mData.addGroup(sGroup: MyGroupModel.createWithTitle(sTitleLocalizationKey: "SmurfTitleKey", withAssetName: "Smurf", withCellNumber: 10)) //ghgfhfhg } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func IAmRich () { mTitleLabel?.text = "0€" } @IBAction func ChangeColor (sSender : UISegmentedControl) { NSLog(" Yahoo !!!!!") // if (mSegmentedBar?.selectedSegmentIndex == 0) // { // mTitleLabel?.textColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) // } // else if (mSegmentedBar?.selectedSegmentIndex == 1) // { // mTitleLabel?.textColor = UIColor.init(red: 1.0, green: 0, blue: 0, alpha: 1) // } // else // { // mTitleLabel?.textColor = UIColor.init(red: 0.0, green: 1.0, blue: 0, alpha: 1) // } switch sSender.selectedSegmentIndex { case 0: if (sSender == mSegmentedBar) { mTitleLabel?.textColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) } else if (sSender == mSegmentedBarB) { mTitleLabel?.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) } break case 1 : if (sSender == mSegmentedBar) { mTitleLabel?.textColor = UIColor.init(red: 1.0, green: 0, blue: 0, alpha: 1) } else if (sSender == mSegmentedBarB) { mTitleLabel?.textColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) } break case 2 : if (sSender == mSegmentedBar) { mTitleLabel?.textColor = UIColor.init(red: 0.0, green: 1.0, blue: 0, alpha: 1) } else if (sSender == mSegmentedBarB) { mTitleLabel?.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) } break default: mTitleLabel?.text = "ERREUR DE COULEUR" break } } }
unlicense
f835338a2c0d57f4f07b4f43a541adad
32.150685
154
0.577479
4.32529
false
false
false
false
safarafa/eld_hackaton2405
iOSBookTheHotelRoomApp/iOSBookTheHotelRoomApp/Source/Request.swift
5
23936
// // Request.swift // // Copyright (c) 2014-2016 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 /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. public protocol RequestAdapter { /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. /// /// - parameter urlRequest: The URL request to adapt. /// /// - throws: An `Error` if the adaptation encounters an error. /// /// - returns: The adapted `URLRequest`. func adapt(_ urlRequest: URLRequest) throws -> URLRequest } // MARK: - /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void /// A type that determines whether a request should be retried after being executed by the specified session manager /// and encountering an error. public protocol RequestRetrier { /// Determines whether the `Request` should be retried by calling the `completion` closure. /// /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly /// cleaned up after. /// /// - parameter manager: The session manager the request was executed on. /// - parameter request: The request that failed due to the encountered error. /// - parameter error: The error encountered when executing the request. /// - parameter completion: The completion closure to be executed when retry decision has been determined. func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) } // MARK: - protocol TaskConvertible { func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask } /// A dictionary of headers to apply to a `URLRequest`. public typealias HTTPHeaders = [String: String] // MARK: - /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. open class Request { // MARK: Helper Types /// A closure executed when monitoring upload or download progress of a request. public typealias ProgressHandler = (Progress) -> Void enum RequestTask { case data(TaskConvertible?, URLSessionTask?) case download(TaskConvertible?, URLSessionTask?) case upload(TaskConvertible?, URLSessionTask?) case stream(TaskConvertible?, URLSessionTask?) } // MARK: Properties /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { get { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } return taskDelegate } set { taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } taskDelegate = newValue } } /// The underlying task. open var task: URLSessionTask? { return delegate.task } /// The session belonging to the underlying task. open let session: URLSession /// The request sent or to be sent to the server. open var request: URLRequest? { return task?.originalRequest } /// The response received from the server, if any. open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } /// The number of times the request has been retried. open internal(set) var retryCount: UInt = 0 let originalTask: TaskConvertible? var startTime: CFAbsoluteTime? var endTime: CFAbsoluteTime? var validations: [() -> Void] = [] private var taskDelegate: TaskDelegate private var taskDelegateLock = NSLock() // MARK: Lifecycle init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { self.session = session switch requestTask { case .data(let originalTask, let task): taskDelegate = DataTaskDelegate(task: task) self.originalTask = originalTask case .download(let originalTask, let task): taskDelegate = DownloadTaskDelegate(task: task) self.originalTask = originalTask case .upload(let originalTask, let task): taskDelegate = UploadTaskDelegate(task: task) self.originalTask = originalTask case .stream(let originalTask, let task): taskDelegate = TaskDelegate(task: task) self.originalTask = originalTask } delegate.error = error delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } } // MARK: Authentication /// Associates an HTTP Basic credential with the request. /// /// - parameter user: The user. /// - parameter password: The password. /// - parameter persistence: The URL credential persistence. `.ForSession` by default. /// /// - returns: The request. @discardableResult open func authenticate( user: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self { let credential = URLCredential(user: user, password: password, persistence: persistence) return authenticate(usingCredential: credential) } /// Associates a specified credential with the request. /// /// - parameter credential: The credential. /// /// - returns: The request. @discardableResult open func authenticate(usingCredential credential: URLCredential) -> Self { delegate.credential = credential return self } /// Returns a base64 encoded basic authentication credential as an authorization header tuple. /// /// - parameter user: The user. /// - parameter password: The password. /// /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } let credential = data.base64EncodedString(options: []) return (key: "Authorization", value: "Basic \(credential)") } // MARK: State /// Resumes the request. open func resume() { guard let task = task else { delegate.queue.isSuspended = false ; return } if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } task.resume() NotificationCenter.default.post( name: Notification.Name.Task.DidResume, object: self, userInfo: [Notification.Key.Task: task] ) } /// Suspends the request. open func suspend() { guard let task = task else { return } task.suspend() NotificationCenter.default.post( name: Notification.Name.Task.DidSuspend, object: self, userInfo: [Notification.Key.Task: task] ) } /// Cancels the request. open func cancel() { guard let task = task else { return } task.cancel() NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task] ) } } // MARK: - CustomStringConvertible extension Request: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as /// well as the response status code if a response has been received. open var description: String { var components: [String] = [] if let HTTPMethod = request?.httpMethod { components.append(HTTPMethod) } if let urlString = request?.url?.absoluteString { components.append(urlString) } if let response = response { components.append("(\(response.statusCode))") } return components.joined(separator: " ") } } // MARK: - CustomDebugStringConvertible extension Request: CustomDebugStringConvertible { /// The textual representation used when written to an output stream, in the form of a cURL command. open var debugDescription: String { return cURLRepresentation() } func cURLRepresentation() -> String { var components = ["$ curl -i"] guard let request = self.request, let url = request.url, let host = url.host else { return "$ curl command could not be created" } if let httpMethod = request.httpMethod, httpMethod != "GET" { components.append("-X \(httpMethod)") } if let credentialStorage = self.session.configuration.urlCredentialStorage { let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in credentials { components.append("-u \(credential.user!):\(credential.password!)") } } else { if let credential = delegate.credential { components.append("-u \(credential.user!):\(credential.password!)") } } } if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"") } } var headers: [AnyHashable: Any] = [:] if let additionalHeaders = session.configuration.httpAdditionalHeaders { for (field, value) in additionalHeaders where field != AnyHashable("Cookie") { headers[field] = value } } if let headerFields = request.allHTTPHeaderFields { for (field, value) in headerFields where field != "Cookie" { headers[field] = value } } for (field, value) in headers { components.append("-H \"\(field): \(value)\"") } if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) { var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"") escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"") components.append("-d \"\(escapedBody)\"") } components.append("\"\(url.absoluteString)\"") return components.joined(separator: " \\\n\t") } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDataTask`. open class DataRequest: Request { // MARK: Helper Types struct Requestable: TaskConvertible { let urlRequest: URLRequest func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let urlRequest = try self.urlRequest.adapt(using: adapter) return queue.sync { session.dataTask(with: urlRequest) } } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let requestable = originalTask as? Requestable { return requestable.urlRequest } return nil } /// The progress of fetching the response data from the server for the request. open var progress: Progress { return dataDelegate.progress } var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } // MARK: Stream /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. /// /// This closure returns the bytes most recently received from the server, not including data from previous calls. /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is /// also important to note that the server data in any `Response` object will be `nil`. /// /// - parameter closure: The code to be executed periodically during the lifecycle of the request. /// /// - returns: The request. @discardableResult open func stream(closure: ((Data) -> Void)? = nil) -> Self { dataDelegate.dataStream = closure return self } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { dataDelegate.progressHandler = (closure, queue) return self } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. open class DownloadRequest: Request { // MARK: Helper Types /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the /// destination URL. public struct DownloadOptions: OptionSet { /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. public let rawValue: UInt /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. /// /// - parameter rawValue: The raw bitmask value for the option. /// /// - returns: A new log level instance. public init(rawValue: UInt) { self.rawValue = rawValue } } /// A closure executed once a download request has successfully completed in order to determine where to move the /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and /// the options defining how the file should be moved. public typealias DownloadFileDestination = ( _ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: DownloadOptions) enum Downloadable: TaskConvertible { case request(URLRequest) case resumeData(Data) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .request(urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.downloadTask(with: urlRequest) } case let .resumeData(resumeData): task = queue.sync { session.downloadTask(withResumeData: resumeData) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { return urlRequest } return nil } /// The resume data of the underlying download task if available after a failure. open var resumeData: Data? { return downloadDelegate.resumeData } /// The progress of downloading the response data from the server for the request. open var progress: Progress { return downloadDelegate.progress } var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } // MARK: State /// Cancels the request. open override func cancel() { downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } NotificationCenter.default.post( name: Notification.Name.Task.DidCancel, object: self, userInfo: [Notification.Key.Task: task as Any] ) } // MARK: Progress /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is read from the server. /// /// - returns: The request. @discardableResult open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { downloadDelegate.progressHandler = (closure, queue) return self } // MARK: Destination /// Creates a download file destination closure which uses the default file manager to move the temporary file to a /// file URL in the first available directory with the specified search path directory and search path domain mask. /// /// - parameter directory: The search path directory. `.DocumentDirectory` by default. /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. /// /// - returns: A download file destination closure. open class func suggestedDownloadDestination( for directory: FileManager.SearchPathDirectory = .documentDirectory, in domain: FileManager.SearchPathDomainMask = .userDomainMask) -> DownloadFileDestination { return { temporaryURL, response in let directoryURLs = FileManager.default.urls(for: directory, in: domain) if !directoryURLs.isEmpty { return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) } return (temporaryURL, []) } } } // MARK: - /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. open class UploadRequest: DataRequest { // MARK: Helper Types enum Uploadable: TaskConvertible { case data(Data, URLRequest) case file(URL, URLRequest) case stream(InputStream, URLRequest) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { do { let task: URLSessionTask switch self { case let .data(data, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, from: data) } case let .file(url, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } case let .stream(_, urlRequest): let urlRequest = try urlRequest.adapt(using: adapter) task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } } return task } catch { throw AdaptError(error: error) } } } // MARK: Properties /// The request sent or to be sent to the server. open override var request: URLRequest? { if let request = super.request { return request } guard let uploadable = originalTask as? Uploadable else { return nil } switch uploadable { case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): return urlRequest } } /// The progress of uploading the payload to the server for the upload request. open var uploadProgress: Progress { return uploadDelegate.uploadProgress } var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } // MARK: Upload Progress /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to /// the server. /// /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress /// of data being read from the server. /// /// - parameter queue: The dispatch queue to execute the closure on. /// - parameter closure: The code to be executed periodically as data is sent to the server. /// /// - returns: The request. @discardableResult open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { uploadDelegate.uploadProgressHandler = (closure, queue) return self } } // MARK: - #if !os(watchOS) /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open class StreamRequest: Request { enum Streamable: TaskConvertible { case stream(hostName: String, port: Int) case netService(NetService) func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { let task: URLSessionTask switch self { case let .stream(hostName, port): task = queue.sync { session.streamTask(withHostName: hostName, port: port) } case let .netService(netService): task = queue.sync { session.streamTask(with: netService) } } return task } } } #endif
mit
16462f3314950fe032033a7f825df5ec
35.995363
131
0.643466
5.13979
false
false
false
false
zhihuitang/Apollo
Apollo/RoundImageView.swift
1
2625
// // RoundImageView.swift // Apollo // // Created by Zhihui Tang on 2017-11-20. // Copyright © 2017 Zhihui Tang. All rights reserved. // import UIKit @IBDesignable class RoundImageView: UIView { @IBInspectable var image: UIImage? { didSet { imageView.image = image } } @IBInspectable var radius: CGFloat = 50.0 { didSet { outerView.layer.cornerRadius = radius outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: radius).cgPath imageView.layer.cornerRadius = radius } } @IBInspectable var shadowRadius: CGFloat = 5.0 { didSet { outerView.layer.shadowRadius = shadowRadius } } @IBInspectable var shadowColor: UIColor = .black { didSet { outerView.layer.shadowColor = shadowColor.cgColor } } @IBInspectable var shadowOffset: CGSize = CGSize.zero { didSet { outerView.layer.shadowOffset = shadowOffset } } @IBInspectable var shadowOpacity: Float = 0 { didSet { outerView.layer.shadowOpacity = shadowOpacity } } @IBInspectable var borderWidth: CGFloat = 2.0 { didSet { outerView.layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor = .white { didSet { outerView.layer.borderColor = borderColor.cgColor } } @IBInspectable var bgColor: UIColor = .white { didSet { outerView.backgroundColor = bgColor } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } lazy private var outerView: UIView = { let view = UIView(frame: self.bounds) return view }() lazy private var imageView: UIImageView = { let view = UIImageView(frame: self.bounds) return view }() private func commonInit() { imageView.clipsToBounds = true outerView.clipsToBounds = false outerView.layer.shadowOpacity = shadowOpacity imageView.contentMode = .scaleAspectFit outerView.addSubview(imageView) self.addSubview(outerView) } override func layoutSubviews() { super.layoutSubviews() outerView.frame = self.bounds imageView.frame = self.bounds } }
apache-2.0
cbe574a47bebfed9a19ff7343354478d
21.817391
113
0.575838
4.932331
false
false
false
false
h3poteto/TimeCamouflage
Example/Tests/Tests.swift
1
1181
// https://github.com/Quick/Quick import Quick import Nimble import TimeCamouflage class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
2f408af45d5de2b05fb6f73093bad67a
22.5
63
0.365957
5.414747
false
false
false
false
ztyjr888/WeChat
WeChat/Plugins/Index/TableViewIndex.swift
1
4626
// // TableViewIndex.swift // WeChat // // Created by Smile on 16/1/10. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit //自定义索引 class TableViewIndex:UIView { var shapeLayer:CAShapeLayer? var fontSize:CGFloat? var letterHeight:CGFloat? var isLayedOut:Bool = false var letters = [String]() var tableView: UITableView? var datas = [ContactSession]() init(frame: CGRect,tableView:UITableView,datas:[ContactSession]) { self.letterHeight = 14; fontSize = 12; //letters = UILocalizedIndexedCollation.currentCollation().sectionTitles self.tableView = tableView self.datas = datas //MARKS: Get All Keys if datas.count > 0 { for(var i = 0;i < datas.count;i++){ let key = datas[i].key if !key.isEmpty { letters.append(key) } } } let height:CGFloat = self.letterHeight! * CGFloat(datas.count) //重新计算位置 let beginY:CGFloat = (tableView.bounds.height - height) / 2 super.init(frame: CGRectMake(frame.origin.x, beginY, frame.width, height)) //super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setUp(){ shapeLayer = CAShapeLayer() shapeLayer!.lineWidth = 0.5// 线条宽度 shapeLayer!.fillColor = UIColor.clearColor().CGColor// 闭环填充的颜色 shapeLayer!.lineJoin = kCALineCapSquare shapeLayer!.strokeColor = UIColor.clearColor().CGColor// 边缘线的颜色 shapeLayer!.strokeEnd = 1.0 self.layer.masksToBounds = false } override func layoutSubviews() { super.layoutSubviews() self.setUp() if !isLayedOut { shapeLayer?.frame.origin = CGPointZero shapeLayer?.frame.size = self.layer.frame.size var count:CGFloat = 0 for i in self.letters{ if !letters.contains(i){ continue } let originY = count * self.letterHeight! let text = textLayerWithSize(fontSize!, string: i, frame: CGRectMake(0, originY, self.frame.size.width, self.letterHeight!)) self.layer.addSublayer(text) count++ } self.layer.addSublayer(shapeLayer!) isLayedOut = true } } func reloadLayout(edgeInsets:UIEdgeInsets){ /*var rect = self.frame; rect.size.height = self.indexs.count * self.letterHeight; rect.origin.y = edgeInsets.top + (self.superview!.bounds.size.height - edgeInsets.top - edgeInsets.bottom - rect.size.height) / 2; self.frame = rect;*/ } func textLayerWithSize(size:CGFloat,string:String,frame:CGRect) -> CATextLayer{ let textLayer = CATextLayer() textLayer.font = CTFontCreateWithName("TrebuchetMS-Bold",size,nil) textLayer.fontSize = size textLayer.frame = frame textLayer.alignmentMode = kCAAlignmentCenter textLayer.contentsScale = UIScreen.mainScreen().scale //textLayer.foregroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1).CGColor textLayer.foregroundColor = UIColor.grayColor().CGColor textLayer.string = string return textLayer } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) sendEventToDelegate(event!) } func sendEventToDelegate(event:UIEvent){ let point = (event.allTouches()! as NSSet).anyObject()?.locationInView(self) let index = Int(floorf(Float(point!.y)) / Float(self.letterHeight!)) if (index < 0 || index > self.letters.count - 1) { return; } didSelectSectionAtIndex(index, withTitle: self.letters[index]) } func didSelectSectionAtIndex(index:Int,withTitle title:String){ if (index > -1){ for(var i = 0; i < tableView!.numberOfSections;i++) { let key = datas[i].key if key == title { tableView!.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: i), atScrollPosition: .Top, animated: false) } } } } }
apache-2.0
143a474360a9a580cebf9cb2bf337cdb
31.856115
140
0.581125
4.631846
false
false
false
false
YF-Raymond/DouYUzhibo
DYZB/DYZB/Classes/Main/View/CollectionBaseCell.swift
1
1273
// // CollectionBaseCell.swift // DYZB // // Created by Raymond on 2016/12/29. // Copyright © 2016年 Raymond. All rights reserved. // import UIKit class CollectionBaseCell: UICollectionViewCell { // MARK:- 控件属性 @IBOutlet weak var sourceImageView: UIImageView! @IBOutlet weak var nicknameBtn: UIButton! @IBOutlet weak var onlineBtn: UIButton! // MARK:- 模型属性 var anchor : AnchorModel? { didSet { // 0.检验模型是否有值 guard let anchor = anchor else { return } // 1.取出在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = String(format: "%.1f万", Float(anchor.online) / 10000.0) onlineStr = onlineStr.replacingOccurrences(of: ".0", with: "") } else { onlineStr = "\(anchor.online)" } onlineBtn.setTitle(onlineStr, for: .normal) // 2.显示昵称 nicknameBtn.setTitle(anchor.nickname, for: .normal) // 3.设置封面图片 guard let sourceURL = URL(string: anchor.vertical_src) else { return } sourceImageView.kf.setImage(with: sourceURL) } } }
mit
92ecbec7679d954e4dd161459912997f
30.421053
83
0.568677
4.373626
false
false
false
false
waterskier2007/Toast-Swift
Toast/Toast.swift
1
30717
// // Toast.swift // Toast-Swift // // Copyright (c) 2015-2017 Charles Scalesse. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit import ObjectiveC /** Toast is a Swift extension that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most toast notifications can be triggered with a single line of code. The `makeToast` methods create a new view and then display it as toast. The `showToast` methods display any view as toast. */ public extension UIView { /** Keys used for associated objects. */ private struct ToastKeys { static var timer = "com.toast-swift.timer" static var duration = "com.toast-swift.duration" static var point = "com.toast-swift.point" static var completion = "com.toast-swift.completion" static var activeToasts = "com.toast-swift.activeToasts" static var activityView = "com.toast-swift.activityView" static var queue = "com.toast-swift.queue" } /** Swift closures can't be directly associated with objects via the Objective-C runtime, so the (ugly) solution is to wrap them in a class that can be used with associated objects. */ private class ToastCompletionWrapper { let completion: ((Bool) -> Void)? init(_ completion: ((Bool) -> Void)?) { self.completion = completion } } private enum ToastError: Error { case missingParameters } private var activeToasts: NSMutableArray { get { if let activeToasts = objc_getAssociatedObject(self, &ToastKeys.activeToasts) as? NSMutableArray { return activeToasts } else { let activeToasts = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.activeToasts, activeToasts, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return activeToasts } } } private var queue: NSMutableArray { get { if let queue = objc_getAssociatedObject(self, &ToastKeys.queue) as? NSMutableArray { return queue } else { let queue = NSMutableArray() objc_setAssociatedObject(self, &ToastKeys.queue, queue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return queue } } } // MARK: - Make Toast Methods /** Creates and presents a new toast view. @param message The message to be displayed @param duration The toast duration @param position The toast's position @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, title: String? = nil, image: UIImage? = nil, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)? = nil) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, position: position, completion: completion) } catch ToastError.missingParameters { print("Error: message, title, and image are all nil") } catch {} } /** Creates a new toast view and presents it at a given center point. @param message The message to be displayed @param duration The toast duration @param point The toast's center point @param title The title @param image The image @param style The style. The shared style will be used when nil @param completion The completion closure, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func makeToast(_ message: String?, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, title: String?, image: UIImage?, style: ToastStyle = ToastManager.shared.style, completion: ((_ didTap: Bool) -> Void)?) { do { let toast = try toastViewForMessage(message, title: title, image: image, style: style) showToast(toast, duration: duration, point: point, completion: completion) } catch ToastError.missingParameters { print("Error: message, title, and image cannot all be nil") } catch {} } // MARK: - Show Toast Methods /** Displays any view as toast at a provided position and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param position The toast's position @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, position: ToastPosition = ToastManager.shared.position, completion: ((_ didTap: Bool) -> Void)? = nil) { let point = position.centerPoint(forToast: toast, inSuperview: self) showToast(toast, duration: duration, point: point, completion: completion) } /** Displays any view as toast at a provided center point and duration. The completion closure executes when the toast view completes. `didTap` will be `true` if the toast view was dismissed from a tap. @param toast The view to be displayed as toast @param duration The notification duration @param point The toast's center point @param completion The completion block, executed after the toast view disappears. didTap will be `true` if the toast view was dismissed from a tap. */ public func showToast(_ toast: UIView, duration: TimeInterval = ToastManager.shared.duration, point: CGPoint, completion: ((_ didTap: Bool) -> Void)? = nil) { objc_setAssociatedObject(toast, &ToastKeys.completion, ToastCompletionWrapper(completion), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); if ToastManager.shared.isQueueEnabled, activeToasts.count > 0 { objc_setAssociatedObject(toast, &ToastKeys.duration, NSNumber(value: duration), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(toast, &ToastKeys.point, NSValue(cgPoint: point), .OBJC_ASSOCIATION_RETAIN_NONATOMIC); queue.add(toast) } else { showToast(toast, duration: duration, point: point) } } // MARK: - Hide Toast Methods /** Hides the active toast. If there are multiple toasts active in a view, this method hides the oldest toast (the first of the toasts to have been presented). @see `hideAllToasts()` to remove all active toasts from a view. @warning This method has no effect on activity toasts. Use `hideToastActivity` to hide activity toasts. */ public func hideToast() { guard let activeToast = activeToasts.firstObject as? UIView else { return } hideToast(activeToast) } /** Hides an active toast. @param toast The active toast view to dismiss. Any toast that is currently being displayed on the screen is considered active. @warning this does not clear a toast view that is currently waiting in the queue. */ public func hideToast(_ toast: UIView) { guard activeToasts.contains(toast) else { return } hideToast(toast, fromTap: false) } /** Hides all toast views. @param includeActivity If `true`, toast activity will also be hidden. Default is `false`. @param clearQueue If `true`, removes all toast views from the queue. Default is `true`. */ public func hideAllToasts(includeActivity: Bool = false, clearQueue: Bool = true) { if clearQueue { clearToastQueue() } activeToasts.flatMap { $0 as? UIView } .forEach { hideToast($0) } if includeActivity { hideToastActivity() } } /** Removes all toast views from the queue. This has no effect on toast views that are active. Use `hideAllToasts(clearQueue:)` to hide the active toasts views and clear the queue. */ public func clearToastQueue() { queue.removeAllObjects() } // MARK: - Activity Methods /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param position The toast's position */ public func makeToastActivity(_ position: ToastPosition) { // sanity guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return } let toast = createToastActivityView() let point = position.centerPoint(forToast: toast, inSuperview: self) makeToastActivity(toast, point: point) } /** Creates and displays a new toast activity indicator view at a specified position. @warning Only one toast activity indicator view can be presented per superview. Subsequent calls to `makeToastActivity(position:)` will be ignored until `hideToastActivity()` is called. @warning `makeToastActivity(position:)` works independently of the `showToast` methods. Toast activity views can be presented and dismissed while toast views are being displayed. `makeToastActivity(position:)` has no effect on the queueing behavior of the `showToast` methods. @param point The toast's center point */ public func makeToastActivity(_ point: CGPoint) { // sanity guard objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView == nil else { return } let toast = createToastActivityView() makeToastActivity(toast, point: point) } /** Dismisses the active toast activity indicator view. */ public func hideToastActivity() { if let toast = objc_getAssociatedObject(self, &ToastKeys.activityView) as? UIView { UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() objc_setAssociatedObject(self, &ToastKeys.activityView, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } // MARK: - Private Activity Methods private func makeToastActivity(_ toast: UIView, point: CGPoint) { toast.alpha = 0.0 toast.center = point objc_setAssociatedObject(self, &ToastKeys.activityView, toast, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: .curveEaseOut, animations: { toast.alpha = 1.0 }) } private func createToastActivityView() -> UIView { let style = ToastManager.shared.style let activityView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: style.activitySize.width, height: style.activitySize.height)) activityView.backgroundColor = style.activityBackgroundColor activityView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] activityView.layer.cornerRadius = style.cornerRadius if style.displayShadow { activityView.layer.shadowColor = style.shadowColor.cgColor activityView.layer.shadowOpacity = style.shadowOpacity activityView.layer.shadowRadius = style.shadowRadius activityView.layer.shadowOffset = style.shadowOffset } let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) activityIndicatorView.center = CGPoint(x: activityView.bounds.size.width / 2.0, y: activityView.bounds.size.height / 2.0) activityView.addSubview(activityIndicatorView) activityIndicatorView.color = style.activityIndicatorColor activityIndicatorView.startAnimating() return activityView } // MARK: - Private Show/Hide Methods private func showToast(_ toast: UIView, duration: TimeInterval, point: CGPoint) { toast.center = point toast.alpha = 0.0 if ToastManager.shared.isTapToDismissEnabled { let recognizer = UITapGestureRecognizer(target: self, action: #selector(UIView.handleToastTapped(_:))) toast.addGestureRecognizer(recognizer) toast.isUserInteractionEnabled = true toast.isExclusiveTouch = true } activeToasts.add(toast) self.addSubview(toast) UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseOut, .allowUserInteraction], animations: { toast.alpha = 1.0 }) { _ in let timer = Timer(timeInterval: duration, target: self, selector: #selector(UIView.toastTimerDidFinish(_:)), userInfo: toast, repeats: false) RunLoop.main.add(timer, forMode: RunLoopMode.commonModes) objc_setAssociatedObject(toast, &ToastKeys.timer, timer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private func hideToast(_ toast: UIView, fromTap: Bool) { if let timer = objc_getAssociatedObject(toast, &ToastKeys.timer) as? Timer { timer.invalidate() } UIView.animate(withDuration: ToastManager.shared.style.fadeDuration, delay: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: { toast.alpha = 0.0 }) { _ in toast.removeFromSuperview() self.activeToasts.remove(toast) if let wrapper = objc_getAssociatedObject(toast, &ToastKeys.completion) as? ToastCompletionWrapper, let completion = wrapper.completion { completion(fromTap) } if let nextToast = self.queue.firstObject as? UIView, let duration = objc_getAssociatedObject(nextToast, &ToastKeys.duration) as? NSNumber, let point = objc_getAssociatedObject(nextToast, &ToastKeys.point) as? NSValue { self.queue.removeObject(at: 0) self.showToast(nextToast, duration: duration.doubleValue, point: point.cgPointValue) } } } // MARK: - Events @objc private func handleToastTapped(_ recognizer: UITapGestureRecognizer) { guard let toast = recognizer.view else { return } hideToast(toast, fromTap: true) } @objc private func toastTimerDidFinish(_ timer: Timer) { guard let toast = timer.userInfo as? UIView else { return } hideToast(toast) } // MARK: - Toast Construction /** Creates a new toast view with any combination of message, title, and image. The look and feel is configured via the style. Unlike the `makeToast` methods, this method does not present the toast view automatically. One of the `showToast` methods must be used to present the resulting view. @warning if message, title, and image are all nil, this method will throw `ToastError.missingParameters` @param message The message to be displayed @param title The title @param image The image @param style The style. The shared style will be used when nil @throws `ToastError.missingParameters` when message, title, and image are all nil @return The newly created toast view */ public func toastViewForMessage(_ message: String?, title: String?, image: UIImage?, style: ToastStyle) throws -> UIView { // sanity guard message != nil || title != nil || image != nil else { throw ToastError.missingParameters } var messageLabel: UILabel? var titleLabel: UILabel? var imageView: UIImageView? let wrapperView = UIView() wrapperView.backgroundColor = style.backgroundColor wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = style.cornerRadius if style.displayShadow { wrapperView.layer.shadowColor = UIColor.black.cgColor wrapperView.layer.shadowOpacity = style.shadowOpacity wrapperView.layer.shadowRadius = style.shadowRadius wrapperView.layer.shadowOffset = style.shadowOffset } if let image = image { imageView = UIImageView(image: image) imageView?.contentMode = .scaleAspectFit imageView?.frame = CGRect(x: style.horizontalPadding, y: style.verticalPadding, width: style.imageSize.width, height: style.imageSize.height) } var imageRect = CGRect.zero if let imageView = imageView { imageRect.origin.x = style.horizontalPadding imageRect.origin.y = style.verticalPadding imageRect.size.width = imageView.bounds.size.width imageRect.size.height = imageView.bounds.size.height } if let title = title { titleLabel = UILabel() titleLabel?.numberOfLines = style.titleNumberOfLines titleLabel?.font = style.titleFont titleLabel?.textAlignment = style.titleAlignment titleLabel?.lineBreakMode = .byTruncatingTail titleLabel?.textColor = style.titleColor titleLabel?.backgroundColor = UIColor.clear titleLabel?.text = title; let maxTitleSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let titleSize = titleLabel?.sizeThatFits(maxTitleSize) if let titleSize = titleSize { titleLabel?.frame = CGRect(x: 0.0, y: 0.0, width: titleSize.width, height: titleSize.height) } } if let message = message { messageLabel = UILabel() messageLabel?.text = message messageLabel?.numberOfLines = style.messageNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textAlignment = style.messageAlignment messageLabel?.lineBreakMode = .byTruncatingTail; messageLabel?.textColor = style.messageColor messageLabel?.backgroundColor = UIColor.clear let maxMessageSize = CGSize(width: (self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, height: self.bounds.size.height * style.maxHeightPercentage) let messageSize = messageLabel?.sizeThatFits(maxMessageSize) if let messageSize = messageSize { let actualWidth = min(messageSize.width, maxMessageSize.width) let actualHeight = min(messageSize.height, maxMessageSize.height) messageLabel?.frame = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) } } var titleRect = CGRect.zero if let titleLabel = titleLabel { titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding titleRect.origin.y = style.verticalPadding titleRect.size.width = titleLabel.bounds.size.width titleRect.size.height = titleLabel.bounds.size.height } var messageRect = CGRect.zero if let messageLabel = messageLabel { messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding messageRect.size.width = messageLabel.bounds.size.width messageRect.size.height = messageLabel.bounds.size.height } let longerWidth = max(titleRect.size.width, messageRect.size.width) let longerX = max(titleRect.origin.x, messageRect.origin.x) let wrapperWidth = max((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) if let titleLabel = titleLabel { titleRect.size.width = longerWidth titleLabel.frame = titleRect wrapperView.addSubview(titleLabel) } if let messageLabel = messageLabel { messageRect.size.width = longerWidth messageLabel.frame = messageRect wrapperView.addSubview(messageLabel) } if let imageView = imageView { wrapperView.addSubview(imageView) } return wrapperView } } // MARK: - Toast Style /** `ToastStyle` instances define the look and feel for toast views created via the `makeToast` methods as well for toast views created directly with `toastViewForMessage(message:title:image:style:)`. @warning `ToastStyle` offers relatively simple styling options for the default toast view. If you require a toast view with more complex UI, it probably makes more sense to create your own custom UIView subclass and present it with the `showToast` methods. */ public struct ToastStyle { public init() {} /** The background color. Default is `.black` at 80% opacity. */ public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8) /** The title color. Default is `UIColor.whiteColor()`. */ public var titleColor: UIColor = .white /** The message color. Default is `.white`. */ public var messageColor: UIColor = .white /** A percentage value from 0.0 to 1.0, representing the maximum width of the toast view relative to it's superview. Default is 0.8 (80% of the superview's width). */ public var maxWidthPercentage: CGFloat = 0.8 { didSet { maxWidthPercentage = max(min(maxWidthPercentage, 1.0), 0.0) } } /** A percentage value from 0.0 to 1.0, representing the maximum height of the toast view relative to it's superview. Default is 0.8 (80% of the superview's height). */ public var maxHeightPercentage: CGFloat = 0.8 { didSet { maxHeightPercentage = max(min(maxHeightPercentage, 1.0), 0.0) } } /** The spacing from the horizontal edge of the toast view to the content. When an image is present, this is also used as the padding between the image and the text. Default is 10.0. */ public var horizontalPadding: CGFloat = 10.0 /** The spacing from the vertical edge of the toast view to the content. When a title is present, this is also used as the padding between the title and the message. Default is 10.0. On iOS11+, this value is added added to the `safeAreaInset.top` and `safeAreaInsets.bottom`. */ public var verticalPadding: CGFloat = 10.0 /** The corner radius. Default is 10.0. */ public var cornerRadius: CGFloat = 10.0; /** The title font. Default is `.boldSystemFont(16.0)`. */ public var titleFont: UIFont = .boldSystemFont(ofSize: 16.0) /** The message font. Default is `.systemFont(ofSize: 16.0)`. */ public var messageFont: UIFont = .systemFont(ofSize: 16.0) /** The title text alignment. Default is `NSTextAlignment.Left`. */ public var titleAlignment: NSTextAlignment = .left /** The message text alignment. Default is `NSTextAlignment.Left`. */ public var messageAlignment: NSTextAlignment = .left /** The maximum number of lines for the title. The default is 0 (no limit). */ public var titleNumberOfLines = 0 /** The maximum number of lines for the message. The default is 0 (no limit). */ public var messageNumberOfLines = 0 /** Enable or disable a shadow on the toast view. Default is `false`. */ public var displayShadow = false /** The shadow color. Default is `.black`. */ public var shadowColor: UIColor = .black /** A value from 0.0 to 1.0, representing the opacity of the shadow. Default is 0.8 (80% opacity). */ public var shadowOpacity: Float = 0.8 { didSet { shadowOpacity = max(min(shadowOpacity, 1.0), 0.0) } } /** The shadow radius. Default is 6.0. */ public var shadowRadius: CGFloat = 6.0 /** The shadow offset. The default is 4 x 4. */ public var shadowOffset = CGSize(width: 4.0, height: 4.0) /** The image size. The default is 80 x 80. */ public var imageSize = CGSize(width: 80.0, height: 80.0) /** The size of the toast activity view when `makeToastActivity(position:)` is called. Default is 100 x 100. */ public var activitySize = CGSize(width: 100.0, height: 100.0) /** The fade in/out animation duration. Default is 0.2. */ public var fadeDuration: TimeInterval = 0.2 /** Activity indicator color. Default is `.white`. */ public var activityIndicatorColor: UIColor = .white /** Activity background color. Default is `.black` at 80% opacity. */ public var activityBackgroundColor: UIColor = UIColor.black.withAlphaComponent(0.8) } // MARK: - Toast Manager /** `ToastManager` provides general configuration options for all toast notifications. Backed by a singleton instance. */ public class ToastManager { /** The `ToastManager` singleton instance. */ public static let shared = ToastManager() /** The shared style. Used whenever toastViewForMessage(message:title:image:style:) is called with with a nil style. */ public var style = ToastStyle() /** Enables or disables tap to dismiss on toast views. Default is `true`. */ public var isTapToDismissEnabled = true /** Enables or disables queueing behavior for toast views. When `true`, toast views will appear one after the other. When `false`, multiple toast views will appear at the same time (potentially overlapping depending on their positions). This has no effect on the toast activity view, which operates independently of normal toast views. Default is `false`. */ public var isQueueEnabled = false /** The default duration. Used for the `makeToast` and `showToast` methods that don't require an explicit duration. Default is 3.0. */ public var duration: TimeInterval = 3.0 /** Sets the default position. Used for the `makeToast` and `showToast` methods that don't require an explicit position. Default is `ToastPosition.Bottom`. */ public var position: ToastPosition = .bottom } // MARK: - ToastPosition public enum ToastPosition { case top case center case bottom fileprivate func centerPoint(forToast toast: UIView, inSuperview superview: UIView) -> CGPoint { let topPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.top let bottomPadding: CGFloat = ToastManager.shared.style.verticalPadding + superview.csSafeAreaInsets.bottom switch self { case .top: return CGPoint(x: superview.bounds.size.width / 2.0, y: (toast.frame.size.height / 2.0) + topPadding) case .center: return CGPoint(x: superview.bounds.size.width / 2.0, y: superview.bounds.size.height / 2.0) case .bottom: return CGPoint(x: superview.bounds.size.width / 2.0, y: (superview.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding) } } } fileprivate extension UIView { fileprivate var csSafeAreaInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return self.safeAreaInsets } else { return .zero } } }
mit
8287412cb1e91fbfadddb18ab20fd719
38.380769
297
0.649477
4.924964
false
false
false
false
shafiullakhan/Swift-Paper
Swift-Paper/Swift-Paper/BaseLayout/CollectionViewLargeLayout.swift
1
2086
// // CollectionViewLargeLayout.swift // Swift-Paper // // Created by Shaf on 8/5/15. // Copyright (c) 2015 Shaffiulla. All rights reserved. // import UIKit class CollectionViewLargeLayout: UICollectionViewFlowLayout { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { // super.init(); self.itemSize = CGSizeMake(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds)); self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0); self.minimumInteritemSpacing = 10.0; self.minimumLineSpacing = 4.0; self.scrollDirection = .Horizontal; } override func shouldInvalidateLayoutForBoundsChange(oldBounds : CGRect) -> Bool{ return true; } override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var offsetAdjustment:CGFloat = CGFloat(MAXFLOAT); let horizontalCenter:CGFloat = proposedContentOffset.x + (CGRectGetWidth(self.collectionView!.bounds) / 2.0); let targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView!.bounds.size.width, self.collectionView!.bounds.size.height); let array = self.layoutAttributesForElementsInRect(targetRect); for layoutAttributes in (array! as NSArray) { if (layoutAttributes.representedElementCategory != .Cell){ continue; // skip headers } let itemHorizontalCenter:CGFloat = layoutAttributes.center.x; if (abs(itemHorizontalCenter - horizontalCenter) < abs(offsetAdjustment)) { offsetAdjustment = itemHorizontalCenter - horizontalCenter; var layoutArr = layoutAttributes as! UICollectionViewLayoutAttributes; layoutArr.alpha = 0.0; } } return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y); } }
mit
fdc24260eb171666a9982cf5f881290e
38.358491
147
0.663471
5.321429
false
false
false
false
DAloG/BlueCap
Examples/PeripheralWithProfile/PeripheralWithProfile/ViewController.swift
1
9889
// // ViewController.swift // Beacon // // Created by Troy Stribling on 4/13/15. // Copyright (c) 2015 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import CoreMotion import BlueCapKit class ViewController: UITableViewController { @IBOutlet var xAccelerationLabel : UILabel! @IBOutlet var yAccelerationLabel : UILabel! @IBOutlet var zAccelerationLabel : UILabel! @IBOutlet var xRawAccelerationLabel : UILabel! @IBOutlet var yRawAccelerationLabel : UILabel! @IBOutlet var zRawAccelerationLabel : UILabel! @IBOutlet var rawUpdatePeriodlabel : UILabel! @IBOutlet var updatePeriodLabel : UILabel! @IBOutlet var startAdvertisingSwitch : UISwitch! @IBOutlet var startAdvertisingLabel : UILabel! @IBOutlet var enableLabel : UILabel! @IBOutlet var enabledSwitch : UISwitch! let accelerometer = Accelerometer() let accelerometerService = MutableService(profile:ConfiguredServiceProfile<TISensorTag.AccelerometerService>()) let accelerometerDataCharacteristic = MutableCharacteristic(profile:RawArrayCharacteristicProfile<TISensorTag.AccelerometerService.Data>()) let accelerometerEnabledCharacteristic = MutableCharacteristic(profile:RawCharacteristicProfile<TISensorTag.AccelerometerService.Enabled>()) let accelerometerUpdatePeriodCharacteristic = MutableCharacteristic(profile:RawCharacteristicProfile<TISensorTag.AccelerometerService.UpdatePeriod>()) required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) self.accelerometerService.characteristics = [self.accelerometerDataCharacteristic, self.accelerometerEnabledCharacteristic, self.accelerometerUpdatePeriodCharacteristic] self.respondToWriteRequests() } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.accelerometer.accelerometerAvailable { self.startAdvertisingSwitch.enabled = true self.startAdvertisingLabel.textColor = UIColor.blackColor() self.enabledSwitch.enabled = true self.enableLabel.textColor = UIColor.blackColor() self.updatePeriod() } else { self.startAdvertisingSwitch.enabled = false self.startAdvertisingSwitch.on = false self.startAdvertisingLabel.textColor = UIColor.lightGrayColor() self.enabledSwitch.enabled = false self.enabledSwitch.on = false self.enableLabel.textColor = UIColor.lightGrayColor() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } @IBAction func toggleEnabled(sender:AnyObject) { if self.accelerometer.accelerometerActive { self.accelerometer.stopAccelerometerUpdates() } else { let accelrometerDataFuture = self.accelerometer.startAcceleromterUpdates() accelrometerDataFuture.onSuccess {data in self.updateAccelerometerData(data) } accelrometerDataFuture.onFailure {error in self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil) } } } @IBAction func toggleAdvertise(sender:AnyObject) { let manager = PeripheralManager.sharedInstance if manager.isAdvertising { manager.stopAdvertising().onSuccess { self.presentViewController(UIAlertController.alertWithMessage("stoped advertising"), animated:true, completion:nil) } self.accelerometerUpdatePeriodCharacteristic.stopProcessingWriteRequests() } else { self.startAdvertising() } } func startAdvertising() { let uuid = CBUUID(string:TISensorTag.AccelerometerService.uuid) let manager = PeripheralManager.sharedInstance // on power on remove all services add service and start advertising let startAdvertiseFuture = manager.powerOn().flatmap {_ -> Future<Void> in manager.removeAllServices() }.flatmap {_ -> Future<Void> in manager.addService(self.accelerometerService) }.flatmap {_ -> Future<Void> in manager.startAdvertising(TISensorTag.AccelerometerService.name, uuids:[uuid]) } startAdvertiseFuture.onSuccess { self.presentViewController(UIAlertController.alertWithMessage("powered on and started advertising"), animated:true, completion:nil) } startAdvertiseFuture.onFailure {error in self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil) self.startAdvertisingSwitch.on = false } // stop advertising and updating accelerometer on bluetooth power off let powerOffFuture = manager.powerOff().flatmap { _ -> Future<Void> in if self.accelerometer.accelerometerActive { self.accelerometer.stopAccelerometerUpdates() self.enabledSwitch.on = false } return manager.stopAdvertising() } powerOffFuture.onSuccess { self.startAdvertisingSwitch.on = false self.startAdvertisingSwitch.enabled = false self.startAdvertisingLabel.textColor = UIColor.lightGrayColor() self.presentViewController(UIAlertController.alertWithMessage("powered off and stopped advertising"), animated:true, completion:nil) } powerOffFuture.onFailure {error in self.startAdvertisingSwitch.on = false self.startAdvertisingSwitch.enabled = false self.startAdvertisingLabel.textColor = UIColor.lightGrayColor() self.presentViewController(UIAlertController.alertWithMessage("advertising failed"), animated:true, completion:nil) } // enable controls when bluetooth is powered on again after stop advertising is successul let powerOffFutureSuccessFuture = powerOffFuture.flatmap {_ -> Future<Void> in manager.powerOn() } powerOffFutureSuccessFuture.onSuccess { self.presentViewController(UIAlertController.alertWithMessage("restart application"), animated:true, completion:nil) } // enable controls when bluetooth is powered on again after stop advertising fails let powerOffFutureFailedFuture = powerOffFuture.recoverWith {_ -> Future<Void> in manager.powerOn() } powerOffFutureFailedFuture.onSuccess { if PeripheralManager.sharedInstance.poweredOn { self.presentViewController(UIAlertController.alertWithMessage("restart application"), animated:true, completion:nil) } } } func respondToWriteRequests() { let accelerometerUpdatePeriodFuture = self.accelerometerUpdatePeriodCharacteristic.startRespondingToWriteRequests(2) accelerometerUpdatePeriodFuture.onSuccess {request in if let value = request.value where value.length > 0 && value.length <= 8 { self.accelerometerUpdatePeriodCharacteristic.value = value self.accelerometerUpdatePeriodCharacteristic.respondToRequest(request, withResult:CBATTError.Success) self.updatePeriod() } else { self.accelerometerUpdatePeriodCharacteristic.respondToRequest(request, withResult:CBATTError.InvalidAttributeValueLength) } } let accelerometerEnabledFuture = self.accelerometerEnabledCharacteristic.startRespondingToWriteRequests(2) accelerometerEnabledFuture.onSuccess {request in if let value = request.value where value.length == 1 { self.accelerometerEnabledCharacteristic.value = value self.accelerometerEnabledCharacteristic.respondToRequest(request, withResult:CBATTError.Success) self.updateEnabled() } else { self.accelerometerEnabledCharacteristic.respondToRequest(request, withResult:CBATTError.InvalidAttributeValueLength) } } } func updateAccelerometerData(data:CMAcceleration) { self.xAccelerationLabel.text = NSString(format: "%.2f", data.x) as String self.yAccelerationLabel.text = NSString(format: "%.2f", data.y) as String self.zAccelerationLabel.text = NSString(format: "%.2f", data.z) as String if let xRaw = Int8(doubleValue:(-64.0*data.x)), yRaw = Int8(doubleValue:(-64.0*data.y)), zRaw = Int8(doubleValue:(64.0*data.z)) { self.xRawAccelerationLabel.text = "\(xRaw)" self.yRawAccelerationLabel.text = "\(yRaw)" self.zRawAccelerationLabel.text = "\(zRaw)" self.accelerometerDataCharacteristic.updateValueWithString(["xRaw":"\(xRaw)", "yRaw":"\(yRaw)","zRaw":"\(zRaw)"]) } } func updatePeriod() { if let data = self.accelerometerUpdatePeriodCharacteristic.stringValue, period = data["period"], periodRaw = data["periodRaw"], periodInt = Int(period) { self.accelerometer.updatePeriod = Double(periodInt)/1000.0 self.updatePeriodLabel.text = period self.rawUpdatePeriodlabel.text = periodRaw } } func updateEnabled() { let currentValue = self.enabledSwitch.on ? "Yes" : "No" if let data = self.accelerometerEnabledCharacteristic.stringValue, enabled = data.values.first where currentValue != enabled { self.enabledSwitch.on = enabled == "Yes" self.toggleEnabled(self) } } }
mit
4910b8c084b2e7cfd58ddf2d4b6d7105
47.955446
177
0.675195
5.293897
false
false
false
false
hermantai/samples
ios/SwiftUI-Cookbook-2nd-Edition/Chapter10-Driving-SwiftUI-with-Combine/01-Introducing-Combine-in-a-SwiftUI-project/CombineCoreLocationManager/CombineCoreLocationManager/ContentView.swift
1
5091
// // ContentView.swift // CombineCoreLocationManager // // Created by Giordano Scalzo on 28/07/2021. // import SwiftUI import CoreLocation import Combine class LocationManager: NSObject { enum LocationError: String, Error { case restricted case denied case unknown } let statusPublisher = PassthroughSubject<CLAuthorizationStatus, LocationError>() let locationPublisher = PassthroughSubject<CLLocation?, Never>() private let locationManager = CLLocationManager() override init() { super.init() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() } func start() { locationManager.startUpdatingLocation() } } extension LocationManager: CLLocationManagerDelegate { func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { switch manager.authorizationStatus { case .restricted: statusPublisher.send(completion: .failure(.restricted)) case .denied: statusPublisher.send(completion: .failure(.denied)) case .notDetermined, .authorizedAlways, .authorizedWhenInUse: statusPublisher.send(manager.authorizationStatus) @unknown default: statusPublisher.send(completion: .failure(.unknown)) } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } locationPublisher.send(location) } } class LocationViewModel: ObservableObject { @Published private var status: CLAuthorizationStatus = .notDetermined @Published private var currentLocation: CLLocation? @Published var errorMessage = "" private let locationManager = LocationManager() var thereIsAnError: Bool { !errorMessage.isEmpty } var latitude: String { currentLocation.latitudeDescription } var longitude: String { currentLocation.longitudeDescription } var statusDescription: String { switch status { case .notDetermined: return "notDetermined" case .authorizedWhenInUse: return "authorizedWhenInUse" case .authorizedAlways: return "authorizedAlways" case .restricted: return "restricted" case .denied: return "denied" @unknown default: return "unknown" } } func startUpdating() { locationManager.start() } private var cancellableSet: Set<AnyCancellable> = [] init() { locationManager .statusPublisher .debounce(for: 0.5, scheduler: RunLoop.main) .removeDuplicates() .sink { completion in switch completion { case .finished: break case .failure(let error): self.errorMessage = error.rawValue } } receiveValue: { self.status = $0} .store(in: &cancellableSet) locationManager.locationPublisher .debounce(for: 0.5, scheduler: RunLoop.main) .removeDuplicates(by: lessThanOneMeter) .assign(to: \.currentLocation, on: self) .store(in: &cancellableSet) } private func lessThanOneMeter(_ lhs: CLLocation?, _ rhs: CLLocation?) -> Bool { if lhs == nil && rhs == nil { return true } guard let lhr = lhs, let rhr = rhs else { return false } return lhr.distance(from: rhr) < 1 } } extension Optional where Wrapped == CLLocation { var latitudeDescription: String { guard let self = self else { return "-" } return String(format: "%0.4f", self.coordinate.latitude) } var longitudeDescription: String { guard let self = self else { return "-" } return String(format: "%0.4f", self.coordinate.longitude) } } struct ContentView: View { @StateObject var locationViewModel = LocationViewModel() var body: some View { Group { if locationViewModel.thereIsAnError { Text("Location Service terminated with error: \(locationViewModel.errorMessage)") } else { Text("Status: \(locationViewModel.statusDescription)") HStack { Text("Latitude: \(locationViewModel.latitude)") Text("Longitude: \(locationViewModel.longitude)") } } } .padding(.horizontal, 24) .task { locationViewModel.startUpdating() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
ee8cf967b3fcb6acb8987936c0726814
27.283333
97
0.59065
5.468314
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Models/Mapping/AuthSettingsModelMapping.swift
1
8507
// // AuthSettingsModelMapping.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 16/01/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift extension AuthSettings: ModelMappeable { //swiftlint:disable function_body_length func map(_ values: JSON, realm: Realm?) { self.uniqueIdentifier = objectForKey(object: values, key: "uniqueID")?.string self.siteURL = objectForKey(object: values, key: "Site_Url")?.string?.removingLastSlashIfNeeded() self.cdnPrefixURL = objectForKey(object: values, key: "CDN_PREFIX")?.string?.removingLastSlashIfNeeded() self.serverName = objectForKey(object: values, key: "Site_Name")?.string if let siteURL = self.siteURL { // Try URL or use defaultURL instead if let assetURL = objectForKey(object: values, key: "Assets_favicon_512")?["url"].string { self.serverFaviconURL = "\(siteURL)/\(assetURL)" } else if let assetURL = objectForKey(object: values, key: "Assets_favicon_512")?["defaultUrl"].string { self.serverFaviconURL = "\(siteURL)/\(assetURL)" } } self.useUserRealName = objectForKey(object: values, key: "UI_Use_Real_Name")?.bool ?? false self.allowSpecialCharsOnRoomNames = objectForKey(object: values, key: "UI_Allow_room_names_with_special_chars")?.bool ?? false self.favoriteRooms = objectForKey(object: values, key: "Favorite_Rooms")?.bool ?? true self.storeLastMessage = objectForKey(object: values, key: "Store_Last_Message")?.bool ?? true // Authentication methods self.isGoogleAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Google")?.bool ?? false self.isFacebookAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Facebook")?.bool ?? false self.isGitHubAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Github")?.bool ?? false self.isGitLabAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Gitlab")?.bool ?? false self.isLinkedInAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Linkedin")?.bool ?? false self.isWordPressAuthenticationEnabled = objectForKey(object: values, key: "Accounts_OAuth_Wordpress")?.bool ?? false self.isLDAPAuthenticationEnabled = objectForKey(object: values, key: "LDAP_Enable")?.bool ?? false self.isCASEnabled = objectForKey(object: values, key: "CAS_enabled")?.bool ?? false self.casLoginUrl = objectForKey(object: values, key: "CAS_login_url")?.string self.gitlabUrl = objectForKey(object: values, key: "API_Gitlab_URL")?.string self.wordpressUrl = objectForKey(object: values, key: "API_Wordpress_URL")?.string self.isUsernameEmailAuthenticationEnabled = objectForKey(object: values, key: "Accounts_ShowFormLogin")?.bool ?? true self.rawRegistrationForm = objectForKey(object: values, key: "Accounts_RegistrationForm")?.string self.isPasswordResetEnabled = objectForKey(object: values, key: "Accounts_PasswordReset")?.bool ?? true self.firstChannelAfterLogin = objectForKey(object: values, key: "First_Channel_After_Login")?.string // Authentication Placeholder Fields self.emailOrUsernameFieldPlaceholder = objectForKey(object: values, key: "Accounts_EmailOrUsernamePlaceholder")?.stringValue ?? "" self.passwordFieldPlaceholder = objectForKey(object: values, key: "Accounts_PasswordPlaceholder")?.stringValue ?? "" // Video Conferencing self.isJitsiEnabled = objectForKey(object: values, key: "Jitsi_Enabled")?.bool ?? false self.isJitsiEnabledForChannels = objectForKey(object: values, key: "Jisti_Enable_Channels")?.bool ?? false self.isJitsiSSL = objectForKey(object: values, key: "Jitsi_SSL")?.bool ?? false self.jitsiDomain = objectForKey(object: values, key: "Jitsi_Domain")?.string ?? "" self.jitsiPrefix = objectForKey(object: values, key: "Jitsi_URL_Room_Prefix")?.string ?? "" // Accounts self.emailVerification = objectForKey(object: values, key: "Accounts_EmailVerification")?.bool ?? false self.isAllowedToEditProfile = objectForKey(object: values, key: "Accounts_AllowUserProfileChange")?.bool ?? false self.isAllowedToEditAvatar = objectForKey(object: values, key: "Accounts_AllowUserAvatarChange")?.bool ?? false self.isAllowedToEditName = objectForKey(object: values, key: "Accounts_AllowRealNameChange")?.bool ?? false self.isAllowedToEditUsername = objectForKey(object: values, key: "Accounts_AllowUsernameChange")?.bool ?? false self.isAllowedToEditEmail = objectForKey(object: values, key: "Accounts_AllowEmailChange")?.bool ?? false self.isAllowedToEditPassword = objectForKey(object: values, key: "Accounts_AllowPasswordChange")?.bool ?? false self.oauthWordpressServerType = objectForKey(object: values, key: "Accounts_OAuth_Wordpress_server_type")?.string ?? "" // Upload self.uploadStorageType = objectForKey(object: values, key: "FileUpload_Storage_Type")?.string self.maxFileSize = objectForKey(object: values, key: "FileUpload_MaxFileSize")?.int ?? 0 // HideType self.hideMessageUserJoined = objectForKey(object: values, key: "Message_HideType_uj")?.bool ?? false self.hideMessageUserLeft = objectForKey(object: values, key: "Message_HideType_ul")?.bool ?? false self.hideMessageUserAdded = objectForKey(object: values, key: "Message_HideType_au")?.bool ?? false self.hideMessageUserMutedUnmuted = objectForKey(object: values, key: "Message_HideType_mute_unmute")?.bool ?? false self.hideMessageUserRemoved = objectForKey(object: values, key: "Message_HideType_ru")?.bool ?? false // Message if let period = objectForKey(object: values, key: "Message_GroupingPeriod")?.int { self.messageGroupingPeriod = period } self.messageAllowPinning = objectForKey(object: values, key: "Message_AllowPinning")?.bool ?? true self.messageAllowStarring = objectForKey(object: values, key: "Message_AllowStarring")?.bool ?? true self.messageShowDeletedStatus = objectForKey(object: values, key: "Message_ShowDeletedStatus")?.bool ?? true self.messageAllowDeleting = objectForKey(object: values, key: "Message_AllowDeleting")?.bool ?? true self.messageAllowDeletingBlockDeleteInMinutes = objectForKey(object: values, key: "Message_AllowDeleting_BlockDeleteInMinutes")?.int ?? 0 self.messageShowEditedStatus = objectForKey(object: values, key: "Message_ShowEditedStatus")?.bool ?? true self.messageAllowEditing = objectForKey(object: values, key: "Message_AllowEditing")?.bool ?? true self.messageAllowEditingBlockEditInMinutes = objectForKey(object: values, key: "Message_AllowEditing_BlockEditInMinutes")?.int ?? 0 self.messageMaxAllowedSize = objectForKey(object: values, key: "Message_MaxAllowedSize")?.int ?? 0 self.messageReadReceiptEnabled = objectForKey(object: values, key: "Message_Read_Receipt_Enabled")?.bool ?? false self.messageReadReceiptStoreUsers = objectForKey(object: values, key: "Message_Read_Receipt_Store_Users")?.bool ?? false // Custom Fields self.rawCustomFields = objectForKey(object: values, key: "Accounts_CustomFields")?.string?.removingWhitespaces() } fileprivate func objectForKey(object: JSON, key: String) -> JSON? { let result = object.array?.filter { obj in return obj["_id"].string == key }.first return result?["value"] } private func getCustomFields(from rawString: String?) -> [CustomField] { guard let encodedString = rawString?.data(using: .utf8, allowLossyConversion: false) else { return [] } do { let customFields = try JSON(data: encodedString) return customFields.map { (key, value) -> CustomField in let field = CustomField.chooseType(from: value, name: key) field.map(value, realm: realm) return field } } catch { Log.debug(error.localizedDescription) return [] } } var customFields: [CustomField] { return getCustomFields(from: rawCustomFields) } }
mit
c12ece1efe5eb1c50c660fb68ae67c75
58.482517
145
0.691512
4.4792
false
false
false
false
coreyjv/Emby.ApiClient.Swift
Emby.ApiClient/model/users/AuthenticationResult.swift
2
922
// // AuthenticationResult.swift // EmbyApiClient // // Created by Kevin Sullivan on 12/14/15. // // import Foundation public struct AuthenticationResult : JSONSerializable { public let user: UserDto public let sessionInfo: SessionInfoDto public let accessToken: String public let serverId: String public init?(jSON: JSON_Object) { if let accessToken = jSON["AccessToken"] as? String, let serverId = jSON["ServerId"] as? String, let userJSON = jSON["User"] as? JSON_Object, let sessionInfoJSON = jSON["SessionInfo"] as? JSON_Object, let user = UserDto(jSON: userJSON) { self.accessToken = accessToken self.serverId = serverId self.user = user self.sessionInfo = SessionInfoDto(jSON: sessionInfoJSON)! } else { return nil } } }
mit
533497382878edee8547828f08d45819
26.147059
70
0.596529
4.411483
false
false
false
false
adrfer/swift
test/Parse/switch.swift
1
7192
// RUN: %target-parse-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{braced block of statements is an unused closure}} expected-error{{expression resolves to an unused function}} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case let z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{12-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case let y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{type 'Int' does not conform to protocol 'BooleanType'}} x = 0 default: x = 1 } // Multiple cases per case block switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (let a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, let a): () case (let a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} case (1, let b): () case (1, let b): // let bindings () // var bindings are not allowed in cases. // FIXME: rdar://problem/23378003 // This will eventually be an error. case (1, var b): // expected-error {{Use of 'var' binding here is not allowed}} {{10-13=let}} () case (var a, 2): // expected-error {{Use of 'var' binding here is not allowed}} {{7-10=let}} () case (let a, 2), (1, let b): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () case (let a, 2), (1, _): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () case (_, 2), (let a, _): // expected-error {{'case' labels with multiple patterns cannot declare variables}} () // OK case (_, 2), (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } // Fallthroughs can't transfer control into a case label with bindings. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' cannot transfer control to a case label that declares variables}} case (let a, let b): t = (b, a) } func test_label(x : Int) { Gronk: switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{enum case 'Bar' not found in type '(Int, Int)'}} break default: break } } // sr-176 enum Whatever { case Thing } func f0(values: [Whatever]) { switch value { // expected-error {{use of unresolved identifier 'value'}} case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>. break } }
apache-2.0
ce56bf0eaef2646b8862489a4f6269c0
25.538745
336
0.65267
3.410147
false
false
false
false
cplaverty/KeitaiWaniKani
AlliCrab/View/WebAddressBarView.swift
1
7175
// // WebAddressBarView.swift // AlliCrab // // Copyright © 2017 Chris Laverty. All rights reserved. // import os import UIKit import WebKit class WebAddressBarView: UIView { // MARK: - Properties private let contentView: UIView private let secureSiteIndicator: UIImageView private let addressLabel: UILabel private let refreshButton: UIButton private let progressView: UIProgressView private let lockImage = UIImage(named: "NavigationBarLock") private let stopLoadingImage = UIImage(named: "NavigationBarStopLoading") private let reloadImage = UIImage(named: "NavigationBarReload") private unowned let webView: WKWebView private var keyValueObservers: [NSKeyValueObservation]? // MARK: - Initialisers required init(frame: CGRect, forWebView webView: WKWebView) { self.webView = webView contentView = UIView(frame: frame) contentView.translatesAutoresizingMaskIntoConstraints = false secureSiteIndicator = UIImageView(image: lockImage) secureSiteIndicator.translatesAutoresizingMaskIntoConstraints = false addressLabel = UILabel() addressLabel.adjustsFontForContentSizeCategory = true addressLabel.font = UIFont.preferredFont(forTextStyle: .callout) addressLabel.translatesAutoresizingMaskIntoConstraints = false addressLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) refreshButton = UIButton(type: .custom) refreshButton.translatesAutoresizingMaskIntoConstraints = false progressView = UIProgressView(progressViewStyle: .default) progressView.translatesAutoresizingMaskIntoConstraints = false progressView.trackTintColor = .clear progressView.progress = 0.0 progressView.alpha = 0.0 super.init(frame: frame) self.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.layoutMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) contentView.backgroundColor = UIColor(white: 0.8, alpha: 0.5) contentView.clipsToBounds = true contentView.layer.cornerRadius = 8 contentView.isOpaque = false refreshButton.addTarget(self, action: #selector(stopOrRefreshWebView(_:)), for: .touchUpInside) keyValueObservers = registerObservers(webView) addSubview(contentView) contentView.addSubview(secureSiteIndicator) contentView.addSubview(addressLabel) contentView.addSubview(refreshButton) contentView.addSubview(progressView) NSLayoutConstraint.activate([ contentView.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), contentView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor), contentView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor), secureSiteIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), refreshButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), addressLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), addressLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor) ]) if #available(iOS 11, *) { addressLabel.topAnchor.constraint(greaterThanOrEqualTo: contentView.layoutMarginsGuide.topAnchor).isActive = true contentView.layoutMarginsGuide.bottomAnchor.constraint(greaterThanOrEqualTo: addressLabel.bottomAnchor).isActive = true } else { addressLabel.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor).isActive = true contentView.bottomAnchor.constraint(greaterThanOrEqualTo: addressLabel.bottomAnchor).isActive = true } let views: [String: Any] = [ "secureSiteIndicator": secureSiteIndicator, "addressLabel": addressLabel, "refreshButton": refreshButton ] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=8)-[secureSiteIndicator]-[addressLabel]-(>=8)-[refreshButton]-|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate([ progressView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), progressView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), progressView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Update UI private func registerObservers(_ webView: WKWebView) -> [NSKeyValueObservation] { let keyValueObservers = [ webView.observe(\.hasOnlySecureContent, options: [.initial]) { [weak self] webView, _ in self?.secureSiteIndicator.isHidden = !webView.hasOnlySecureContent }, webView.observe(\.url, options: [.initial]) { [weak self] webView, _ in guard let self = self else { return } self.addressLabel.text = self.host(for: webView.url) }, webView.observe(\.estimatedProgress, options: [.initial]) { [weak self] webView, _ in guard let self = self else { return } let animated = webView.isLoading && self.progressView.progress < Float(webView.estimatedProgress) self.progressView.setProgress(Float(webView.estimatedProgress), animated: animated) }, webView.observe(\.isLoading, options: [.initial]) { [weak self] webView, _ in guard let self = self else { return } if webView.isLoading { self.progressView.alpha = 1.0 self.refreshButton.setImage(self.stopLoadingImage, for: .normal) } else { UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn], animations: { self.progressView.alpha = 0.0 }) self.refreshButton.setImage(self.reloadImage, for: .normal) } } ] return keyValueObservers } @objc func stopOrRefreshWebView(_ sender: UIButton) { if webView.isLoading { webView.stopLoading() } else { webView.reload() } } private let hostPrefixesToStrip = ["m.", "www."] private func host(for url: URL?) -> String? { guard let host = url?.host?.lowercased() else { return nil } for prefix in hostPrefixesToStrip { if host.hasPrefix(prefix) { return String(host.dropFirst(prefix.count)) } } return host } }
mit
c5053678cbc4745e934948a30b0c7445
40.953216
200
0.642041
5.734612
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/AssistantV1/Models/MessageResponse.swift
1
2780
/** * Copyright IBM Corporation 2018 * * 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 /** A response from the Watson Assistant service. */ public struct MessageResponse: Decodable { /// The user input from the request. public var input: MessageInput? /// An array of intents recognized in the user input, sorted in descending order of confidence. public var intents: [RuntimeIntent] /// An array of entities identified in the user input. public var entities: [RuntimeEntity] /// Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. public var alternateIntents: Bool? /// State information for the conversation. public var context: Context /// Output from the dialog, including the response to the user, the nodes that were triggered, and log messages. public var output: OutputData /// Additional properties associated with this model. public var additionalProperties: [String: JSON] // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case input = "input" case intents = "intents" case entities = "entities" case alternateIntents = "alternate_intents" case context = "context" case output = "output" static let allValues = [input, intents, entities, alternateIntents, context, output] } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) input = try container.decodeIfPresent(MessageInput.self, forKey: .input) intents = try container.decode([RuntimeIntent].self, forKey: .intents) entities = try container.decode([RuntimeEntity].self, forKey: .entities) alternateIntents = try container.decodeIfPresent(Bool.self, forKey: .alternateIntents) context = try container.decode(Context.self, forKey: .context) output = try container.decode(OutputData.self, forKey: .output) let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self) additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues) } }
mit
3125b495d1f64417777f7708b5c5ffca
41.121212
116
0.715108
4.695946
false
false
false
false
zcfsmile/Swifter
BasicSyntax/024类型转换/024TypeCasting.playground/Contents.swift
1
3386
//: Playground - noun: a place where people can play import UIKit //: 类型转换 //: 类型转换 可以判断实例的类型,也可以将实例看做是其父类或者子类的实例。 //: is as class MediaItem { var name: String init(name: String) { self.name = name } } class Movie: MediaItem { var director: String init(name: String, director: String) { self.director = director super.init(name: name) } } class Song: MediaItem { var artist: String init(name: String, artist: String) { self.artist = artist super.init(name: name) } } let library = [ Movie(name: "Casablanca", director: "Michael Curtiz"), Song(name: "Blue Suede Shoes", artist: "Elvis Presley"), Movie(name: "Citizen Kane", director: "Orson Welles"), Song(name: "The One And Only", artist: "Chesney Hawkes"), Song(name: "Never Gonna Give You Up", artist: "Rick Astley") ] type(of: library) // [MediaItem] //: 检查类型 var movieCount = 0 var songCount = 0 for item in library { if item is Movie { movieCount += 1 } else if item is Song { songCount += 1 } } print("Media librery contains \(movieCount) movies and \(songCount) songs") //: 向下转型 //: 某类型的一个常量或变量可能在幕后实际上属于一个子类。当确定是这种情况时,你可以尝试向下转到它的子类型,用类型转换操作符(as? 或 as!)。 for item in library { if let movie = item as? Movie { print("Movie: \(movie.name), dir. \(movie.director)") } else if let song = item as? Song { print("Song: \(song.name), by \(song.artist)") } } //: Any、AnyObject //: Swift 为不确定类型提供了两种特殊的类型别名: // Any 可以表示任何类型,包括函数类型。 // AnyObject 可以表示任何类类型的实例。 var things = [Any]() things.append(0) things.append(0.0) things.append(42) things.append(3.14) things.append("Hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) things.append({ (name: String) -> String in "Hello, \(name)" }) for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of \(someDouble)") case is Double: print("some other double value that I don't want to print") case let someString as String: print("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): print("an (x, y) point at \(x), \(y)") case let movie as Movie: print("a movie called '\(movie.name)', dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("something else") } } //: Any类型可以表示所有类型的值,包括可选类型。Swift 会在你用Any类型来表示一个可选值的时候,给你一个警告。如果你确实想使用Any类型来承载可选值,你可以使用as操作符显式转换为Any let optionalNumber: Int? = 3 things.append(optionalNumber) // 警告 things.append(optionalNumber as Any)
mit
6f7094eab034ac79f65176d588191a7a
23.099174
99
0.636831
3.340206
false
false
false
false
megabitsenmzq/PomoNow-iOS
PomoNow/PomoNow/TagSelectView.swift
1
2650
// // TagSelectViewController.swift // PomoNow // // Created by Megabits on 15/10/18. // Copyright © 2015年 ScrewBox. All rights reserved. // import UIKit var taskString = "" var selectTag = 0 class TagSelectView: UIView, UITextFieldDelegate { var select:[Bool] = [true,false,false,false,false] @IBOutlet weak var task: UITextField! { didSet{ task.delegate = self } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() //释放键盘 return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { NotificationCenter.default.removeObserver(self) return true } func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { NotificationCenter.default.addObserver(self, selector: #selector(TagSelectView.didChange(_:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil) //为文字改变添加监视 return true } @objc func didChange(_ notification: Notification) { taskString = task.text ?? "" } @IBOutlet weak var tagA: UIView! @IBOutlet weak var tagB: UIView! @IBOutlet weak var tagC: UIView! @IBOutlet weak var tagD: UIView! @IBOutlet weak var tagE: UIView! @IBAction func Select(_ sender: UITapGestureRecognizer) { selectedTag = sender.view!.tag } var selectedTag = 0{ didSet { for i in 0...4 { select[i] = false } select[selectedTag] = true updateUI() selectTag = selectedTag } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! taskString = "" selectTag = 0 } override init(frame: CGRect) { super.init(frame: frame) } override func awakeFromNib() { let time: TimeInterval = 0.1 let delay = DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delay) { self.task.becomeFirstResponder() } } class func instanceFromNib() -> UIView { return UINib(nibName: "TagSelectView", bundle: nil).instantiate(withOwner: self, options: nil)[0] as! UIView } func updateUI() { //单选控制器状态刷新 tagA.isHidden = !select[0] tagB.isHidden = !select[1] tagC.isHidden = !select[2] tagD.isHidden = !select[3] tagE.isHidden = !select[4] } }
mit
d16d99f073bb2a9f79f7980d44fbeb75
26.4
116
0.593546
4.37479
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/RDS/RDS_Error.swift
1
30876
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for RDS public struct RDSErrorType: AWSErrorType { enum Code: String { case authorizationAlreadyExistsFault = "AuthorizationAlreadyExists" case authorizationNotFoundFault = "AuthorizationNotFound" case authorizationQuotaExceededFault = "AuthorizationQuotaExceeded" case backupPolicyNotFoundFault = "BackupPolicyNotFoundFault" case certificateNotFoundFault = "CertificateNotFound" case customAvailabilityZoneAlreadyExistsFault = "CustomAvailabilityZoneAlreadyExists" case customAvailabilityZoneNotFoundFault = "CustomAvailabilityZoneNotFound" case customAvailabilityZoneQuotaExceededFault = "CustomAvailabilityZoneQuotaExceeded" case dBClusterAlreadyExistsFault = "DBClusterAlreadyExistsFault" case dBClusterBacktrackNotFoundFault = "DBClusterBacktrackNotFoundFault" case dBClusterEndpointAlreadyExistsFault = "DBClusterEndpointAlreadyExistsFault" case dBClusterEndpointNotFoundFault = "DBClusterEndpointNotFoundFault" case dBClusterEndpointQuotaExceededFault = "DBClusterEndpointQuotaExceededFault" case dBClusterNotFoundFault = "DBClusterNotFoundFault" case dBClusterParameterGroupNotFoundFault = "DBClusterParameterGroupNotFound" case dBClusterQuotaExceededFault = "DBClusterQuotaExceededFault" case dBClusterRoleAlreadyExistsFault = "DBClusterRoleAlreadyExists" case dBClusterRoleNotFoundFault = "DBClusterRoleNotFound" case dBClusterRoleQuotaExceededFault = "DBClusterRoleQuotaExceeded" case dBClusterSnapshotAlreadyExistsFault = "DBClusterSnapshotAlreadyExistsFault" case dBClusterSnapshotNotFoundFault = "DBClusterSnapshotNotFoundFault" case dBInstanceAlreadyExistsFault = "DBInstanceAlreadyExists" case dBInstanceAutomatedBackupNotFoundFault = "DBInstanceAutomatedBackupNotFound" case dBInstanceAutomatedBackupQuotaExceededFault = "DBInstanceAutomatedBackupQuotaExceeded" case dBInstanceNotFoundFault = "DBInstanceNotFound" case dBInstanceRoleAlreadyExistsFault = "DBInstanceRoleAlreadyExists" case dBInstanceRoleNotFoundFault = "DBInstanceRoleNotFound" case dBInstanceRoleQuotaExceededFault = "DBInstanceRoleQuotaExceeded" case dBLogFileNotFoundFault = "DBLogFileNotFoundFault" case dBParameterGroupAlreadyExistsFault = "DBParameterGroupAlreadyExists" case dBParameterGroupNotFoundFault = "DBParameterGroupNotFound" case dBParameterGroupQuotaExceededFault = "DBParameterGroupQuotaExceeded" case dBProxyAlreadyExistsFault = "DBProxyTargetExistsFault" case dBProxyNotFoundFault = "DBProxyNotFoundFault" case dBProxyQuotaExceededFault = "DBProxyQuotaExceededFault" case dBProxyTargetAlreadyRegisteredFault = "DBProxyTargetAlreadyRegisteredFault" case dBProxyTargetGroupNotFoundFault = "DBProxyTargetGroupNotFoundFault" case dBProxyTargetNotFoundFault = "DBProxyTargetNotFoundFault" case dBSecurityGroupAlreadyExistsFault = "DBSecurityGroupAlreadyExists" case dBSecurityGroupNotFoundFault = "DBSecurityGroupNotFound" case dBSecurityGroupNotSupportedFault = "DBSecurityGroupNotSupported" case dBSecurityGroupQuotaExceededFault = "QuotaExceeded.DBSecurityGroup" case dBSnapshotAlreadyExistsFault = "DBSnapshotAlreadyExists" case dBSnapshotNotFoundFault = "DBSnapshotNotFound" case dBSubnetGroupAlreadyExistsFault = "DBSubnetGroupAlreadyExists" case dBSubnetGroupDoesNotCoverEnoughAZs = "DBSubnetGroupDoesNotCoverEnoughAZs" case dBSubnetGroupNotAllowedFault = "DBSubnetGroupNotAllowedFault" case dBSubnetGroupNotFoundFault = "DBSubnetGroupNotFoundFault" case dBSubnetGroupQuotaExceededFault = "DBSubnetGroupQuotaExceeded" case dBSubnetQuotaExceededFault = "DBSubnetQuotaExceededFault" case dBUpgradeDependencyFailureFault = "DBUpgradeDependencyFailure" case domainNotFoundFault = "DomainNotFoundFault" case eventSubscriptionQuotaExceededFault = "EventSubscriptionQuotaExceeded" case exportTaskAlreadyExistsFault = "ExportTaskAlreadyExists" case exportTaskNotFoundFault = "ExportTaskNotFound" case globalClusterAlreadyExistsFault = "GlobalClusterAlreadyExistsFault" case globalClusterNotFoundFault = "GlobalClusterNotFoundFault" case globalClusterQuotaExceededFault = "GlobalClusterQuotaExceededFault" case iamRoleMissingPermissionsFault = "IamRoleMissingPermissions" case iamRoleNotFoundFault = "IamRoleNotFound" case installationMediaAlreadyExistsFault = "InstallationMediaAlreadyExists" case installationMediaNotFoundFault = "InstallationMediaNotFound" case instanceQuotaExceededFault = "InstanceQuotaExceeded" case insufficientAvailableIPsInSubnetFault = "InsufficientAvailableIPsInSubnetFault" case insufficientDBClusterCapacityFault = "InsufficientDBClusterCapacityFault" case insufficientDBInstanceCapacityFault = "InsufficientDBInstanceCapacity" case insufficientStorageClusterCapacityFault = "InsufficientStorageClusterCapacity" case invalidDBClusterCapacityFault = "InvalidDBClusterCapacityFault" case invalidDBClusterEndpointStateFault = "InvalidDBClusterEndpointStateFault" case invalidDBClusterSnapshotStateFault = "InvalidDBClusterSnapshotStateFault" case invalidDBClusterStateFault = "InvalidDBClusterStateFault" case invalidDBInstanceAutomatedBackupStateFault = "InvalidDBInstanceAutomatedBackupState" case invalidDBInstanceStateFault = "InvalidDBInstanceState" case invalidDBParameterGroupStateFault = "InvalidDBParameterGroupState" case invalidDBProxyStateFault = "InvalidDBProxyStateFault" case invalidDBSecurityGroupStateFault = "InvalidDBSecurityGroupState" case invalidDBSnapshotStateFault = "InvalidDBSnapshotState" case invalidDBSubnetGroupFault = "InvalidDBSubnetGroupFault" case invalidDBSubnetGroupStateFault = "InvalidDBSubnetGroupStateFault" case invalidDBSubnetStateFault = "InvalidDBSubnetStateFault" case invalidEventSubscriptionStateFault = "InvalidEventSubscriptionState" case invalidExportOnlyFault = "InvalidExportOnly" case invalidExportSourceStateFault = "InvalidExportSourceState" case invalidExportTaskStateFault = "InvalidExportTaskStateFault" case invalidGlobalClusterStateFault = "InvalidGlobalClusterStateFault" case invalidOptionGroupStateFault = "InvalidOptionGroupStateFault" case invalidRestoreFault = "InvalidRestoreFault" case invalidS3BucketFault = "InvalidS3BucketFault" case invalidSubnet = "InvalidSubnet" case invalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault" case kMSKeyNotAccessibleFault = "KMSKeyNotAccessibleFault" case optionGroupAlreadyExistsFault = "OptionGroupAlreadyExistsFault" case optionGroupNotFoundFault = "OptionGroupNotFoundFault" case optionGroupQuotaExceededFault = "OptionGroupQuotaExceededFault" case pointInTimeRestoreNotEnabledFault = "PointInTimeRestoreNotEnabled" case provisionedIopsNotAvailableInAZFault = "ProvisionedIopsNotAvailableInAZFault" case reservedDBInstanceAlreadyExistsFault = "ReservedDBInstanceAlreadyExists" case reservedDBInstanceNotFoundFault = "ReservedDBInstanceNotFound" case reservedDBInstanceQuotaExceededFault = "ReservedDBInstanceQuotaExceeded" case reservedDBInstancesOfferingNotFoundFault = "ReservedDBInstancesOfferingNotFound" case resourceNotFoundFault = "ResourceNotFoundFault" case sNSInvalidTopicFault = "SNSInvalidTopic" case sNSNoAuthorizationFault = "SNSNoAuthorization" case sNSTopicArnNotFoundFault = "SNSTopicArnNotFound" case sharedSnapshotQuotaExceededFault = "SharedSnapshotQuotaExceeded" case snapshotQuotaExceededFault = "SnapshotQuotaExceeded" case sourceNotFoundFault = "SourceNotFound" case storageQuotaExceededFault = "StorageQuotaExceeded" case storageTypeNotSupportedFault = "StorageTypeNotSupported" case subnetAlreadyInUse = "SubnetAlreadyInUse" case subscriptionAlreadyExistFault = "SubscriptionAlreadyExist" case subscriptionCategoryNotFoundFault = "SubscriptionCategoryNotFound" case subscriptionNotFoundFault = "SubscriptionNotFound" } private let error: Code public let context: AWSErrorContext? /// initialize RDS public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The specified CIDR IP range or Amazon EC2 security group is already authorized for the specified DB security group. public static var authorizationAlreadyExistsFault: Self { .init(.authorizationAlreadyExistsFault) } /// The specified CIDR IP range or Amazon EC2 security group might not be authorized for the specified DB security group. Or, RDS might not be authorized to perform necessary actions using IAM on your behalf. public static var authorizationNotFoundFault: Self { .init(.authorizationNotFoundFault) } /// The DB security group authorization quota has been reached. public static var authorizationQuotaExceededFault: Self { .init(.authorizationQuotaExceededFault) } public static var backupPolicyNotFoundFault: Self { .init(.backupPolicyNotFoundFault) } /// CertificateIdentifier doesn't refer to an existing certificate. public static var certificateNotFoundFault: Self { .init(.certificateNotFoundFault) } /// CustomAvailabilityZoneName is already used by an existing custom Availability Zone. public static var customAvailabilityZoneAlreadyExistsFault: Self { .init(.customAvailabilityZoneAlreadyExistsFault) } /// CustomAvailabilityZoneId doesn't refer to an existing custom Availability Zone identifier. public static var customAvailabilityZoneNotFoundFault: Self { .init(.customAvailabilityZoneNotFoundFault) } /// You have exceeded the maximum number of custom Availability Zones. public static var customAvailabilityZoneQuotaExceededFault: Self { .init(.customAvailabilityZoneQuotaExceededFault) } /// The user already has a DB cluster with the given identifier. public static var dBClusterAlreadyExistsFault: Self { .init(.dBClusterAlreadyExistsFault) } /// BacktrackIdentifier doesn't refer to an existing backtrack. public static var dBClusterBacktrackNotFoundFault: Self { .init(.dBClusterBacktrackNotFoundFault) } /// The specified custom endpoint can't be created because it already exists. public static var dBClusterEndpointAlreadyExistsFault: Self { .init(.dBClusterEndpointAlreadyExistsFault) } /// The specified custom endpoint doesn't exist. public static var dBClusterEndpointNotFoundFault: Self { .init(.dBClusterEndpointNotFoundFault) } /// The cluster already has the maximum number of custom endpoints. public static var dBClusterEndpointQuotaExceededFault: Self { .init(.dBClusterEndpointQuotaExceededFault) } /// DBClusterIdentifier doesn't refer to an existing DB cluster. public static var dBClusterNotFoundFault: Self { .init(.dBClusterNotFoundFault) } /// DBClusterParameterGroupName doesn't refer to an existing DB cluster parameter group. public static var dBClusterParameterGroupNotFoundFault: Self { .init(.dBClusterParameterGroupNotFoundFault) } /// The user attempted to create a new DB cluster and the user has already reached the maximum allowed DB cluster quota. public static var dBClusterQuotaExceededFault: Self { .init(.dBClusterQuotaExceededFault) } /// The specified IAM role Amazon Resource Name (ARN) is already associated with the specified DB cluster. public static var dBClusterRoleAlreadyExistsFault: Self { .init(.dBClusterRoleAlreadyExistsFault) } /// The specified IAM role Amazon Resource Name (ARN) isn't associated with the specified DB cluster. public static var dBClusterRoleNotFoundFault: Self { .init(.dBClusterRoleNotFoundFault) } /// You have exceeded the maximum number of IAM roles that can be associated with the specified DB cluster. public static var dBClusterRoleQuotaExceededFault: Self { .init(.dBClusterRoleQuotaExceededFault) } /// The user already has a DB cluster snapshot with the given identifier. public static var dBClusterSnapshotAlreadyExistsFault: Self { .init(.dBClusterSnapshotAlreadyExistsFault) } /// DBClusterSnapshotIdentifier doesn't refer to an existing DB cluster snapshot. public static var dBClusterSnapshotNotFoundFault: Self { .init(.dBClusterSnapshotNotFoundFault) } /// The user already has a DB instance with the given identifier. public static var dBInstanceAlreadyExistsFault: Self { .init(.dBInstanceAlreadyExistsFault) } /// No automated backup for this DB instance was found. public static var dBInstanceAutomatedBackupNotFoundFault: Self { .init(.dBInstanceAutomatedBackupNotFoundFault) } /// The quota for retained automated backups was exceeded. This prevents you from retaining any additional automated backups. The retained automated backups quota is the same as your DB Instance quota. public static var dBInstanceAutomatedBackupQuotaExceededFault: Self { .init(.dBInstanceAutomatedBackupQuotaExceededFault) } /// DBInstanceIdentifier doesn't refer to an existing DB instance. public static var dBInstanceNotFoundFault: Self { .init(.dBInstanceNotFoundFault) } /// The specified RoleArn or FeatureName value is already associated with the DB instance. public static var dBInstanceRoleAlreadyExistsFault: Self { .init(.dBInstanceRoleAlreadyExistsFault) } /// The specified RoleArn value doesn't match the specified feature for the DB instance. public static var dBInstanceRoleNotFoundFault: Self { .init(.dBInstanceRoleNotFoundFault) } /// You can't associate any more AWS Identity and Access Management (IAM) roles with the DB instance because the quota has been reached. public static var dBInstanceRoleQuotaExceededFault: Self { .init(.dBInstanceRoleQuotaExceededFault) } /// LogFileName doesn't refer to an existing DB log file. public static var dBLogFileNotFoundFault: Self { .init(.dBLogFileNotFoundFault) } /// A DB parameter group with the same name exists. public static var dBParameterGroupAlreadyExistsFault: Self { .init(.dBParameterGroupAlreadyExistsFault) } /// DBParameterGroupName doesn't refer to an existing DB parameter group. public static var dBParameterGroupNotFoundFault: Self { .init(.dBParameterGroupNotFoundFault) } /// The request would result in the user exceeding the allowed number of DB parameter groups. public static var dBParameterGroupQuotaExceededFault: Self { .init(.dBParameterGroupQuotaExceededFault) } /// The specified proxy name must be unique for all proxies owned by your AWS account in the specified AWS Region. public static var dBProxyAlreadyExistsFault: Self { .init(.dBProxyAlreadyExistsFault) } /// The specified proxy name doesn't correspond to a proxy owned by your AWS accoutn in the specified AWS Region. public static var dBProxyNotFoundFault: Self { .init(.dBProxyNotFoundFault) } /// Your AWS account already has the maximum number of proxies in the specified AWS Region. public static var dBProxyQuotaExceededFault: Self { .init(.dBProxyQuotaExceededFault) } /// The proxy is already associated with the specified RDS DB instance or Aurora DB cluster. public static var dBProxyTargetAlreadyRegisteredFault: Self { .init(.dBProxyTargetAlreadyRegisteredFault) } /// The specified target group isn't available for a proxy owned by your AWS account in the specified AWS Region. public static var dBProxyTargetGroupNotFoundFault: Self { .init(.dBProxyTargetGroupNotFoundFault) } /// The specified RDS DB instance or Aurora DB cluster isn't available for a proxy owned by your AWS account in the specified AWS Region. public static var dBProxyTargetNotFoundFault: Self { .init(.dBProxyTargetNotFoundFault) } /// A DB security group with the name specified in DBSecurityGroupName already exists. public static var dBSecurityGroupAlreadyExistsFault: Self { .init(.dBSecurityGroupAlreadyExistsFault) } /// DBSecurityGroupName doesn't refer to an existing DB security group. public static var dBSecurityGroupNotFoundFault: Self { .init(.dBSecurityGroupNotFoundFault) } /// A DB security group isn't allowed for this action. public static var dBSecurityGroupNotSupportedFault: Self { .init(.dBSecurityGroupNotSupportedFault) } /// The request would result in the user exceeding the allowed number of DB security groups. public static var dBSecurityGroupQuotaExceededFault: Self { .init(.dBSecurityGroupQuotaExceededFault) } /// DBSnapshotIdentifier is already used by an existing snapshot. public static var dBSnapshotAlreadyExistsFault: Self { .init(.dBSnapshotAlreadyExistsFault) } /// DBSnapshotIdentifier doesn't refer to an existing DB snapshot. public static var dBSnapshotNotFoundFault: Self { .init(.dBSnapshotNotFoundFault) } /// DBSubnetGroupName is already used by an existing DB subnet group. public static var dBSubnetGroupAlreadyExistsFault: Self { .init(.dBSubnetGroupAlreadyExistsFault) } /// Subnets in the DB subnet group should cover at least two Availability Zones unless there is only one Availability Zone. public static var dBSubnetGroupDoesNotCoverEnoughAZs: Self { .init(.dBSubnetGroupDoesNotCoverEnoughAZs) } /// The DBSubnetGroup shouldn't be specified while creating read replicas that lie in the same region as the source instance. public static var dBSubnetGroupNotAllowedFault: Self { .init(.dBSubnetGroupNotAllowedFault) } /// DBSubnetGroupName doesn't refer to an existing DB subnet group. public static var dBSubnetGroupNotFoundFault: Self { .init(.dBSubnetGroupNotFoundFault) } /// The request would result in the user exceeding the allowed number of DB subnet groups. public static var dBSubnetGroupQuotaExceededFault: Self { .init(.dBSubnetGroupQuotaExceededFault) } /// The request would result in the user exceeding the allowed number of subnets in a DB subnet groups. public static var dBSubnetQuotaExceededFault: Self { .init(.dBSubnetQuotaExceededFault) } /// The DB upgrade failed because a resource the DB depends on can't be modified. public static var dBUpgradeDependencyFailureFault: Self { .init(.dBUpgradeDependencyFailureFault) } /// Domain doesn't refer to an existing Active Directory domain. public static var domainNotFoundFault: Self { .init(.domainNotFoundFault) } /// You have reached the maximum number of event subscriptions. public static var eventSubscriptionQuotaExceededFault: Self { .init(.eventSubscriptionQuotaExceededFault) } /// You can't start an export task that's already running. public static var exportTaskAlreadyExistsFault: Self { .init(.exportTaskAlreadyExistsFault) } /// The export task doesn't exist. public static var exportTaskNotFoundFault: Self { .init(.exportTaskNotFoundFault) } public static var globalClusterAlreadyExistsFault: Self { .init(.globalClusterAlreadyExistsFault) } public static var globalClusterNotFoundFault: Self { .init(.globalClusterNotFoundFault) } public static var globalClusterQuotaExceededFault: Self { .init(.globalClusterQuotaExceededFault) } /// The IAM role requires additional permissions to export to an Amazon S3 bucket. public static var iamRoleMissingPermissionsFault: Self { .init(.iamRoleMissingPermissionsFault) } /// The IAM role is missing for exporting to an Amazon S3 bucket. public static var iamRoleNotFoundFault: Self { .init(.iamRoleNotFoundFault) } /// The specified installation medium has already been imported. public static var installationMediaAlreadyExistsFault: Self { .init(.installationMediaAlreadyExistsFault) } /// InstallationMediaID doesn't refer to an existing installation medium. public static var installationMediaNotFoundFault: Self { .init(.installationMediaNotFoundFault) } /// The request would result in the user exceeding the allowed number of DB instances. public static var instanceQuotaExceededFault: Self { .init(.instanceQuotaExceededFault) } /// The requested operation can't be performed because there aren't enough available IP addresses in the proxy's subnets. Add more CIDR blocks to the VPC or remove IP address that aren't required from the subnets. public static var insufficientAvailableIPsInSubnetFault: Self { .init(.insufficientAvailableIPsInSubnetFault) } /// The DB cluster doesn't have enough capacity for the current operation. public static var insufficientDBClusterCapacityFault: Self { .init(.insufficientDBClusterCapacityFault) } /// The specified DB instance class isn't available in the specified Availability Zone. public static var insufficientDBInstanceCapacityFault: Self { .init(.insufficientDBInstanceCapacityFault) } /// There is insufficient storage available for the current action. You might be able to resolve this error by updating your subnet group to use different Availability Zones that have more storage available. public static var insufficientStorageClusterCapacityFault: Self { .init(.insufficientStorageClusterCapacityFault) } /// Capacity isn't a valid Aurora Serverless DB cluster capacity. Valid capacity values are 2, 4, 8, 16, 32, 64, 128, and 256. public static var invalidDBClusterCapacityFault: Self { .init(.invalidDBClusterCapacityFault) } /// The requested operation can't be performed on the endpoint while the endpoint is in this state. public static var invalidDBClusterEndpointStateFault: Self { .init(.invalidDBClusterEndpointStateFault) } /// The supplied value isn't a valid DB cluster snapshot state. public static var invalidDBClusterSnapshotStateFault: Self { .init(.invalidDBClusterSnapshotStateFault) } /// The requested operation can't be performed while the cluster is in this state. public static var invalidDBClusterStateFault: Self { .init(.invalidDBClusterStateFault) } /// The automated backup is in an invalid state. For example, this automated backup is associated with an active instance. public static var invalidDBInstanceAutomatedBackupStateFault: Self { .init(.invalidDBInstanceAutomatedBackupStateFault) } /// The DB instance isn't in a valid state. public static var invalidDBInstanceStateFault: Self { .init(.invalidDBInstanceStateFault) } /// The DB parameter group is in use or is in an invalid state. If you are attempting to delete the parameter group, you can't delete it when the parameter group is in this state. public static var invalidDBParameterGroupStateFault: Self { .init(.invalidDBParameterGroupStateFault) } /// The requested operation can't be performed while the proxy is in this state. public static var invalidDBProxyStateFault: Self { .init(.invalidDBProxyStateFault) } /// The state of the DB security group doesn't allow deletion. public static var invalidDBSecurityGroupStateFault: Self { .init(.invalidDBSecurityGroupStateFault) } /// The state of the DB snapshot doesn't allow deletion. public static var invalidDBSnapshotStateFault: Self { .init(.invalidDBSnapshotStateFault) } /// The DBSubnetGroup doesn't belong to the same VPC as that of an existing cross-region read replica of the same source instance. public static var invalidDBSubnetGroupFault: Self { .init(.invalidDBSubnetGroupFault) } /// The DB subnet group cannot be deleted because it's in use. public static var invalidDBSubnetGroupStateFault: Self { .init(.invalidDBSubnetGroupStateFault) } /// The DB subnet isn't in the available state. public static var invalidDBSubnetStateFault: Self { .init(.invalidDBSubnetStateFault) } /// This error can occur if someone else is modifying a subscription. You should retry the action. public static var invalidEventSubscriptionStateFault: Self { .init(.invalidEventSubscriptionStateFault) } /// The export is invalid for exporting to an Amazon S3 bucket. public static var invalidExportOnlyFault: Self { .init(.invalidExportOnlyFault) } /// The state of the export snapshot is invalid for exporting to an Amazon S3 bucket. public static var invalidExportSourceStateFault: Self { .init(.invalidExportSourceStateFault) } /// You can't cancel an export task that has completed. public static var invalidExportTaskStateFault: Self { .init(.invalidExportTaskStateFault) } public static var invalidGlobalClusterStateFault: Self { .init(.invalidGlobalClusterStateFault) } /// The option group isn't in the available state. public static var invalidOptionGroupStateFault: Self { .init(.invalidOptionGroupStateFault) } /// Cannot restore from VPC backup to non-VPC DB instance. public static var invalidRestoreFault: Self { .init(.invalidRestoreFault) } /// The specified Amazon S3 bucket name can't be found or Amazon RDS isn't authorized to access the specified Amazon S3 bucket. Verify the SourceS3BucketName and S3IngestionRoleArn values and try again. public static var invalidS3BucketFault: Self { .init(.invalidS3BucketFault) } /// The requested subnet is invalid, or multiple subnets were requested that are not all in a common VPC. public static var invalidSubnet: Self { .init(.invalidSubnet) } /// The DB subnet group doesn't cover all Availability Zones after it's created because of users' change. public static var invalidVPCNetworkStateFault: Self { .init(.invalidVPCNetworkStateFault) } /// An error occurred accessing an AWS KMS key. public static var kMSKeyNotAccessibleFault: Self { .init(.kMSKeyNotAccessibleFault) } /// The option group you are trying to create already exists. public static var optionGroupAlreadyExistsFault: Self { .init(.optionGroupAlreadyExistsFault) } /// The specified option group could not be found. public static var optionGroupNotFoundFault: Self { .init(.optionGroupNotFoundFault) } /// The quota of 20 option groups was exceeded for this AWS account. public static var optionGroupQuotaExceededFault: Self { .init(.optionGroupQuotaExceededFault) } /// SourceDBInstanceIdentifier refers to a DB instance with BackupRetentionPeriod equal to 0. public static var pointInTimeRestoreNotEnabledFault: Self { .init(.pointInTimeRestoreNotEnabledFault) } /// Provisioned IOPS not available in the specified Availability Zone. public static var provisionedIopsNotAvailableInAZFault: Self { .init(.provisionedIopsNotAvailableInAZFault) } /// User already has a reservation with the given identifier. public static var reservedDBInstanceAlreadyExistsFault: Self { .init(.reservedDBInstanceAlreadyExistsFault) } /// The specified reserved DB Instance not found. public static var reservedDBInstanceNotFoundFault: Self { .init(.reservedDBInstanceNotFoundFault) } /// Request would exceed the user's DB Instance quota. public static var reservedDBInstanceQuotaExceededFault: Self { .init(.reservedDBInstanceQuotaExceededFault) } /// Specified offering does not exist. public static var reservedDBInstancesOfferingNotFoundFault: Self { .init(.reservedDBInstancesOfferingNotFoundFault) } /// The specified resource ID was not found. public static var resourceNotFoundFault: Self { .init(.resourceNotFoundFault) } /// SNS has responded that there is a problem with the SND topic specified. public static var sNSInvalidTopicFault: Self { .init(.sNSInvalidTopicFault) } /// You do not have permission to publish to the SNS topic ARN. public static var sNSNoAuthorizationFault: Self { .init(.sNSNoAuthorizationFault) } /// The SNS topic ARN does not exist. public static var sNSTopicArnNotFoundFault: Self { .init(.sNSTopicArnNotFoundFault) } /// You have exceeded the maximum number of accounts that you can share a manual DB snapshot with. public static var sharedSnapshotQuotaExceededFault: Self { .init(.sharedSnapshotQuotaExceededFault) } /// The request would result in the user exceeding the allowed number of DB snapshots. public static var snapshotQuotaExceededFault: Self { .init(.snapshotQuotaExceededFault) } /// The requested source could not be found. public static var sourceNotFoundFault: Self { .init(.sourceNotFoundFault) } /// The request would result in the user exceeding the allowed amount of storage available across all DB instances. public static var storageQuotaExceededFault: Self { .init(.storageQuotaExceededFault) } /// Storage of the StorageType specified can't be associated with the DB instance. public static var storageTypeNotSupportedFault: Self { .init(.storageTypeNotSupportedFault) } /// The DB subnet is already in use in the Availability Zone. public static var subnetAlreadyInUse: Self { .init(.subnetAlreadyInUse) } /// The supplied subscription name already exists. public static var subscriptionAlreadyExistFault: Self { .init(.subscriptionAlreadyExistFault) } /// The supplied category does not exist. public static var subscriptionCategoryNotFoundFault: Self { .init(.subscriptionCategoryNotFoundFault) } /// The subscription name does not exist. public static var subscriptionNotFoundFault: Self { .init(.subscriptionNotFoundFault) } } extension RDSErrorType: Equatable { public static func == (lhs: RDSErrorType, rhs: RDSErrorType) -> Bool { lhs.error == rhs.error } } extension RDSErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
ed26580ee9a8c20d3e0aa2d96a4c41e8
78.57732
217
0.775619
5.579328
false
false
false
false
xwu/swift
libswift/Sources/Optimizer/PassManager/PassUtils.swift
2
3444
//===--- PassUtils.swift - Utilities for optimzation passes ---------------===// // // 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 SIL import OptimizerBridging public typealias BridgedFunctionPassCtxt = OptimizerBridging.BridgedFunctionPassCtxt public typealias BridgedInstructionPassCtxt = OptimizerBridging.BridgedInstructionPassCtxt struct PassContext { fileprivate let passContext: BridgedPassContext var isSwift51RuntimeAvailable: Bool { PassContext_isSwift51RuntimeAvailable(passContext) != 0 } var aliasAnalysis: AliasAnalysis { let bridgedAA = PassContext_getAliasAnalysis(passContext) return AliasAnalysis(bridged: bridgedAA) } var calleeAnalysis: CalleeAnalysis { let bridgeCA = PassContext_getCalleeAnalysis(passContext) return CalleeAnalysis(bridged: bridgeCA) } func erase(instruction: Instruction) { if instruction is FullApplySite { PassContext_notifyChanges(passContext, callsChanged) } if instruction is TermInst { PassContext_notifyChanges(passContext, branchesChanged) } PassContext_notifyChanges(passContext, instructionsChanged) PassContext_eraseInstruction(passContext, instruction.bridged) } func setOperand(of instruction: Instruction, at index : Int, to value: Value) { if instruction is FullApplySite && index == ApplyOperands.calleeOperandIndex { PassContext_notifyChanges(passContext, callsChanged) } PassContext_notifyChanges(passContext, instructionsChanged) SILInstruction_setOperand(instruction.bridged, index, value.bridged) } } struct FunctionPass { let name: String let runFunction: (Function, PassContext) -> () public init(name: String, _ runFunction: @escaping (Function, PassContext) -> ()) { self.name = name self.runFunction = runFunction } func run(_ bridgedCtxt: BridgedFunctionPassCtxt) { let function = bridgedCtxt.function.function let context = PassContext(passContext: bridgedCtxt.passContext) runFunction(function, context) } } struct InstructionPass<InstType: Instruction> { let name: String let runFunction: (InstType, PassContext) -> () public init(name: String, _ runFunction: @escaping (InstType, PassContext) -> ()) { self.name = name self.runFunction = runFunction } func run(_ bridgedCtxt: BridgedInstructionPassCtxt) { let inst = bridgedCtxt.instruction.getAs(InstType.self) let context = PassContext(passContext: bridgedCtxt.passContext) runFunction(inst, context) } } extension StackList { init(_ context: PassContext) { self.init(context: context.passContext) } } extension Builder { init(at insPnt: Instruction, location: Location, _ context: PassContext) { self.init(insertionPoint: insPnt, location: location, passContext: context.passContext) } init(at insPnt: Instruction, _ context: PassContext) { self.init(insertionPoint: insPnt, location: insPnt.location, passContext: context.passContext) } }
apache-2.0
7baf5e1d034ae79741c9a92147539a52
29.210526
82
0.711963
4.666667
false
false
false
false
jozsef-vesza/CustomTransitionsDemo
CustomTransitionsDemo/Animation controllers/FlipAnimationController.swift
1
2599
// // FlipAnimationController.swift // CustomTransitionsDemo // // Created by Vesza Jozsef on 08/06/15. // Copyright (c) 2015 József Vesza. All rights reserved. // import UIKit class FlipAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var reverse = false func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 1. Setup let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let containerView = transitionContext.containerView() containerView.addSubview(toView) // 2. Add a perspective transform var transform = CATransform3DIdentity transform.m34 = -0.002 containerView.layer.sublayerTransform = transform // 3. Both views start from the same frame let initialFrame = transitionContext.initialFrameForViewController(fromVC) fromView.frame = initialFrame toView.frame = initialFrame // 4. Reverse? let factor = reverse ? 1.0 : -1.0 // 5. Hide `toView` by flipping it halfway round toView.layer.transform = yRotation(factor * -M_PI_2) // 6. Animate let duration = transitionDuration(transitionContext) UIView.animateKeyframesWithDuration( duration, delay: 0, options: .CalculationModeCubic, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: { // 7. Rotate `fromView` fromView.layer.transform = self.yRotation(factor * M_PI_2) }) UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { // 8. Rotate `toView` toView.layer.transform = self.yRotation(0.0) }) }, completion: { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } private func yRotation(angle: Double) -> CATransform3D { return CATransform3DMakeRotation(CGFloat(angle), 0.0, 1.0, 0.0) } }
mit
1bab79811dc8f76a30af33db736b7e3b
35.083333
104
0.622017
5.672489
false
false
false
false
naokits/my-programming-marathon
NCMB_iOSAppDemo/NCMB_iOSAppDemo/LoginViewController.swift
1
4810
// // LoginViewController.swift // NCMB_iOSAppDemo // // Created by Naoki Tsutsui on 2/11/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit import NCMB class LoginViewController: UIViewController { @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var mailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! // ------------------------------------------------------------------------ // MARK: - Lifecycle // ------------------------------------------------------------------------ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ------------------------------------------------------------------------ // MARK: - Navigation // ------------------------------------------------------------------------ // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } // ------------------------------------------------------------------------ // MARK: - Login or Signup // ------------------------------------------------------------------------ /// ログイン or 新規登録が成功した場合の処理 /// /// - parameter user: NCMBUserインスタンス /// - returns: None func successLoginOrSignupForUser(user: NCMBUser) { print("会員登録後の処理") // ACLを本人のみに設定 let acl = NCMBACL(user: NCMBUser.currentUser()) user.ACL = acl user.saveInBackgroundWithBlock({ (error: NSError!) -> Void in if error == nil { self.dismissViewControllerAnimated(true, completion: nil) } else { print("ACL設定の保存失敗: \(error)") } }) } // ------------------------------------------------------------------------ // MARK: - Login or Signup // ------------------------------------------------------------------------ /// 未登録なのか、登録済みなのかを判断する方法がなさそう?なので、ログインを実行してみて、エラーなら新規登録を行います。 /// /// - parameter username: ログイン時に指定するユーザ名 /// - parameter email: ログイン時に指定するメールアドレス /// - parameter password: ログイン時に指定するパスワード /// - returns: None /// func loginWithUserName(username: String, password: String, mailaddress: String) { User.logInWithUsernameInBackground(username, password: password) { user, error in if let e = error { print("ログインが失敗したので、サインアップします: \(e)") self.signupWithUserName(username, password: password, mailaddress: mailaddress) } else { self.successLoginOrSignupForUser(user) } } } /// ユーザの新規登録を行います。 /// /// - parameter username: ログイン時に指定するユーザ名 /// - parameter email: ログイン時に指定するメールアドレス /// - parameter password: ログイン時に指定するパスワード /// - returns: None /// func signupWithUserName(username: String, password: String, mailaddress: String) { let u = User() u.userName = username u.password = password u.mailAddress = mailaddress u.signUpInBackgroundWithBlock { error in if let e = error { print("サインアップ失敗: \(e)") return } print("サインアップ成功") self.successLoginOrSignupForUser(u) } } // ------------------------------------------------------------------------ // MARK: - Action // ------------------------------------------------------------------------ /// ログインボタンをタップした時に実行されます。 @IBAction func tappedLoginButton(sender: AnyObject) { let userName = self.userNameTextField.text let mail = self.mailTextField.text let password = self.passwordTextField.text self.loginWithUserName(userName!, password: password!, mailaddress: mail!) } }
mit
f35a4ff4ac18eb4a409eb1eef9a51619
34.280992
106
0.495901
5.12485
false
false
false
false
joncardasis/ChromaColorPicker
Source/Extensions/UIView+DropShadow.swift
2
1389
// // UIView+DropShadow.swift // ChromaColorPicker // // Created by Jon Cardasis on 4/11/19. // Copyright © 2019 Jonathan Cardasis. All rights reserved. // import UIKit internal struct ShadowProperties { internal let color: CGColor internal let opacity: Float internal let offset: CGSize internal let radius: CGFloat } internal extension UIView { var dropShadowProperties: ShadowProperties? { guard let shadowColor = layer.shadowColor else { return nil } return ShadowProperties(color: shadowColor, opacity: layer.shadowOpacity, offset: layer.shadowOffset, radius: layer.shadowRadius) } func applyDropShadow(color: UIColor, opacity: Float, offset: CGSize, radius: CGFloat) { clipsToBounds = false layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowOffset = offset layer.shadowRadius = radius layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale } func applyDropShadow(_ properties: ShadowProperties) { applyDropShadow(color: UIColor(cgColor: properties.color), opacity: properties.opacity, offset: properties.offset, radius: properties.radius) } func removeDropShadow() { layer.shadowColor = nil layer.shadowOpacity = 0 } }
mit
8fec0c71ae3cd3a11a9d554cb092649f
29.844444
149
0.688761
4.904594
false
false
false
false
lhc70000/iina
iina/JustXMLRPC.swift
2
5549
// // JustXMLRPC.swift // iina // // Created by lhc on 11/3/2017. // Copyright © 2017 lhc. All rights reserved. // import Cocoa import Just fileprivate let ISO8601FormatString = "yyyyMMdd'T'HH:mm:ss" class JustXMLRPC { struct XMLRPCError: Error { var method: String var httpCode: Int var reason: String var readableDescription: String { return "\(method): [\(httpCode)] \(reason)" } } enum Result { case ok(Any) case failure case error(XMLRPCError) } /** (success, result) */ typealias CallBack = (Result) -> Void private static let iso8601DateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = ISO8601FormatString return formatter }() var location: String init(_ loc: String) { self.location = loc } /** * Call a XMLRPC method. */ func call(_ method: String, _ parameters: [Any] = [], callback: @escaping CallBack) { let params = XMLElement(name: "params") for parameter in parameters { let param = XMLElement(name: "param") param.addChild(JustXMLRPC.toValueElement(parameter)) params.addChild(param) } let methodName = XMLElement(name: "methodName", stringValue: method) let methodCall = XMLElement(name: "methodCall") methodCall.addChild(methodName) methodCall.addChild(params) let reqXML = XMLDocument(rootElement: methodCall) // Request Just.post(location, requestBody: reqXML.xmlData) { response in if response.ok, let content = response.content, let responseDoc = try? XMLDocument(data: content) { let rootElement = responseDoc.rootElement() if let _ = rootElement?.child("fault") { callback(.failure) } else if let params = rootElement?.child("params")?.child("param")?.children, params.count == 1 { callback(.ok(JustXMLRPC.value(fromValueElement: params[0] as! XMLElement))) } else { // unexpected return value callback(.error(XMLRPCError(method: method, httpCode: response.statusCode ?? 0, reason: "Bad response"))) } } else { // http error callback(.error(XMLRPCError(method: method, httpCode: response.statusCode ?? 0, reason: response.reason))) } } } private static func toValueElement(_ value: Any) -> XMLElement { let valueElement = XMLElement(name: "value") switch value { case is Bool: valueElement.addChild(XMLElement(name: "boolean", stringValue: (value as! Bool) ? "1" : "0")) case is Int, is Int8, is Int16, is UInt, is UInt8, is UInt16: valueElement.addChild(XMLElement(name: "int", stringValue: "\(value)")) case is Float, is Double: valueElement.addChild(XMLElement(name: "double", stringValue: "\(value)")) case is String: valueElement.addChild(XMLElement(name: "string", stringValue: (value as! String))) case is Date: let stringDate = iso8601DateFormatter.string(from: value as! Date) valueElement.addChild(XMLElement(name: "dateTime.iso8601", stringValue: stringDate)) case is Data: let stringData = (value as! Data).base64EncodedString() valueElement.addChild(XMLElement(name: "base64", stringValue: stringData)) case is [Any]: let arrayElement = XMLElement(name: "array") let dataElement = XMLElement(name: "data") for e in (value as! [Any]) { dataElement.addChild(JustXMLRPC.toValueElement(e)) } arrayElement.addChild(dataElement) valueElement.addChild(arrayElement) case is [String: Any]: let structElement = XMLElement(name: "struct") for (k, v) in (value as! [String: Any]) { let entryElement = XMLElement(name: "member") entryElement.addChild(XMLElement(name: "name", stringValue: k)) entryElement.addChild(JustXMLRPC.toValueElement(v)) structElement.addChild(entryElement) } valueElement.addChild(structElement) default: Logger.log("XMLRPC: Value type not supported", level: .warning) } return valueElement } private static func value(fromValueElement element: XMLElement) -> Any { let valueElement = element.child(at: 0)! as! XMLElement let s = valueElement.stringValue ?? "" switch valueElement.name { case "boolean": return Bool(s) as Any case "int", "i4": return Int(s) as Any case "double": return Double(s) as Any case "string": return s as Any case "dateTime.iso8601": return iso8601DateFormatter.date(from: s)! case "base64": return Data(base64Encoded: s) ?? Data() case "array": var resultArray: [Any] = [] for child in valueElement.child("data")?.findChildren("value") ?? [] { resultArray.append(JustXMLRPC.value(fromValueElement: child)) } return resultArray case "struct": var resultDict: [String: Any] = [:] for child in valueElement.findChildren("member") ?? [] { let key = child.child("name")!.stringValue! let value = JustXMLRPC.value(fromValueElement: child.child("value")!) resultDict[key] = value } return resultDict default: Logger.log("XMLRPC: Unexpected value type: \(valueElement.name ?? "")", level: .error) return 0 } } } extension XMLNode { func findChildren(_ name: String) -> [XMLElement]? { return self.children?.filter { $0.name == name } as? [XMLElement] } func child(_ name: String) -> XMLElement? { return self.findChildren(name)?.first } }
gpl-3.0
6d6c613f8353d98d49a2e919189a3ab0
32.02381
115
0.647621
4.031977
false
false
false
false
proversity-org/edx-app-ios
Source/DiscoveryConfig.swift
2
3759
// // DiscoveryConfig.swift // edX // // Created by Akiva Leffert on 1/5/16. // Copyright © 2016 edX. All rights reserved. // import Foundation import edXCore enum DiscoveryConfigType: String { case native = "native" case webview = "webview" case none = "none" } enum DiscoveryKeys: String, RawStringExtractable { case discovery = "DISCOVERY" case discoveryType = "TYPE" case webview = "WEBVIEW" case baseURL = "BASE_URL" case detailTemplate = "DETAIL_TEMPLATE" case searchEnabled = "SEARCH_ENABLED" case course = "COURSE" case subjectFilterEnabled = "SUBJECT_FILTER_ENABLED" case exploreSubjectsURL = "EXPLORE_SUBJECTS_URL" case program = "PROGRAM" case degree = "DEGREE" } @objc class DiscoveryWebviewConfig: NSObject { @objc let baseURL: URL? @objc let exploreSubjectsURL: URL? @objc let detailTemplate: String? @objc let searchEnabled: Bool @objc let subjectFilterEnabled: Bool init(dictionary: [String: AnyObject]) { baseURL = (dictionary[DiscoveryKeys.baseURL] as? String).flatMap { URL(string:$0)} detailTemplate = dictionary[DiscoveryKeys.detailTemplate] as? String searchEnabled = dictionary[DiscoveryKeys.searchEnabled] as? Bool ?? false subjectFilterEnabled = dictionary[DiscoveryKeys.subjectFilterEnabled] as? Bool ?? false exploreSubjectsURL = (dictionary[DiscoveryKeys.exploreSubjectsURL] as? String).flatMap { URL(string:$0)} } } class DiscoveryConfig: NSObject { @objc let course: CourseDiscovery @objc let program: ProgramDiscovery @objc let degree: DegreeDiscovery init(dictionary: [String: AnyObject]) { course = CourseDiscovery(dictionary: dictionary[DiscoveryKeys.course] as? [String: AnyObject] ?? [:]) program = ProgramDiscovery(with: course, dictionary: dictionary[DiscoveryKeys.program] as? [String: AnyObject] ?? [:]) degree = DegreeDiscovery(with: program, dictionary: dictionary[DiscoveryKeys.degree] as? [String: AnyObject] ?? [:]) } } class CourseDiscovery: DiscoveryBase { var isEnabled: Bool { return type != .none } // Associated swift enums can not be used in objective-c, that's why this extra computed property needed @objc var isCourseDiscoveryNative: Bool { return type == .native } } class ProgramDiscovery: DiscoveryBase { private let courseDiscovery: CourseDiscovery init(with courseDiscovery: CourseDiscovery, dictionary: [String : AnyObject]) { self.courseDiscovery = courseDiscovery super.init(dictionary: dictionary) } var isEnabled: Bool { return courseDiscovery.type == .webview && type == .webview } } class DegreeDiscovery: DiscoveryBase { private let programDiscovery: ProgramDiscovery init(with programDiscovery: ProgramDiscovery, dictionary: [String : AnyObject]) { self.programDiscovery = programDiscovery super.init(dictionary: dictionary) } var isEnabled: Bool { return programDiscovery.isEnabled && type == .webview } } class DiscoveryBase: NSObject { private(set) var type: DiscoveryConfigType @objc let webview: DiscoveryWebviewConfig init(dictionary: [String: AnyObject]) { type = (dictionary[DiscoveryKeys.discoveryType] as? String).flatMap { DiscoveryConfigType(rawValue: $0) } ?? .none webview = DiscoveryWebviewConfig(dictionary: dictionary[DiscoveryKeys.webview] as? [String: AnyObject] ?? [:]) } } extension OEXConfig { @objc var discovery: DiscoveryConfig { return DiscoveryConfig(dictionary: self.properties[DiscoveryKeys.discovery.rawValue] as? [String:AnyObject] ?? [:]) } }
apache-2.0
2a35a2a611a61a98b25bf32272c8939d
31.678261
126
0.690793
4.344509
false
true
false
false
nicolastinkl/TKSwift-3rd
TKSwift-3rd/TKSwift-3rd/PlaygroundFiles/MyPlaygroundC.playground/section-1.swift
1
485
// Playground - noun: a place where people can play import Cocoa var level : Int? var one = 3 var currentValue = level ?? one currentValue func TK<T>(optional:T?,defaultValue : @autoclosure ()->T) ->T { switch optional { case .Some(let value): return value case .None: return defaultValue() } } var someOne:String = "come on" var someTwo:String = "come on baby" //let some = TK(optional: someOne) (someTwo)
mit
a513e041a23584e24d0f0e6e2864c2c4
12.472222
61
0.595876
3.619403
false
false
false
false
Nicejinux/NXDrawKit
NXDrawKit/Classes/CircleButton.swift
1
2646
// // CircleButton.swift // NXDrawKit // // Created by Nicejinux on 2016. 7. 12.. // Copyright © 2016년 Nicejinux. All rights reserved. // import UIKit class CircleButton: UIButton { @objc var color: UIColor! var opacity: CGFloat! var diameter: CGFloat! override var isSelected: Bool { willSet(selectedValue) { super.isSelected = selectedValue let isBright = self.color.isEqual(UIColor.white) || self.color.isEqual(UIColor.clear) let selectedColor = !self.isEnabled ? UIColor.clear : isBright ? UIColor.gray : UIColor.white self.layer.borderColor = self.isSelected ? selectedColor.cgColor : self.color?.cgColor } } override var isEnabled: Bool { willSet(enabledValue) { super.isEnabled = enabledValue // if button is disabled, selected color should be changed to clear color let selected = self.isSelected self.isSelected = selected } } // MARK: - Initializer @objc init(diameter: CGFloat, color: UIColor, opacity: CGFloat) { super.init(frame: CGRect.init(x: 0, y: 0, width: diameter, height: diameter)) self.initialize(diameter, color: color, opacity: opacity) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private func initialize(_ diameter: CGFloat, color: UIColor, opacity: CGFloat) { self.color = color self.opacity = opacity self.diameter = diameter self.layer.cornerRadius = diameter / 2.0 self.layer.borderColor = color.cgColor self.layer.borderWidth = (diameter > 3) ? 3.0 : diameter / 3.0 self.backgroundColor = color.withAlphaComponent(opacity) if self.color.isEqual(UIColor.clear) { self.setBackgroundImage(self.image("icon_eraser"), for: UIControl.State()) } } // MARK: - Internal Methods @objc internal func update(_ color: UIColor) { self.color = color self.isSelected = super.isSelected self.backgroundColor = color.withAlphaComponent(self.opacity!) } // MARK: - Private Methods private func image(_ name: String) -> UIImage? { let podBundle = Bundle(for: self.classForCoder) if let bundleURL = podBundle.url(forResource: "NXDrawKit", withExtension: "bundle") { if let bundle = Bundle(url: bundleURL) { let image = UIImage(named: name, in: bundle, compatibleWith: nil) return image } } return nil } }
mit
5e1a0b118fc6a21289378f55589ccbc1
31.62963
105
0.61067
4.502555
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Mixing Nodes.xcplaygroundpage/Contents.swift
1
3214
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Mixing Nodes //: So, what about connecting multiple sources to the output instead of //: feeding operations into each other in sequential order? To do that, you'll need a mixer. import AudioKitPlaygrounds import AudioKit //: This section prepares the players let drumFile = try AKAudioFile(readFileName: "drumloop.wav") let bassFile = try AKAudioFile(readFileName: "bassloop.wav") let guitarFile = try AKAudioFile(readFileName: "guitarloop.wav") let leadFile = try AKAudioFile(readFileName: "leadloop.wav") var drums = try AKAudioPlayer(file: drumFile) var bass = try AKAudioPlayer(file: bassFile) var guitar = try AKAudioPlayer(file: guitarFile) var lead = try AKAudioPlayer(file: leadFile) drums.looping = true bass.looping = true guitar.looping = true lead.looping = true //: Any number of inputs can be summed into one output let mixer = AKMixer(drums, bass, guitar, lead) AudioKit.output = mixer AudioKit.start() drums.play() bass.play() guitar.play() lead.play() //: Adjust the individual track volumes here drums.volume = 0.9 bass.volume = 0.9 guitar.volume = 0.6 lead.volume = 0.7 drums.pan = 0.0 bass.pan = 0.0 guitar.pan = 0.2 lead.pan = -0.2 //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Mixer") addView(AKButton(title: "Stop All") { button in drums.isPlaying ? drums.stop() : drums.play() bass.isPlaying ? bass.stop() : bass.play() guitar.isPlaying ? guitar.stop() : guitar.play() lead.isPlaying ? lead.stop() : lead.play() if drums.isPlaying { button.title = "Stop All" } else { button.title = "Start All" } }) addView(AKSlider(property: "Drums Volume", value: drums.volume) { sliderValue in drums.volume = sliderValue }) addView(AKSlider(property: "Drums Pan", value: drums.pan, range: -1 ... 1) { sliderValue in drums.pan = sliderValue }) addView(AKSlider(property: "Bass Volume", value: bass.volume) { sliderValue in bass.volume = sliderValue }) addView(AKSlider(property: "Bass Pan", value: bass.pan, range: -1 ... 1) { sliderValue in bass.pan = sliderValue }) addView(AKSlider(property: "Guitar Volume", value: guitar.volume) { sliderValue in guitar.volume = sliderValue }) addView(AKSlider(property: "Guitar Pan", value: guitar.pan, range: -1 ... 1) { sliderValue in guitar.pan = sliderValue }) addView(AKSlider(property: "Lead Volume", value: lead.volume) { sliderValue in lead.volume = sliderValue }) addView(AKSlider(property: "Lead Pan", value: lead.pan, range: -1 ... 1) { sliderValue in lead.pan = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView() //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
7ccac3e6ba92a52e4d0e0a323f04c5f3
30.509804
101
0.641879
3.82619
false
false
false
false
RylynnLai/V2EX--practise
V2EX/Nodes/RLNodeTopicsTVC.swift
1
4687
// // RLNodeTopicsTVC.swift // V2EX // // Created by LLZ on 16/3/22. // Copyright © 2016年 ucs. All rights reserved. // import UIKit class RLNodeTopicsTVC: UITableViewController { var nodeModel:RLNode? // 顶部刷新 let header = MJRefreshNormalHeader() let footer = MJRefreshBackNormalFooter() //懒加载 private lazy var topics:NSMutableArray = {[]}() private lazy var headView:RLNodesHeadView = { return RLNodesHeadView.instantiateFromNib() as! RLNodesHeadView }() override func viewDidLoad() { super.viewDidLoad() //MJRefresh header.setRefreshingTarget(self, refreshingAction: #selector(RLNodeTopicsTVC.refreshData)) self.tableView.mj_header = header footer.setRefreshingTarget(self, refreshingAction: #selector(RLNodeTopicsTVC.loadMore)) footer.setTitle("再拉也没用,Livid只给了我10条数据", forState: .Refreshing) self.tableView.mj_footer = footer loadData() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //只能放在这,配合table的头视图代理方法,自适应高度 self.tableView.tableHeaderView = self.headView } func loadData() { self.title = nodeModel?.title self.headView.nodeModel = nodeModel //获取完整的节点数据 let path = "/api/nodes/show.json?id=\(nodeModel!.ID!)" RLNetWorkManager.defaultNetWorkManager.requestWithPath(path, success: { [weak self] (response) -> Void in if let strongSelf = self {//如果self还没被释放(即当前还是强引用) strongSelf.nodeModel = RLNode.mj_objectWithKeyValues(response) strongSelf.headView.nodeModel = strongSelf.nodeModel strongSelf.tableView.mj_header.beginRefreshing() } }, failure:{ () -> Void in }) } //下拉刷新 func refreshData() { if nodeModel != nil { RLNetWorkManager.defaultNetWorkManager.requestNodeTopicssWithID(nodeModel!.ID!, success: { [weak self] (response) -> Void in if let strongSelf = self {//如果self还没被释放(即当前还是强引用) strongSelf.topics = RLTopic.mj_objectArrayWithKeyValuesArray(response) strongSelf.tableView.mj_header.endRefreshing() strongSelf.tableView.reloadData() } }, failure: { () -> Void in self.tableView.mj_header.endRefreshing() }) } } //上拉加载更多 func loadMore() { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { [weak self] () -> Void in if let strongSelf = self {//如果self还没被释放(即当前还是强引用) strongSelf.tableView.mj_footer.endRefreshing() } } } //MARK: -Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topics.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("nodeTopicCell") if cell == nil { cell = (RLTopicCell.instantiateFromNib() as! UITableViewCell) } if topics.count > 0 { let topicCell:RLTopicCell = cell as! RLTopicCell topicCell.topicModel = (self.topics[indexPath.row] as! RLTopic) } return cell! } //MARK: -UITableViewDelegate override func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return headView.mj_h } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return headView } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 130 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if topics.count > 0 { let topicDetallVC = RLTopicDetailVC.init(nibName: NSStringFromClass(RLTopicDetailVC), bundle: nil) topicDetallVC.topicModel = self.topics[indexPath.row] as? RLTopic self.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(topicDetallVC, animated: true) self.hidesBottomBarWhenPushed = false } } }
mit
629db10b2b6ab3078ba3ce8ceefdfa58
36.847458
146
0.639946
4.656934
false
false
false
false
jainanisha90/codepath_Twitter
Twitter/User.swift
1
2445
// // User.swift // Twitter // // Created by Anisha Jain on 4/12/17. // Copyright © 2017 Anisha Jain. All rights reserved. // import UIKit var _currentUser: User? let currentUserKey = "kCuurentUserKey" let userDidLoginNotification = "userDidLoginNotification" let userDidLogoutNotification = "userDidLogoutNotification" enum Notifications: String { case userDidLoginNotification = "userDidLoginNotification" case userDidLogoutNotification = "userDidLogoutNotification" var name : Notification.Name { return Notification.Name(rawValue: self.rawValue ) } } class User: NSObject { var name: String? var screenName: String? var profileImageUrl: URL? var tagline: String? var dictionary: NSDictionary init(dictionary: NSDictionary) { self.dictionary = dictionary name = dictionary["name"] as? String screenName = dictionary["screen_name"] as? String let profileImageUrlString = dictionary["profile_image_url"] as? String if profileImageUrlString != nil { profileImageUrl = URL(string: profileImageUrlString!) } else { profileImageUrl = nil } tagline = dictionary["description"] as? String } class var currentUser: User? { get { if _currentUser == nil { let data = UserDefaults.standard.object(forKey: currentUserKey) as? Data if data != nil { do { let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary _currentUser = User(dictionary: dictionary) } catch { } } } return _currentUser } set(user) { _currentUser = user if _currentUser != nil { do { let data = try JSONSerialization.data(withJSONObject: user!.dictionary, options: []) UserDefaults.standard.set(data, forKey: currentUserKey) } catch { UserDefaults.standard.removeObject(forKey: currentUserKey) } } else { UserDefaults.standard.removeObject(forKey: currentUserKey) } UserDefaults.standard.synchronize() } } }
mit
a220390a8978717f744ddb64cf3d85f0
28.804878
116
0.56874
5.419069
false
false
false
false
ibm-wearables-sdk-for-mobile/ios
Connectors/Gemsense.swift
2
6636
/* * © Copyright 2015 IBM Corp. * * Licensed under the Mobile Edge iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 GemSDK import IBMMobileEdge public class Gemsense : DeviceConnector, GemScanDelegate, GemDelegate { var gemManager:GemManager! var gem:Gem! var highestRssi:NSNumber! var accelerometerDataEvents:SensorEvents! var gyroscopeDataEvents:SensorEvents! var pedometerDataEvents:SensorEvents! var isAccelerometrEnabled = false var isGyroscopeEnabled = false var isTryingToConnect = false var isReady = false var timer:NSTimer! let scanningTime:NSTimeInterval = 5 override init(){ super.init() deviceName = "Gemsense" gemManager = GemManager.sharedInstace() gemManager.delegate = self } override public func connect(connectionStatusDelegate:ConnectionStatusDelegate!){ self.connectionStatusDelegate = connectionStatusDelegate isTryingToConnect = true clearRssi() //connect only if ready, if not it will be connected at the isReady callback if isReady{ handleConnection() } } func clearRssi(){ highestRssi = -10000 } override public func disconnect(){ gemManager.disconnectGem(self.gem) } override public func registerForEvents(systemEvents: SystemEvents){ accelerometerDataEvents = systemEvents.getSensorEvents(.Accelerometer) gyroscopeDataEvents = systemEvents.getSensorEvents(.Gyroscope) pedometerDataEvents = systemEvents.getSensorEvents(.Pedometer) //accelerometer accelerometerDataEvents.turnOnCommand.addHandler { () -> () in self.isAccelerometrEnabled = true } accelerometerDataEvents.turnOffCommand.addHandler { () -> () in self.isAccelerometrEnabled = false } //gyroscope gyroscopeDataEvents.turnOnCommand.addHandler { () -> () in self.isGyroscopeEnabled = true } gyroscopeDataEvents.turnOffCommand.addHandler { () -> () in self.isGyroscopeEnabled = false } //pedometer pedometerDataEvents.turnOnCommand.addHandler { () -> () in if let connectedGem = self.gem { self.gemManager.enablePedometer(connectedGem) } } pedometerDataEvents.turnOffCommand.addHandler { () -> () in if let connectedGem = self.gem { self.gemManager.disablePedometer(connectedGem) } } } override public func getSupportedSensors() -> [SensorType]{ return [.Accelerometer,.Gyroscope,.Pedometer] } public func onDeviceDiscovered(gem: Gem!, rssi: NSNumber!) { print("Gemsense discovered: \(gem.getName()). With rssi: \(rssi)") //update the discovered gem if it is higher if rssi.doubleValue > highestRssi.doubleValue { highestRssi = rssi self.gem = gem } } public func onErrorOccurred(error: NSError!) { print("Gemsense Error: " + error.localizedDescription) } public func onInitializationError(error: InitializationError){ print("Gemsense Error: \(error)") } public func onReady() { print("Gemsense onReady called") isReady = true if isTryingToConnect{ handleConnection() } } func handleConnection(){ if let current = gem{ gemManager.connectGem(current) } else{ //start scanning gemManager.startScan() //start the delay timer to wait until the scan is complete timer = NSTimer.scheduledTimerWithTimeInterval(scanningTime, target: self, selector: "connectToDevice", userInfo: nil, repeats: false) } } func connectToDevice(){ if let _ = gem { self.gem.delegate = self gemManager.connectGem(gem) gemManager.stopScan() clearRssi() } } public func onStateChanged(state: GemState) { switch(state) { case.Connected: updateConnectionStatus(.Connected) gemManager.enableRawData(self.gem) print("Gemsense Connected") case.Connecting: print("Gemsense Connecting") case.Disconnected: isTryingToConnect = false updateConnectionStatus(.Disconnected) print("Gemsense Disconnected") case.Disconnecting: print("Gemsense Disconnecting") } } public func onRawData(data: GemRawData!) { if (isAccelerometrEnabled){ triggerAccelerometerDataUpdate(data) } if (isGyroscopeEnabled){ triggerGyroscopeDataUpdate(data) } } public func onPedometerData(steps: UInt32, walkTime: Float){ let pedometerData = PedometerData() pedometerData.steps = UInt(steps) pedometerDataEvents.dataEvent.trigger(pedometerData) } func triggerAccelerometerDataUpdate(data: GemRawData!){ let accelerometerData = AccelerometerData() accelerometerData.x = data.acceleration[0].doubleValue accelerometerData.y = data.acceleration[1].doubleValue accelerometerData.z = data.acceleration[2].doubleValue accelerometerDataEvents.dataEvent.trigger(accelerometerData) } func triggerGyroscopeDataUpdate(data: GemRawData!){ let gyroscopeData = GyroscopeData() gyroscopeData.x = data.gyroscope[0].doubleValue gyroscopeData.y = data.gyroscope[1].doubleValue gyroscopeData.z = data.gyroscope[2].doubleValue gyroscopeDataEvents.dataEvent.trigger(gyroscopeData) } }
epl-1.0
b86262c0f7b4962684b3d9a661601a61
28.625
146
0.610098
5.139427
false
false
false
false
fqhuy/minimind
minimind/MyPlayground.playground/Pages/OperatorOverloading.xcplaygroundpage/Contents.swift
1
1235
//: Playground - noun: a place where people can play // import UIKit var str = "Hello, playground" import Surge //import minimind var m = Matrix<Float>([[1.0, 2.0],[1.0, 1.0]]) let v = m //let v1 = -1.0 * m // func / <T:ExpressibleByFloatLiteral & FloatingPoint>(lhs: T, rhs: Matrix<T>) -> Matrix<T> { return lhs / rhs } func * <T:ExpressibleByFloatLiteral & FloatingPoint>(lhs: Matrix<T>, rhs: T) -> Matrix<T> { return lhs * rhs } prefix func -<T: ExpressibleByFloatLiteral & FloatingPoint>(mat: Matrix<T>) -> Matrix<T> { var newmat = mat newmat.grid = -newmat.grid return newmat } prefix func -<T: SignedNumber>(arr: [T]) -> [T] { return arr.map{x in -x} } func * <T: FloatingPoint>(lhs: T, rhs: [T]) -> [T] { return rhs.map{ lhs * $0 } } func -<T: SignedNumber>(lhs: [T], rhs: [T]) -> [T] { return (0..<lhs.count).map{ lhs[$0] - rhs[$0] } } let s = [1.0, 2.0] s - [1.0, 1.0] 10.0 * m // // //let x: Int = 10 //let y = x //pow(5.0, 10.0) // //public class C { // public init(){ // // } // public subscript(index idx: Int) -> Int { // get { // return idx // } // // } //} // //let a = Array([1,2,3]) //a[0] print(m) m[column: 0] = [9.0, 9.0] print(m)
mit
c99e7ef12411dce1e537abcd4be5de8f
16.898551
91
0.54413
2.578288
false
false
false
false
jmgc/swift
test/Concurrency/Runtime/async_taskgroup_is_empty.swift
1
1054
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency) | %FileCheck %s --dump-input always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: OS=macosx // REQUIRES: CPU=x86_64 import Dispatch #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #endif func asyncEcho(_ value: Int) async -> Int { value } func test_taskGroup_isEmpty() async { _ = await try! Task.withGroup(resultType: Int.self) { (group) async -> Int in // CHECK: before add: isEmpty=true print("before add: isEmpty=\(group.isEmpty)") await group.add { sleep(2) return await asyncEcho(1) } // CHECK: while add running, outside: isEmpty=false print("while add running, outside: isEmpty=\(group.isEmpty)") // CHECK: next: 1 while let value = await try! group.next() { print("next: \(value)") } // CHECK: after draining tasks: isEmpty=true print("after draining tasks: isEmpty=\(group.isEmpty)") return 0 } } runAsyncAndBlock(test_taskGroup_isEmpty)
apache-2.0
8d90dcf8653342f06500c70af0f2806d
23.511628
113
0.673624
3.659722
false
true
false
false
Accountabilibuddy/hustle
Hustle/Hustle/CloudKit.swift
1
6014
// // CloudKit.swift // Hustle // // Created by Kyle Hillman on 4/10/17. // Copyright © 2017 Eve Denison. All rights reserved. // import UIKit import CloudKit typealias SuccessCompletion = (Bool) -> () typealias JobSearchCompletion = ([JobSearch]?)->() typealias UserCompletion = ([User])->() typealias ProfileName = (String)->() typealias ProfileImage = (UIImage?)->() class CloudKit { static let shared = CloudKit() var userName = String() let container = CKContainer.default() var publicDatabase : CKDatabase { return container.publicCloudDatabase } //save method for regular records func save(record: CKRecord, completion: @escaping SuccessCompletion) { publicDatabase.save(record, completionHandler: { (record, error) in if error != nil { completion(false) } if let record = record { print("record \(record)") completion(true) } else { completion(false) } }) } //save method ONLY for profile image func saveProfileImage(user: User, completion: @escaping SuccessCompletion){ do { if let record = try User.recordFor(user: user){ publicDatabase.save(record, completionHandler: { (record, error) in if error != nil { completion(false) return } if let record = record { print("image record is being printed: \(record)") completion(true) } else { completion(false) } }) } } catch{ print(error) } } func getProfileImageRecord(completion: @escaping ProfileImage){ let imageQuery = CKQuery(recordType: "ProfileImage", predicate: NSPredicate(value: true)) self.publicDatabase.perform(imageQuery, inZoneWith: nil) { (records, error) in if error != nil { OperationQueue.main.addOperation { completion(nil) } } if let records = records { let record = records.first if let asset = record?["userImage"] as? CKAsset { print("ASSET\(asset)") //dont delete this print statement because I dont know let path = asset.fileURL.path if let image = UIImage(contentsOfFile: path){ OperationQueue.main.addOperation { completion(image) } } } } } } func getJobSearchRecords(completion: @escaping JobSearchCompletion) { let recordQuery = CKQuery(recordType: "JobSearch", predicate: NSPredicate(value: true)) self.publicDatabase.perform(recordQuery, inZoneWith: nil) { (records, error) in if error != nil { OperationQueue.main.addOperation { completion(nil) } } if let records = records { var jobSearchRecord = [JobSearch]() for record in records { if let didHighVolumeSearch = record["didHighVolumeSearch"] as? Bool, let targetedSearch = record["targetedSearch"] as? Bool, let targetedEvents = record["targetedEvents"] as? Bool, let committedToGitHub = record["committedToGitHub"] as? Bool, let codingWars = record["codingWars"] as? Bool, let whiteBoarding = record["whiteBoarding"] as? Bool, let interviewQuestions = record["interviewQuestions"] as? Bool, let infoCoffee = record["infoCoffee"] as? Bool, let meetupEvents = record["meetupEvents"] as? Bool, let visitCompanies = record["visitCompanies"] as? Bool, let followUp = record["followUp"] as? Bool, let textFieldNotes = record["textFieldNotes"] as? String, let date = record["date"] as? Date { let newRecord = JobSearch(didHighVolumeSearch: didHighVolumeSearch, targetedSearch: targetedSearch, targetedEvents: targetedEvents, committedToGitHub: committedToGitHub, codingWars: codingWars, whiteBoarding: whiteBoarding, interviewQuestions: interviewQuestions, infoCoffee: infoCoffee, meetupEvents: meetupEvents, visitCompanies: visitCompanies, followUp: followUp, textFieldNotes: textFieldNotes, date: date) jobSearchRecord.append(newRecord) } } print() OperationQueue.main.addOperation { completion(jobSearchRecord) } } } } func getUserID(completion: @escaping ProfileName) { CKContainer.default().requestApplicationPermission(.userDiscoverability) { (status, error) in CKContainer.default().fetchUserRecordID(completionHandler: { (record, error) in CKContainer.default().discoverUserIdentity(withUserRecordID: record!, completionHandler: { (userID, error) in print(userID?.hasiCloudAccount ?? "User Name not Defined") self.userName = ((userID?.nameComponents?.givenName)! + " " + (userID?.nameComponents?.familyName)!) OperationQueue.main.addOperation { completion(self.userName) } }) }) } } }
mit
c10bed7e72b276e40e33771ee50566c9
37.544872
435
0.524696
5.55217
false
false
false
false
Laurensesss/Learning-iOS-Programming-with-Swift
Project03_SimpleTable/SimpleTable/AppDelegate.swift
1
2846
// // AppDelegate.swift // SimpleTable // // Created by 石韬 on 16/5/20. // Copyright © 2016年 石韬. 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. UINavigationBar.appearance().barTintColor = UIColor.orangeColor() // UIColor(red: 242.0/255.0, green: 116.0/255.0, blue: 119.0/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor.whiteColor() if let barFont = UIFont(name: "Avenir-Light", size: 24.0) { UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSFontAttributeName:barFont] } UIApplication.sharedApplication().statusBarStyle = .LightContent UITabBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().barTintColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) UITabBar.appearance().backgroundImage = UIImage(named: "tabbar-background") 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
89e9cb381739432ee60162bb5b81877d
45.47541
281
0.758377
5.035524
false
false
false
false
PiHanHsu/myscorebaord_lite
myscoreboard_lite/Controller/GameScheduleTableViewController.swift
1
5313
// // GameScheduleTableViewController.swift // myscoreboard_lite // // Created by PiHan on 2017/9/18. // Copyright © 2017年 PiHan. All rights reserved. // import UIKit class GameScheduleTableViewController: UITableViewController { var selectedPlayers : Array<Player> { get{ return DataSource.sharedInstance.selectedPlayers } } var playerBasket : Array<Player> { get{ return DataSource.sharedInstance.playerBasket } } var courtCount: Int = DataSource.sharedInstance.courtCount var gameByCourt: Array<Array<Player>> { get { return DataSource.sharedInstance.gameByCourt } } var gameHistory: Array<Array<Player>> { get { return DataSource.sharedInstance.gameHistory } } var isFirstTimeEnter = true override func viewDidLoad() { super.viewDidLoad() navigationController?.setNavigationBarHidden(false, animated: false) tableView.tableFooterView = UIView(frame: CGRect.zero) // Register cell classes let nib = UINib(nibName: "GameScheduleTableViewCell", bundle: nil) tableView?.register(nib, forCellReuseIdentifier: "GameScheduleTableViewCell") //set notificationCenter NotificationCenter.default.addObserver(self, selector: #selector(self.updateData(notification:)), name: .updateData, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isFirstTimeEnter { DataSource.sharedInstance.createGamePlayList() isFirstTimeEnter = false } } @objc func updateData(notification: NSNotification) { tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return courtCount case 1: return DataSource.sharedInstance.gameHistory.count default: return 0 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: return 120.0 case 1: return 100.0 default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "正在進行比賽" case 1: return "歷史比賽紀錄" default: return "" } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: "GameScheduleTableViewCell", for: indexPath) as! GameScheduleTableViewCell cell.player1Label.text = gameByCourt[indexPath.row][0].name cell.player2Label.text = gameByCourt[indexPath.row][1].name cell.player3Label.text = gameByCourt[indexPath.row][2].name cell.player4Label.text = gameByCourt[indexPath.row][3].name cell.courtNumLabel.text = "Court \(indexPath.row + 1)" cell.finishButton.isHidden = false cell.finishButton.tag = indexPath.row cell.finishButton.addTarget(self, action: #selector(gameFinished(sender:)), for: .touchUpInside) return cell case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "GameScheduleTableViewCell", for: indexPath) as! GameScheduleTableViewCell cell.player1Label.text = gameHistory[indexPath.row][0].name cell.player2Label.text = gameHistory[indexPath.row][1].name cell.player3Label.text = gameHistory[indexPath.row][2].name cell.player4Label.text = gameHistory[indexPath.row][3].name cell.finishButton.isHidden = true cell.courtNumLabel.text = "Game \(indexPath.row + 1)" return cell default: return UITableViewCell() } } @objc func gameFinished(sender: UIButton){ let alert = UIAlertController(title: "結束本場比賽?", message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "確定", style: .default) { a in let index = sender.tag DataSource.sharedInstance.createNextGame(finshedIndex: index) } let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil) alert.addAction(okAction) alert.addAction(cancel) present(alert, animated: true, completion: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "GameHistory" { let vc = segue.destination as! GameHistoryTableViewController vc.gameHistory = gameHistory } } }
mit
712e678a27685b01dfa0e6aa7608bd48
32.316456
143
0.616261
4.869565
false
false
false
false
CrowdShelf/ios
CrowdShelf/CrowdShelf/TableViewCells/ShelfTableViewCell.swift
1
2069
// // ShelfTableViewCell.swift // CrowdShelf // // Created by Øyvind Grimnes on 30/09/15. // Copyright © 2015 Øyvind Grimnes. All rights reserved. // import UIKit protocol ShelfTableViewCellDelegate { func showAllBooksForShelfTableViewCell(shelfTableViewCell: ShelfTableViewCell) func shelfTableViewCell(shelfTableViewCell: ShelfTableViewCell, didSelectTitle title: BookInformation) } class ShelfTableViewCell: UITableViewCell, UICollectionViewDelegate { var shelf: Shelf? { didSet { self.updateView() } } var collectionViewDataSource: CollectionViewArrayDataSource? var delegate: ShelfTableViewCellDelegate? @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var collectionView: UICollectionView? @IBOutlet weak var showAllButton: UIButton? override func awakeFromNib() { collectionView?.registerCellForClass(CollectableCell) self.collectionViewDataSource = CollectionViewArrayDataSource(cellReuseIdentifier: CollectableCell.cellReuseIdentifier) { ($0 as! CollectableCell).collectable = $1 as? Listable } self.collectionView!.dataSource = self.collectionViewDataSource self.collectionView!.delegate = self self.updateView() } private func updateView() { self.collectionViewDataSource?.data = self.shelf?.titles ?? [] self.collectionView?.reloadData() self.titleLabel?.text = self.shelf?.name self.showAllButton?.hidden = self.shelf?.books.isEmpty ?? true } // MARK: Collection View Delegate func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.delegate?.shelfTableViewCell(self, didSelectTitle: self.collectionViewDataSource?.dataForIndexPath(indexPath) as! BookInformation) } // MARK: Actions @IBAction func showAll(sender: UIButton) { self.delegate?.showAllBooksForShelfTableViewCell(self) } }
mit
a6c74150e6151a28ac32ae96bb4edf68
30.784615
143
0.698935
5.366234
false
false
false
false
DarrenKong/firefox-ios
Sync/Synchronizers/Bookmarks/Merging.swift
3
10849
/* 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 Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger // Because generic protocols in Swift are a pain in the ass. public protocol BookmarkStorer: class { // TODO: this should probably return a timestamp. func applyUpstreamCompletionOp(_ op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> } open class UpstreamCompletionOp: PerhapsNoOp { // Upload these records from the buffer, but with these child lists. open var amendChildrenFromBuffer: [GUID: [GUID]] = [:] // Upload these records from the mirror, but with these child lists. open var amendChildrenFromMirror: [GUID: [GUID]] = [:] // Upload these records from local, but with these child lists. open var amendChildrenFromLocal: [GUID: [GUID]] = [:] // Upload these records as-is. open var records: [Record<BookmarkBasePayload>] = [] open let ifUnmodifiedSince: Timestamp? open var isNoOp: Bool { return records.isEmpty } public init(ifUnmodifiedSince: Timestamp?=nil) { self.ifUnmodifiedSince = ifUnmodifiedSince } } open class BookmarksMergeResult: PerhapsNoOp { let uploadCompletion: UpstreamCompletionOp let overrideCompletion: LocalOverrideCompletionOp let bufferCompletion: BufferCompletionOp let itemSources: ItemSources open var isNoOp: Bool { return self.uploadCompletion.isNoOp && self.overrideCompletion.isNoOp && self.bufferCompletion.isNoOp } func applyToClient(_ client: BookmarkStorer, storage: SyncableBookmarks, buffer: BookmarkBufferStorage) -> Success { return client.applyUpstreamCompletionOp(self.uploadCompletion, itemSources: self.itemSources, trackingTimesInto: self.overrideCompletion) >>> { storage.applyLocalOverrideCompletionOp(self.overrideCompletion, itemSources: self.itemSources) } >>> { buffer.applyBufferCompletionOp(self.bufferCompletion, itemSources: self.itemSources) } } init(uploadCompletion: UpstreamCompletionOp, overrideCompletion: LocalOverrideCompletionOp, bufferCompletion: BufferCompletionOp, itemSources: ItemSources) { self.uploadCompletion = uploadCompletion self.overrideCompletion = overrideCompletion self.bufferCompletion = bufferCompletion self.itemSources = itemSources } static func NoOp(_ itemSources: ItemSources) -> BookmarksMergeResult { return BookmarksMergeResult(uploadCompletion: UpstreamCompletionOp(), overrideCompletion: LocalOverrideCompletionOp(), bufferCompletion: BufferCompletionOp(), itemSources: itemSources) } } // MARK: - Errors. open class BookmarksMergeError: MaybeErrorType, SyncPingFailureFormattable { fileprivate let error: Error? init(error: Error?=nil) { self.error = error } open var description: String { return "Merge error: \(self.error ??? "nil")" } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class BookmarksMergeConsistencyError: BookmarksMergeError { override open var description: String { return "Merge consistency error" } } open class BookmarksMergeErrorTreeIsUnrooted: BookmarksMergeConsistencyError { open let roots: Set<GUID> public init(roots: Set<GUID>) { self.roots = roots } override open var description: String { return "Tree is unrooted: roots are \(self.roots)" } } enum MergeState<T: Equatable>: Equatable { case unknown // Default state. case unchanged // Nothing changed: no work needed. case remote // Take the associated remote value. case local // Take the associated local value. case new(value: T) // Take this synthesized value. var isUnchanged: Bool { if case .unchanged = self { return true } return false } var isUnknown: Bool { if case .unknown = self { return true } return false } var label: String { switch self { case .unknown: return "Unknown" case .unchanged: return "Unchanged" case .remote: return "Remote" case .local: return "Local" case .new: return "New" } } static func ==(lhs: MergeState, rhs: MergeState) -> Bool { switch (lhs, rhs) { case (.unknown, .unknown), (.unchanged, .unchanged), (.remote, .remote), (.local, .local): return true case let (.new(lh), .new(rh)): return lh == rh default: return false } } } /** * Using this: * * You get one for the root. Then you give it children for the roots * from the mirror. * * Then you walk those, populating the remote and local nodes by looking * at the left/right trees. * * By comparing left and right, and doing value-based comparisons if necessary, * a merge state is decided and assigned for both value and structure. * * One then walks both left and right child structures (both to ensure that * all nodes on both left and right will be visited!) recursively. */ class MergedTreeNode { let guid: GUID let mirror: BookmarkTreeNode? var remote: BookmarkTreeNode? var local: BookmarkTreeNode? var hasLocal: Bool { return self.local != nil } var hasMirror: Bool { return self.mirror != nil } var hasRemote: Bool { return self.remote != nil } var valueState: MergeState<BookmarkMirrorItem> = MergeState.unknown var structureState: MergeState<BookmarkTreeNode> = MergeState.unknown var hasDecidedChildren: Bool { return !self.structureState.isUnknown } var mergedChildren: [MergedTreeNode]? // One-sided constructors. static func forRemote(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: remote.recordGUID, mirror: mirror, structureState: MergeState.remote) n.remote = remote n.valueState = MergeState.remote return n } static func forLocal(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: local.recordGUID, mirror: mirror, structureState: MergeState.local) n.local = local n.valueState = MergeState.local return n } static func forUnchanged(_ mirror: BookmarkTreeNode) -> MergedTreeNode { let n = MergedTreeNode(guid: mirror.recordGUID, mirror: mirror, structureState: MergeState.unchanged) n.valueState = MergeState.unchanged return n } init(guid: GUID, mirror: BookmarkTreeNode?, structureState: MergeState<BookmarkTreeNode>) { self.guid = guid self.mirror = mirror self.structureState = structureState } init(guid: GUID, mirror: BookmarkTreeNode?) { self.guid = guid self.mirror = mirror } // N.B., you cannot recurse down `decidedStructure`: you'll depart from the // merged tree. You need to use `mergedChildren` instead. fileprivate var decidedStructure: BookmarkTreeNode? { switch self.structureState { case .unknown: return nil case .unchanged: return self.mirror case .remote: return self.remote case .local: return self.local case let .new(node): return node } } func asUnmergedTreeNode() -> BookmarkTreeNode { return self.decidedStructure ?? BookmarkTreeNode.unknown(guid: self.guid) } // Recursive. Starts returning Unknown when nodes haven't been processed. func asMergedTreeNode() -> BookmarkTreeNode { guard let decided = self.decidedStructure, let merged = self.mergedChildren else { return BookmarkTreeNode.unknown(guid: self.guid) } if case .folder = decided { let children = merged.map { $0.asMergedTreeNode() } return BookmarkTreeNode.folder(guid: self.guid, children: children) } return decided } var isFolder: Bool { return self.mergedChildren != nil } func dump(_ indent: Int) { precondition(indent < 200) let r: Character = "R" let l: Character = "L" let m: Character = "M" let ind = indenting(indent) print(ind, "[V: ", box(self.remote, r), box(self.mirror, m), box(self.local, l), self.guid, self.valueState.label, "]") guard self.isFolder else { return } print(ind, "[S: ", self.structureState.label, "]") if let children = self.mergedChildren { print(ind, " ..") for child in children { child.dump(indent + 2) } } } } private func box<T>(_ x: T?, _ c: Character) -> Character { if x == nil { return "□" } return c } private func indenting(_ by: Int) -> String { return String(repeating: " ", count: by) } class MergedTree { var root: MergedTreeNode var deleteLocally: Set<GUID> = Set() var deleteRemotely: Set<GUID> = Set() var deleteFromMirror: Set<GUID> = Set() var acceptLocalDeletion: Set<GUID> = Set() var acceptRemoteDeletion: Set<GUID> = Set() var allGUIDs: Set<GUID> { var out = Set<GUID>([self.root.guid]) func acc(_ node: MergedTreeNode) { guard let children = node.mergedChildren else { return } out.formUnion(Set(children.map { $0.guid })) children.forEach(acc) } acc(self.root) return out } init(mirrorRoot: BookmarkTreeNode) { self.root = MergedTreeNode(guid: mirrorRoot.recordGUID, mirror: mirrorRoot, structureState: MergeState.unchanged) self.root.valueState = MergeState.unchanged } func dump() { print("Deleted locally: \(self.deleteLocally.joined(separator: ", "))") print("Deleted remotely: \(self.deleteRemotely.joined(separator: ", "))") print("Deleted from mirror: \(self.deleteFromMirror.joined(separator: ", "))") print("Accepted local deletions: \(self.acceptLocalDeletion.joined(separator: ", "))") print("Accepted remote deletions: \(self.acceptRemoteDeletion.joined(separator: ", "))") print("Root: ") self.root.dump(0) } }
mpl-2.0
4f8e239b19384cfc7f8f2d63871e6560
31.573574
192
0.643957
4.736681
false
false
false
false
belkevich/DTModelStorage
DTModelStorage/CoreData/CoreDataStorage.swift
1
7783
// // CoreDataStorage.swift // DTModelStorageTests // // Created by Denys Telezhkin on 06.07.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreData private struct DTFetchedResultsSectionInfoWrapper : Section { let fetchedObjects : [AnyObject] let numberOfObjects: Int var objects : [Any] { return fetchedObjects.map { $0 } } } /// This class represents model storage in CoreData /// It uses NSFetchedResultsController to monitor all changes in CoreData and automatically notify delegate of any changes public class CoreDataStorage : BaseStorage { /// Fetched results controller of storage public let fetchedResultsController : NSFetchedResultsController /// Initialize CoreDataStorage with NSFetchedResultsController /// - Parameter fetchedResultsController: fetch results controller public init(fetchedResultsController: NSFetchedResultsController) { self.fetchedResultsController = fetchedResultsController super.init() self.fetchedResultsController.delegate = self } /// Sections of fetched results controller as required by StorageProtocol /// - SeeAlso: `StorageProtocol` /// - SeeAlso: `MemoryStorage` public var sections : [Section] { if let sections = self.fetchedResultsController.sections { return sections.map { DTFetchedResultsSectionInfoWrapper(fetchedObjects: $0.objects!, numberOfObjects: $0.numberOfObjects) } } return [] } } extension CoreDataStorage : StorageProtocol { /// Retrieve object at index path from `CoreDataStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func objectAtIndexPath(path: NSIndexPath) -> Any? { return fetchedResultsController.objectAtIndexPath(path) } } extension CoreDataStorage : HeaderFooterStorageProtocol { /// Header model for section. /// - Requires: supplementaryHeaderKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: header model for section, or nil if there are no model public func headerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryHeaderKind != nil, "Supplementary header kind must be set before retrieving header model for section index") if self.supplementaryHeaderKind == nil { return nil } return self.supplementaryModelOfKind(self.supplementaryHeaderKind!, sectionIndex: index) } /// Footer model for section. /// - Requires: supplementaryFooterKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: footer model for section, or nil if there are no model public func footerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryFooterKind != nil, "Supplementary footer kind must be set before retrieving header model for section index") if self.supplementaryFooterKind == nil { return nil } return self.supplementaryModelOfKind(self.supplementaryFooterKind!, sectionIndex: index) } } extension CoreDataStorage : SupplementaryStorageProtocol { /// Retrieve supplementary model of specific kind for section. /// - Parameter kind: kind of supplementary model /// - Parameter sectionIndex: index of section /// - SeeAlso: `headerModelForSectionIndex` /// - SeeAlso: `footerModelForSectionIndex` public func supplementaryModelOfKind(kind: String, sectionIndex: Int) -> Any? { if kind == self.supplementaryHeaderKind { if let sections = self.fetchedResultsController.sections { return sections[sectionIndex].name } return nil } return nil } } extension CoreDataStorage : NSFetchedResultsControllerDelegate { /// NSFetchedResultsController is about to start changing content - we'll start monitoring for updates. @objc public func controllerWillChangeContent(controller: NSFetchedResultsController) { self.startUpdate() } /// React to specific change in NSFetchedResultsController @objc public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { if self.currentUpdate == nil { return } switch type { case .Insert: if self.currentUpdate!.insertedSectionIndexes.containsIndex(newIndexPath!.section) { // If we've already been told that we're adding a section for this inserted row we skip it since it will handled by the section insertion. return } self.currentUpdate!.insertedRowIndexPaths.append(newIndexPath!) case .Delete: if self.currentUpdate!.deletedSectionIndexes.containsIndex(indexPath!.section) { // If we've already been told that we're deleting a section for this deleted row we skip it since it will handled by the section deletion. return } self.currentUpdate?.deletedRowIndexPaths.append(indexPath!) case .Move: if !self.currentUpdate!.insertedSectionIndexes.containsIndex(newIndexPath!.section) { self.currentUpdate!.insertedRowIndexPaths.append(newIndexPath!) } if !self.currentUpdate!.deletedSectionIndexes.containsIndex(indexPath!.section) { self.currentUpdate!.deletedRowIndexPaths.append(indexPath!) } case .Update: self.currentUpdate?.updatedRowIndexPaths.append(indexPath!) } } /// React to changed section in NSFetchedResultsController @objc public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { if self.currentUpdate == nil { return } switch type { case .Insert: self.currentUpdate!.insertedSectionIndexes.addIndex(sectionIndex) case .Delete: self.currentUpdate!.deletedSectionIndexes.addIndex(sectionIndex) default: () } } /// Finish update from NSFetchedResultsController @objc public func controllerDidChangeContent(controller: NSFetchedResultsController) { self.finishUpdate() } }
mit
14c3874c49b3057511cd879a34de50e8
39.541667
200
0.696647
5.393624
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/call/WebRTCCallMessageHandler.swift
1
2629
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit import SignalMessaging @objc(OWSWebRTCCallMessageHandler) public class WebRTCCallMessageHandler: NSObject, OWSCallMessageHandler { // MARK: Initializers @objc public override init() { super.init() SwiftSingletons.register(self) } // MARK: - Dependencies private var messageSender: MessageSender { return SSKEnvironment.shared.messageSender } private var accountManager: AccountManager { return AppEnvironment.shared.accountManager } private var callService: CallService { return AppEnvironment.shared.callService } // MARK: - Call Handlers public func receivedOffer(_ offer: SSKProtoCallMessageOffer, from caller: SignalServiceAddress) { AssertIsOnMainThread() let thread = TSContactThread.getOrCreateThread(contactAddress: caller) self.callService.handleReceivedOffer(thread: thread, callId: offer.id, sessionDescription: offer.sessionDescription) } public func receivedAnswer(_ answer: SSKProtoCallMessageAnswer, from caller: SignalServiceAddress) { AssertIsOnMainThread() let thread = TSContactThread.getOrCreateThread(contactAddress: caller) self.callService.handleReceivedAnswer(thread: thread, callId: answer.id, sessionDescription: answer.sessionDescription) } public func receivedIceUpdate(_ iceUpdate: SSKProtoCallMessageIceUpdate, from caller: SignalServiceAddress) { AssertIsOnMainThread() let thread = TSContactThread.getOrCreateThread(contactAddress: caller) // Discrepency between our protobuf's sdpMlineIndex, which is unsigned, // while the RTC iOS API requires a signed int. let lineIndex = Int32(iceUpdate.sdpMlineIndex) self.callService.handleRemoteAddedIceCandidate(thread: thread, callId: iceUpdate.id, sdp: iceUpdate.sdp, lineIndex: lineIndex, mid: iceUpdate.sdpMid) } public func receivedHangup(_ hangup: SSKProtoCallMessageHangup, from caller: SignalServiceAddress) { AssertIsOnMainThread() let thread = TSContactThread.getOrCreateThread(contactAddress: caller) self.callService.handleRemoteHangup(thread: thread, callId: hangup.id) } public func receivedBusy(_ busy: SSKProtoCallMessageBusy, from caller: SignalServiceAddress) { AssertIsOnMainThread() let thread = TSContactThread.getOrCreateThread(contactAddress: caller) self.callService.handleRemoteBusy(thread: thread, callId: busy.id) } }
gpl-3.0
3099549b801874f1bff7205a4dcd466a
33.142857
157
0.735641
5.124756
false
false
false
false
rdhiggins/PythonMacros
PythonMacros/LineNumberLayoutManager.swift
1
4097
// // LineNumberLayoutManager.swift // MIT License // // Copyright (c) 2016 Spazstik Software, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /// Custom layout manager class used to display line numbers for code. The /// gutter is on the left. This class is used in conjunction with /// LineNumberTextView class. This class takes care of displaying the actual /// line numbers. class LineNumberLayoutManager: NSLayoutManager { /// Property containing the color to use for the text var textColor: UIColor = UIColor.white { didSet { setupFontAttributes() } } /// Property containing the width of the line number gutter var gutterWidth: CGFloat = 40.0 /// Property containing the font to use for the line numbers var font: UIFont! = UIFont(name: "Menlo", size: 10.0) { didSet { setupFontAttributes() } } fileprivate var fontAttributes: [String : NSObject] = [ NSFontAttributeName : UIFont(name: "Menlo", size: 10.0)!, NSForegroundColorAttributeName : UIColor.white ] /// Private method used to update the text color in the font /// attributes fileprivate func setupFontAttributes() { fontAttributes = [ NSFontAttributeName : font, NSForegroundColorAttributeName: textColor ] } /// Overridden method used to drawing the glyphs background. Instead, we /// figure out the line number for the glyph and draw that in the gutter. /// /// - parameter glyphsToShow: A range of the glyphs that need to updated /// - parameter atPoint: origin point override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) { super.drawBackground(forGlyphRange: glyphsToShow, at: origin) // Enumerate over the lines that need refresh enumerateLineFragments(forGlyphRange: glyphsToShow) { rect, usedRect, textContainer, glyphRange, stop in let charRange = self.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil) let before = (self.textStorage!.string as NSString) .substring(to: charRange.location) let lineNumber = before .components( separatedBy: CharacterSet.newlines).count let r = CGRect(x: 0, y: rect.origin.y, width: self.gutterWidth, height: rect.size.height) let gutterRect = r.offsetBy(dx: origin.x, dy: origin.y) let s = String(format: "%ld", lineNumber) let size = s.size(attributes: self.fontAttributes) let ds = gutterRect.offsetBy(dx: gutterRect.width - 4 - size.width, dy: (gutterRect.height - size.height) / 2.0) s.draw(in: ds, withAttributes: self.fontAttributes) } } }
mit
dbe3a3fb2c83ffc26955915a18ebc165
37.28972
91
0.643886
4.990256
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsComponents/SettingsSectionViewModel/SettingsSectionType.swift
1
5233
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import PlatformUIKit import RxDataSources enum SettingsSectionType: Int, Equatable { case referral = 0 case profile = 1 case preferences = 2 case connect = 3 case security = 4 case banks = 5 case cards = 6 case help = 7 enum CellType: Equatable, IdentifiableType { var identity: AnyHashable { switch self { case .badge(let type, _): return type.rawValue case .banks(let type): return type.identity case .cards(let type): return type.identity case .clipboard(let type): return type.rawValue case .common(let type): return type.rawValue case .switch(let type, _): return type.rawValue case .refferal(let type, _): return type.rawValue } } static func == (lhs: SettingsSectionType.CellType, rhs: SettingsSectionType.CellType) -> Bool { switch (lhs, rhs) { case (.badge(let left, _), .badge(let right, _)): return left == right case (.switch(let left, _), .switch(let right, _)): return left == right case (.clipboard(let left), .clipboard(let right)): return left == right case (.cards(let left), .cards(let right)): return left == right case (.common(let left), .common(let right)): return left == right case (.banks(let left), .banks(let right)): return left == right case (.refferal(let left, _), .refferal(let right, _)): return left == right default: return false } } case badge(BadgeCellType, BadgeCellPresenting) case `switch`(SwitchCellType, SwitchCellPresenting) case clipboard(ClipboardCellType) case cards(LinkedPaymentMethodCellType<AddPaymentMethodCellPresenter, LinkedCardCellPresenter>) case banks(LinkedPaymentMethodCellType<AddPaymentMethodCellPresenter, BeneficiaryLinkedBankViewModel>) case common(CommonCellType) case refferal(ReferralCellType, ReferralTableViewCellViewModel) enum BadgeCellType: String { case limits case emailVerification case mobileVerification case currencyPreference case tradingCurrencyPreference case pitConnection case recoveryPhrase case cardIssuing } enum SwitchCellType: String { case cloudBackup case sms2FA case emailNotifications case balanceSyncing case bioAuthentication } enum ClipboardCellType: String { case walletID } enum ReferralCellType: String { case referral } /// Any payment method can get under this category enum LinkedPaymentMethodCellType< AddNewCellPresenter: IdentifiableType, LinkedCellPresenter: Equatable & IdentifiableType >: Equatable, IdentifiableType { var identity: AnyHashable { switch self { case .skeleton(let index): return "skeleton.\(index)" case .add(let presenter): return presenter.identity case .linked(let presenter): return presenter.identity } } case skeleton(Int) case linked(LinkedCellPresenter) case add(AddNewCellPresenter) static func == ( lhs: SettingsSectionType.CellType.LinkedPaymentMethodCellType<AddNewCellPresenter, LinkedCellPresenter>, rhs: SettingsSectionType.CellType.LinkedPaymentMethodCellType<AddNewCellPresenter, LinkedCellPresenter> ) -> Bool { switch (lhs, rhs) { case (.skeleton(let left), .skeleton(let right)): return left == right case (.linked(let left), .linked(let right)): return left == right case (.add(let lhsPresenter), .add(let rhsPresenter)): return lhsPresenter.identity == rhsPresenter.identity default: return false } } } enum CommonCellType: String { case loginToWebWallet case webLogin case changePassword case changePIN case rateUs case termsOfService case privacyPolicy case cookiesPolicy case logout case addresses case contactSupport case cardIssuing case notifications case userDeletion } } } extension SettingsSectionType { static let `default`: [SettingsSectionType] = [ .referral, .profile, .preferences, .security, .help ] }
lgpl-3.0
96428f51aa0bd9c69f041ccff91a904c
32.113924
120
0.550459
5.787611
false
false
false
false
KevinGong2013/Printer
Sources/Printer/Ticket/ESC_POSCommand.swift
1
3975
// // ESC_POSCommand.swift // Ticket // // Created by gix on 2019/6/30. // Copyright © 2019 gix. All rights reserved. // import Foundation extension Data { init(esc_pos cmd: ESC_POSCommand...) { self.init(cmd.reduce([], { (r, cmd) -> [UInt8] in return r + cmd.rawValue })) } static var reset: Data { return Data(esc_pos: .initialize) } static func print(_ feed: UInt8) -> Data { return Data(esc_pos: .feed(points: feed)) } } public struct ESC_POSCommand: RawRepresentable { public typealias RawValue = [UInt8] public let rawValue: [UInt8] public init(rawValue: [UInt8]) { self.rawValue = rawValue } public init(_ rawValue: [UInt8]) { self.rawValue = rawValue } } // ref: http://content.epson.de/fileadmin/content/files/RSD/downloads/escpos.pdf //Control Commands extension ESC_POSCommand { // Clears the data in the print buffer and resets the printer modes to the modes that were in effect when the power was turned on. static let initialize = ESC_POSCommand(rawValue: [27, 64]) // Prints the data in the print buffer and feeds n lines. static func printAndFeed(lines: UInt8 = 1) -> ESC_POSCommand { return ESC_POSCommand([27, 100, lines]) } static func feed(points: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 74, points]) } // Prints the data in the print buffer and feeds n lines in the reverse direction. static func printAndReverseFeed(lines: UInt8 = 1) -> ESC_POSCommand { return ESC_POSCommand([27, 101, lines]) } // Turn emphasized mode on/off static func emphasize(mode: Bool) -> ESC_POSCommand { return ESC_POSCommand([27, 69, mode ? 1 : 0]) } // Select character font static func font(_ n: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 77, n]) } // Selects the printing color specified by n static func color(n: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 114, n]) } // Turn white/black reverse printing mode on/off static func whiteBlackReverse(mode: Bool) -> ESC_POSCommand { return ESC_POSCommand([29, 66, mode ? 1 : 0]) } // Aligns all the data in one line to the position specified by n as follows: static func justification(_ n: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 97, n]) } // Selects the character font and styles (emphasize, double-height, double-width, and underline) together. static func print(modes n: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 33, n]) } // Turns underline mode on or off static func underline(mode: UInt8) -> ESC_POSCommand { return ESC_POSCommand([27, 45, mode]) } enum ImageSize: UInt8 { case normal = 48 case doubleWidth = 49 case doubleHeight = 50 case doubleSize = 51 } // modified Pradeep Sakharelia 18/05/2019 static func beginPrintImage(m: ImageSize = .normal, xl: UInt8, xH: UInt8, yl: UInt8, yH: UInt8) -> ESC_POSCommand { return ESC_POSCommand(rawValue: [29, 118, 48, m.rawValue, xl, xH, yl, yH]) } // Configure QR static func QRSetSize(point: UInt8 = 8) -> ESC_POSCommand { return ESC_POSCommand([29, 40, 107, 3, 0, 49, 67, point]) } static func QRSetRecoveryLevel() -> ESC_POSCommand { return ESC_POSCommand(rawValue: [29, 40, 107, 3, 0, 49, 69, 51]) } static func QRGetReadyToStore(text: String) -> ESC_POSCommand { let s = text.count + 3 let pl = s % 256 let ph = s / 256 return ESC_POSCommand([29, 40, 107, UInt8(pl), UInt8(ph), 49, 80, 48]) } static func QRPrint() -> ESC_POSCommand { return ESC_POSCommand([29, 40, 107, 3, 0, 49, 81, 48]) } }
apache-2.0
cac4f6c84e52e85bdf9201bdd09d963e
28.879699
134
0.601409
3.669437
false
false
false
false
huonw/swift
stdlib/public/SDK/Foundation/CharacterSet.swift
3
32203
//===----------------------------------------------------------------------===// // // 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 Foundation // Clang module import CoreFoundation import _SwiftCoreFoundationOverlayShims import _SwiftFoundationOverlayShims private func _utfRangeToCFRange(_ inRange : Range<Unicode.Scalar>) -> CFRange { return CFRange( location: Int(inRange.lowerBound.value), length: Int(inRange.upperBound.value - inRange.lowerBound.value)) } private func _utfRangeToCFRange(_ inRange : ClosedRange<Unicode.Scalar>) -> CFRange { return CFRange( location: Int(inRange.lowerBound.value), length: Int(inRange.upperBound.value - inRange.lowerBound.value + 1)) } // MARK: - fileprivate final class _CharacterSetStorage : Hashable { fileprivate enum Backing { case immutable(CFCharacterSet) case mutable(CFMutableCharacterSet) } fileprivate var _backing : Backing @nonobjc init(immutableReference r : CFCharacterSet) { _backing = .immutable(r) } @nonobjc init(mutableReference r : CFMutableCharacterSet) { _backing = .mutable(r) } // MARK: - fileprivate var hashValue : Int { switch _backing { case .immutable(let cs): return Int(CFHash(cs)) case .mutable(let cs): return Int(CFHash(cs)) } } fileprivate static func ==(_ lhs : _CharacterSetStorage, _ rhs : _CharacterSetStorage) -> Bool { switch (lhs._backing, rhs._backing) { case (.immutable(let cs1), .immutable(let cs2)): return CFEqual(cs1, cs2) case (.immutable(let cs1), .mutable(let cs2)): return CFEqual(cs1, cs2) case (.mutable(let cs1), .immutable(let cs2)): return CFEqual(cs1, cs2) case (.mutable(let cs1), .mutable(let cs2)): return CFEqual(cs1, cs2) } } // MARK: - fileprivate func mutableCopy() -> _CharacterSetStorage { switch _backing { case .immutable(let cs): return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs)) case .mutable(let cs): return _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutableCopy(nil, cs)) } } // MARK: Immutable Functions fileprivate var bitmapRepresentation : Data { switch _backing { case .immutable(let cs): return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data case .mutable(let cs): return CFCharacterSetCreateBitmapRepresentation(nil, cs) as Data } } fileprivate func hasMember(inPlane plane: UInt8) -> Bool { switch _backing { case .immutable(let cs): return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane)) case .mutable(let cs): return CFCharacterSetHasMemberInPlane(cs, CFIndex(plane)) } } // MARK: Mutable functions fileprivate func insert(charactersIn range: Range<Unicode.Scalar>) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range)) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range)) } } fileprivate func insert(charactersIn range: ClosedRange<Unicode.Scalar>) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetAddCharactersInRange(r, _utfRangeToCFRange(range)) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetAddCharactersInRange(cs, _utfRangeToCFRange(range)) } } fileprivate func remove(charactersIn range: Range<Unicode.Scalar>) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range)) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range)) } } fileprivate func remove(charactersIn range: ClosedRange<Unicode.Scalar>) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetRemoveCharactersInRange(r, _utfRangeToCFRange(range)) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetRemoveCharactersInRange(cs, _utfRangeToCFRange(range)) } } fileprivate func insert(charactersIn string: String) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetAddCharactersInString(r, string as CFString) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetAddCharactersInString(cs, string as CFString) } } fileprivate func remove(charactersIn string: String) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetRemoveCharactersInString(r, string as CFString) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetRemoveCharactersInString(cs, string as CFString) } } fileprivate func invert() { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! CFCharacterSetInvert(r) _backing = .mutable(r) case .mutable(let cs): CFCharacterSetInvert(cs) } } // ----- // MARK: - // MARK: SetAlgebraType @discardableResult fileprivate func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) { insert(charactersIn: character...character) // TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet return (true, character) } @discardableResult fileprivate func update(with character: Unicode.Scalar) -> Unicode.Scalar? { insert(character) // TODO: This should probably return the truth, but figuring it out requires two calls into NSCharacterSet return character } @discardableResult fileprivate func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? { // TODO: Add method to CFCharacterSet to do this in one call let result : Unicode.Scalar? = contains(character) ? character : nil remove(charactersIn: character...character) return result } fileprivate func contains(_ member: Unicode.Scalar) -> Bool { switch _backing { case .immutable(let cs): return CFCharacterSetIsLongCharacterMember(cs, member.value) case .mutable(let cs): return CFCharacterSetIsLongCharacterMember(cs, member.value) } } // MARK: - // Why do these return CharacterSet instead of CharacterSetStorage? // We want to keep the knowledge of if the returned value happened to contain a mutable or immutable CFCharacterSet as close to the creation of that instance as possible // When the underlying collection does not have a method to return new CharacterSets with changes applied, so we will copy and apply here private static func _apply(_ lhs : _CharacterSetStorage, _ rhs : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) -> CharacterSet { let copyOfMe : CFMutableCharacterSet switch lhs._backing { case .immutable(let cs): copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)! case .mutable(let cs): copyOfMe = CFCharacterSetCreateMutableCopy(nil, cs)! } switch rhs._backing { case .immutable(let cs): f(copyOfMe, cs) case .mutable(let cs): f(copyOfMe, cs) } return CharacterSet(_uncopiedStorage: _CharacterSetStorage(mutableReference: copyOfMe)) } private func _applyMutation(_ other : _CharacterSetStorage, _ f : (CFMutableCharacterSet, CFCharacterSet) -> ()) { switch _backing { case .immutable(let cs): let r = CFCharacterSetCreateMutableCopy(nil, cs)! switch other._backing { case .immutable(let otherCs): f(r, otherCs) case .mutable(let otherCs): f(r, otherCs) } _backing = .mutable(r) case .mutable(let cs): switch other._backing { case .immutable(let otherCs): f(cs, otherCs) case .mutable(let otherCs): f(cs, otherCs) } } } fileprivate var inverted : CharacterSet { switch _backing { case .immutable(let cs): return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs))) case .mutable(let cs): // Even if input is mutable, the result is immutable return CharacterSet(_uncopiedStorage: _CharacterSetStorage(immutableReference: CFCharacterSetCreateInvertedSet(nil, cs))) } } fileprivate func union(_ other: _CharacterSetStorage) -> CharacterSet { return _CharacterSetStorage._apply(self, other, CFCharacterSetUnion) } fileprivate func formUnion(_ other: _CharacterSetStorage) { _applyMutation(other, CFCharacterSetUnion) } fileprivate func intersection(_ other: _CharacterSetStorage) -> CharacterSet { return _CharacterSetStorage._apply(self, other, CFCharacterSetIntersect) } fileprivate func formIntersection(_ other: _CharacterSetStorage) { _applyMutation(other, CFCharacterSetIntersect) } fileprivate func subtracting(_ other: _CharacterSetStorage) -> CharacterSet { return intersection(other.inverted._storage) } fileprivate func subtract(_ other: _CharacterSetStorage) { _applyMutation(other.inverted._storage, CFCharacterSetIntersect) } fileprivate func symmetricDifference(_ other: _CharacterSetStorage) -> CharacterSet { return union(other).subtracting(intersection(other)) } fileprivate func formSymmetricDifference(_ other: _CharacterSetStorage) { // This feels like cheating _backing = symmetricDifference(other)._storage._backing } fileprivate func isSuperset(of other: _CharacterSetStorage) -> Bool { switch _backing { case .immutable(let cs): switch other._backing { case .immutable(let otherCs): return CFCharacterSetIsSupersetOfSet(cs, otherCs) case .mutable(let otherCs): return CFCharacterSetIsSupersetOfSet(cs, otherCs) } case .mutable(let cs): switch other._backing { case .immutable(let otherCs): return CFCharacterSetIsSupersetOfSet(cs, otherCs) case .mutable(let otherCs): return CFCharacterSetIsSupersetOfSet(cs, otherCs) } } } // MARK: - fileprivate var description: String { switch _backing { case .immutable(let cs): return CFCopyDescription(cs) as String case .mutable(let cs): return CFCopyDescription(cs) as String } } fileprivate var debugDescription: String { return description } // MARK: - public func bridgedReference() -> NSCharacterSet { switch _backing { case .immutable(let cs): return cs as NSCharacterSet case .mutable(let cs): return cs as NSCharacterSet } } } // MARK: - /** A `CharacterSet` represents a set of Unicode-compliant characters. Foundation types use `CharacterSet` to group characters together for searching operations, so that they can find any of a particular set of characters during a search. This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSCharacterSet` class. */ public struct CharacterSet : ReferenceConvertible, Equatable, Hashable, SetAlgebra { public typealias ReferenceType = NSCharacterSet fileprivate var _storage : _CharacterSetStorage // MARK: Init methods /// Initialize an empty instance. public init() { // It's unlikely that we are creating an empty character set with no intention to mutate it _storage = _CharacterSetStorage(mutableReference: CFCharacterSetCreateMutable(nil)) } /// Initialize with a range of integers. /// /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired. public init(charactersIn range: Range<Unicode.Scalar>) { _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range))) } /// Initialize with a closed range of integers. /// /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired. public init(charactersIn range: ClosedRange<Unicode.Scalar>) { _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInRange(nil, _utfRangeToCFRange(range))) } /// Initialize with the characters in the given string. /// /// - parameter string: The string content to inspect for characters. public init(charactersIn string: String) { _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithCharactersInString(nil, string as CFString)) } /// Initialize with a bitmap representation. /// /// This method is useful for creating a character set object with data from a file or other external data source. /// - parameter data: The bitmap representation. public init(bitmapRepresentation data: Data) { _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData)) } /// Initialize with the contents of a file. /// /// Returns `nil` if there was an error reading the file. /// - parameter file: The file to read. public init?(contentsOfFile file: String) { do { let data = try Data(contentsOf: URL(fileURLWithPath: file), options: .mappedIfSafe) _storage = _CharacterSetStorage(immutableReference: CFCharacterSetCreateWithBitmapRepresentation(nil, data as CFData)) } catch { return nil } } fileprivate init(_bridged characterSet: NSCharacterSet) { _storage = _CharacterSetStorage(immutableReference: characterSet.copy() as! CFCharacterSet) } fileprivate init(_uncopiedImmutableReference characterSet: CFCharacterSet) { _storage = _CharacterSetStorage(immutableReference: characterSet) } fileprivate init(_uncopiedStorage : _CharacterSetStorage) { _storage = _uncopiedStorage } fileprivate init(_builtIn: CFCharacterSetPredefinedSet) { _storage = _CharacterSetStorage(immutableReference: CFCharacterSetGetPredefined(_builtIn)) } // MARK: Static functions /// Returns a character set containing the characters in Unicode General Category Cc and Cf. public static var controlCharacters : CharacterSet { return CharacterSet(_builtIn: .control) } /// Returns a character set containing the characters in Unicode General Category Zs and `CHARACTER TABULATION (U+0009)`. public static var whitespaces : CharacterSet { return CharacterSet(_builtIn: .whitespace) } /// Returns a character set containing characters in Unicode General Category Z*, `U+000A ~ U+000D`, and `U+0085`. public static var whitespacesAndNewlines : CharacterSet { return CharacterSet(_builtIn: .whitespaceAndNewline) } /// Returns a character set containing the characters in the category of Decimal Numbers. public static var decimalDigits : CharacterSet { return CharacterSet(_builtIn: .decimalDigit) } /// Returns a character set containing the characters in Unicode General Category L* & M*. public static var letters : CharacterSet { return CharacterSet(_builtIn: .letter) } /// Returns a character set containing the characters in Unicode General Category Ll. public static var lowercaseLetters : CharacterSet { return CharacterSet(_builtIn: .lowercaseLetter) } /// Returns a character set containing the characters in Unicode General Category Lu and Lt. public static var uppercaseLetters : CharacterSet { return CharacterSet(_builtIn: .uppercaseLetter) } /// Returns a character set containing the characters in Unicode General Category M*. public static var nonBaseCharacters : CharacterSet { return CharacterSet(_builtIn: .nonBase) } /// Returns a character set containing the characters in Unicode General Categories L*, M*, and N*. public static var alphanumerics : CharacterSet { return CharacterSet(_builtIn: .alphaNumeric) } /// Returns a character set containing individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of "standard decomposition" in version 3.2 of the Unicode character encoding standard. public static var decomposables : CharacterSet { return CharacterSet(_builtIn: .decomposable) } /// Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard. public static var illegalCharacters : CharacterSet { return CharacterSet(_builtIn: .illegal) } @available(*, unavailable, renamed: "punctuationCharacters") public static var punctuation : CharacterSet { return CharacterSet(_builtIn: .punctuation) } /// Returns a character set containing the characters in Unicode General Category P*. public static var punctuationCharacters : CharacterSet { return CharacterSet(_builtIn: .punctuation) } /// Returns a character set containing the characters in Unicode General Category Lt. public static var capitalizedLetters : CharacterSet { return CharacterSet(_builtIn: .capitalizedLetter) } /// Returns a character set containing the characters in Unicode General Category S*. public static var symbols : CharacterSet { return CharacterSet(_builtIn: .symbol) } /// Returns a character set containing the newline characters (`U+000A ~ U+000D`, `U+0085`, `U+2028`, and `U+2029`). public static var newlines : CharacterSet { return CharacterSet(_builtIn: .newline) } // MARK: Static functions, from NSURL /// Returns the character set for characters allowed in a user URL subcomponent. public static var urlUserAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLUserAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLUserAllowedCharacterSet() as! NSCharacterSet) } } /// Returns the character set for characters allowed in a password URL subcomponent. public static var urlPasswordAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPasswordAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPasswordAllowedCharacterSet() as! NSCharacterSet) } } /// Returns the character set for characters allowed in a host URL subcomponent. public static var urlHostAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLHostAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLHostAllowedCharacterSet() as! NSCharacterSet) } } /// Returns the character set for characters allowed in a path URL component. public static var urlPathAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLPathAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLPathAllowedCharacterSet() as! NSCharacterSet) } } /// Returns the character set for characters allowed in a query URL component. public static var urlQueryAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLQueryAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLQueryAllowedCharacterSet() as! NSCharacterSet) } } /// Returns the character set for characters allowed in a fragment URL component. public static var urlFragmentAllowed : CharacterSet { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return CharacterSet(_uncopiedImmutableReference: _CFURLComponentsGetURLFragmentAllowedCharacterSet() as NSCharacterSet) } else { return CharacterSet(_uncopiedImmutableReference: _NSURLComponentsGetURLFragmentAllowedCharacterSet() as! NSCharacterSet) } } // MARK: Immutable functions /// Returns a representation of the `CharacterSet` in binary format. @nonobjc public var bitmapRepresentation: Data { return _storage.bitmapRepresentation } /// Returns an inverted copy of the receiver. @nonobjc public var inverted : CharacterSet { return _storage.inverted } /// Returns true if the `CharacterSet` has a member in the specified plane. /// /// This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane (BMP) is plane 0. public func hasMember(inPlane plane: UInt8) -> Bool { return _storage.hasMember(inPlane: plane) } // MARK: Mutable functions /// Insert a range of integer values in the `CharacterSet`. /// /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired. public mutating func insert(charactersIn range: Range<Unicode.Scalar>) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.insert(charactersIn: range) } /// Insert a closed range of integer values in the `CharacterSet`. /// /// It is the caller's responsibility to ensure that the values represent valid `Unicode.Scalar` values, if that is what is desired. public mutating func insert(charactersIn range: ClosedRange<Unicode.Scalar>) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.insert(charactersIn: range) } /// Remove a range of integer values from the `CharacterSet`. public mutating func remove(charactersIn range: Range<Unicode.Scalar>) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.remove(charactersIn: range) } /// Remove a closed range of integer values from the `CharacterSet`. public mutating func remove(charactersIn range: ClosedRange<Unicode.Scalar>) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.remove(charactersIn: range) } /// Insert the values from the specified string into the `CharacterSet`. public mutating func insert(charactersIn string: String) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.insert(charactersIn: string) } /// Remove the values from the specified string from the `CharacterSet`. public mutating func remove(charactersIn string: String) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.remove(charactersIn: string) } /// Invert the contents of the `CharacterSet`. public mutating func invert() { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.invert() } // ----- // MARK: - // MARK: SetAlgebraType /// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`. /// /// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func insert(_ character: Unicode.Scalar) -> (inserted: Bool, memberAfterInsert: Unicode.Scalar) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } return _storage.insert(character) } /// Insert a `Unicode.Scalar` representation of a character into the `CharacterSet`. /// /// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func update(with character: Unicode.Scalar) -> Unicode.Scalar? { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } return _storage.update(with: character) } /// Remove a `Unicode.Scalar` representation of a character from the `CharacterSet`. /// /// `Unicode.Scalar` values are available on `Swift.String.UnicodeScalarView`. @discardableResult public mutating func remove(_ character: Unicode.Scalar) -> Unicode.Scalar? { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } return _storage.remove(character) } /// Test for membership of a particular `Unicode.Scalar` in the `CharacterSet`. public func contains(_ member: Unicode.Scalar) -> Bool { return _storage.contains(member) } /// Returns a union of the `CharacterSet` with another `CharacterSet`. public func union(_ other: CharacterSet) -> CharacterSet { return _storage.union(other._storage) } /// Sets the value to a union of the `CharacterSet` with another `CharacterSet`. public mutating func formUnion(_ other: CharacterSet) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.formUnion(other._storage) } /// Returns an intersection of the `CharacterSet` with another `CharacterSet`. public func intersection(_ other: CharacterSet) -> CharacterSet { return _storage.intersection(other._storage) } /// Sets the value to an intersection of the `CharacterSet` with another `CharacterSet`. public mutating func formIntersection(_ other: CharacterSet) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.formIntersection(other._storage) } /// Returns a `CharacterSet` created by removing elements in `other` from `self`. public func subtracting(_ other: CharacterSet) -> CharacterSet { return _storage.subtracting(other._storage) } /// Sets the value to a `CharacterSet` created by removing elements in `other` from `self`. public mutating func subtract(_ other: CharacterSet) { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.mutableCopy() } _storage.subtract(other._storage) } /// Returns an exclusive or of the `CharacterSet` with another `CharacterSet`. public func symmetricDifference(_ other: CharacterSet) -> CharacterSet { return _storage.symmetricDifference(other._storage) } /// Sets the value to an exclusive or of the `CharacterSet` with another `CharacterSet`. public mutating func formSymmetricDifference(_ other: CharacterSet) { self = symmetricDifference(other) } /// Returns true if `self` is a superset of `other`. public func isSuperset(of other: CharacterSet) -> Bool { return _storage.isSuperset(of: other._storage) } // MARK: - public var hashValue: Int { return _storage.hashValue } /// Returns true if the two `CharacterSet`s are equal. public static func ==(lhs : CharacterSet, rhs: CharacterSet) -> Bool { return lhs._storage == rhs._storage } } // MARK: Objective-C Bridging extension CharacterSet : _ObjectiveCBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSCharacterSet.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSCharacterSet { return _storage.bridgedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) { result = CharacterSet(_bridged: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSCharacterSet, result: inout CharacterSet?) -> Bool { result = CharacterSet(_bridged: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCharacterSet?) -> CharacterSet { guard let src = source else { return CharacterSet() } return CharacterSet(_bridged: src) } } extension CharacterSet : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return _storage.description } public var debugDescription: String { return _storage.debugDescription } } extension NSCharacterSet : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as CharacterSet) } } extension CharacterSet : Codable { private enum CodingKeys : Int, CodingKey { case bitmap } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let bitmap = try container.decode(Data.self, forKey: .bitmap) self.init(bitmapRepresentation: bitmap) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.bitmapRepresentation, forKey: .bitmap) } }
apache-2.0
29b2730bbf1d2da13e4e0369ba33c8a3
38.033939
274
0.658231
5.158257
false
false
false
false
snazzware/Mergel
HexMatch/HexMap/HCPosition.swift
2
1623
// // HCPosition.swift // HexMatch // // Created by Josh McKee on 2/5/16. // Copyright © 2016 Josh McKee. All rights reserved. // import Foundation class HCPosition : NSObject { var x: Int var y: Int init(_ x: Int, _ y: Int) { self.x = x self.y = y super.init() } var north:HCPosition { get { return HCPosition(self.x,self.y+1) } } var northEast:HCPosition { get { if (self.x % 2 == 0) { // even return HCPosition(self.x+1,self.y+1) } else { return HCPosition(self.x+1,self.y) } } } var northWest:HCPosition { get { if (self.x % 2 == 0) { // even return HCPosition(self.x-1,self.y+1) } else { return HCPosition(self.x-1,self.y) } } } var south:HCPosition { get { return HCPosition(self.x,self.y-1) } } var southEast:HCPosition { get { if (self.x % 2 == 0) { // even return HCPosition(self.x+1,self.y) } else { return HCPosition(self.x+1,self.y-1) } } } var southWest:HCPosition { get { if (self.x % 2 == 0) { // even return HCPosition(self.x-1,self.y) } else { return HCPosition(self.x-1,self.y-1) } } } override var description: String { return "\(self.x),\(self.y)" } }
mit
3742b23005660c749e5be693cb940095
20.077922
53
0.431566
3.6614
false
false
false
false
EZ-NET/ESGists
Sources/ESGists/API/Request/Scope.swift
1
3450
// // Scope.swift // ESGist // // Created by Tomohiro Kumagai on H27/07/21. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import Himotoki public enum Scope : String { /// Grants read-only access to public information (includes public user profile info, public repository info, and gists) case None = "" /// Grants read/write access to profile info only. Note that this scope includes user:email and user:follow. case User = "user" /// Grants read access to a user’s email addresses. case User_Email = "user:email" /// Grants access to follow or unfollow other users. case User_Follow = "user:follow" /// Grants read/write access to code, commit statuses, collaborators, and deployment statuses for public repositories and organizations. Also required for starring public repositories. case PublicRepo = "public_repo" /// Grants read/write access to code, commit statuses, collaborators, and deployment statuses for public and private repositories and organizations. case Repo = "repo" /// Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code. case RepoDeployment = "repo_deployment" /// Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code. case Repo_Status = "repo:status" /// Grants access to delete adminable repositories. case DeleteRepo = "delete_repo" /// Grants read access to a user’s notifications. repo also provides this access. case Notifications = "notifications" /// Grants write access to gists. case Gist = "gist" /// Grants read and ping access to hooks in public or private repositories. case Read_RepoHook = "read:repo_hook" /// Grants read, write, and ping access to hooks in public or private repositories. case Write_RepoHook = "write:repo_hook" /// Grants read, write, ping, and delete access to hooks in public or private repositories. case Admin_RepoHook = "admin:repo_hook" /// Grants read, write, ping, and delete access to organization hooks. Note: OAuth tokens will only be able to perform these actions on organization hooks which were created by the OAuth application. Personal access tokens will only be able to perform these actions on organization hooks created by a user. case Admin_OrgHook = "admin:org_hook" /// Read-only access to organization, teams, and membership. case Read_Org = "read:org" /// Publicize and unpublicize organization membership. case Write_Org = "write:org" /// Fully manage organization, teams, and memberships. case Admin_Org = "admin:org" /// List and view details for public keys. case Read_PublicKey = "read:public_key" /// Create, list, and view details for public keys. case Write_PublicKey = "write:public_key" /// Fully manage public keys. case Admin_PublicKey = "admin:public_key" } extension Scope : Decodable { public static func decode(e: Extractor) throws -> Scope { let string = try String.decode(e) guard let result = Scope(rawValue: string) else { throw DecodeError.TypeMismatch(expected: "\(DecodedType.self)", actual: "\(string)", keyPath: nil) } return result } }
mit
fa1a785dfa7a1e1b5ede6a881bca0cdf
37.211111
307
0.729282
4.055425
false
false
false
false
mfreiwald/RealDebridKit
RealDebridKit/Classes/Models/ErrorCode.swift
1
1251
// // ErrorCode.swift // Pods // // Created by Michael Freiwald on 24.11.16. // // import Foundation public enum ErrorCode : Int { case UnknownError = -500 case JsonReadError = -499 case InternalError = -1 case MissingParameter = 1 case BadParameterValue = 2 case UnknownMethod = 3 case MethodNotAllowed = 4 case SlowDown = 5 case RessourceUnreachable = 6 case ResourceNotFound = 7 case BadToken = 8 case PermissionDenied = 9 case TwoFactorAuthenticationNeeded = 10 case TwoFactorAuthenticationPending = 11 case InvalidLogin = 12 case InvalidPassword = 13 case AccountLocked = 14 case AccountNotActivated = 15 case UnsupportedHoster = 16 case HosterInMaintenance = 17 case HosterLimitReached = 18 case HosterTemporarilyUnavailable = 19 case HosterNotAvailableForFreeUsers = 20 case TooManyActiveDownloads = 21 case IpAddressNotAllowed = 22 case TrafficExhausted = 23 case FileUnavailable = 24 case ServiceUnavailable = 25 case UploadTooBig = 26 case UploadError = 27 case FileNotAllowed = 28 case TorrentTooBig = 29 case TorrentFileInvalid = 30 case ActionAlreadyDone = 31 case ImageResolutionError = 32 }
mit
bbcb911307aef7c821122ab8974a0363
25.617021
44
0.705835
4.516245
false
false
false
false
kesun421/firefox-ios
Extensions/SendTo/ClientPickerViewController.swift
3
13464
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage import SnapKit protocol ClientPickerViewControllerDelegate { func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) } struct ClientPickerViewControllerUX { static let TableHeaderRowHeight = CGFloat(50) static let TableHeaderTextFont = UIFont.systemFont(ofSize: 16) static let TableHeaderTextColor = UIColor.gray static let TableHeaderTextPaddingLeft = CGFloat(20) static let DeviceRowTintColor = UIColor(red: 0.427, green: 0.800, blue: 0.102, alpha: 1.0) static let DeviceRowHeight = CGFloat(50) static let DeviceRowTextFont = UIFont.systemFont(ofSize: 16) static let DeviceRowTextPaddingLeft = CGFloat(72) static let DeviceRowTextPaddingRight = CGFloat(50) } /// The ClientPickerViewController displays a list of clients associated with the provided Account. /// The user can select a number of devices and hit the Send button. /// This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. /// That is up to it's delegate, who can listen for cancellation and success events. class ClientPickerViewController: UITableViewController { var profile: Profile? var profileNeedsShutdown = true var clientPickerDelegate: ClientPickerViewControllerDelegate? var reloading = true var clients: [RemoteClient] = [] var selectedClients = NSMutableSet() // ShareItem has been added as we are now using this class outside of the ShareTo extension to provide Share To functionality // And in this case we need to be able to store the item we are sharing as we may not have access to the // url later. Currently used only when sharing an item from the Tab Tray from a Preview Action. var shareItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Send Tab", tableName: "SendTo", comment: "Title of the dialog that allows you to send a tab to a different device") refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(ClientPickerViewController.refresh), for: UIControlEvents.valueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem( title: Strings.SendToCancelButton, style: .plain, target: self, action: #selector(ClientPickerViewController.cancel) ) tableView.register(ClientPickerTableViewHeaderCell.self, forCellReuseIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier) tableView.register(ClientPickerTableViewCell.self, forCellReuseIdentifier: ClientPickerTableViewCell.CellIdentifier) tableView.register(ClientPickerNoClientsTableViewCell.self, forCellReuseIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier) tableView.tableFooterView = UIView(frame: CGRect.zero) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let refreshControl = refreshControl { refreshControl.beginRefreshing() let height = -(refreshControl.bounds.size.height + (self.navigationController?.navigationBar.bounds.size.height ?? 0)) self.tableView.contentOffset = CGPoint(x: 0, y: height) } reloadClients() } override func numberOfSections(in tableView: UITableView) -> Int { if clients.count == 0 { return 1 } else { return 2 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if clients.count == 0 { return 1 } else { if section == 0 { return 1 } else { return clients.count } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell if clients.count > 0 { if indexPath.section == 0 { cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewHeaderCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewHeaderCell } else { let clientCell = tableView.dequeueReusableCell(withIdentifier: ClientPickerTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerTableViewCell clientCell.nameLabel.text = clients[indexPath.row].name clientCell.clientType = clients[indexPath.row].type == "mobile" ? ClientType.Mobile : ClientType.Desktop clientCell.checked = selectedClients.contains(indexPath) cell = clientCell } } else { if reloading == false { cell = tableView.dequeueReusableCell(withIdentifier: ClientPickerNoClientsTableViewCell.CellIdentifier, for: indexPath) as! ClientPickerNoClientsTableViewCell } else { cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "ClientCell") } } return cell } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if clients.count > 0 && indexPath.section == 1 { tableView.deselectRow(at: indexPath, animated: true) if selectedClients.contains(indexPath) { selectedClients.remove(indexPath) } else { selectedClients.add(indexPath) } tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) navigationItem.rightBarButtonItem?.isEnabled = (selectedClients.count != 0) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if clients.count > 0 { if indexPath.section == 0 { return ClientPickerViewControllerUX.TableHeaderRowHeight } else { return ClientPickerViewControllerUX.DeviceRowHeight } } else { return tableView.frame.height } } fileprivate func reloadClients() { // If we were not given a profile, open the default profile. This happens in case we are called from an app // extension. That also means that we need to shut down the profile, otherwise the app extension will be // terminated when it goes into the background. if self.profile == nil { self.profile = BrowserProfile(localName: "profile") self.profileNeedsShutdown = true } guard let profile = self.profile else { return } // Re-open the profile it was shutdown. This happens when we run from an app extension, where we must // make sure that the profile is only open for brief moments of time. if profile.isShutdown { profile.reopen() } reloading = true profile.getClients().upon({ result in withExtendedLifetime(profile) { // If we are running from an app extension then make sure we shut down the profile as soon as we are // done with it. if self.profileNeedsShutdown { profile.shutdown() } self.reloading = false guard let c = result.successValue else { return } self.clients = c DispatchQueue.main.async { if self.clients.count == 0 { self.navigationItem.rightBarButtonItem = nil } else { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Send", tableName: "SendTo", comment: "Navigation bar button to Send the current page to a device"), style: UIBarButtonItemStyle.done, target: self, action: #selector(ClientPickerViewController.send)) self.navigationItem.rightBarButtonItem?.isEnabled = false } self.selectedClients.removeAllObjects() self.tableView.reloadData() self.refreshControl?.endRefreshing() } } }) } func refresh() { reloadClients() } func cancel() { clientPickerDelegate?.clientPickerViewControllerDidCancel(self) } func send() { var clients = [RemoteClient]() for indexPath in selectedClients { clients.append(self.clients[(indexPath as AnyObject).row]) } clientPickerDelegate?.clientPickerViewController(self, didPickClients: clients) // Replace the Send button with a loading indicator since it takes a while to sync // up our changes to the server. let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 25, height: 25)) loadingIndicator.color = .darkGray loadingIndicator.startAnimating() let customBarButton = UIBarButtonItem(customView: loadingIndicator) self.navigationItem.rightBarButtonItem = customBarButton } } class ClientPickerTableViewHeaderCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewSectionHeader" let nameLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.TableHeaderTextFont nameLabel.text = NSLocalizedString("Available devices:", tableName: "SendTo", comment: "Header for the list of devices table") nameLabel.textColor = ClientPickerViewControllerUX.TableHeaderTextColor nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.TableHeaderTextPaddingLeft) make.centerY.equalTo(self) make.right.equalTo(self) } preservesSuperviewLayoutMargins = false layoutMargins = UIEdgeInsets.zero separatorInset = UIEdgeInsets.zero } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public enum ClientType: String { case Mobile = "deviceTypeMobile" case Desktop = "deviceTypeDesktop" } class ClientPickerTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerTableViewCell" var nameLabel: UILabel var checked: Bool = false { didSet { self.accessoryType = checked ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none } } var clientType: ClientType = ClientType.Mobile { didSet { self.imageView?.image = UIImage(named: clientType.rawValue) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { nameLabel = UILabel() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) nameLabel.font = ClientPickerViewControllerUX.DeviceRowTextFont nameLabel.numberOfLines = 2 nameLabel.lineBreakMode = NSLineBreakMode.byWordWrapping self.tintColor = ClientPickerViewControllerUX.DeviceRowTintColor self.preservesSuperviewLayoutMargins = false self.selectionStyle = UITableViewCellSelectionStyle.none } override func layoutSubviews() { super.layoutSubviews() nameLabel.snp.makeConstraints { (make) -> Void in make.left.equalTo(ClientPickerViewControllerUX.DeviceRowTextPaddingLeft) make.centerY.equalTo(self.snp.centerY) make.right.equalTo(self.snp.right).offset(-ClientPickerViewControllerUX.DeviceRowTextPaddingRight) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class ClientPickerNoClientsTableViewCell: UITableViewCell { static let CellIdentifier = "ClientPickerNoClientsTableViewCell" override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupHelpView(contentView, introText: NSLocalizedString("You don’t have any other devices connected to this Firefox Account available to sync.", tableName: "SendTo", comment: "Error message shown in the remote tabs panel"), showMeText: "") // TODO We used to have a 'show me how to ...' text here. But, we cannot open web pages from the extension. So this is clear for now until we decide otherwise. // Move the separator off screen separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
e8879606d851cd6bfd60349dcfc3fb47
41.06875
306
0.671891
5.463474
false
false
false
false
tinypass/piano-sdk-for-ios
Sources/OAuth/OAuth/PianoIDError.swift
1
1001
import Foundation @objc public enum PianoIDError: Int, Error, CustomStringConvertible { case invalidAuthorizationUrl = -1 case cannotGetDeploymentHost = -2 case signInFailed = -3 case refreshFailed = -4 case signOutFailed = -5 case googleSignInFailed = -6 case facebookSignInFailed = -7 public var description: String { switch self { case .invalidAuthorizationUrl: return "Invalid authorization URL" case .cannotGetDeploymentHost: return "Cannot get deployment host for application" case .signInFailed: return "Sign in failed" case .refreshFailed: return "Refresh failed" case .signOutFailed: return "Sign out failed" case .googleSignInFailed: return "Google sign in failed" case .facebookSignInFailed: return "Facebook sign in failed" } } }
apache-2.0
b025f859432f695aa817ff2a4d581402
30.28125
67
0.593407
5.296296
false
false
false
false
Yalantis/EatFit
EatFit/Extensions/UIView+YALFrames.swift
1
4373
// // UIView+YALFrames.swift // EatFit // // Created by Dmitriy Demchenko on 7/12/16. // Copyright © 2016 Dmitriy Demchenko. All rights reserved. // import UIKit extension UIView { // MARK: - GETTERS func yal_x() -> CGFloat { return self.frame.origin.x } func yal_y() -> CGFloat { return self.frame.origin.y } func yal_width() -> CGFloat { return self.frame.size.width } func yal_height() -> CGFloat { return self.frame.size.height } func yal_rightEdge() -> CGFloat { return self.frame.origin.x + self.frame.size.width } func yal_bottomEdge() -> CGFloat { return self.frame.origin.y + self.frame.size.height } // MARK: - MOVE // MARK: absolute @discardableResult func yal_setX(_ x: CGFloat) -> UIView { var frame = self.frame frame.origin.x = x self.frame = frame return self } @discardableResult func yal_setY(_ y: CGFloat) -> UIView { var frame = self.frame frame.origin.y = y self.frame = frame return self } @discardableResult func yal_setOrigin(_ origin: CGPoint) -> UIView { var frame = self.frame frame.origin = origin self.frame = frame return self } @discardableResult func yal_placeBottomAt(_ bottomY: CGFloat) -> UIView { var frame = self.frame frame.origin.y = bottomY - self.frame.height self.frame = frame return self } @discardableResult func yal_placeRightAt(_ rightX: CGFloat) -> UIView { var frame = self.frame frame.origin.y = rightX - self.frame.width self.frame = frame return self } // MARK: offset @discardableResult func yal_moveX(_ x: CGFloat) -> UIView { var frame = self.frame frame.origin.x += x self.frame = frame return self } @discardableResult func yal_moveY(_ y: CGFloat) -> UIView { var frame = self.frame frame.origin.y += y self.frame = frame return self } // MARK: - CHANGE DIMENSIONS // MARK: absolute @discardableResult func yal_setWidth(_ width: CGFloat) -> UIView { var frame = self.frame frame.size.width = width self.frame = frame return self } @discardableResult func yal_setHeight(_ height: CGFloat) -> UIView { var frame = self.frame frame.size.height = height self.frame = frame return self } @discardableResult func yal_moveBottomEdgeTo(_ bottomY: CGFloat) -> UIView { var frame = self.frame frame.size.height = bottomY - frame.origin.y self.frame = frame return self } @discardableResult func yal_moveRightEdgeTo(_ rightX: CGFloat) -> UIView { var frame = self.frame frame.size.width = rightX - frame.origin.x self.frame = frame return self } // MARK: - relative @discardableResult func yal_trimTop(_ topOffset: CGFloat) -> UIView { var frame = self.frame frame.origin.y += topOffset frame.size.height -= topOffset self.frame = frame return self } @discardableResult func yal_trimBottom(_ bottomOffset: CGFloat) -> UIView { var frame = self.frame frame.size.height -= bottomOffset self.frame = frame return self } @discardableResult func yal_trimLeft(_ leftOffset: CGFloat) -> UIView { var frame = self.frame frame.origin.x += leftOffset frame.size.width -= leftOffset self.frame = frame return self } @discardableResult func yal_trimRight(_ rightOffset: CGFloat) -> UIView { var frame = self.frame frame.size.width -= rightOffset self.frame = frame return self } @discardableResult func yal_moveToCenterOf(_ view: UIView) -> UIView { var frame = self.frame let center = view.center frame.origin.x = center.x - self.yal_width() / 2 frame.origin.y = center.y - self.yal_height() / 2 self.frame = frame return self } }
mit
c07cad11d008ef29a2bb4bfad7fb984f
23.154696
61
0.5629
4.248785
false
false
false
false
ymedialabs/Swift-Notes
Swift-Notes.playground/Pages/17. Optional Chaining.xcplaygroundpage/Contents.swift
3
3012
//: # Swift Foundation //: ---- //: ## Optional Chaining //: ***Optional chaining*** is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. /*: Optional chaining return two values * if the optional contains a 'value' then calling its related property, methods and subscripts returns values * if the optional contains a 'nil' value all its its related property, methods and subscripts returns nil */ //: In simpler words, Optional chaining makes it easy to dig into multiple levels of optional values. Implicitly unwrapped (Forced unwrapped) optionals, while not as safe as normal optionals, are often used under the assumption that the value that it is describing is never, or usually not, nil. class PetOwner { var pet: Pet? } class Pet { var name: String var favoriteFood: PetFood? var allFoods = [PetFood]() init(name: String){ self.name = name } subscript(index: Int) -> PetFood { get { return allFoods[index] } set { allFoods[index] = newValue } } } class PetFood { var foodName: String = "" func printFood() { print("Fav food is \(foodName)") } } let arya = PetOwner() let nymeriaFood = arya.pet?.favoriteFood?.foodName //Result is of type String? //: Because the attempt to access `foodName` has the potential to fail, the optional chaining attempt returns a value of type String?, or “optional String”. Note that this is true even if `foodName` is a non-optional String. arya.pet = Pet(name: "Nymeria") //(1) arya.pet?.favoriteFood = PetFood() //(2) arya.pet?.favoriteFood?.foodName = "Chicken" //Let's comment out lines (1) and (2) one by one and see the result. if let favFood = arya.pet?.favoriteFood?.foodName { print("Fav. food is \(favFood)") } else { print("No fav. food 😔") } //: Instead of writing a series of `if let` checks to extract the value, Swift makes it easier and with less code by *Optional Chaining*. //: ### Accessing methods through optional chaining if arya.pet?.favoriteFood?.printFood() != nil { print("Fav. food was printed") } else { print("Could not print fav. food 😔") } //: The functiona `printFood()` doesn't return a value. But functions with no return type have an implicit return type of `Void` or an empty tuple `()`. //: Hence the resultant value will be of type `Void?` since the result of optional chaining is always an optional. //: ### Accessing subscripts through optional chaining arya.pet?.allFoods.append(PetFood()) let someFood = arya.pet?[0] //Place the ? before the square braces. //someFood is of type PetFood? someFood?.foodName //Accessing subscripts of optional type //: Place the question mark after the subscript’s closing bracket to chain on its optional return value let knights = ["Arthur": [98,90,93], "Barriston": [89,86,84]] knights["Arthur"]?[0] //: ---- //: [Next](@next)
mit
36695193ea26b32e314cb2d6abb500d6
29.30303
297
0.680333
3.870968
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Goodies/Localizer.swift
4
12273
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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. extension StandardLibrary { /** StandardLibrary.Localizer provides localization of Mustache sections or data. let localizer = StandardLibrary.Localizer(bundle: nil, table: nil) template.registerInBaseContext("localize", Box(localizer)) ### Localizing data: `{{ localize(greeting) }}` renders `NSLocalizedString(@"Hello", nil)`, assuming the `greeting` key resolves to the `Hello` string. ### Localizing sections: `{{#localize}}Hello{{/localize}}` renders `NSLocalizedString(@"Hello", nil)`. ### Localizing sections with arguments: `{{#localize}}Hello {{name}}{{/localize}}` builds the format string `Hello %@`, localizes it with NSLocalizedString, and finally injects the name with `String(format:...)`. ### Localize sections with arguments and conditions: `{{#localize}}Good morning {{#title}}{{title}}{{/title}} {{name}}{{/localize}}` build the format string `Good morning %@" or @"Good morning %@ %@`, depending on the presence of the `title` key. It then injects the name, or both title and name, with `String(format:...)`, to build the final rendering. */ public class Localizer : MustacheBoxable { /// The bundle public let bundle: NSBundle /// The table public let table: String? /** Returns a Localizer. :param: bundle The bundle where to look for localized strings. If nil, the main bundle is used. :param: table The table where to look for localized strings. If nil, the default Localizable.strings table would be used. */ public init(bundle: NSBundle?, table: String?) { self.bundle = bundle ?? NSBundle.mainBundle() self.table = table } /** `Localizer` conforms to the `MustacheBoxable` protocol so that it can feed Mustache templates. */ public var mustacheBox: MustacheBox { // Return a multi-facetted box, because Localizer interacts in // various ways with Mustache rendering. return Box( // It has a value value: self, // Localizer can be used as a filter: {{ localize(x) }}: filter: Filter(self.filter), // Localizer performs custom rendering, so that it can localize // the sections it is attached to: {{# localize }}Hello{{/ localize }}. render: self.render, // Localizer needs to observe the rendering of variables tags // inside the section it is attached to: {{# localize }}Hello {{ name }}{{/ localize }}. willRender: self.willRender, didRender: self.didRender) } // ===================================================================== // MARK: - Not public private var formatArguments: [String]? // This function is used for evaluating `localize(x)` expressions. private func filter(rendering: Rendering, error: NSErrorPointer) -> Rendering? { return Rendering(localizedStringForKey(rendering.string), rendering.contentType) } // This functionis used to render a {{# localize }}Hello{{/ localize }} section. private func render(info: RenderingInfo, error: NSErrorPointer) -> Rendering? { // Perform a first rendering of the section tag, that will turn // variable tags into a custom placeholder. // // "...{{name}}..." will get turned into "...GRMustacheLocalizerValuePlaceholder...". // // For that, we make sure we are notified of tag rendering, so that // our willRender(tag: Tag, box:) method has the tags render // GRMustacheLocalizerValuePlaceholder instead of the regular values. // // This behavior of willRender() is trigerred by the nil value of // self.formatArguments: formatArguments = nil // Push self in the context stack in order to trigger our // willRender() method. let context = info.context.extendedContext(Box(self)) // Render the localizable format string if let localizableFormatRendering = info.tag.render(context, error: error) { // Now perform a second rendering that will fill our // formatArguments array with HTML-escaped tag renderings. // // Now our willRender() method will let the tags render regular // values. Our didRender() method will grab those renderings, // and fill self.formatArguments. // // This behavior of willRender() is not the same as the previous // one, and is trigerred by the non-nil value of // self.formatArguments: formatArguments = [] // Render again info.tag.render(context) let rendering: Rendering if formatArguments!.isEmpty { // There is no format argument, which means no inner // variable tag: {{# localize }}plain text{{/ localize }} rendering = Rendering(localizedStringForKey(localizableFormatRendering.string), localizableFormatRendering.contentType) } else { // There are format arguments, which means inner variable // tags: {{# localize }}...{{ name }}...{{/ localize }}. // // Take special precaution with the "%" character: // // When rendering {{#localize}}%d {{name}}{{/localize}}, // the localizable format we need is "%%d %@". // // Yet the localizable format we have built so far is // "%d GRMustacheLocalizerValuePlaceholder". // // In order to get an actual format string, we have to: // - turn GRMustacheLocalizerValuePlaceholder into %@ // - escape % into %%. // // The format string will then be "%%d %@", as needed. let localizableFormat = localizableFormatRendering.string.stringByReplacingOccurrencesOfString("%", withString: "%%").stringByReplacingOccurrencesOfString(Placeholder.string, withString: "%@") // Now localize the format let localizedFormat = localizedStringForKey(localizableFormat) // Apply arguments let localizedRendering = stringWithFormat(format: localizedFormat, argumentsArray: formatArguments!) // And we have the final rendering rendering = Rendering(localizedRendering, localizableFormatRendering.contentType) } // Clean up formatArguments = nil // Done return rendering } else { // Error in the rendering of the inner content of the localized // section return nil } } private func willRender(tag: Tag, box: MustacheBox) -> MustacheBox { switch tag.type { case .Variable: // {{ value }} // // We behave as stated in the documentation of render(): if formatArguments == nil { return Box(Placeholder.string) } else { return box } case .Section: // {{# value }} // {{^ value }} // // We do not want to mess with Mustache handling of boolean and // loop sections such as {{#true}}...{{/}}. return box } } private func didRender(tag: Tag, box: MustacheBox, string: String?) { switch tag.type { case .Variable: // {{ value }} // // We behave as stated in the documentation of render(): if formatArguments != nil { if let string = string { formatArguments!.append(string) } } case .Section: // {{# value }} // {{^ value }} break } } private func localizedStringForKey(key: String) -> String { return bundle.localizedStringForKey(key, value:"", table:table) } private func stringWithFormat(#format: String, argumentsArray args:[String]) -> String { switch count(args) { case 0: return format case 1: return String(format: format, args[0]) case 2: return String(format: format, args[0], args[1]) case 3: return String(format: format, args[0], args[1], args[2]) case 4: return String(format: format, args[0], args[1], args[2], args[3]) case 5: return String(format: format, args[0], args[1], args[2], args[3], args[4]) case 6: return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5]) case 7: return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6]) case 8: return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]) case 9: return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]) case 10: return String(format: format, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]) default: fatalError("Not implemented: format with \(count(args)) parameters") } } struct Placeholder { static let string = "GRMustacheLocalizerValuePlaceholder" } } }
mit
d4136877470a8389c3a5bb16aecbf7cf
40.883959
212
0.519312
5.619048
false
false
false
false
laszlokorte/reform-swift
ReformApplication/ReformApplication/IfConditionInstructionDetailController.swift
1
2109
// // IfConditionInstructionDetailController.swift // Reform // // Created by Laszlo Korte on 06.10.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import Cocoa import ReformCore import ReformExpression class IfConditionInstructionDetailController : NSViewController, InstructionDetailController { @IBOutlet var errorLabel : NSTextField? @IBOutlet var conditionField : NSTextField? var stringifier : Stringifier? var parser : ((String) -> Result<ReformExpression.Expression, ShuntingYardError>)? var intend : (() -> ())? var error : String? { didSet { updateError() } } override var representedObject : Any? { didSet { updateLabel() } } override func viewDidLoad() { updateLabel() updateError() } func updateError() { if let error = error { errorLabel?.stringValue = error if let errorLabel = errorLabel { self.view.addSubview(errorLabel) } } else { errorLabel?.removeFromSuperview() } } func updateLabel() { guard let node = representedObject as? InstructionNode else { return } guard let instruction = node.instruction as? IfConditionInstruction else { return } guard let stringifier = stringifier else { return } conditionField?.stringValue = stringifier.stringFor(instruction.expression) ?? "" } @IBAction func onChange(_ sender: Any?) { guard let parser = parser, let string = conditionField?.stringValue, let intend = intend else { return } guard let node = representedObject as? InstructionNode else { return } switch parser(string) { case .success(let expr): node.replaceWith(IfConditionInstruction(expression: expr)) intend() case .fail(let err): print(err) } } }
mit
8c68a28aaeda813ee8b221c1243ce0e1
22.685393
94
0.573529
5.27
false
false
false
false
RedRoster/rr-ios
RedRoster/Roster/TermListViewController.swift
1
4065
// // TermListViewController.swift // RedRoster // // Created by Daniel Li on 3/27/16. // Copyright © 2016 dantheli. All rights reserved. // import UIKit import RealmSwift class TermListViewController: RosterViewController, UITableViewDataSource, UITableViewDelegate { var terms: Results<Term> = try! Realm().objects(Term.self) var termsDict: [Int:[Term]] = [:] var years: [Int] = [] override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Course Roster" setupTableView() setupRetryButton() fetch() } override func setupTableView() { super.setupTableView() tableView.register(UINib(nibName: "TermCell", bundle: nil), forCellReuseIdentifier: "TermCell") tableView.dataSource = self tableView.delegate = self tableView.rowHeight = 56.0 } override func fetch() { if terms.isEmpty { tableView.alpha = 0.0 setupActivityIndicator() } setupNotification(self.terms) NetworkManager.fetchTerms { error in self.activityIndicator?.removeFromSuperview() if let error = error { self.alert(errorMessage: error.localizedDescription) { Void in if self.terms.isEmpty { self.retryButton.fadeShow() } } } } } override func configureTableView() { if !terms.isEmpty { termsDict.removeAll() for term in terms { if termsDict[term.year] == nil { termsDict[term.year] = [term] } else { termsDict[term.year]?.insert(term, at: 0) } } for (year, terms) in termsDict { termsDict[year] = terms.sorted { $0.season.sortIndex < $1.season.sortIndex } } years = Array(termsDict.keys).sorted { $1 < $0 } tableView.reloadData() UIView.animate(withDuration: 0.25, animations: { self.tableView.alpha = 1.0 }) } } func numberOfSections(in tableView: UITableView) -> Int { return years.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return termsDict[years[section]]!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TermCell", for: indexPath) as! TermCell let year = years[indexPath.section] let term = termsDict[year]![indexPath.row] cell.backgroundColor = UIColor.rosterCellBackgroundColor() let background = UIView() background.backgroundColor = UIColor.rosterCellSelectionColor() cell.selectedBackgroundView = background cell.iconImageView.image = UIImage(named: term.season.description.lowercased()) cell.iconImageView.tintColor = UIColor.rosterCellTitleColor() cell.seasonLabel.textColor = UIColor.rosterCellTitleColor() cell.seasonLabel.text = term.season.description return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let term = termsDict[years[indexPath.section]]![indexPath.row] let subjectsViewController = SubjectsViewController() subjectsViewController.term = term navigationController?.pushViewController(subjectsViewController, animated: true) dismiss(animated: true, completion: nil) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "\(years[section])" } }
apache-2.0
f534dd7f1759fc3c3edbe24709a08030
31.512
105
0.5844
5.243871
false
false
false
false
box/box-ios-sdk
Sources/Requests/BodyData/FileRequestCopyRequest.swift
1
2690
// // FileRequestCopyRequest.swift // BoxSDK-iOS // // Created by Artur Jankowski on 09/08/2022. // Copyright © Box. All rights reserved. // import Foundation // The request body to copy a file request. public struct FileRequestCopyRequest: Encodable { // MARK: - Properties /// An optional new title for the file request. /// This can be used to change the title of the file request. public let title: String? /// An optional new description for the file request. /// This can be used to change the description of the file request. public let description: String? /// An optional new status of the file request. public let status: FileRequestStatus? /// Whether a file request submitter is required to provide their email address. /// When this setting is set to true, the Box UI will show an email field on the file request form. public let isEmailRequired: Bool? /// Whether a file request submitter is required to provide a description of the files they are submitting. /// When this setting is set to true, the Box UI will show a description field on the file request form. public let isDescriptionRequired: Bool? /// The date after which a file request will no longer accept new submissions. /// After this date, the `status` will automatically be set to `inactive`. public let expiresAt: Date? /// The folder to associate the new file request to. public let folder: FolderEntity /// Initializer. /// /// - Parameters: /// - title: An optional new title for the file request. /// - description: An optional new description for the file request. /// - status: An optional new status of the file request. /// - isEmailRequired: Whether a file request submitter is required to provide their email address. /// - isDescriptionRequired: Whether a file request submitter is required to provide a description of the files they are submitting. /// - expiresAt: The date after which a file request will no longer accept new submissions. /// - folder: The folder to associate the new file request to. public init( title: String? = nil, description: String? = nil, status: FileRequestStatus? = nil, isEmailRequired: Bool? = nil, isDescriptionRequired: Bool? = nil, expiresAt: Date? = nil, folder: FolderEntity ) { self.title = title self.description = description self.status = status self.isEmailRequired = isEmailRequired self.isDescriptionRequired = isDescriptionRequired self.expiresAt = expiresAt self.folder = folder } }
apache-2.0
0ca89ff24446703defe157e1af1bd5a2
41.68254
138
0.683897
4.628227
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Home/AccountCellContent.swift
2
6206
// // AccountCell.swift // Neocom // // Created by Artem Shimanski on 11/25/19. // Copyright © 2019 Artem Shimanski. All rights reserved. // import SwiftUI import EVEAPI import Expressible struct AccountCellContent: View { @Environment(\.managedObjectContext) private var managedObjectContext struct Subject { let name: String let image: Image? } struct Skill { var name: String var level: Int var trainingTime: TimeInterval } var character: Subject? var corporation: Subject? var alliance: Subject? var ship: String? var location: String? var sp: Int64? var isk: Double? var skill: ESI.SkillQueueItem? var skillQueue: Int? var error: Error? private var shipAndLocation: some View { HStack { Text(ship ?? "") Text(location ?? "").foregroundColor(.secondary) } } private var skills: some View { var skillName: String? var t: TimeInterval? var progress: Float? if let skill = self.skill { let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(skill.skillID)).first() let item = type.flatMap{Pilot.Skill(type: $0)}.map{Pilot.SkillQueueItem(skill: $0, queuedSkill: skill)} skillName = type?.typeName t = skill.finishDate?.timeIntervalSinceNow progress = item?.trainingProgress } return Group { HStack{ if skill != nil { SkillName(name: skillName ?? " ", level: skill!.finishedLevel) } else { Text(" ") } Spacer() t.map { t in Text(TimeIntervalFormatter.localizedString(from: t, precision: .minutes)) } }.padding(.horizontal).background(ProgressView(progress: progress ?? 0).accentColor(.skyBlueBackground)) Text(skillQueue.map{$0 > 0 ? "\($0) \(NSLocalizedString("skills in queue", comment: ""))" : NSLocalizedString("Skill queue is empty", comment: "")} ?? "") } } private var iskAndSP: some View { HStack { VStack(alignment: .trailing) { Text("SP:") Text("ISK:") }.foregroundColor(.skyBlue) VStack(alignment: .leading) { Text(sp.map{UnitFormatter.localizedString(from: $0, unit: .none, style: .short)} ?? "") Text(isk.map{UnitFormatter.localizedString(from: $0, unit: .none, style: .short)} ?? "") } }.frame(minWidth: 64) } private var characterName: some View { (character?.name).map{Text($0)}.font(.title2) } private var corporationAndAlliance: some View { HStack { (corporation?.name).map{Text($0)} (alliance?.name).map{ name in Group{ Text("/") Text(name) } } }.foregroundColor(.secondary) } var body: some View { HStack(alignment: .top, spacing: 15) { VStack(spacing: 8) { Avatar(image: character?.image).frame(width: 64, height: 64) if error == nil { iskAndSP } } if error != nil { VStack(alignment: .leading) { characterName Text(error!).foregroundColor(.secondary) .lineLimit(4) } } else { VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading) { characterName corporationAndAlliance }.frame(height: 64) VStack(alignment: .leading, spacing: 0) { shipAndLocation skills } } } } .font(.subheadline) .lineLimit(1) } } #if DEBUG struct AccountCellContent_Previews: PreviewProvider { static var previews: some View { let row = AccountCellContent(character: .init(name: "Artem Valiant", image: Image("character")), corporation: .init(name: "Necrorise Squadron", image: Image("corporation")), alliance: .init(name: "Red Alert", image: Image("alliance")), ship: "Dominix", location: "Rens VII, Moon 8", sp: 1000, isk: 1000, skill: ESI.SkillQueueItem(finishDate: Date(timeIntervalSinceNow: 360000), finishedLevel: 5, levelEndSP: 1000000, levelStartSP: 0, queuePosition: 0, skillID: 24313, startDate: Date(timeIntervalSinceNow: -3600), trainingStartSP: 0), skillQueue: 5).padding() return VStack { row.background(Color(UIColor.systemGroupedBackground)).colorScheme(.light) row.background(Color(UIColor.systemGroupedBackground)).colorScheme(.dark) AccountCellContent(character: nil, corporation: nil, alliance: nil, ship: nil, location: nil, sp: nil, isk: nil, skill: nil, skillQueue: nil, error: nil).padding().background(Color(UIColor.systemGroupedBackground)) } .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
adc41b38d07e7eb6bcb79fb45c679575
34.867052
166
0.472683
5.307956
false
false
false
false
jacobwhite/firefox-ios
Client/Frontend/Widgets/GradientProgressBar.swift
3
6587
/* 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/. */ // ADAPTED FROM: // // GradientProgressBar.swift // GradientProgressBar // // Created by Felix Mau on 01.03.17. // Copyright © 2017 Felix Mau. All rights reserved. // import UIKit open class GradientProgressBar: UIProgressView { private struct DefaultValues { static let backgroundColor = UIColor.clear static let animationDuration = 0.2 // CALayer default animation duration } var gradientColors: [CGColor] = [] // Alpha mask for visible part of gradient. private var alphaMaskLayer: CALayer = CALayer() // Gradient layer. open var gradientLayer: CAGradientLayer = CAGradientLayer() // Duration for "setProgress(animated: true)" open var animationDuration = DefaultValues.animationDuration // Workaround to handle orientation change, as "layoutSubviews()" gets triggered each time // the progress value is changed. override open var bounds: CGRect { didSet { updateAlphaMaskLayerWidth() } } // Update layer mask on direct changes to progress value. override open var progress: Float { didSet { updateAlphaMaskLayerWidth() } } func setGradientColors(startColor: UIColor, endColor: UIColor) { gradientColors = [startColor, endColor, startColor, endColor, startColor, endColor, startColor].map { $0.cgColor } gradientLayer.colors = gradientColors } func commonInit() { setupProgressViewColors() setupAlphaMaskLayer() setupGradientLayer() layer.insertSublayer(gradientLayer, at: 0) updateAlphaMaskLayerWidth() } override public init(frame: CGRect) { gradientColors = [] super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } // MARK: - Setup UIProgressView private func setupProgressViewColors() { backgroundColor = DefaultValues.backgroundColor trackTintColor = .clear progressTintColor = .clear } // MARK: - Setup layers private func setupAlphaMaskLayer() { alphaMaskLayer.frame = bounds alphaMaskLayer.cornerRadius = 3 alphaMaskLayer.anchorPoint = .zero alphaMaskLayer.position = .zero alphaMaskLayer.backgroundColor = UIColor.white.cgColor } private func setupGradientLayer() { // Apply "alphaMaskLayer" as a mask to the gradient layer in order to show only parts of the current "progress" gradientLayer.mask = alphaMaskLayer gradientLayer.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height) gradientLayer.colors = gradientColors gradientLayer.locations = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0] gradientLayer.startPoint = .zero gradientLayer.endPoint = CGPoint(x: 1, y: 0) gradientLayer.drawsAsynchronously = true } func hideProgressBar() { guard progress == 1 else { return } CATransaction.begin() let moveAnimation = CABasicAnimation(keyPath: "position") moveAnimation.duration = DefaultValues.animationDuration moveAnimation.fromValue = gradientLayer.position moveAnimation.toValue = CGPoint(x: gradientLayer.frame.width, y: gradientLayer.position.y) moveAnimation.fillMode = kCAFillModeForwards moveAnimation.isRemovedOnCompletion = false CATransaction.setCompletionBlock { self.resetProgressBar() } gradientLayer.add(moveAnimation, forKey: "position") CATransaction.commit() } func resetProgressBar() { // Call on super instead so no animation layers are created super.setProgress(0, animated: false) isHidden = true // The URLBar will unhide the view before starting the next animation. } override open func layoutSubviews() { super.layoutSubviews() self.gradientLayer.frame = CGRect(x: bounds.origin.x - 4, y: bounds.origin.y, width: bounds.size.width * 2, height: bounds.size.height) } func animateGradient() { let gradientChangeAnimation = CABasicAnimation(keyPath: "locations") gradientChangeAnimation.duration = DefaultValues.animationDuration * 4 gradientChangeAnimation.toValue = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.0] gradientChangeAnimation.fromValue = [0.0, 0.0, 0.0, 0.2, 0.4, 0.6, 0.8] gradientChangeAnimation.fillMode = kCAFillModeForwards gradientChangeAnimation.isRemovedOnCompletion = false gradientChangeAnimation.repeatCount = .infinity gradientLayer.add(gradientChangeAnimation, forKey: "colorChange") } // MARK: - Update gradient open func updateAlphaMaskLayerWidth(animated: Bool = false) { CATransaction.begin() // Workaround for non animated progress change // Source: https://stackoverflow.com/a/16381287/3532505 CATransaction.setAnimationDuration(animated ? DefaultValues.animationDuration : 0.0) alphaMaskLayer.frame = bounds.updateWidth(byPercentage: CGFloat(progress)) if progress == 1 { // Delay calling hide until the last animation has completed CATransaction.setCompletionBlock({ DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DefaultValues.animationDuration, execute: { self.hideProgressBar() }) }) } CATransaction.commit() } override open func setProgress(_ progress: Float, animated: Bool) { if progress < self.progress && self.progress != 1 { return } // Setup animations gradientLayer.removeAnimation(forKey: "position") if gradientLayer.animation(forKey: "colorChange") == nil { animateGradient() } super.setProgress(progress, animated: animated) updateAlphaMaskLayerWidth(animated: animated) } } extension CGRect { func updateWidth(byPercentage percentage: CGFloat) -> CGRect { return CGRect(x: origin.x, y: origin.y, width: size.width * percentage, height: size.height) } }
mpl-2.0
1030dc83605e5bcffc7cf3f671031d68
34.408602
143
0.651078
4.929641
false
false
false
false
fjbelchi/CodeTest-BoardingPass-Swift
BoardingCards/Models/BoardingPlanePass.swift
1
1653
// // BoardingPlanePass.swift // // Copyright (c) 2015 Francisco J. Belchi. All rights reserved. import Foundation public struct BoardingPlanePass : BoardingPassType { public let boardingId: String public let cityFrom: City public let cityTo: City public let flightNumber: String public let gate: String public let seatNumber: String public init?(boardingId: String, cityFrom: City, cityTo: City, flightNumber: String, gate: String, seat: String) { guard boardingId.characters.count != 0 else { return nil } guard seat.characters.count != 0 else { return nil } guard flightNumber.characters.count != 0 else { return nil } self.boardingId = boardingId self.cityFrom = cityFrom self.cityTo = cityTo self.flightNumber = flightNumber self.gate = gate self.seatNumber = seat } } // MARK: Hashable extension BoardingPlanePass : Hashable { public var hashValue : Int { return self.boardingId.hash } } // MARK: Equatable extension BoardingPlanePass : Equatable {} public func == (lhs: BoardingPlanePass, rhs: BoardingPlanePass) -> Bool { return lhs.boardingId == rhs.boardingId } // MARK: CustomStringConvertible extension BoardingPlanePass : CustomStringConvertible { public var description : String { return "BoardingPlanePass : id=\(self.boardingId), from=\(self.cityFrom.name), to=\(self.cityTo.name), seat=\(self.seatNumber), flightNumber=\(self.flightNumber), gate=\(self.gate), seat=\(self.seatNumber)" } }
mit
63af6496dfd4f877584be8bf71c7ae7d
26.114754
214
0.650938
4.408
false
false
false
false
RedRoma/Lexis-Database
LexisDatabase/FilePersistence.swift
1
3905
// // FilePersistence.swift // LexisDatabase // // Created by Wellington Moreno on 9/25/16. // Copyright © 2016 RedRoma, Inc. All rights reserved. // import Foundation import Archeota class FilePersistence: LexisPersistence { private let filePath = NSHomeDirectory().appending("/Library/Caches/LexisWords.json") static let instance = FilePersistence() private let parallelism = 6 private let async: OperationQueue private let serializer = BasicJSONSerializer.instance private init() { async = OperationQueue() async.maxConcurrentOperationCount = parallelism } func getAllWords() -> [LexisWord] { LOG.info("Reading words from file :\(filePath)") guard let json = try? String(contentsOfFile: filePath) else { LOG.info("Failed to read JSON from file \(filePath)") return [] } guard let array = serializer.fromJSON(jsonString: json) as? NSArray else { LOG.info("Words not found in file \(filePath)") return [] } LOG.info("Read \(array.count) words from file: \(filePath)") guard let objects = array as? [NSDictionary] else { LOG.info("Words found in incorrect format") return [] } LOG.info("Deserializing \(objects.count) words") let pieces = objects.split(into: parallelism) var lexisWords = [LexisWord]() LOG.debug("Converting objects in \(pieces.count) threads") var completed = 0 var stillWorking: Bool { return completed < pieces.count } let group = DispatchGroup() let semaphore = DispatchSemaphore(value: 1) for words in pieces { group.enter() async.addOperation { let convertedWords = words.compactMap() { dictionary in return (LexisWord.fromJSON(json: dictionary) as? LexisWord) } semaphore.wait() lexisWords += convertedWords semaphore.signal() LOG.debug("Converted \(convertedWords.count) words") completed += 1 group.leave() } } group.wait() LOG.info("Deserialized \(lexisWords.count) words") return lexisWords } func save(words: [LexisWord]) throws { LOG.info("Serializing \(words.count)") let array = words.compactMap() { $0.asJSON() as? NSDictionary } LOG.info("Serialized \(array.count) words from \(words.count)") let nsArray = NSArray(array: array) guard let jsonString = serializer.toJSON(object: nsArray) else { LOG.warn("Failed to convert array to JSON") throw LexisPersistenceError.ConversionError } LOG.info("Writing \(nsArray.count) words to JSON File: \(filePath)") do { try jsonString.write(toFile: filePath, atomically: true, encoding: .utf8) LOG.info("Wrote words to JSON file") } catch { LOG.error("Failed to write JSON to file \(filePath) : \(error)") throw LexisPersistenceError.IOError } } func removeAll() { let fileManager = FileManager() guard fileManager.fileExists(atPath: filePath) else { LOG.info("Skipping delete of file \(filePath) since it does not exist") return } do { try fileManager.removeItem(atPath: filePath) LOG.info("Deleted file at \(filePath)") } catch { LOG.error("Failed to delete file at \(filePath): \(error)") } } }
apache-2.0
77f15f303978967be3310c9be2c5731a
27.289855
89
0.550717
5.037419
false
false
false
false
blue42u/swift-t
stc/tests/681-app-target.swift
4
490
// Test app location dispatch import assert; import files; import io; import string; import location; app (file o) hostname() { "hostname" @stdout=o; } (string o) extract_hostname(file f) { o = trim(read(f)); } main { foreach i in [1:10] { string host1 = extract_hostname(hostname()); // Run on same host string host2 = extract_hostname(@location=hostmap_one_worker(host1) hostname()); assertEqual(host1, host2, sprintf("Check hostnames same trial %i", i)); } }
apache-2.0
3bc9762951c8362e02d7e9ed49e53f98
19.416667
84
0.669388
3.223684
false
false
false
false
codepath-volunteer-app/VolunteerMe
VolunteerMe/Pods/DateToolsSwift/DateToolsSwift/DateTools/Date+Format.swift
7
6092
// // Date+Format.swift // DateToolsTests // // Created by Matthew York on 8/23/16. // Copyright © 2016 Matthew York. All rights reserved. // import Foundation /** * Extends the Date class by adding convenience methods for formatting dates. */ public extension Date { // MARK: - Formatted Date - Style /** * Get string representation of date. * * - parameter dateStyle: The date style in which to represent the date * - parameter timeZone: The time zone of the date * - parameter locale: Encapsulates information about linguistic, cultural, and technological conventions and standards * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateStyle: DateFormatter.Style, timeZone: TimeZone, locale: Locale) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = dateStyle dateFormatter.timeZone = timeZone dateFormatter.locale = locale return dateFormatter.string(from: self) } /** * Get string representation of date. Locale is automatically selected as the current locale of the system. * * - parameter dateStyle: The date style in which to represent the date * - parameter timeZone: The time zone of the date * * - returns String? - Represenation of the date (self) in the specified format */ public func format(with dateStyle: DateFormatter.Style, timeZone: TimeZone) -> String { #if os(Linux) return format(with: dateStyle, timeZone: timeZone, locale: Locale.current) #else return format(with: dateStyle, timeZone: timeZone, locale: Locale.autoupdatingCurrent) #endif } /** * Get string representation of date. * Time zone is automatically selected as the current time zone of the system. * * - parameter dateStyle: The date style in which to represent the date * - parameter locale: Encapsulates information about linguistic, cultural, and technological conventions and standards. * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateStyle: DateFormatter.Style, locale: Locale) -> String { return format(with: dateStyle, timeZone: TimeZone.autoupdatingCurrent, locale: locale) } /** * Get string representation of date. * Locale and time zone are automatically selected as the current locale and time zone of the system. * * - parameter dateStyle: The date style in which to represent the date * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateStyle: DateFormatter.Style) -> String { #if os(Linux) return format(with: dateStyle, timeZone: TimeZone.autoupdatingCurrent, locale: Locale.current) #else return format(with: dateStyle, timeZone: TimeZone.autoupdatingCurrent, locale: Locale.autoupdatingCurrent) #endif } // MARK: - Formatted Date - String /** * Get string representation of date. * * - parameter dateFormat: The date format string, according to Apple's date formatting guide in which to represent the date * - parameter timeZone: The time zone of the date * - parameter locale: Encapsulates information about linguistic, cultural, and technological conventions and standards * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateFormat: String, timeZone: TimeZone, locale: Locale) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormat dateFormatter.timeZone = timeZone dateFormatter.locale = locale return dateFormatter.string(from: self) } /** * Get string representation of date. * Locale is automatically selected as the current locale of the system. * * - parameter dateFormat: The date format string, according to Apple's date formatting guide in which to represent the date * - parameter timeZone: The time zone of the date * * - returns: Representation of the date (self) in the specified format */ public func format(with dateFormat: String, timeZone: TimeZone) -> String { #if os(Linux) return format(with: dateFormat, timeZone: timeZone, locale: Locale.current) #else return format(with: dateFormat, timeZone: timeZone, locale: Locale.autoupdatingCurrent) #endif } /** * Get string representation of date. * Time zone is automatically selected as the current time zone of the system. * * - parameter dateFormat: The date format string, according to Apple's date formatting guide in which to represent the date * - parameter locale: Encapsulates information about linguistic, cultural, and technological conventions and standards * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateFormat: String, locale: Locale) -> String { return format(with: dateFormat, timeZone: TimeZone.autoupdatingCurrent, locale: locale) } /** * Get string representation of date. * Locale and time zone are automatically selected as the current locale and time zone of the system. * * - parameter dateFormat: The date format string, according to Apple's date formatting guide in which to represent the date * * - returns: Represenation of the date (self) in the specified format */ public func format(with dateFormat: String) -> String { #if os(Linux) return format(with: dateFormat, timeZone: TimeZone.autoupdatingCurrent, locale: Locale.current) #else return format(with: dateFormat, timeZone: TimeZone.autoupdatingCurrent, locale: Locale.autoupdatingCurrent) #endif } }
mit
cb768e9f4fbd9d27aed9176c8977576c
40.435374
129
0.670169
4.826466
false
true
false
false
studyYF/YueShiJia
YueShiJia/YueShiJia/Classes/Shop/Controllers/YFShopViewController.swift
1
3609
// // YFShopViewController.swift // YueShiJia // // Created by YangFan on 2017/5/10. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit typealias ShopData = ([YFShopItem],[Banner],[ClassifyItem],Channer) private let shopHeaderID = "YFShopHeaderView" private let shopCellID = "YFShopCell" private let saleCellID = "YFChannerCell" class YFShopViewController: ViewController { //MARK: 定义属性 var data: ShopData? lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: kWidth, height: kHeight - kNavigationHeight + 20), style: .grouped) tableView.backgroundColor = UIColor.white tableView.separatorStyle = .none tableView.register(UINib.init(nibName: saleCellID, bundle: nil), forCellReuseIdentifier: saleCellID) tableView.register(UINib.init(nibName: shopCellID, bundle: nil), forCellReuseIdentifier: shopCellID) tableView.register(UINib.init(nibName: shopHeaderID, bundle: nil), forHeaderFooterViewReuseIdentifier: shopHeaderID) return tableView }() //MARK: 生命周期函数 override func viewDidLoad() { super.viewDidLoad() addTitleView() addSearchButton() setUI() loadData() } } //MARK: 网络加载 extension YFShopViewController { fileprivate func loadData() { YFHttpRequest.shareInstance.loadShopData { [weak self] (shopData) in self?.data = shopData self?.tableView.reloadData() } } } //MARK: 设置UI extension YFShopViewController { fileprivate func setUI() { tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) } } //MARK: 方法 extension YFShopViewController { } //MARK: UITableView代理方法 extension YFShopViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = (data?.0.count) ?? -1 return count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 && data!.3.isKind(of: Channer.self) { let cell = tableView.dequeueReusableCell(withIdentifier: saleCellID, for: indexPath) as! YFChannerCell cell.channer = data?.3 return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: shopCellID, for: indexPath) as! YFShopCell cell.item = data?.0[indexPath.row - 1] return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 150 * kRate } else { return 405 * kRate } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = YFSpecialGoodsViewController() vc.special_id = data?.0[indexPath.row - 1].special_id navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: shopHeaderID) as! YFShopHeaderView headerView.bannerItems = data?.1 headerView.classifyItem = data?.2 return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 450 * kRate } }
apache-2.0
77389059502a51b8fd7c11143dc49024
31.678899
136
0.663111
4.644068
false
false
false
false
michael-lehew/swift-corelibs-foundation
Foundation/NSURLCredential.swift
1
7209
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /*! @enum NSURLCredentialPersistence @abstract Constants defining how long a credential will be kept around @constant NSURLCredentialPersistenceNone This credential won't be saved. @constant NSURLCredentialPersistenceForSession This credential will only be stored for this session. @constant NSURLCredentialPersistencePermanent This credential will be stored permanently. Note: Whereas in Mac OS X any application can access any credential provided the user gives permission, in iPhone OS an application can access only its own credentials. @constant NSURLCredentialPersistenceSynchronizable This credential will be stored permanently. Additionally, this credential will be distributed to other devices based on the owning AppleID. Note: Whereas in Mac OS X any application can access any credential provided the user gives permission, on iOS an application can access only its own credentials. */ extension URLCredential { public enum Persistence : UInt { case none case forSession case permanent case synchronizable } } /*! @class NSURLCredential @discussion This class is an immutable object representing an authentication credential. The actual type of the credential is determined by the constructor called in the categories declared below. */ open class URLCredential : NSObject, NSSecureCoding, NSCopying { private var _user : String private var _password : String private var _persistence : Persistence /*! @method initWithUser:password:persistence: @abstract Initialize a NSURLCredential with a user and password @param user the username @param password the password @param persistence enum that says to store per session, permanently or not at all @result The initialized NSURLCredential */ public init(user: String, password: String, persistence: Persistence) { guard persistence != .permanent && persistence != .synchronizable else { NSUnimplemented() } _user = user _password = password _persistence = persistence super.init() } /*! @method credentialWithUser:password:persistence: @abstract Create a new NSURLCredential with a user and password @param user the username @param password the password @param persistence enum that says to store per session, permanently or not at all @result The new autoreleased NSURLCredential */ public required init?(coder aDecoder: NSCoder) { NSUnimplemented() } open func encode(with aCoder: NSCoder) { NSUnimplemented() } static public var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } /*! @method persistence @abstract Determine whether this credential is or should be stored persistently @result A value indicating whether this credential is stored permanently, per session or not at all. */ open var persistence: Persistence { return _persistence } /*! @method user @abstract Get the username @result The user string */ open var user: String? { return _user } /*! @method password @abstract Get the password @result The password string @discussion This method might actually attempt to retrieve the password from an external store, possible resulting in prompting, so do not call it unless needed. */ open var password: String? { return _password } /*! @method hasPassword @abstract Find out if this credential has a password, without trying to get it @result YES if this credential has a password, otherwise NO @discussion If this credential's password is actually kept in an external store, the password method may return nil even if this method returns YES, since getting the password may fail, or the user may refuse access. */ open var hasPassword: Bool { // Currently no support for SecTrust/SecIdentity, always return true return true } } // TODO: We have no implementation for Security.framework primitive types SecIdentity and SecTrust yet /* extension NSURLCredential { /*! @method initWithIdentity:certificates:persistence: @abstract Initialize an NSURLCredential with an identity and array of at least 1 client certificates (SecCertificateRef) @param identity a SecIdentityRef object @param certArray an array containing at least one SecCertificateRef objects @param persistence enum that says to store per session, permanently or not at all @result the Initialized NSURLCredential */ public convenience init(identity: SecIdentity, certificates certArray: [AnyObject]?, persistence: NSURLCredentialPersistence) /*! @method credentialWithIdentity:certificates:persistence: @abstract Create a new NSURLCredential with an identity and certificate array @param identity a SecIdentityRef object @param certArray an array containing at least one SecCertificateRef objects @param persistence enum that says to store per session, permanently or not at all @result The new autoreleased NSURLCredential */ /*! @method identity @abstract Returns the SecIdentityRef of this credential, if it was created with a certificate and identity @result A SecIdentityRef or NULL if this is a username/password credential */ public var identity: SecIdentity? { NSUnimplemented() } /*! @method certificates @abstract Returns an NSArray of SecCertificateRef objects representing the client certificate for this credential, if this credential was created with an identity and certificate. @result an NSArray of SecCertificateRef or NULL if this is a username/password credential */ public var certificates: [AnyObject] { NSUnimplemented() } } extension NSURLCredential { /*! @method initWithTrust: @abstract Initialize a new NSURLCredential which specifies that the specified trust has been accepted. @result the Initialized NSURLCredential */ public convenience init(trust: SecTrust) { NSUnimplemented() } /*! @method credentialForTrust: @abstract Create a new NSURLCredential which specifies that a handshake has been trusted. @result The new autoreleased NSURLCredential */ public convenience init(forTrust trust: SecTrust) { NSUnimplemented() } } */
apache-2.0
312126911a89dc68fdc9eb7279c7099e
39.05
262
0.697323
5.59705
false
false
false
false
xiangpengzhu/QuickStart
QuickStart/SystemOverride/TouchEdgeViews.swift
1
2817
// // TouchEdgeViews.swift // QuickStart // // Created by zhuxiangpeng on 16/9/18. // Copyright © 2016年 zQS. All rights reserved. // import UIKit /** * 扩大View的响应范围的协议 */ protocol QSViewTouchEdgeExtend { var responseInsets: UIEdgeInsets {get set} } extension UIView { /** 计算一个点是否在view的响应范围内 - parameter point: 点 - parameter responseInsets: 扩大边界 - returns: 是否可以响应 */ fileprivate func pointCanResponse(_ point: CGPoint, responseInsets: UIEdgeInsets) -> Bool { let parentLocation = self.convert(point, to: self.superview) var responseRect = self.frame; responseRect.origin.x -= responseInsets.left; responseRect.origin.y -= responseInsets.top; responseRect.size.width += (responseInsets.left + responseInsets.right); responseRect.size.height += (responseInsets.top + responseInsets.bottom); return responseRect.contains(parentLocation); } } /// 可扩大响应范围的UIView open class QSTouchEdgeView: QSView, QSViewTouchEdgeExtend { /// 扩大的边界 public var responseInsets = UIEdgeInsets.zero override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return self.pointCanResponse(point, responseInsets: responseInsets) } } /// 可扩大响应范围的UIScrollView open class QSTouchEdgeScrollView: QSScrollView, QSViewTouchEdgeExtend { /// 扩大的边界 public var responseInsets = UIEdgeInsets.zero override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return self.pointCanResponse(point, responseInsets: responseInsets) } } /// 可扩大响应范围的UILabel open class QSTouchEdgeLabel: QSLabel, QSViewTouchEdgeExtend { /// 扩大的边界 public var responseInsets = UIEdgeInsets.zero override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return self.pointCanResponse(point, responseInsets: responseInsets) } } /// 可扩大响应范围的UIButton open class QSTouchEdgeButton: QSButton, QSViewTouchEdgeExtend { /// 扩大的边界 public var responseInsets = UIEdgeInsets.zero override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return self.pointCanResponse(point, responseInsets: responseInsets) } } /// 可扩大响应范围的UIButton open class QSTouchEdgeImageView: QSImageView, QSViewTouchEdgeExtend { /// 扩大的边界 public var responseInsets = UIEdgeInsets.zero override open func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return self.pointCanResponse(point, responseInsets: responseInsets) } }
gpl-3.0
a1b21fca785fcf9fca86afaf0fa0bfc9
28.370787
95
0.695103
3.930827
false
false
false
false
mz2/Carpaccio
Sources/Carpaccio/Collection+Extensions.swift
1
3660
// // NSArray+Extensions.swift // Carpaccio // // Created by Matias Piipari on 28/08/2016. // Copyright © 2016 Matias Piipari & Co. All rights reserved. // import Foundation // Inspired by http://moreindirection.blogspot.co.uk/2015/07/gcd-and-parallel-collections-in-swift.html extension Swift.Collection where Index == Int { public func parallelMap<T>(_ transform: @escaping ((Iterator.Element) throws -> T)) throws -> [T] { return try self.parallelCompactMap(transform) } public func parallelCompactMap<T>(_ transform: @escaping ((Iterator.Element) throws -> T?)) throws -> [T] { guard !self.isEmpty else { return [] } var result: [(Int, T?)] = [] let group = DispatchGroup() let lock = DispatchQueue(label: "pcompactmap") var caughtError: Swift.Error? = nil DispatchQueue.concurrentPerform(iterations: self.count) { i in if caughtError != nil { return } do { let t = try transform(self[i]) lock.async(group: group) { result += [(i, t)] } } catch { caughtError = error } } group.wait() if let error = caughtError { throw error } return result.sorted { $0.0 < $1.0 }.compactMap { $0.1 } } } // Commented out, for now, due to unreliable operation: some elements might go missing from the result. /* // Inspired by http://moreindirection.blogspot.co.uk/2015/07/gcd-and-parallel-collections-in-swift.html extension Swift.Sequence { public func parallelMap<T>(maxParallelism:Int? = nil, _ transform: @escaping ((Iterator.Element) throws -> T)) throws -> [T] { return try self.parallelCompactMap(maxParallelism: maxParallelism, transform) } public func parallelCompactMap<T>(maxParallelism:Int? = nil, _ transform: @escaping ((Iterator.Element) throws -> T?)) throws -> [T] { if let maxParallelism = maxParallelism, maxParallelism == 1 { return try self.compactMap(transform) } var result: [(Int64, T)] = [] let group = DispatchGroup() let lock = DispatchQueue(label: "pcompactmap") let parallelism:Int = { if let maxParallelism = maxParallelism { precondition(maxParallelism > 0) return maxParallelism } return ProcessInfo.processInfo.activeProcessorCount }() let semaphore = DispatchSemaphore(value: parallelism) var iterator = self.makeIterator() var index:Int64 = 0 var caughtError: Swift.Error? = nil repeat { guard let item = iterator.next() else { break } semaphore.wait() DispatchQueue.global().async { [index] in do { if let mappedElement = try transform(item) { lock.async { result += [(index, mappedElement)] } } } catch { caughtError = error } semaphore.signal() } index += 1 } while true group.wait() if let error = caughtError { throw error } return result.sorted { $0.0 < $1.0 } .compactMap { $0.1 } } } */
mit
a9727cc2672a2ecfb494e62999edfd18
30.008475
136
0.517354
4.751948
false
false
false
false
bellots/usefulExtensions
UsefulExtensions/DoubleExtensions.swift
1
808
// // DoubleExtensions.swift // JoeBee // // Created by Andrea Bellotto on 14/11/16. // Copyright © 2016 JoeBee Srl. All rights reserved. // import Foundation extension Double { // rounds to fraction digits the double public func roundToDecimal(fractionDigits: Int) -> Double { let multiplier = pow(10.0, Double(fractionDigits)) return (self * multiplier).rounded() / multiplier } // returns number formatted in what you need public func format(with locale:Locale, and format:NumberFormatter.Style)->String{ let converted = NSDecimalNumber(decimal: Decimal(self)) let formatter = NumberFormatter() formatter.locale = locale formatter.numberStyle = format return formatter.string(from: converted)! } }
mit
8a27cff044253ba0dd271fcdd8956646
26.827586
85
0.665428
4.483333
false
false
false
false
NestedWorld/NestedWorld-iOS
nestedworld/nestedworld/APIUserAuthenticationRequestManager.swift
1
3312
// // APIUserAuthenticationRequestManager.swift // nestedworld // // Created by Jean-Antoine Dupont on 26/04/2016. // Copyright © 2016 NestedWorld. All rights reserved. // import Foundation class APIUserAuthenticationRequestManager { private var httpRequestManager: HttpRequestManagerProtocol private var requestRoot: String = "" private let appToken: String = "test" // MARK: ... init(httpRequestManager: HttpRequestManagerProtocol, apiRootURL: String) { self.httpRequestManager = httpRequestManager self.requestRoot = apiRootURL + "/auth" } // MARK: ... func login(email: String, password: String, data: Dictionary<String, AnyObject>?, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void) { let url: String = self.requestRoot + "/login/simple" let params: Dictionary<String, AnyObject> = [ "email": email, "password": password, "data": (data != nil ? data! : Dictionary<String, AnyObject>()), "app_token": self.appToken, ] self.httpRequestManager.post(url, params: params, headers: nil, success: { (response) -> Void in success(response: response) }) { (error, response) -> Void in failure(error: error, response: response) } } // MARK: ... func logout(token: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void) { let url: String = self.requestRoot + "/logout" let headers: Dictionary<String, String> = [ "Authorization": token ] self.httpRequestManager.get(url, headers: headers, success: { (response) -> Void in success(response: response) }) { (error, response) -> Void in failure(error: error, response: response) } } // MARK: ... func register(email: String, nickname: String, password: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void) { let url: String = self.requestRoot + "/register" let params: Dictionary<String, AnyObject> = [ "email": email, "pseudo": nickname, "password": password ] self.httpRequestManager.post(url, params: params, headers: nil, success: { (response) -> Void in success(response: response) }) { (error, response) -> Void in failure(error: error, response: response) } } // MARK: ... func resetPassword(email: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void) { let url: String = self.requestRoot + "/resetpassword" let params: Dictionary<String, AnyObject> = [ "email": email ] self.httpRequestManager.post(url, params: params, headers: nil, success: { (response) -> Void in success(response: response) }) { (error, response) -> Void in failure(error: error, response: response) } } }
mit
b8386701fc6566790ec1f3f9a15fdc3a
33.14433
129
0.572033
4.504762
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/Model/User.swift
1
1698
// // Trip.swift // TravelApp // // Created by rawat on 28/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class User: NSObject { var id: NSNumber? var name: String? var email: String? var instagram_access_token: String? var instagram_profile_picture: String? var instagram_user_name: String? var profile_pic: ProfilePic? var cover_photo: CoverPic? var total_followers: NSNumber? var total_following: NSNumber? var total_trips: NSNumber? var updated_at: String? var created_at: String? var is_followed_by_current_user: Bool = false init(dictionary: [String: AnyObject]) { super.init() setValuesForKeys(dictionary) if let profilePicDict = dictionary["profile_pic"] as! [String: AnyObject]? { profile_pic = ProfilePic(dictionary: profilePicDict) } if let coverPhotoDict = dictionary["cover_photo"] as! [String: AnyObject]? { cover_photo = CoverPic(dictionary: coverPhotoDict) } } override func setValue(_ value: Any?, forKey key: String) { let _key = key if (["profile_pic", "cover_photo", "website_url", "blog_url", "facebook_url", "twitter_url", "instagram_url"].contains(_key)) { return } super.setValue(value, forKey: _key) } } class ProfilePic: NSObject { var url: String? var public_id: String? init(dictionary: [String: AnyObject]) { super.init() public_id = dictionary["public_id"] as! String? url = dictionary["url"] as! String? } } class CoverPic: ProfilePic { }
mit
986a85cae9f06e165ec2beffe013d02b
25.515625
135
0.602829
3.910138
false
false
false
false
Mazyod/OrganicPicker
OrganicPicker/OrganicPicker.swift
1
3544
// // OrganicPicker.swift // OrganicPickerDemo // // Created by Mazyad Alabduljaleel on 11/11/14. // Copyright (c) 2014 ArabianDevs. All rights reserved. // import UIKit @objc protocol OrganicPickerCell { func setOrganicItem(_ item: Any) } class OrganicPicker: UIControl, OrganicCollectionViewControllerDelegate { lazy var collectionViewController = OrganicCollectionViewController(delegate: self) var items: [String] = [] { didSet { guard items != oldValue else { return } collectionViewController.collectionView?.reloadData() } } var selectedIndex: Int = -1 { didSet { guard selectedIndex != oldValue else { return } accessibilityValue = items[selectedIndex] let indexPath = IndexPath(item: selectedIndex, section: 0) collectionViewController.selectedIndexPath = indexPath } } @IBInspectable var itemSpacing: CGFloat = 2 var backgroundView: UIView? var foregroundView: UIView? { didSet { oldValue?.removeFromSuperview() if let view = foregroundView { view.frame = bounds view.isUserInteractionEnabled = false addSubview(view) } } } var maskingLayer: CALayer? { didSet { layer.mask = maskingLayer layer.masksToBounds = true } } /** Organic picker can be customized by subclassing or closures. * Name your poison, and name it wisely. */ // MARK: - Initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } convenience init() { self.init(frame: CGRect.zero) } func commonInit() { isAccessibilityElement = true accessibilityNavigationStyle = .combined accessibilityHint = NSLocalizedString("ACCESS_ORGANIC_PICKER_HINT", comment: "") clipsToBounds = true addSubview(collectionViewController.view) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(OrganicPicker.controlTapped(_:))) tapGesture.require(toFail: collectionViewController.collectionView!.panGestureRecognizer) addGestureRecognizer(tapGesture) } // MARK: - View lifecycle override func layoutSubviews() { super.layoutSubviews() if collectionViewController.view.bounds.size != bounds.size { collectionViewController.view.frame = bounds } maskingLayer?.frame = bounds foregroundView?.frame = bounds if let view = foregroundView { bringSubviewToFront(view) } } // MARK: - Action @objc func controlTapped(_ gesture: UITapGestureRecognizer?) { // allow rolling through options for accessibility sake selectedIndex = (selectedIndex + 1) % items.count sendActions(for: .valueChanged) } // MARK: - OrganicCollectionViewDelegate func organicCollectionViewStopped(atIndex index: Int) { selectedIndex = index sendActions(for: .valueChanged) } }
mit
0c44b596a7f38243fa403f605aec8181
24.868613
113
0.580982
5.679487
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_12/HomeKitSample/App/Code/Controller/TriggerViewController.swift
1
4230
// // TriggerViewController.swift // // Created by ToKoRo on 2017-08-22. // import UIKit import HomeKit class TriggerViewController: UITableViewController, ContextHandler { typealias ContextType = HMTrigger @IBOutlet weak var nameLabel: UILabel? @IBOutlet weak var uniqueIdentifierLabel: UILabel? @IBOutlet weak var isEnabledLabel: UILabel? @IBOutlet weak var lastFireDateLabel: UILabel? @IBOutlet weak var actionSetsCountLabel: UILabel? var trigger: HMTrigger { return context! } override func viewDidLoad() { super.viewDidLoad() refresh() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setToolbarHidden(false, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "ActionSet"?: sendContext(trigger, to: segue.destination) default: break } } func refresh() { nameLabel?.text = trigger.name uniqueIdentifierLabel?.text = trigger.uniqueIdentifier.uuidString isEnabledLabel?.text = String(trigger.isEnabled) lastFireDateLabel?.text = { guard let date = trigger.lastFireDate else { return nil } return DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .short) }() actionSetsCountLabel?.text = String(trigger.actionSets.count) } private func updateName() { let trigger = self.trigger let alert = UIAlertController(title: nil, message: "Triggerの名前を入力してください", preferredStyle: .alert) alert.addTextField { textField in textField.text = trigger.name } alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in guard let name = alert.textFields?.first?.text, name.count > 0 else { return } self?.handleNewTriggerName(name) }) alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel)) present(alert, animated: true) } private func handleNewTriggerName(_ name: String) { trigger.updateName(name) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } private func displayEnableAction() { let message = "Enables/disables this trigger" let alert = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Enable", style: .default) { [weak self] _ in self?.enable(true) }) alert.addAction(UIAlertAction(title: "Disable", style: .default) { [weak self] _ in self?.enable(false) }) alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel)) present(alert, animated: true) } private func enable(_ enable: Bool) { trigger.enable(enable) { [weak self] error in if let error = error { print("# error: \(error)") } self?.refresh() } } } // MARK: - Actions extension TriggerViewController { @IBAction func removeButtonDidTap(sender: AnyObject) { ResponderChain(from: self).send(trigger, protocol: TriggerActionHandler.self) { [weak self] trigger, handler in handler.handleRemove(trigger) DispatchQueue.main.async { self?.navigationController?.popViewController(animated: true) } } } } // MARK: - UITableViewDelegate extension TriggerViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } switch (indexPath.section, indexPath.row) { case (0, 0): // name updateName() case (0, 2): // enable displayEnableAction() default: break } } }
mit
7fffce9c691c8db9e8226d61aa1d826e
29.333333
119
0.601529
4.76223
false
false
false
false
tkohout/Genie
GenieTests/Asserts.swift
1
1131
// // Asserts.swift // Genie // // Created by Tomas Kohout on 08/01/2017. // Copyright © 2017 Genie. All rights reserved. // import Foundation import XCTest func AssertEqualIgnoringIndentation(_ expression1: [String], _ expression2: [String], file: StaticString = #file, line: UInt = #line) { let expressions = [expression1, expression2].map { $0.map{ $0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) }} if expressions[0] != expressions[1]{ if expressions[0].count != expressions[1].count { XCTAssert(false, "Expressions length is not equal \(expressions[0].count) != \(expressions[1].count)", file: file, line: line) return } expressions[0].enumerated().forEach { (index, exp1) in let exp2 = expressions[1][index] if exp1 != exp2 { XCTAssert(false, "Expressions differ on line \(index + 1): '\(exp1)' vs. '\(exp2)'", file: file, line: line) } } } XCTAssertEqual(expressions[0], expressions[1], file: file, line: line) }
mit
e3545aef6ed63524b97df5a26390a3c9
33.242424
138
0.587611
4.079422
false
false
false
false
barteljan/VISPER
VISPER-Wireframe/Classes/Wireframe/DefaultRouteResult.swift
1
873
// // RouteResult.swift // Pods-VISPER-Wireframe_Example // // Created by bartel on 19.11.17. // import Foundation import VISPER_Core public struct DefaultRouteResult : RouteResult, Equatable { public let routePattern: String public let parameters: [String : Any] public var routingOption: RoutingOption? public init(routePattern: String, parameters: [String : Any], routingOption: RoutingOption?){ self.routePattern = routePattern self.parameters = parameters self.routingOption = routingOption } public init(routePattern: String,parameters: [String : Any]){ self.init(routePattern: routePattern, parameters: parameters, routingOption: nil) } public static func ==(lhs: DefaultRouteResult, rhs: DefaultRouteResult) -> Bool { return lhs.isEqual(routeResult: rhs) } }
mit
17ad39e3fed731c51f4cff1d410771cc
27.16129
97
0.68614
4.365
false
false
false
false
coderMONSTER/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketRequestManage.swift
1
5819
// // SocketPacketManage.swift // viossvc // // Created by yaowang on 2016/11/22. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit //import XCGLogger class SocketRequestManage: NSObject { static let shared = SocketRequestManage(); fileprivate var socketRequests = [UInt64: SocketRequest]() fileprivate var _timer: Timer? fileprivate var _lastHeardBeatTime:TimeInterval! fileprivate var _lastConnectedTime:TimeInterval! fileprivate var _reqeustId:UInt32 = 10000 fileprivate var _socketHelper:SocketHelper? fileprivate var _sessionId:UInt64 = 0 fileprivate var timelineRequest: SocketRequest? var receiveMatching:CompleteBlock? var receiveOrderResult:CompleteBlock? var operate_code = 0 func start() { _lastHeardBeatTime = timeNow() _lastConnectedTime = timeNow() stop() _timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(didActionTimer), userInfo: nil, repeats: true) #if true _socketHelper = APISocketHelper() #else _socketHelper = LocalSocketHelper() #endif _socketHelper?.connect() } func stop() { _timer?.invalidate() _timer = nil objc_sync_enter(self) _socketHelper?.disconnect() _socketHelper = nil objc_sync_exit(self) } var sessionId:UInt64 { get { objc_sync_enter(self) if _sessionId > 2000000000 { _sessionId = 10000 } _sessionId += 1 objc_sync_exit(self) return _sessionId; } } func notifyResponsePacket(_ packet: SocketDataPacket) { objc_sync_enter(self) var socketReqeust = socketRequests[packet.session_id] if packet.operate_code == SocketConst.OPCode.timeLine.rawValue + 1{ socketReqeust = timelineRequest }else if packet.operate_code == SocketConst.OPCode.receiveMatching.rawValue { let response:SocketJsonResponse = SocketJsonResponse(packet:packet) self.receiveMatching!(response) }else if packet.operate_code == SocketConst.OPCode.orderResult.rawValue{ let response:SocketJsonResponse = SocketJsonResponse(packet:packet) self.receiveOrderResult!(response) }else if packet.operate_code == SocketConst.OPCode.onlyLogin.rawValue{ stop() NotificationCenter.default.post(name: Notification.Name.init(rawValue: AppConst.NoticeKey.onlyLogin.rawValue), object: nil, userInfo: nil) }else{ socketRequests.removeValue(forKey: packet.session_id) } objc_sync_exit(self) let response:SocketJsonResponse = SocketJsonResponse(packet:packet) let statusCode:Int = response.statusCode; if statusCode == AppConst.frozeCode{ ShareDataModel.share().controlSwitch = false return } if ( statusCode < 0) && packet.data?.count != 0 { socketReqeust?.onError(statusCode) } else { socketReqeust?.onComplete(response) } } func checkReqeustTimeout() { objc_sync_enter(self) for (key,reqeust) in socketRequests { if reqeust.isReqeustTimeout() { socketRequests.removeValue(forKey: key) reqeust.onError(-11011) print(">>>>>>>>>>>>>>>>>>>>>>>>>>\(key)") break } } objc_sync_exit(self) } fileprivate func sendRequest(_ packet: SocketDataPacket) { let block:()->() = { [weak self] in self?._socketHelper?.sendData(packet.serializableData()!) } objc_sync_enter(self) if _socketHelper == nil { SocketRequestManage.shared.start() let when = DispatchTime.now() + Double((Int64)(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: when,execute: block) } else { block() } objc_sync_exit(self) } func startJsonRequest(_ packet: SocketDataPacket, complete: CompleteBlock?, error: ErrorBlock?) { let socketReqeust = SocketRequest(); socketReqeust.error = error; socketReqeust.complete = complete; packet.request_id = 0; packet.session_id = sessionId; operate_code = Int(packet.operate_code) objc_sync_enter(self) if packet.operate_code == SocketConst.OPCode.timeLine.rawValue{ timelineRequest = socketReqeust } else { socketRequests[packet.session_id] = socketReqeust } objc_sync_exit(self) sendRequest(packet) } fileprivate func timeNow() ->TimeInterval { return Date().timeIntervalSince1970 } fileprivate func lastTimeNow(_ last:TimeInterval) ->TimeInterval { return timeNow() - last } fileprivate func isDispatchInterval(_ lastTime:inout TimeInterval,interval:TimeInterval) ->Bool { if timeNow() - lastTime >= interval { lastTime = timeNow() return true } return false } fileprivate func sendHeart() { let packet = SocketDataPacket(opcode: .heart,dict:[SocketConst.Key.uid: 0 as AnyObject]) sendRequest(packet) } func didActionTimer() { if _socketHelper != nil && _socketHelper!.isConnected { _lastConnectedTime = timeNow() } else if( isDispatchInterval(&_lastConnectedTime!,interval: 10) ) { _socketHelper?.connect() } checkReqeustTimeout() } }
gpl-3.0
929314006682b7d3bf1296c849f68b2f
30.956044
150
0.598349
4.846667
false
false
false
false