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
icecoffin/GlossLite
GlossLite/Views/AddEditWord/AddEditWordViewController.swift
1
3909
// // AddEditWordViewController.swift // GlossLite // // Created by Daniel on 01/10/16. // Copyright © 2016 icecoffin. All rights reserved. // import UIKit import SnapKit import IQKeyboardManagerSwift class AddEditWordViewController: UIViewController { fileprivate let viewModel: AddEditWordViewModel private let scrollView = UIScrollView() private let containerView = IQPreviousNextView() private let wordInputView = WordInputView() private let definitionInputView = DefinitionInputView() private let lookUpButton = UIButton(type: .system) // MARK: Initialization init(viewModel: AddEditWordViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View lifecycle & configuration override func viewDidLoad() { super.viewDidLoad() configureView() bindToViewModel() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _ = wordInputView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) } private func configureView() { view.backgroundColor = .white title = viewModel.title addScrollView() addContainerView() addWordInputView() addDefinitionInputView() addLookUpButton() } private func addScrollView() { view.addSubview(scrollView) scrollView.snp.makeConstraints { make in make.edges.equalToSuperview() } } private func addContainerView() { scrollView.addSubview(containerView) containerView.snp.makeConstraints { make in make.width.edges.equalToSuperview() } } private func addWordInputView() { containerView.addSubview(wordInputView) wordInputView.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() } wordInputView.text = viewModel.wordText } private func addDefinitionInputView() { containerView.addSubview(definitionInputView) definitionInputView.snp.makeConstraints { make in make.top.equalTo(wordInputView.snp.bottom).offset(8) make.leading.trailing.equalToSuperview() } definitionInputView.text = viewModel.definition } private func addLookUpButton() { containerView.addSubview(lookUpButton) lookUpButton.snp.makeConstraints { make in make.centerX.equalToSuperview() make.top.equalTo(definitionInputView.snp.bottom).offset(16) make.bottom.equalToSuperview().offset(-16) } lookUpButton.setTitle(NSLocalizedString("Look up in the dictionary", comment: ""), for: .normal) lookUpButton.titleLabel?.font = Fonts.openSans(size: 14) lookUpButton.addTarget(self, action: #selector(lookUpButtonTapped(_:)), for: .touchUpInside) } // MARK: View model private func bindToViewModel() { viewModel.onWordDefinitionNotFound = { [unowned self] text in Alert.show(onViewController: self, withTitle: "", message: NSLocalizedString("Definition for '\(text)' couldn't be found", comment: "")) } } // MARK: Actions func lookUpButtonTapped(_ sender: UIButton) { let wordText = wordInputView.text viewModel.lookUpWord(withText: wordText) } func saveWord() { let wordText = wordInputView.text let definition = definitionInputView.text let result = viewModel.validateAndSave(wordText: wordText, definition: definition) switch result { case .emptyWord: handleEmptyWordIssue() default: break } } private func handleEmptyWordIssue() { Alert.show(onViewController: self, withTitle: NSLocalizedString("Validation Error", comment: ""), message: NSLocalizedString("Word text can't be empty.", comment: "")) } }
mit
a1fccc31effee979e59e18e077971f91
26.328671
103
0.702661
4.806888
false
false
false
false
linkedin/LayoutKit
LayoutKitTests/CGFloatExtensionTests.swift
6
4502
// Copyright 2016 LinkedIn Corp. // 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. import XCTest @testable import LayoutKit class CGFloatExtensionTests: XCTestCase { struct TestCase { let rawValue: CGFloat /// Map of screen density to rounded value. let roundedValue: [CGFloat: CGFloat] } func testRoundedUpToFractionalPoint() { let scale = UIScreen.main.scale let testCases: [TestCase] = [ TestCase(rawValue: -1.1, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -1.0, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.9, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.5, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -1.0/3.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: -1.0/3.0]), TestCase(rawValue: -0.3, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.3, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 1.0/3.0, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.5, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.9, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.0, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.1, roundedValue: [1.0: 2.0, 2.0: 1.5, 3.0: 1.0 + 1.0/3.0]) ] for testCase in testCases { let expected = testCase.roundedValue[scale] XCTAssertEqual(testCase.rawValue.roundedUpToFractionalPoint, expected) } } func testRoundedToFractionalPoint() { let scale = UIScreen.main.scale let testCases: [TestCase] = [ TestCase(rawValue: -1.1, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -1.0, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.9, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -1.0]), TestCase(rawValue: -0.8, roundedValue: [1.0: -1.0, 2.0: -1.0, 3.0: -2.0/3.0]), TestCase(rawValue: -0.7, roundedValue: [1.0: -1.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.6, roundedValue: [1.0: -1.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.5, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -2.0/3.0]), TestCase(rawValue: -0.4, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -0.3, roundedValue: [1.0: 0.0, 2.0: -0.5, 3.0: -1.0/3.0]), TestCase(rawValue: -0.2, roundedValue: [1.0: 0.0, 2.0: -0.0, 3.0: -1.0/3.0]), TestCase(rawValue: -0.1, roundedValue: [1.0: 0.0, 2.0: -0.0, 3.0: 0.0]), TestCase(rawValue: 0.0, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.1, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 0.0]), TestCase(rawValue: 0.2, roundedValue: [1.0: 0.0, 2.0: 0.0, 3.0: 1.0/3.0]), TestCase(rawValue: 0.3, roundedValue: [1.0: 0.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.4, roundedValue: [1.0: 0.0, 2.0: 0.5, 3.0: 1.0/3.0]), TestCase(rawValue: 0.5, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.6, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.7, roundedValue: [1.0: 1.0, 2.0: 0.5, 3.0: 2.0/3.0]), TestCase(rawValue: 0.8, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 2.0/3.0]), TestCase(rawValue: 0.9, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.0, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), TestCase(rawValue: 1.1, roundedValue: [1.0: 1.0, 2.0: 1.0, 3.0: 1.0]), ] for testCase in testCases { let expected = testCase.roundedValue[scale] XCTAssertEqual(testCase.rawValue.roundedToFractionalPoint, expected) } } }
apache-2.0
2cf7e0522c81c7b77b9d7f8cb84395f2
55.275
131
0.550644
2.597807
false
true
false
false
carabina/DDMathParser
MathParser/FunctionSet.swift
2
2481
// // FunctionSet.swift // DDMathParser // // Created by Dave DeLong on 9/18/15. // // import Foundation internal class FunctionSet { private var functionsByName = Dictionary<String, FunctionRegistration>() private let caseSensitive: Bool internal init(caseSensitive: Bool) { self.caseSensitive = caseSensitive Function.standardFunctions.forEach { do { try registerFunction($0) } catch _ { fatalError("Conflicting name/alias in built-in functions") } } } internal func normalize(name: String) -> String { return caseSensitive ? name : name.lowercaseString } private func registeredFunctionForName(name: String) -> FunctionRegistration? { let casedName = normalize(name) return functionsByName[casedName] } internal func evaluatorForName(name: String) -> FunctionEvaluator? { return registeredFunctionForName(name)?.function } internal func addAlias(alias: String, forFunctionName name: String) throws { guard registeredFunctionForName(alias) == nil else { throw FunctionRegistrationError.FunctionAlreadyExists(alias) } guard let registration = registeredFunctionForName(name) else { throw FunctionRegistrationError.FunctionDoesNotExist(name) } let casedAlias = normalize(alias) registration.addAlias(casedAlias) functionsByName[casedAlias] = registration } internal func registerFunction(function: Function) throws { let registration = FunctionRegistration(function: function, caseSensitive: caseSensitive) // we need to make sure that every name is accounted for for name in registration.names { guard registeredFunctionForName(name) == nil else { throw FunctionRegistrationError.FunctionAlreadyExists(name) } } registration.names.forEach { self.functionsByName[$0] = registration } } } private class FunctionRegistration { var names: Set<String> let function: FunctionEvaluator init(function: Function, caseSensitive: Bool) { self.function = function.evaluator self.names = Set(function.names.map { caseSensitive ? $0.lowercaseString : $0 }) } func addAlias(name: String) { names.insert(name) } }
mit
cc18b023382921f8a0198673eb5d21da
29.62963
97
0.64208
5.278723
false
false
false
false
PerrchicK/swift-app
SomeApp/SomeApp/UI/XibViewContainer.swift
1
1223
// // XibViewContainer.swift // SomeApp // // Created by Perry on 16/01/2018. // Copyright © 2018 PerrchicK. All rights reserved. // import UIKit /// Reference: https://medium.com/zenchef-tech-and-product/how-to-visualize-reusable-xibs-in-storyboards-using-ibdesignable-c0488c7f525d class XibViewContainer: UIView { private(set) var contentView:UIView? @IBInspectable var nibName:String? override func awakeFromNib() { super.awakeFromNib() xibSetup() } func xibSetup() { guard let view = loadViewFromNib() else { return } view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(view) contentView = view } func loadViewFromNib() -> UIView? { guard let nibName = nibName else { return nil } let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate( withOwner: self, options: nil).first as? UIView } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() xibSetup() contentView?.prepareForInterfaceBuilder() } }
apache-2.0
56077cfc5252c4c48d0a41258e5f8de9
27.418605
136
0.641571
4.379928
false
false
false
false
nderkach/FlightKit
Pod/Classes/AutoCompleteTextField/AirportTextField.swift
1
16672
// // AutoCompleteTextField.swift // AutocompleteTextfieldSwift // // Created by Mylene Bayan on 6/13/15. // Copyright (c) 2015 MaiLin. All rights reserved. // import Foundation import UIKit public class AirportTextField: UITextField, UITableViewDataSource, UITableViewDelegate { let placeholderLabel = UILabel() var tintedClearImage: UIImage? /// Manages the instance of tableview private var autoCompleteTableView:UITableView? /// Holds the collection of attributed strings private var attributedAutoCompleteStrings:[NSAttributedString]? /// Handles user selection action on autocomplete table view public var onSelect:(String, NSIndexPath)->() = {_,_ in} /// Handles textfield's textchanged public var onTextChange:(String)->() = {_ in} /// Font for the text suggestions public var autoCompleteTextFont = UIFont(name: "HelveticaNeue-Light", size: 12) /// Color of the text suggestions public var autoCompleteTextColor = UIColor.blackColor() /// Used to set the height of cell for each suggestions public var autoCompleteCellHeight:CGFloat = 44.0 /// The maximum visible suggestion public var maximumAutoCompleteCount = 3 /// Used to set your own preferred separator inset public var autoCompleteSeparatorInset = UIEdgeInsetsZero /// Shows autocomplete text with formatting public var enableAttributedText = false /// User Defined Attributes public var autoCompleteAttributes:[String:AnyObject]? // Hides autocomplete tableview after selecting a suggestion public var hidesWhenSelected = true /// Hides autocomplete tableview when the textfield is empty public var hidesWhenEmpty:Bool? { didSet{ assert(hidesWhenEmpty != nil, "hideWhenEmpty cannot be set to nil") autoCompleteTableView?.hidden = hidesWhenEmpty! } } /// The table view height public var autoCompleteTableHeight:CGFloat?{ didSet{ redrawTable() } } /// The strings to be shown on as suggestions, setting the value of this automatically reload the tableview public var autoCompleteStrings:[String]?{ didSet{ reload() } } //MARK: - Init override init(frame: CGRect) { super.init(frame: frame) commonInit() setupAutocompleteTable(superview!) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } public override func awakeFromNib() { super.awakeFromNib() commonInit() setupAutocompleteTable(superview!) } override public func layoutSubviews() { super.layoutSubviews() for view in subviews { if view is UIButton { let button = view as! UIButton if let uiImage = button.imageForState(.Highlighted) { if tintedClearImage == nil { tintedClearImage = tintImage(uiImage, color: tintColor) } button.setImage(tintedClearImage, forState: .Normal) button.setImage(tintedClearImage, forState: .Highlighted) } } } } private func tintImage(image: UIImage, color: UIColor) -> UIImage { let size = image.size UIGraphicsBeginImageContextWithOptions(size, false, 2) let context = UIGraphicsGetCurrentContext() image.drawAtPoint(CGPointZero, blendMode: .Normal, alpha: 1.0) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetBlendMode(context, .SourceIn) CGContextSetAlpha(context, 1.0) let rect = CGRectMake( CGPointZero.x, CGPointZero.y, image.size.width, image.size.height) CGContextFillRect(UIGraphicsGetCurrentContext(), rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } public override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) commonInit() setupAutocompleteTable(newSuperview!) if newSuperview != nil { NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidEndEditing", name:UITextFieldTextDidEndEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidBeginEditing", name:UITextFieldTextDidBeginEditingNotification, object: self) } else { NSNotificationCenter.defaultCenter().removeObserver(self) } } private func commonInit(){ hidesWhenEmpty = true autoCompleteAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()] autoCompleteAttributes![NSFontAttributeName] = UIFont(name: "HelveticaNeue-Bold", size: 12) self.addTarget(self, action: "textFieldDidChange", forControlEvents: .EditingChanged) textColor = tintColor } private func setupAutocompleteTable(view:UIView){ let screenSize = UIScreen.mainScreen().bounds.size let tableView = UITableView(frame: CGRectMake(self.frame.origin.x, self.frame.origin.y + CGRectGetHeight(self.frame), screenSize.width - (self.frame.origin.x * 2), 30.0)) tableView.dataSource = self tableView.delegate = self tableView.rowHeight = autoCompleteCellHeight tableView.hidden = hidesWhenEmpty ?? true tableView.backgroundColor = FlightColors.presqueWhite.colorWithAlphaComponent(0.1) tableView.scrollEnabled = false tableView.tableFooterView = UIView(frame: CGRectZero) view.addSubview(tableView) autoCompleteTableView = tableView autoCompleteTableHeight = CGFloat(maximumAutoCompleteCount) * autoCompleteCellHeight } private func redrawTable(){ if autoCompleteTableView != nil{ var newFrame = autoCompleteTableView!.frame newFrame.size.height = autoCompleteTableHeight! autoCompleteTableView!.frame = newFrame } } public func hideAutoCompleteTableView() { autoCompleteTableView?.hidden = true } //MARK: - UITableViewDataSource public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return autoCompleteStrings != nil ? (autoCompleteStrings!.count > maximumAutoCompleteCount ? maximumAutoCompleteCount : autoCompleteStrings!.count) : 0 } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "autocompleteCellIdentifier" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) if cell == nil{ cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) } cell?.backgroundColor = UIColor.clearColor() cell?.selectionStyle = .None if enableAttributedText{ cell?.textLabel?.attributedText = attributedAutoCompleteStrings![indexPath.row] } else{ cell?.textLabel?.font = autoCompleteTextFont cell?.textLabel?.textColor = autoCompleteTextColor cell?.textLabel?.text = autoCompleteStrings![indexPath.row] } return cell! } //MARK: - UITableViewDelegate public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) onSelect(cell!.textLabel!.text!, indexPath) dispatch_async(dispatch_get_main_queue(), { () -> Void in tableView.hidden = self.hidesWhenSelected }) } public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("setSeparatorInset:"){ cell.separatorInset = autoCompleteSeparatorInset} if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:"){ cell.preservesSuperviewLayoutMargins = false} if cell.respondsToSelector("setLayoutMargins:"){ cell.layoutMargins = autoCompleteSeparatorInset} } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return autoCompleteCellHeight } //MARK: - Private Interface private func reload(){ if enableAttributedText{ let attrs = [NSForegroundColorAttributeName:autoCompleteTextColor, NSFontAttributeName:UIFont.systemFontOfSize(12.0)] if attributedAutoCompleteStrings == nil{ attributedAutoCompleteStrings = [NSAttributedString]() } else{ if attributedAutoCompleteStrings?.count > 0 { attributedAutoCompleteStrings?.removeAll(keepCapacity: false) } } if autoCompleteStrings != nil{ for i in 0..<autoCompleteStrings!.count{ let str = autoCompleteStrings![i] as NSString let range = str.rangeOfString(text!, options: .CaseInsensitiveSearch) let attString = NSMutableAttributedString(string: autoCompleteStrings![i], attributes: attrs) attString.addAttributes(autoCompleteAttributes!, range: range) attributedAutoCompleteStrings?.append(attString) } } } if let ac = autoCompleteStrings { if (ac.count < 3) { autoCompleteTableHeight = CGFloat(ac.count) * autoCompleteCellHeight } else { autoCompleteTableHeight = CGFloat(maximumAutoCompleteCount) * autoCompleteCellHeight } } else { autoCompleteTableHeight = 0 } autoCompleteTableView?.reloadData() } //MARK: - Internal func textFieldDidChange(){ if let _ = text { onTextChange(text!) } if text!.isEmpty{ autoCompleteStrings = nil } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.autoCompleteTableView?.hidden = self.hidesWhenEmpty! ? self.text!.isEmpty : false }) } public var borderInactiveColor: UIColor? { didSet { updateBorder() } } public var borderActiveColor: UIColor? { didSet { updateBorder() } } public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 2) private let placeholderInsets = CGPoint(x: 0, y: 6) private let textFieldInsets = CGPoint(x: 0, y: 12) private let inactiveBorderLayer = CALayer() private let activeBorderLayer = CALayer() private var inactivePlaceholderPoint: CGPoint = CGPointZero private var activePlaceholderPoint: CGPoint = CGPointZero // MARK: - TextFieldsEffectsProtocol func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(self.font!) updateBorder() updatePlaceholder() layer.addSublayer(inactiveBorderLayer) layer.addSublayer(activeBorderLayer) addSubview(placeholderLabel) inactivePlaceholderPoint = placeholderLabel.frame.origin activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y) } private func updateBorder() { inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFill: true) inactiveBorderLayer.backgroundColor = borderInactiveColor?.CGColor activeBorderLayer.frame = rectForBorder(borderThickness.active, isFill: false) activeBorderLayer.backgroundColor = borderActiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || !text!.isEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65) return smallerFont } private func rectForBorder(thickness: CGFloat, isFill: Bool) -> CGRect { if isFill { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: CGRectGetWidth(frame), height: thickness)) } else { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: 0, height: thickness)) } } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch self.textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) } func animateViewsForTextEntry() { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ [unowned self] in if self.text!.isEmpty { self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y) self.placeholderLabel.alpha = 0 } }), completion: { [unowned self] (completed) in self.layoutPlaceholderInTextRect() self.placeholderLabel.frame.origin = self.activePlaceholderPoint UIView.animateWithDuration(0.2, animations: { () -> Void in self.placeholderLabel.alpha = 0.5 }) }) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFill: true) } func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ [unowned self] in self.layoutPlaceholderInTextRect() self.placeholderLabel.alpha = 1 }), completion: nil) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFill: false) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func prepareForInterfaceBuilder() { drawViewsForRect(frame) } // MARK: - Overrides override public func drawRect(rect: CGRect) { drawViewsForRect(rect) } override public func drawPlaceholderInRect(rect: CGRect) { // Don't draw any placeholders } public func textFieldDidBeginEditing() { animateViewsForTextEntry() } public func textFieldDidEndEditing() { animateViewsForTextDisplay() } }
mit
4d38d8869f0a3967f676d8b1a52fe0fa
37.594907
201
0.643774
5.83141
false
false
false
false
q231950/road-to-bishkek
Bish/Cities/CitySelectionViewController.swift
1
4585
// // CitySelectionViewController.swift // Bish // // Created by Martin Kim Dung-Pham on 02.07.17. // Copyright © 2017 elbedev.com. All rights reserved. // import UIKit import CoreData import CloudKit class CitySelectionViewController: UITableViewController { public var selectedCity: City? private var filteredCities = [City]() private let cloud = CityCloud() private var searchTermChanged = false private var searchTerm: String? private var updateTimer: Timer! private var cursor: CKQueryCursor? override func viewDidLoad() { super.viewDidLoad() setupTitle() setupSearchController() } private func setupTitle() { navigationController?.navigationBar.prefersLargeTitles = true title = "City Selection" } private func setupSearchController() { navigationItem.searchController = UISearchController(searchResultsController: nil) navigationItem.searchController?.searchResultsUpdater = self navigationItem.searchController?.dimsBackgroundDuringPresentation = false navigationItem.hidesSearchBarWhenScrolling = false navigationItem.searchController?.searchBar.delegate = self definesPresentationContext = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupTimer() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) updateTimer.invalidate() } private func setupTimer() { updateTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true, block: { [weak self] (_) in self?.updateResults(cursor: self?.cursor) }) } } extension CitySelectionViewController: UISearchResultsUpdating { func loadMore() { searchTermChanged = true updateResults(cursor: cursor) } func updateSearchResults(for searchController: UISearchController) { guard let name = searchController.searchBar.text, name.count > 0 else { return } searchTerm = name searchTermChanged = true } private func updateResults(cursor: CKQueryCursor?) { guard let name = searchTerm, searchTermChanged == true else { return } searchTermChanged = false var newCursor: CKQueryCursor? if cursor == nil { filteredCities.removeAll() DispatchQueue.main.async { self.tableView.reloadData() } } else { newCursor = cursor self.cursor = nil } self.cloud.citiesNamed(name, cursor: newCursor, completion: { (city, error) in if let city = city { self.filteredCities.append(city) } DispatchQueue.main.async { self.tableView.reloadData() } }, next: { (cursor) in self.cursor = cursor }) } } extension CitySelectionViewController { override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell", for: indexPath) let city = filteredCities[indexPath.row] cell.textLabel?.text = city.name cell.detailTextLabel?.text = city.countryCode if let selectedCity = selectedCity { cell.accessoryType = selectedCity == city ? .checkmark : .none } if indexPath.row == filteredCities.count - 1 && cursor != nil { loadMore() } return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredCities.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let city = filteredCities[indexPath.row] selectedCity = city do { try DataStore.shared.deselectAllCities() try DataStore.shared.select(city) DataStore.shared.saveContext() } catch { } DispatchQueue.main.async { self.navigationItem.searchController?.isActive = false self.tableView.reloadData() } } } extension CitySelectionViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.cursor = nil } }
mit
4229242402c3eee37437bb21af6de35c
27.47205
109
0.636998
5.556364
false
false
false
false
aidenluo177/GitHubber
GitHubber/Pods/GCDKit/GCDKit/GCDGroup.swift
1
5262
// // GCDGroup.swift // GCDKit // // Copyright (c) 2014 John Rommel Estropia // // 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 wrapper and utility class for dispatch_group_t. */ @available(iOS, introduced=7.0) public struct GCDGroup { /** Creates a new group with which block objects can be associated. */ public init() { self.rawObject = dispatch_group_create() } /** Submits a closure to a queue and associates the closure to the group. - returns: The group. Useful when chaining async invocations on the group. */ public func async(queue: GCDQueue, _ closure: () -> Void) -> GCDGroup { dispatch_group_async(self.rawObject, queue.dispatchQueue()) { autoreleasepool(closure) } return self } /** Explicitly indicates that a block has entered the group. */ public func enter() { dispatch_group_enter(self.rawObject) } /** Explicitly indicates that a block in the group has completed. */ public func leave() { dispatch_group_leave(self.rawObject) } /** Explicitly indicates that a block has entered the group. - returns: Returns a once-token that may be passed to `leaveOnce()` */ public func enterOnce() -> Int32 { dispatch_group_enter(self.rawObject) return 1 } /** Explicitly indicates that a block in the group has completed. This method accepts a `onceToken` which `GCDGroup` can used to prevent multiple calls `dispatch_group_leave()` which may crash the app. - parameter onceToken: The address of the value returned from `enterOnce()`. - returns: Returns `true` if `dispatch_group_leave()` was called, or `false` if not. */ public func leaveOnce(inout onceToken: Int32) -> Bool { if OSAtomicCompareAndSwapInt(1, 0, &onceToken) { dispatch_group_leave(self.rawObject) return true } return false } /** Schedules a closure to be submitted to a queue when a group of previously submitted blocks have completed. - parameter queue: The queue to which the supplied closure is submitted when the group completes. - parameter closure: The closure to submit to the target queue. */ public func notify(queue: GCDQueue, _ closure: () -> Void) { dispatch_group_notify(self.rawObject, queue.dispatchQueue()) { autoreleasepool(closure) } } /** Waits synchronously for the previously submitted blocks to complete. */ public func wait() { dispatch_group_wait(self.rawObject, DISPATCH_TIME_FOREVER) } /** Waits synchronously for the previously submitted blocks to complete; returns if the blocks do not complete before the specified timeout period has elapsed. - parameter timeout: The number of seconds before timeout. - returns: Returns zero on success, or non-zero if the timeout occurred. */ public func wait(timeout: NSTimeInterval) -> Int { return dispatch_group_wait(self.rawObject, dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * NSTimeInterval(NSEC_PER_SEC)))) } /** Waits synchronously for the previously submitted blocks to complete; returns if the blocks do not complete before the specified date has elapsed. - parameter date: The timeout date. - returns: Returns zero on success, or non-zero if the timeout occurred. */ public func wait(date: NSDate) -> Int { return self.wait(date.timeIntervalSinceNow) } /** Returns the dispatch_group_t object associated with this value. - returns: The dispatch_group_t object associated with this value. */ public func dispatchGroup() -> dispatch_group_t { return self.rawObject } private let rawObject: dispatch_group_t } public func ==(lhs: GCDGroup, rhs: GCDGroup) -> Bool { return lhs.dispatchGroup() === rhs.dispatchGroup() } extension GCDGroup: Equatable { }
mit
ee49843a66e9eb9db5cc39717577da17
31.8875
201
0.656975
4.685663
false
false
false
false
ello/ello-ios
Sources/Controllers/Stream/Calculators/NotificationCellSizeCalculator.swift
1
3431
//// /// NotificationCellSizeCalculator.swift // class NotificationCellSizeCalculator: CellSizeCalculator, UIWebViewDelegate { private static let textViewForSizing = ElloTextView(frame: CGRect.zero, textContainer: nil) var notificationWidth: CGFloat { let notification = cellItem.jsonable as! Notification return NotificationCell.Size.messageHtmlWidth( forCellWidth: width, hasImage: notification.hasImage ) } var webView: UIWebView = ElloWebView() { didSet { didSetWebView() } } override init(item: StreamCellItem, width: CGFloat, columnCount: Int) { super.init(item: item, width: width, columnCount: columnCount) didSetWebView() } private func didSetWebView() { webView.frame = CGRect(x: 0, y: 0, width: notificationWidth, height: 0) webView.delegate = self } override func process() { guard let notification = cellItem.jsonable as? Notification, let textRegion = notification.textRegion else { assignCellHeight(nil) return } let content = textRegion.content let strippedContent = content.stripHtmlImgSrc() let html = StreamTextCellHTML.postHTML(strippedContent) webView.loadHTMLString(html, baseURL: URL(string: "/")) } func webViewDidFinishLoad(_ webView: UIWebView) { let webContentHeight = webView.windowContentSize()?.height ?? 0 assignCellHeight(webContentHeight) } private func assignCellHeight(_ webContentHeight: CGFloat?) { NotificationCellSizeCalculator.assignTotalHeight( webContentHeight, item: cellItem, cellWidth: width ) finish() } class func assignTotalHeight( _ webContentHeight: CGFloat?, item: StreamCellItem, cellWidth: CGFloat ) { let notification = item.jsonable as! Notification textViewForSizing.attributedText = NotificationAttributedTitle.from( notification: notification ) let titleWidth = NotificationCell.Size.messageHtmlWidth( forCellWidth: cellWidth, hasImage: notification.hasImage ) let titleSize = textViewForSizing.sizeThatFits( CGSize(width: titleWidth, height: .greatestFiniteMagnitude) ) var totalTextHeight = ceil(titleSize.height) totalTextHeight += NotificationCell.Size.CreatedAtFixedHeight if let webContentHeight = webContentHeight, webContentHeight > 0 { totalTextHeight += webContentHeight + NotificationCell.Size.WebHeightCorrection + NotificationCell.Size.InnerMargin } if notification.canReplyToComment || notification.canBackFollow { totalTextHeight += NotificationCell.Size.ButtonHeight + NotificationCell.Size.InnerMargin } let totalImageHeight = NotificationCell.Size.imageHeight( imageRegion: notification.imageRegion ) var height = max(totalTextHeight, totalImageHeight) height += 2 * NotificationCell.Size.SideMargins if let webContentHeight = webContentHeight { item.calculatedCellHeights.webContent = webContentHeight } item.calculatedCellHeights.oneColumn = height item.calculatedCellHeights.multiColumn = height } }
mit
f33d4722d08eebbf570a95c6b670a46d
34.010204
95
0.662198
5.55178
false
false
false
false
ktmswzw/FeelClient
FeelingClient/MVC/M/Message.swift
1
2799
// // Message.swift // FeelingClient // // Created by vincent on 9/3/16. // Copyright © 2016 xecoder. All rights reserved. // import Foundation import ObjectMapper class MessageBean: BaseModel { override static func newInstance() -> Mappable { return MessageBean(); } override func mapping(map: Map) { super.mapping(map) id <- map["id"] to <- map["to"] from <- map["from"] limitDate <- map["limit_date"] content <- map["content"] //photos <- map["photos"] video <- map["videoPath"] sound <- map["soundPath"] burnAfterReading <- map["burn_after_reading"] x <- map["x"] y <- map["y"] question <- map["question"] distance <- map["distance"] address <- map["address"] point <- map["point"] fromId <- map["fromId"] avatar <- map["avatar"] } var id: String = "" //接受对象 var to: String = "" // var from: String = "" //期限 var limitDate: String = "" //内容 var content: String = "" //图片地址 var photos: [String] = [] //视频地址 var video: String = "" //音频地址 var sound: String = "" //阅后即焚 var burnAfterReading: Bool = false //坐标 var x: Double = 0.0 //坐标 var y: Double = 0.0 //距离 var distance: Double = 0.0 var fromId = "" var avatar = "" //头像地址 var address = "" //问题 var question: String = "" var answer: String = "" var point: GeoJsonPoint? } //坐标点 class GeoJsonPoint:BaseModel { //坐标 var x: Double = 0.0 //坐标 var y: Double = 0.0 override static func newInstance() -> Mappable { return GeoJsonPoint(); } override func mapping(map: Map) { super.mapping(map) x <- map["x"] y <- map["y"] } } //解密消息 class MessagesSecret:BaseModel { var msgId: String? //期限 var limitDate: String? //内容 var content: String? //图片地址 var photos: [String] = [] //视频地址 var video: String? //音频地址 var sound: String? //阅后即焚 var burnAfterReading: Bool = false //答案 var answer: String? override static func newInstance() -> Mappable { return MessagesSecret(); } override func mapping(map: Map) { super.mapping(map) limitDate <- map["limit_date"] content <- map["content"] photos <- map["photos"] video <- map["videoPath"] sound <- map["soundPath"] answer <- map["answer"] burnAfterReading <- map["burn_after_reading"] } }
mit
b33fe0086168141ca92b4de4e531e0e6
19.952756
53
0.516917
3.917526
false
false
false
false
mbernson/HomeControl.iOS
Pods/Promissum/src/Promissum/PromiseSource.swift
1
6054
// // PromiseSource.swift // Promissum // // Created by Tom Lokhorst on 2014-10-11. // Copyright (c) 2014 Tom Lokhorst. All rights reserved. // import Foundation /** ## Creating Promises A PromiseSource is used to create a Promise that can be resolved or rejected. Example: ``` let source = PromiseSource<Int, String>() let promise = source.promise // Register handlers with Promise promise .then { value in print("The value is: \(value)") } .trap { error in print("The error is: \(error)") } // Resolve the source (will call the Promise handler) source.resolve(42) ``` Once a PromiseSource is Resolved or Rejected it cannot be changed anymore. All subsequent calls to `resolve` and `reject` are ignored. ## When to use A PromiseSource is needed when transforming an asynchronous operation into a Promise. Example: ``` func someOperationPromise() -> Promise<String, ErrorType> { let source = PromiseSource<String, ErrorType>() someOperation(callback: { (error, value) in if let error = error { source.reject(error) } if let value = value { source.resolve(value) } }) return promise } ``` ## Memory management Make sure, when creating a PromiseSource, that someone retains a reference to the source. In the example above the `someOperation` retains the callback. But in some cases, often when using weak delegates, the callback is not retained. In that case, you must manually retain the PromiseSource, or the Promise will never complete. Note that `PromiseSource.deinit` by default will log a warning when an unresolved PromiseSource is deallocated. */ public class PromiseSource<Value, Error> { typealias ResultHandler = (Result<Value, Error>) -> Void private var handlers: [(Result<Value, Error>) -> Void] = [] internal let dispatchKey: DispatchSpecificKey<Void> internal let dispatchMethod: DispatchMethod /// The current state of the PromiseSource private(set) public var state: State<Value, Error> /// Print a warning on deinit of an unresolved PromiseSource public var warnUnresolvedDeinit: Bool // MARK: Initializers & deinit internal convenience init(value: Value) { self.init(state: .resolved(value), dispatchKey: DispatchSpecificKey(), dispatchMethod: .unspecified, warnUnresolvedDeinit: false) } internal convenience init(error: Error) { self.init(state: .rejected(error), dispatchKey: DispatchSpecificKey(), dispatchMethod: .unspecified, warnUnresolvedDeinit: false) } /// Initialize a new Unresolved PromiseSource /// /// - parameter warnUnresolvedDeinit: Print a warning on deinit of an unresolved PromiseSource public convenience init(dispatch dispatchMethod: DispatchMethod = .unspecified, warnUnresolvedDeinit: Bool = true) { self.init(state: .unresolved, dispatchKey: DispatchSpecificKey(), dispatchMethod: dispatchMethod, warnUnresolvedDeinit: warnUnresolvedDeinit) } internal init(state: State<Value, Error>, dispatchKey: DispatchSpecificKey<Void>, dispatchMethod: DispatchMethod, warnUnresolvedDeinit: Bool) { self.state = state self.dispatchKey = dispatchKey self.dispatchMethod = dispatchMethod self.warnUnresolvedDeinit = warnUnresolvedDeinit } deinit { if warnUnresolvedDeinit { switch state { case .unresolved: print("PromiseSource.deinit: WARNING: Unresolved PromiseSource deallocated, maybe retain this object?") default: break } } } // MARK: Computed properties /// Promise related to this PromiseSource public var promise: Promise<Value, Error> { return Promise(source: self) } // MARK: Resolve / reject /// Resolve an Unresolved PromiseSource with supplied value. /// /// When called on a PromiseSource that is already Resolved or Rejected, the call is ignored. public func resolve(_ value: Value) { resolveResult(.value(value)) } /// Reject an Unresolved PromiseSource with supplied error. /// /// When called on a PromiseSource that is already Resolved or Rejected, the call is ignored. public func reject(_ error: Error) { resolveResult(.error(error)) } internal func resolveResult(_ result: Result<Value, Error>) { switch state { case .unresolved: state = result.state executeResultHandlers(result) default: break } } private func executeResultHandlers(_ result: Result<Value, Error>) { // Call all previously scheduled handlers callHandlers(result, handlers: handlers, dispatchKey: dispatchKey, dispatchMethod: dispatchMethod) // Cleanup handlers = [] } // MARK: Adding result handlers internal func addOrCallResultHandler(_ handler: @escaping (Result<Value, Error>) -> Void) { switch state { case .unresolved: // Save handler for later handlers.append(handler) case .resolved(let value): // Value is already available, call handler immediately callHandlers(Result.value(value), handlers: [handler], dispatchKey: dispatchKey, dispatchMethod: dispatchMethod) case .rejected(let error): // Error is already available, call handler immediately callHandlers(Result.error(error), handlers: [handler], dispatchKey: dispatchKey, dispatchMethod: dispatchMethod) } } } internal func callHandlers<T>(_ value: T, handlers: [(T) -> Void], dispatchKey: DispatchSpecificKey<Void>, dispatchMethod: DispatchMethod) { for handler in handlers { switch dispatchMethod { case .unspecified: // Main queue doesn't guarantee main thread, so this is merely an optimization if Thread.isMainThread { handler(value) } else { DispatchQueue.main.async { handler(value) } } case .synchronous: handler(value) case .queue(let targetQueue): let alreadyOnQueue = DispatchQueue.getSpecific(key: dispatchKey) != nil if alreadyOnQueue { handler(value) } else { targetQueue.async { handler(value) } } } } }
mit
70ef13d465768ebfa68cd674efc583dd
26.643836
145
0.703337
4.714953
false
false
false
false
brave/browser-ios
Client/Frontend/Widgets/SiteTableViewController.swift
1
6884
/* 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 Storage struct SiteTableViewControllerUX { static let HeaderHeight = CGFloat(25) static let RowHeight = CGFloat(58) static let HeaderBorderColor = UIColor(rgb: 0xCFD5D9).withAlphaComponent(0.8) static let HeaderTextColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.black : UIColor(rgb: 0x232323) static let HeaderBackgroundColor = UIColor(rgb: 0xECF0F3).withAlphaComponent(0.3) static let HeaderFont = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium) static let HeaderTextMargin = CGFloat(10) } class SiteTableViewHeader : UITableViewHeaderFooterView { // I can't get drawRect to play nicely with the glass background. As a fallback // we just use views for the top and bottom borders. let topBorder = UIView() let bottomBorder = UIView() let titleLabel = UILabel() override var textLabel: UILabel? { return titleLabel } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) topBorder.backgroundColor = UIColor.white bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor contentView.backgroundColor = UIColor.white titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight titleLabel.textColor = SiteTableViewControllerUX.HeaderTextColor titleLabel.textAlignment = .left addSubview(topBorder) addSubview(bottomBorder) contentView.addSubview(titleLabel) topBorder.snp.makeConstraints { make in make.left.right.equalTo(self) make.top.equalTo(self).offset(-0.5) make.height.equalTo(0.5) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(self) make.height.equalTo(0.5) } // A table view will initialize the header with CGSizeZero before applying the actual size. Hence, the label's constraints // must not impose a minimum width on the content view. titleLabel.snp.makeConstraints { make in make.left.equalTo(contentView).offset(SiteTableViewControllerUX.HeaderTextMargin).priority(999) make.right.equalTo(contentView).offset(-SiteTableViewControllerUX.HeaderTextMargin).priority(999) make.centerY.equalTo(contentView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /** * Provides base shared functionality for site rows and headers. */ class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { fileprivate let DefaultCellIdentifier = "Cell" fileprivate let CellIdentifier = "CellIdentifier" fileprivate let HeaderIdentifier = "HeaderIdentifier" var iconForSiteId = [Int : Favicon]() var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) return } tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: DefaultCellIdentifier) tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: CellIdentifier) tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier) tableView.layoutMargins = UIEdgeInsets.zero tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag tableView.backgroundColor = UIConstants.PanelBackgroundColor tableView.separatorColor = UIConstants.SeparatorColor tableView.accessibilityIdentifier = "SiteTable" tableView.cellLayoutMarginsFollowReadableWidth = false // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } func reloadData() { self.tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) if self.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath) { cell.separatorInset = UIEdgeInsets.zero } if tableView.isEditing == false { cell.gestureRecognizers?.forEach { cell.removeGestureRecognizer($0) } let lp = UILongPressGestureRecognizer(target: self, action: #selector(longPressOnCell)) cell.addGestureRecognizer(lp) } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderIdentifier) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return SiteTableViewControllerUX.HeaderHeight } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return SiteTableViewControllerUX.RowHeight } func tableView(_ tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: IndexPath) -> Bool { return false } func getLongPressUrl(forIndexPath indexPath: IndexPath) -> (URL?, [Int]?) { print("override in subclass for long press behaviour") return (nil, nil) } @objc func longPressOnCell(_ gesture: UILongPressGestureRecognizer) { if tableView.isEditing { //disable context menu on editing mode return } if gesture.state != .began { return } guard let cell = gesture.view as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else { return } let (url, folder) = getLongPressUrl(forIndexPath: indexPath) let tappedElement = ContextMenuHelper.Elements(link: url, image: nil, folder: folder) var p = getApp().window!.convert(cell.center, from:cell.superview!) p.x += cell.frame.width * 0.33 getApp().browserViewController.showContextMenu(tappedElement, touchPoint: p) } }
mpl-2.0
b29215fe3f2421036ec4966eb9e00b0f
38.563218
130
0.697995
5.332301
false
false
false
false
cuappdev/tempo
Tempo/Controllers/SettingsScrollViewController.swift
1
15374
// // SettingsScrollViewController.swift // Tempo // // Created by Keivan Shahida on 4/15/17. // Copyright © 2017 CUAppDev. All rights reserved. // import UIKit import FBSDKShareKit class SettingsScrollViewController: UIViewController, UIScrollViewDelegate { static let sharedInstance = SettingsScrollViewController() static let registeredForRemotePushNotificationsKey = "SettingsViewController.registeredForRemotePushNotificationsKey" static let presentedAlertForRemotePushNotificationsKey = "SettingsViewController.presentedAlertForRemotePushNotificationsKey" let buttonHeight: CGFloat = 50 var playerCenter = PlayerCenter.sharedInstance let spotifyDescription = "Log in to allow Tempo to add songs your find to your Spotify." var nameLabel: UILabel! var usernameLabel: UILabel! var initialsLabel: UILabel! var profilePicture: UIImageView! var initialsView: UIView! var spotifyTitle: UILabel! var spotifyDescriptionLabel: UILabel! var spotifyDescriptionView: UIView! var loginSpotifyButton: UIButton! var logoutSpotifyButton: UIButton! var toSpotifyButton: UIButton! var optionsTitle: UILabel! var notificationView: UIView! var notificationLabel: UILabel! var notificationSwitch: UISwitch! var enableMusicView: UIView! var enableMusicLabel: UILabel! var enableMusicSwitch: UISwitch! var aboutButton: UIButton! var logoutTempoButton: UIButton! var screenWidth: CGFloat! let sectionSpacing: CGFloat = 30 let viewPadding: CGFloat = 11 let settingsFont = UIFont(name: "AvenirNext-Regular", size: 14.0)! override func viewDidLoad() { super.viewDidLoad() title = "Settings" screenWidth = view.frame.width let scrollViewHeight = view.frame.height - tabBarHeight - miniPlayerHeight let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: scrollViewHeight)) scrollView.delegate = self scrollView.backgroundColor = .backgroundDarkGrey scrollView.bounces = false view = scrollView setupSettingsView() //FIX THIS !!! ALSO TEXT GETTING CUT OFF !!! updateSpotifyState() profilePicture.hnk_setImageFromURL(User.currentUser.imageURL) profilePicture.layer.masksToBounds = false profilePicture.layer.cornerRadius = profilePicture.frame.height/2 profilePicture.clipsToBounds = true scrollView.contentSize = CGSize(width: screenWidth, height: 480 + tabBarHeight + miniPlayerHeight + 50) } override func viewWillAppear(_ animated: Bool) { updateSpotifyState() notificationSwitch.setOn(User.currentUser.remotePushNotificationsEnabled, animated: false) enableMusicSwitch.setOn(UserDefaults.standard.bool(forKey: "music_on_off"), animated: false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) title = "Settings" view.backgroundColor = .readCellColor updateSpotifyState() profilePicture.hnk_setImageFromURL(User.currentUser.imageURL) } func setupSettingsView(){ //Spotify Section Title spotifyTitle = UILabel(frame: CGRect(x: 22, y: 30, width: 52, height: 18)) spotifyTitle.text = "SPOTIFY" spotifyTitle.font = settingsFont spotifyTitle.textColor = .cellOffWhite spotifyTitle.textAlignment = .left spotifyTitle.sizeToFit() view.addSubview(spotifyTitle) //Description View spotifyDescriptionView = UIView(frame: CGRect(x: 0, y: 59, width: screenWidth, height: 91)) spotifyDescriptionView.backgroundColor = .tempoDarkGray spotifyDescriptionLabel = UILabel(frame: CGRect(x: 0, y: 26.5, width: 276, height: 38.5)) spotifyDescriptionLabel.text = spotifyDescription spotifyDescriptionLabel.font = settingsFont spotifyDescriptionLabel.textColor = .sectionTitleGrey spotifyDescriptionLabel.textAlignment = .center spotifyDescriptionLabel.numberOfLines = 2 spotifyDescriptionLabel.sizeToFit() spotifyDescriptionLabel.center.x = spotifyDescriptionView.center.x spotifyDescriptionView.addSubview(spotifyDescriptionLabel) nameLabel = UILabel(frame: CGRect(x: 86, y: 22, width: 250, height: 24)) //h 22 nameLabel.text = "Name" nameLabel.font = UIFont(name: "AvenirNext-Medium", size: 16.0) nameLabel.textColor = .offWhite nameLabel.textAlignment = .left nameLabel.isHidden = true spotifyDescriptionView.addSubview(nameLabel) usernameLabel = UILabel(frame: CGRect(x: 86, y: 47, width: 200, height: 20)) usernameLabel.text = "@username" usernameLabel.font = settingsFont usernameLabel.textColor = .sectionTitleGrey usernameLabel.textAlignment = .left usernameLabel.isHidden = true spotifyDescriptionView.addSubview(usernameLabel) initialsLabel = UILabel(frame: CGRect(x: 22, y: 37, width: 48, height: 21)) initialsLabel.text = "" initialsLabel.font = UIFont(name: "AvenirNext-Medium", size: 18.0) initialsLabel.textColor = .sectionTitleGrey initialsLabel.textAlignment = .center initialsLabel.sizeToFit() spotifyDescriptionView.addSubview(initialsLabel) initialsView = UIView(frame: CGRect(x: 22, y: 22, width: 48, height: 48)) spotifyDescriptionView.addSubview(initialsView) profilePicture = UIImageView(frame: CGRect(x: 22, y: 22, width: 48, height: 48)) profilePicture.layer.cornerRadius = profilePicture.frame.width / 2.0 spotifyDescriptionView.addSubview(profilePicture) view.addSubview(spotifyDescriptionView) //Login Button loginSpotifyButton = UIButton(frame: CGRect(x: 0, y: 151, width: screenWidth, height: 50)) loginSpotifyButton.setTitleColor(.sectionTitleGrey, for: .normal) loginSpotifyButton.addTarget(self, action: #selector(loginToSpotify), for: .touchUpInside) loginSpotifyButton.setTitle("Log In to Spotify", for: .normal) loginSpotifyButton.titleLabel?.font = settingsFont loginSpotifyButton.backgroundColor = .tempoDarkGray loginSpotifyButton.center.x = view.center.x view.addSubview(loginSpotifyButton) //Log out Button logoutSpotifyButton = UIButton(frame: CGRect(x: 0, y: 151, width: screenWidth, height: 50)) logoutSpotifyButton.setTitleColor(.sectionTitleGrey, for: .normal) logoutSpotifyButton.addTarget(self, action: #selector(logOutSpotify), for: .touchUpInside) logoutSpotifyButton.setTitle("Log Out of Spotify", for: .normal) logoutSpotifyButton.titleLabel?.font = settingsFont logoutSpotifyButton.backgroundColor = .tempoDarkGray logoutSpotifyButton.center.x = view.center.x view.addSubview(logoutSpotifyButton) //Options Section Title optionsTitle = UILabel(frame: CGRect(x: 22, y: loginSpotifyButton.frame.origin.y + loginSpotifyButton.frame.height + sectionSpacing, width: 62.5, height: 20)) optionsTitle.text = "OPTIONS" optionsTitle.font = settingsFont optionsTitle.textColor = .cellOffWhite optionsTitle.textAlignment = .left optionsTitle.sizeToFit() view.addSubview(optionsTitle) //Notifications View notificationView = UIView(frame: CGRect(x: 0, y: optionsTitle.frame.origin.y + optionsTitle.frame.height + viewPadding, width: screenWidth, height: 50)) notificationView.backgroundColor = .tempoDarkGray notificationLabel = UILabel(frame: CGRect(x: 22, y: 15, width: 128, height: 20)) notificationLabel.text = "Enable Notifications" notificationLabel.font = settingsFont notificationLabel.textColor = .sectionTitleGrey notificationLabel.textAlignment = .left notificationLabel.sizeToFit() notificationView.addSubview(notificationLabel) notificationSwitch = UISwitch(frame: CGRect(x: 0, y: 0, width: 51, height: 31)) notificationSwitch.onTintColor = .tempoRed notificationSwitch.addTarget(self, action: #selector(toggledNotifications(_:)), for: .valueChanged) notificationView.addSubview(notificationSwitch) view.addSubview(notificationView) let centerNotificationSwitchY = NSLayoutConstraint(item: notificationSwitch, attribute: .centerY, relatedBy: .equal,toItem: self.notificationView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let trailingNotificationSwitchConstraints = NSLayoutConstraint(item: notificationSwitch, attribute: .trailingMargin, relatedBy: .equal, toItem: self.notificationView, attribute: .trailingMargin, multiplier: 1.0, constant: -15) notificationSwitch.translatesAutoresizingMaskIntoConstraints = false; self.view.addConstraints([centerNotificationSwitchY, trailingNotificationSwitchConstraints]) //Enable Music View enableMusicView = UIView(frame: CGRect(x: 0, y: notificationView.frame.origin.y + notificationView.frame.height + 1, width: screenWidth, height: 50)) enableMusicView.backgroundColor = .tempoDarkGray enableMusicLabel = UILabel(frame: CGRect(x: 22, y: 15, width: 166, height: 20)) enableMusicLabel.text = "Enable Music On App Exit" enableMusicLabel.font = settingsFont enableMusicLabel.textColor = .sectionTitleGrey enableMusicLabel.textAlignment = .left enableMusicLabel.sizeToFit() enableMusicView.addSubview(enableMusicLabel) enableMusicSwitch = UISwitch(frame: CGRect(x: 0, y: 0, width: 51, height: 31)) enableMusicSwitch.onTintColor = .tempoRed enableMusicSwitch.addTarget(self, action: #selector(toggledMusicOnExit(_:)), for: .valueChanged) enableMusicView.addSubview(enableMusicSwitch) view.addSubview(enableMusicView) let centerY = NSLayoutConstraint(item: enableMusicSwitch, attribute: .centerY, relatedBy: .equal, toItem: self.enableMusicView, attribute: .centerY, multiplier: 1.0, constant: 0.0) let trailingConstraints = NSLayoutConstraint(item: enableMusicSwitch, attribute: .trailingMargin, relatedBy: .equal, toItem: self.enableMusicView, attribute: .trailingMargin, multiplier: 1.0, constant: -15) enableMusicSwitch.translatesAutoresizingMaskIntoConstraints = false; self.view.addConstraints([trailingConstraints, centerY]) //About Button aboutButton = UIButton(frame: CGRect(x: 0, y: enableMusicView.frame.origin.y + enableMusicView.frame.height + sectionSpacing, width: screenWidth, height: 50)) aboutButton.setTitleColor(.cellOffWhite, for: .normal) aboutButton.setTitle("About", for: .normal) aboutButton.titleLabel?.font = settingsFont aboutButton.backgroundColor = .tempoDarkGray aboutButton.center.x = view.center.x aboutButton.addTarget(self, action: #selector(navigateToAbout), for: .touchUpInside) view.addSubview(aboutButton) //Log out Tempo logoutTempoButton = UIButton(frame: CGRect(x: 0, y: aboutButton.frame.origin.y + aboutButton.frame.height + 1, width: screenWidth, height: 50)) logoutTempoButton.setTitleColor(.cellOffWhite, for: .normal) logoutTempoButton.setTitle("Log Out", for: .normal) logoutTempoButton.titleLabel?.font = settingsFont logoutTempoButton.backgroundColor = .tempoDarkGray logoutTempoButton.center.x = view.center.x logoutTempoButton.addTarget(self, action: #selector(logOutUser), for: .touchUpInside) view.addSubview(logoutTempoButton) toSpotifyButton = UIButton(frame: CGRect(x: 0, y: 59, width: screenWidth, height: 91)) toSpotifyButton.addTarget(self, action: #selector(goToSpotify(_:)), for: .touchUpInside) view.addSubview(toSpotifyButton) view.bringSubview(toFront: toSpotifyButton) } // Can be called after successful login to Spotify SDK func updateSpotifyState() { if let session = SPTAuth.defaultInstance().session, session.isValid() { SpotifyController.sharedController.setSpotifyUser(session.accessToken, completion: { (success: Bool) in DispatchQueue.main.async { if let currentSpotifyUser = User.currentUser.currentSpotifyUser { self.nameLabel?.text = "\(User.currentUser.firstName) \(User.currentUser.lastName)" self.usernameLabel?.text = "@\(currentSpotifyUser.username)" self.initialsLabel?.text = setUserInitials(firstName: User.currentUser.firstName, lastName: User.currentUser.lastName) self.loggedInToSpotify(session.isValid()) } } }) } else { loggedInToSpotify(false) } playerCenter.updateAddButton() playerCenter.getPlayerDelegate()?.didToggleAdd?() } func loggedInToSpotify(_ loggedIn: Bool) { toSpotifyButton.isEnabled = loggedIn loginSpotifyButton?.isHidden = loggedIn spotifyDescriptionLabel?.isHidden = loggedIn profilePicture?.isHidden = !loggedIn initialsView.isHidden = !loggedIn initialsLabel?.isHidden = !loggedIn nameLabel?.isHidden = !loggedIn usernameLabel?.isHidden = !loggedIn logoutSpotifyButton?.isHidden = !loggedIn } func loginToSpotify() { SpotifyController.sharedController.loginToSpotify(vc: self) { (success) in if success { self.updateSpotifyState() } } } func logOutSpotify(_ sender: UIButton) { SpotifyController.sharedController.closeCurrentSpotifySession() User.currentUser.currentSpotifyUser = nil updateSpotifyState() } func goToSpotify(_ sender: UIButton) { SpotifyController.sharedController.openSpotifyURL() } func toggledNotifications(_ sender: UISwitch) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let didRegisterForPushNotifications = UserDefaults.standard.bool(forKey: SettingsScrollViewController.registeredForRemotePushNotificationsKey) let didPresentAlertForPushNotifications = UserDefaults.standard.bool(forKey: SettingsScrollViewController.presentedAlertForRemotePushNotificationsKey) if didPresentAlertForPushNotifications && !UIApplication.shared.isRegisteredForRemoteNotifications && sender.isOn { sender.setOn(false, animated: false) showPromptIfPushNotificationsDisabled() return } if sender.isOn && UserDefaults.standard.data(forKey: AppDelegate.remotePushNotificationsDeviceTokenKey) == nil { appDelegate.registerForRemotePushNotifications() return } if let deviceToken = UserDefaults.standard.data(forKey: AppDelegate.remotePushNotificationsDeviceTokenKey), !didRegisterForPushNotifications { API.sharedAPI.registerForRemotePushNotificationsWithDeviceToken(deviceToken, completion: { _ in }) return } let enabled = sender.isOn API.sharedAPI.toggleRemotePushNotifications(userID: User.currentUser.id, enabled: enabled, completion: { (success: Bool) in if !success { sender.setOn(!enabled, animated: true) } }) } func toggledMusicOnExit(_ sender: UISwitch) { let enabled = UserDefaults.standard.bool(forKey: "music_on_off") UserDefaults.standard.set(!enabled, forKey: "music_on_off") sender.setOn(UserDefaults.standard.bool(forKey: "music_on_off"), animated: true) } //!!! // TO DO: CREATE FUNCTION TO CHANGE BUTTON TITLE OPACITY !!! //!!! func navigateToAbout() { navigationController?.pushViewController(AboutViewController.sharedInstance, animated: true) } func logOutUser() { let appDelegate = UIApplication.shared.delegate as! AppDelegate PlayerCenter.sharedInstance.resetPlayerCells() FBSDKAccessToken.setCurrent(nil) appDelegate.toggleRootVC(toTabButton: 0) appDelegate.feedVC.refreshNeeded = true } func showPromptIfPushNotificationsDisabled() { let alertController = UIAlertController(title: "Push Notifications Disabled", message: "Please enable push notifications for Tempo in the Settings app", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) in if let url = URL(string:UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(url) } }) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } }
mit
e3d1da3657d0a47d3c68c87310f6c891
39.562005
228
0.773499
4.359898
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/UploadWidget/WidgetElements/CLDWidgetAssetContainer.swift
1
3309
// // CLDWidgetAssetContainer.swift // // Copyright (c) 2020 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import AVKit class CLDWidgetAssetContainer: NSObject { enum AssetType: Int { case image case video } private(set) var originalImage : UIImage? var editedImage : UIImage? private(set) var originalVideo : AVPlayerItem? var presentationImage: UIImage private(set) var assetType : AssetType init(originalImage: UIImage, editedImage: UIImage) { self.originalImage = originalImage self.editedImage = editedImage self.presentationImage = editedImage assetType = .image super.init() } init(videoUrl: URL) { let playerItem = AVPlayerItem(url: videoUrl) self.originalVideo = playerItem self.presentationImage = CLDWidgetAssetContainer.createThumbnailForVideo(playerItem: self.originalVideo) assetType = .video super.init() } init(videoItem: AVPlayerItem) { self.originalVideo = videoItem self.presentationImage = CLDWidgetAssetContainer.createThumbnailForVideo(playerItem: self.originalVideo) assetType = .video super.init() } private static func createThumbnailForVideo(playerItem: AVPlayerItem?) -> UIImage { if let urlAsset = playerItem?.asset as? AVURLAsset { let url = urlAsset.url let asset = AVAsset(url: url) let avAssetImageGenerator = AVAssetImageGenerator(asset: asset) avAssetImageGenerator.appliesPreferredTrackTransform = true let thumnailTime = CMTimeMake(value: 2, timescale: 1) do { let cgThumbImage = try avAssetImageGenerator.copyCGImage(at: thumnailTime, actualTime: nil) return UIImage(cgImage: cgThumbImage) } catch { print(error.localizedDescription) return UIImage() } } else { return UIImage() } } }
mit
8d5602c3d6f30bfd2be75ee7bddce0fa
34.202128
112
0.642792
5.051908
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Compose/GroupCreateViewController.swift
11
6535
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class GroupCreateViewController: AAViewController, UITextFieldDelegate { private var addPhotoButton = UIButton() private var avatarImageView = UIImageView() private var hint = UILabel() private var groupName = UITextField() private var groupNameFieldSeparator = UIView() private var image: UIImage? override init(){ super.init(nibName: nil, bundle: nil) self.navigationItem.title = NSLocalizedString("CreateGroupTitle", comment: "Compose Title") self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: localized("NavigationNext"), style: UIBarButtonItemStyle.Plain, target: self, action: "doNext") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = MainAppTheme.list.bgColor view.addSubview(addPhotoButton) view.addSubview(avatarImageView) view.addSubview(hint) view.addSubview(groupName) view.addSubview(groupNameFieldSeparator) UIGraphicsBeginImageContextWithOptions(CGSize(width: 110, height: 110), false, 0.0); let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor); CGContextFillEllipseInRect(context, CGRectMake(0.0, 0.0, 110.0, 110.0)); CGContextSetStrokeColorWithColor(context, UIColor.RGB(0xd9d9d9).CGColor); CGContextSetLineWidth(context, 1.0); CGContextStrokeEllipseInRect(context, CGRectMake(0.5, 0.5, 109.0, 109.0)); let buttonImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); addPhotoButton.exclusiveTouch = true addPhotoButton.setBackgroundImage(buttonImage, forState: UIControlState.Normal) addPhotoButton.addTarget(self, action: "photoTap", forControlEvents: UIControlEvents.TouchUpInside) let addPhotoLabelFirst = UILabel() addPhotoLabelFirst.text = NSLocalizedString("AuthProfileAddPhoto1", comment: "Title") addPhotoLabelFirst.font = UIFont.systemFontOfSize(15.0) addPhotoLabelFirst.backgroundColor = UIColor.clearColor() addPhotoLabelFirst.textColor = UIColor.RGB(0xd9d9d9) addPhotoLabelFirst.sizeToFit() let addPhotoLabelSecond = UILabel() addPhotoLabelSecond.text = NSLocalizedString("AuthProfileAddPhoto2", comment: "Title") addPhotoLabelSecond.font = UIFont.systemFontOfSize(15.0) addPhotoLabelSecond.backgroundColor = UIColor.clearColor() addPhotoLabelSecond.textColor = UIColor.RGB(0xd9d9d9) addPhotoLabelSecond.sizeToFit() addPhotoButton.addSubview(addPhotoLabelFirst) addPhotoButton.addSubview(addPhotoLabelSecond) addPhotoLabelFirst.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelFirst.frame.size.width) / 2, 22, addPhotoLabelFirst.frame.size.width, addPhotoLabelFirst.frame.size.height)); addPhotoLabelSecond.frame = CGRectIntegral(CGRectMake((80 - addPhotoLabelSecond.frame.size.width) / 2, 22 + 22, addPhotoLabelSecond.frame.size.width, addPhotoLabelSecond.frame.size.height)); // groupName.backgroundColor = UIColor.whiteColor() groupName.backgroundColor = MainAppTheme.list.bgColor groupName.textColor = MainAppTheme.list.textColor groupName.font = UIFont.systemFontOfSize(20) groupName.keyboardType = UIKeyboardType.Default groupName.returnKeyType = UIReturnKeyType.Next groupName.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("CreateGroupNamePlaceholder", comment: "Enter group title"), attributes: [NSForegroundColorAttributeName: MainAppTheme.list.hintColor]) groupName.delegate = self groupName.contentVerticalAlignment = UIControlContentVerticalAlignment.Center groupName.autocapitalizationType = UITextAutocapitalizationType.Words groupNameFieldSeparator.backgroundColor = MainAppTheme.list.separatorColor hint.text = localized("CreateGroupHint") hint.font = UIFont.systemFontOfSize(15) hint.lineBreakMode = .ByWordWrapping hint.numberOfLines = 0 hint.textColor = MainAppTheme.list.hintColor } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let screenSize = UIScreen.mainScreen().bounds.size avatarImageView.frame = CGRectMake(20, 20 + 66, 80, 80) addPhotoButton.frame = avatarImageView.frame hint.frame = CGRectMake(120, 20 + 66, screenSize.width - 140, 80) groupName.frame = CGRectMake(20, 106 + 66, screenSize.width - 20, 56.0) groupNameFieldSeparator.frame = CGRectMake(20, 156 + 66, screenSize.width - 20, 1) } func photoTap() { let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"], cancelButton: "AlertCancel", destructButton: self.avatarImageView.image != nil ? "PhotoRemove" : nil, sourceView: self.view, sourceRect: self.view.bounds, tapClosure: { (index) -> () in if index == -2 { self.avatarImageView.image = nil self.image = nil } else if index >= 0 { let takePhoto: Bool = (index == 0) && hasCamera self.pickAvatar(takePhoto, closure: { (image) -> () in self.image = image self.avatarImageView.image = image.roundImage(80) }) } }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) groupName.becomeFirstResponder() } func textFieldShouldReturn(textField: UITextField) -> Bool { doNext() return false } func doNext() { let title = groupName.text!.trim() if (title.length == 0) { shakeView(groupName, originalX: groupName.frame.origin.x) return } navigateNext(GroupMembersController(title: title, image: image), removeCurrent: true) } }
mit
04d7fffbde3a6899dbddab1d1d7c0cdb
43.767123
222
0.669472
5.436772
false
false
false
false
brentdax/swift
test/Interpreter/SDK/objc_extensions.swift
3
1139
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation extension NSObject { func frob() { print("I've been frobbed!") } var asHerself : NSObject { return self } var blackHoleWithHawkingRadiation : NSObject? { get { print("e+") return nil } set { print("e-") } } } var o = NSObject() func drop(_ x: NSObject?) {} // CHECK: true print(o.responds(to: "frob")) // CHECK: true print(o.responds(to: "asHerself")) // CHECK: false print(o.responds(to: "setAsHerself:")) // CHECK: true print(o.responds(to: "blackHoleWithHawkingRadiation")) // CHECK: true print(o.responds(to: "setBlackHoleWithHawkingRadiation:")) // Test #selector for referring to methods. // CHECK: true print(o.responds(to: #selector(NSObject.frob))) // CHECK: I've been frobbed! o.frob() // CHECK: true print(o === o.asHerself) // CHECK: e+ drop(o.blackHoleWithHawkingRadiation) // CHECK: e- o.blackHoleWithHawkingRadiation = NSObject() // Use of extensions via bridging let str = "Hello, world" // CHECK: I've been frobbed! str.frob()
apache-2.0
de7040c5ed62dec55dc79e9ab64531e2
18.305085
58
0.664618
3.199438
false
false
false
false
bengottlieb/ios
FiveCalls/FiveCalls/BorderedButton.swift
4
2324
// // BorderedButton.swift // FiveCalls // // Created by Ben Scheirman on 2/6/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit @IBDesignable class BorderedButton : UIButton { @IBInspectable var borderWidth: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable var borderColor: UIColor = .black { didSet { setNeedsDisplay() } } @IBInspectable var allBorders: Bool { get { return leftBorder && topBorder && rightBorder && bottomBorder } set { leftBorder = newValue topBorder = newValue rightBorder = newValue leftBorder = newValue } } @IBInspectable var leftBorder: Bool = false { didSet { setNeedsDisplay() } } @IBInspectable var topBorder: Bool = false { didSet { setNeedsDisplay() } } @IBInspectable var rightBorder: Bool = false{ didSet { setNeedsDisplay() } } @IBInspectable var bottomBorder: Bool = false { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { guard borderWidth > 0 else { return } guard let context = UIGraphicsGetCurrentContext() else { return } context.setLineWidth(borderWidth) context.setStrokeColor(borderColor.cgColor) let topLeft = CGPoint.zero let bottomLeft = CGPoint(x: 0, y: bounds.size.height) let topRight = CGPoint(x: bounds.size.width, y: 0) let bottomRight = CGPoint(x: bounds.size.width, y: bounds.size.height) if leftBorder { context.move(to: topLeft) context.addLine(to: bottomLeft) } if topBorder { context.move(to: topLeft) context.addLine(to: topRight) } if rightBorder { context.move(to: topRight) context.addLine(to: bottomRight) } if bottomBorder { context.move(to: bottomLeft) context.addLine(to: bottomRight) } context.strokePath() } }
mit
c45fe94a8dcb62266bb5ead85163fdda
21.553398
78
0.524322
5.196868
false
false
false
false
evan-liu/FormationLayout
Documentation/Doc.playground/Sources/demo.swift
1
1840
import UIKit public func createIcon() -> UIView { return UIImageView(image: UIImage(named: "swift")) } public func createView(size: CGFloat = 100) -> UIView { let view = UIView(frame: CGRect(x: 0, y: 0, width: size, height: size)) view.layer.backgroundColor = UIColor.white.cgColor view.layer.borderColor = UIColor.lightGray.cgColor view.layer.borderWidth = 0.2 return view } public func layoutView(view: UIView, size: CGFloat = 100) { NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size).isActive = true NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size).isActive = true view.layoutIfNeeded() } public func demo(size: CGFloat = 100, block:(UIView, UIView) -> Void) -> UIView { let view = createView(size: size) block(view, createIcon()) layoutView(view: view, size: size) return view } public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView) -> Void) -> UIView { let view = createView(size: size) block(view, createIcon(), createIcon()) layoutView(view: view, size: size) return view } public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView, UIView) -> Void) -> UIView { let view = createView(size: size) block(view, createIcon(), createIcon(), createIcon()) layoutView(view: view, size: size) return view } public func demo(size: CGFloat = 100, block: (UIView, UIView, UIView, UIView, UIView, UIView) -> Void) -> UIView { let view = createView(size: size) block(view, createIcon(), createIcon(), createIcon(), createIcon(), createIcon()) layoutView(view: view, size: size) return view }
mit
88038c60fd18f9f24fa4248f57b15212
31.857143
161
0.672826
3.965517
false
false
false
false
TTVS/NightOut
Clubber/VerificationViewController.swift
1
2347
// // VerificationViewController.swift // Clubber // // Created by Terra on 8/19/15. // Copyright (c) 2015 Dino Media Asia. All rights reserved. // import UIKit class VerificationViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate { // swipe to go back let swipeBack = UISwipeGestureRecognizer() @IBOutlet var verificationCodeTextField: UITextField! // Go To HANavigationVC @IBAction func signUpPressed(sender: UIButton) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewControllerWithIdentifier("HANavigationVC") as! UINavigationController self.presentViewController(controller, animated: true, completion: nil) } @IBAction func back(sender: AnyObject) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } override func viewDidLoad() { super.viewDidLoad() // swipe to go back swipeBack.direction = UISwipeGestureRecognizerDirection.Right swipeBack.addTarget(self, action: "swipeBack:") self.view.addGestureRecognizer(swipeBack) self.verificationCodeTextField.delegate = self //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard") self.view.addGestureRecognizer(tap) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { self.verificationCodeTextField.resignFirstResponder() return true } //Calls this function when the tap is recognized. func DismissKeyboard(){ //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } //MARK: Swipe to go Back Gesture func swipeBack(sender: UISwipeGestureRecognizer) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } }
apache-2.0
e7dd3de9422729de3b73c1a23a980ed5
29.480519
120
0.663826
5.45814
false
false
false
false
thanhtrdang/FluentYogaKit
FluentYogaKit/Duration.swift
1
6330
// Copyright 2016 Swift Studies // // 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 /// Definition of a block that can be used for measurements public typealias MeasuredBlock = () -> Void private var depth = 0 private var depthIndent: String { return String(repeating: "\t", count: depth) } private var now: Double { return Date().timeIntervalSinceReferenceDate } /// Define different styles of reporting public enum MeasurementLogStyle { /// Don't measure anything case none /// Log results of measurements to the console case print } /// Provides static methods for performing measurements public class Duration { private static var timingStack = [(startTime: Double, name: String, reported: Bool)]() private static var logStyleStack = [MeasurementLogStyle]() /// When you are releasing and want to turn off logging, and your library /// may be used by another, it is better to push/pop a logging state. This /// will ensure your settings do not impact those of other modules. By pushing /// your desired log style, and sub-sequently pop'ing before returning from /// your measured method only your desired measuremets will be logged. public static func pushLogStyle(style: MeasurementLogStyle) { logStyleStack.append(logStyle) logStyle = style } /// Pops the last pushed logging style and restores the logging style to /// its previous style public static func popLogStyle() { logStyle = logStyleStack.removeLast() } /// Set to control how measurements are reported. It is recommended to use /// `pushLogStyle` and `popLogStyle` if you intend to make your module /// available for others to use public static var logStyle = MeasurementLogStyle.print /// Ensures that if any parent measurement boundaries have not yet resulted /// in output that their headers are displayed private static func reportContaining() { if depth > 0 && logStyle == .print { for stackPointer in 0 ..< timingStack.count { let containingMeasurement = timingStack[stackPointer] if !containingMeasurement.reported { print(String(repeating: "\t" + "Measuring \(containingMeasurement.name):", count: stackPointer)) timingStack[stackPointer] = (containingMeasurement.startTime, containingMeasurement.name, true) } } } } /// Start a measurement, call `stopMeasurement` when you have completed your /// desired operations. The `name` will be used to identify this specific /// measurement. Multiple calls will nest measurements within each other. public static func startMeasurement(_ name: String) { reportContaining() timingStack.append((now, name, false)) depth += 1 } /// Stops measuring and generates a log entry. Note if you wish to include /// additional information (for example, the number of items processed) then /// you can use the `stopMeasurement(executionDetails:String?)` version of /// the function. public static func stopMeasurement() -> Double { return stopMeasurement(nil) } /// Prints a message, optionally with a time stamp (measured from the /// start of the current measurement. public static func log(message: String, includeTimeStamp: Bool = false) { reportContaining() if includeTimeStamp { let currentTime = now let timeStamp = currentTime - timingStack[timingStack.count - 1].startTime return print("\(depthIndent)\(message) \(timeStamp.milliSeconds)ms") } else { return print("\(depthIndent)\(message)") } } /// Stop measuring operations and generate log entry. public static func stopMeasurement(_ executionDetails: String?) -> Double { let endTime = now precondition(depth > 0, "Attempt to stop a measurement when none has been started") let beginning = timingStack.removeLast() depth -= 1 let took = endTime - beginning.startTime if logStyle == .print { print("\(depthIndent)\(beginning.name) took: \(took.milliSeconds)" + (executionDetails == nil ? "" : " (\(executionDetails!))")) } return took } /// /// Calls a particular block measuring the time taken to complete the block. /// @discardableResult public static func measure(_ name: String, block: MeasuredBlock) -> Double { startMeasurement(name) block() return stopMeasurement() } /// /// Calls a particular block the specified number of times, returning the average /// number of seconds it took to complete the code. The time /// take for each iteration will be logged as well as the average time and /// standard deviation. @discardableResult public static func measure(name: String, iterations: Int = 10, forBlock block: MeasuredBlock) -> [String: Double] { precondition(iterations > 0, "Iterations must be a positive integer") var data: [String: Double] = [:] var total: Double = 0 var samples = [Double]() if logStyle == .print { print("\(depthIndent)Measuring \(name)") } for i in 0 ..< iterations { let took = measure("Iteration \(i + 1)", block: block) samples.append(took) total += took data["\(i + 1)"] = took } let mean = total / Double(iterations) var deviation = 0.0 for result in samples { let difference = result - mean deviation += difference * difference } let variance = deviation / Double(iterations) data["average"] = mean data["stddev"] = variance if logStyle == .print { print("\(depthIndent)\(name) Average", mean.milliSeconds) print("\(depthIndent)\(name) STD Dev.", variance.milliSeconds) } return data } } private extension Double { var milliSeconds: String { return String(format: "%03.2fms", self * 1000) } }
apache-2.0
e6cf54755cf4a8128a4de5a06a31a5e7
30.809045
134
0.690047
4.606987
false
false
false
false
Nautiyalsachin/SwiftMQTT
SwiftMQTT/SwiftMQTT/Models/MQTTStreamable.swift
1
3749
// // MQTTStreamable.swift // SwiftMQTT // // Created by David Giovannini on 6/9/17. // Copyright © 2017 Ankit. All rights reserved. // import Foundation /* OCI Changes: Optimizations to receiveDataOnStream Fixed bugs where read/writes needed to be in loops Handle more unhappy paths */ typealias StreamReader = (_ buffer: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int typealias StreamWriter = (_ buffer: UnsafePointer<UInt8>, _ len: Int) -> Int protocol MQTTStreamable { init?(len: Int, from read: StreamReader) func write(to write: StreamWriter) -> Bool } extension MQTTStreamable { static func readPackedLength(from read: StreamReader) -> Int? { var multiplier = 1 var value = 0 var encodedByte: UInt8 = 0 repeat { let bytesRead = read(&encodedByte, 1) if bytesRead < 0 { return nil } value += (Int(encodedByte) & 127) * multiplier multiplier *= 128 } while ((Int(encodedByte) & 128) != 0) return value <= 128*128*128 ? value : nil } } extension Data: MQTTStreamable { init?(len: Int, from read: StreamReader) { self.init(count: len) if self.read(from: read) == false { return nil } } mutating func read(from read: StreamReader) -> Bool { let totalLength = self.count var readLength: Int = 0 self.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) in repeat { let b = UnsafeMutablePointer(mutating: buffer) + readLength let bytesRead = read(b, totalLength - readLength) if bytesRead < 0 { break } readLength += bytesRead } while readLength < totalLength } return readLength == totalLength } func write(to write: StreamWriter) -> Bool { let totalLength = self.count guard totalLength <= 128*128*128 else { return false } var writeLength: Int = 0 self.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) in repeat { let b = UnsafeMutablePointer(mutating: buffer) + writeLength let byteWritten = write(b, totalLength - writeLength) if byteWritten < 0 { break } writeLength += byteWritten } while writeLength < totalLength } return writeLength == totalLength } } /* // TODO: create a file strategy for large messages extension FileHandle: MQTTStreamable { static let chunkSize: Int = 1024 * 64 private func read(from read: StreamReader, totalLength: UInt64) -> Bool { var readLength: UInt64 = 0 repeat { if let data = Data(len: FileHandle.chunkSize, from: read) { self.write(data) readLength += UInt64(FileHandle.chunkSize) } else { break } } while readLength == totalLength return readLength == totalLength } func write(to write: StreamWriter) -> Bool { let totalLength = self.seekToEndOfFile() self.seek(toFileOffset: 0) guard totalLength <= 128*128*128 else { return false } var writeLength: UInt64 = 0 repeat { let data = self.readData(ofLength: FileHandle.chunkSize) if data.count == 0 { break } if data.write(to: write) == false { break } writeLength += UInt64(data.count) } while writeLength < totalLength return writeLength == totalLength } } */
mit
370e89445b4ceed7edb6ed9f11b1b57b
28.054264
83
0.560832
4.836129
false
false
false
false
byvapps/ByvManager-iOS
ByvManager/Classes/ConManager.swift
1
17270
// // ByvConnectionManage.swift // Pods // // Created by Adrian Apodaca on 26/10/16. // // import Foundation import Alamofire import SwiftyJSON import SVProgressHUD public typealias Params = [String: Any] public typealias ConError = (status: Int, error_id: String, error_description: String, localized_description: String, response: DataResponse<Data>?) public typealias SuccessHandler = (_ response: DataResponse<Data>?) -> Void public typealias ErrorHandler = (_ error: ConError) -> Void public typealias CompletionHandler = () -> Void public struct ConManager { static private var authManager:SessionManager? = nil static private let defaultManager = SessionManager.default /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, /// `method`, `parameters`, `encoding` and `headers`. /// /// - parameter url: The URL. /// - parameter method: The HTTP method. `.get` by default. /// - parameter parameters: The parameters. `nil` by default. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. /// - parameter headers: The HTTP headers. `nil` by default. /// /// - returns: The created `DataRequest`. @discardableResult public static func request( _ path: URLConvertible, auth: Bool, method: HTTPMethod = .get, params: Params? = nil, encoding: ParameterEncoding,// = URLEncoding.default, // JSONEncoding.default sendDevice: Bool = true, sendLanguage: Bool = true, extraHeaders: [String: String] = [:]) -> DataRequest { var manager = defaultManager if auth { if authManager == nil { let oAuthHandler = OAuthHandler() authManager = SessionManager() authManager!.adapter = oAuthHandler authManager!.retrier = oAuthHandler } manager = authManager! } var headers: HTTPHeaders = [:] if sendDevice, let dId = Device().deviceId { headers["DeviceId"] = "\(dId)" } if sendLanguage { var langCode = Locale.current.languageCode if let lang = UserDefaults.standard.array(forKey: "AppleLanguages")?.first as? String { langCode = lang } if let langCode = langCode { headers["DeviceLang"] = langCode } } for key in extraHeaders.keys { headers[key] = extraHeaders[key] } var url = "\(Environment.baseUrl())/\(path)" if "\(path)".hasPrefix("http") { url = "\(path)" } return manager.request( url, method: method, parameters: params, encoding: encoding, headers: headers ) } // MARK: - public methods public static func paginatedInfo(_ responseData:DataResponse<Data>?) -> (pages: Int?, count: Int?) { var pages: Int? = nil var count: Int? = nil if responseData?.data != nil { if let pagesStr: String = responseData?.response?.allHeaderFields["X-Total-Pages"] as? String, let pagesInt: Int = Int(pagesStr), let countStr: String = responseData?.response?.allHeaderFields["X-Total-Count"] as? String, let countInt: Int = Int(countStr){ pages = pagesInt count = countInt } } return (pages, count) } public static func OPTIONS(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .options, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func GET(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .get, auth: auth, encoding: URLEncoding.default, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func LIST(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .get, auth: auth, encoding: URLEncoding.default, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func HEAD(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .head, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func POST(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .post, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func PUT(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .put, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func PATCH(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .patch, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func DELETE(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .delete, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func TRACE(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .trace, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func CONNECT(_ path: URLConvertible, params: Params? = nil, auth: Bool = false, encoding: ParameterEncoding = JSONEncoding.default, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { ConManager.connection(path, params: params, method: .connect, auth: auth, encoding: encoding, extraHeaders: extraHeaders, background: background, success: success, failed: failed, completion: completion) } public static func connection(_ path: URLConvertible, params: Params? = nil, method: HTTPMethod = .get, auth: Bool = false, encoding: ParameterEncoding, extraHeaders: [String: String] = [:], background: Bool = true, success: SuccessHandler? = nil, failed: ErrorHandler? = nil, completion: CompletionHandler? = nil) { if !background { SVProgressHUD.show() } self.request(path, auth: auth, method: method, params: params, encoding: encoding, sendDevice: true, sendLanguage: true, extraHeaders: extraHeaders) .validate(statusCode: 200..<300) .responseData { response in if ByvManager.debugMode { print("REQUEST:\nParams:") dump(params) debugPrint(response) } var responseCode: Int = 500 if let code = response.response?.statusCode { responseCode = code } switch response.result { case .success: if !background { SVProgressHUD.dismiss() } success?(response) case .failure(let error): if let data = response.data { let result = String(data: data, encoding: .utf8) print("Error(\(responseCode)): \(String(describing: result))") let err = ConManager.getError(response, _error: error, _code: responseCode) if !background { SVProgressHUD.showError(withStatus: err.localized_description) } failed?(err) } } completion?() } } // MARK: - private private static func getError(_ response: DataResponse<Data>?, _error: Error, _code: Int ) -> ConError { var error:ConError = ConError(status: _code, error_id: "", error_description: "", localized_description: _error.localizedDescription, response: response) if let data:Data = response?.data { do { let json = try JSON(data: data) if let status: Int = json["status"].int { error.status = status } if let error_id: String = json["errorKey"].string { error.error_id = error_id } if let error_description: String = json["errorDescription"].string { error.error_description = error_description error.localized_description = error_description } if let localized_description: String = json["localizedDescription"].string { error.localized_description = localized_description } else if let message: String = json["message"].string { error.localized_description = message } } catch { print("JSON parse ERROR") } } return error } }
mit
d7f4938aedc0522627613f5b17393c49
43.510309
161
0.43399
6.614324
false
false
false
false
vlevschanov/Arduino
iOS/iCar/iCar/Model/Settings.swift
1
1444
// // Settings.swift // iCar // // Created by Viktor Levshchanov on 4/17/17. // Copyright © 2017 Viktor Levshchanov. All rights reserved. // struct Settings { var frontLeftForwardSpeed: Int = 0 var frontLeftBackwardSpeed: Int = 0 var frontRightForwardSpeed: Int = 0 var frontRightBackwardSpeed: Int = 0 var rearLeftForwardSpeed: Int = 0 var rearLeftBackwardSpeed: Int = 0 var rearRightForwardSpeed: Int = 0 var rearRightBackwardSpeed: Int = 0 init() { } init(withJson json: [String:Any]) { frontLeftForwardSpeed = json["fl_fwd"] as! Int frontLeftBackwardSpeed = json["fl_bwd"] as! Int frontRightForwardSpeed = json["fr_fwd"] as! Int frontRightBackwardSpeed = json["fr_bwd"] as! Int rearLeftForwardSpeed = json["rl_fwd"] as! Int rearLeftBackwardSpeed = json["rl_bwd"] as! Int rearRightForwardSpeed = json["rr_fwd"] as! Int rearRightBackwardSpeed = json["rr_bwd"] as! Int } func toJson() -> [String:Any] { return [ "fl_fwd" : frontLeftForwardSpeed, "fl_bwd" : frontLeftBackwardSpeed, "fr_fwd" : frontRightForwardSpeed, "fr_bwd" : frontRightBackwardSpeed, "rl_fwd" : rearLeftForwardSpeed, "rl_bwd" : rearLeftBackwardSpeed, "rr_fwd" : rearRightForwardSpeed, "rr_bwd" : rearRightBackwardSpeed ] } }
mit
93c8be3f54b27219e8b919109a2b54ab
31.066667
61
0.616078
4.219298
false
false
false
false
KrishMunot/swift
stdlib/public/core/StringCore.swift
1
23286
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// The core implementation of a highly-optimizable String that /// can store both ASCII and UTF-16, and can wrap native Swift /// _StringBuffer or NSString instances. /// /// Usage note: when elements are 8 bits wide, this code may /// dereference one past the end of the byte array that it owns, so /// make sure that storage is allocated! You want a null terminator /// anyway, so it shouldn't be a burden. // // Implementation note: We try hard to avoid branches in this code, so // for example we use integer math to avoid switching on the element // size with the ternary operator. This is also the cause of the // extra element requirement for 8 bit elements. See the // implementation of subscript(Int) -> UTF16.CodeUnit below for details. @_fixed_layout public struct _StringCore { //===--------------------------------------------------------------------===// // Internals public var _baseAddress: OpaquePointer var _countAndFlags: UInt public var _owner: AnyObject? /// (private) create the implementation of a string from its component parts. init( baseAddress: OpaquePointer, _countAndFlags: UInt, owner: AnyObject? ) { self._baseAddress = baseAddress self._countAndFlags = _countAndFlags self._owner = owner _invariantCheck() } func _invariantCheck() { // Note: this code is intentionally #if'ed out. It unconditionally // accesses lazily initialized globals, and thus it is a performance burden // in non-checked builds. #if INTERNAL_CHECKS_ENABLED _sanityCheck(count >= 0) if _baseAddress == nil { #if _runtime(_ObjC) _sanityCheck(hasCocoaBuffer, "Only opaque cocoa strings may have a null base pointer") #endif _sanityCheck(elementWidth == 2, "Opaque cocoa strings should have an elementWidth of 2") } else if _baseAddress == _emptyStringBase { _sanityCheck(!hasCocoaBuffer) _sanityCheck(count == 0, "Empty string storage with non-zero count") _sanityCheck(_owner == nil, "String pointing at empty storage has owner") } else if let buffer = nativeBuffer { _sanityCheck(!hasCocoaBuffer) _sanityCheck(elementWidth == buffer.elementWidth, "_StringCore elementWidth doesn't match its buffer's") _sanityCheck(UnsafeMutablePointer(_baseAddress) >= buffer.start) _sanityCheck(UnsafeMutablePointer(_baseAddress) <= buffer.usedEnd) _sanityCheck( UnsafeMutablePointer(_pointer(toElementAt: count)) <= buffer.usedEnd) } #endif } /// Bitmask for the count part of `_countAndFlags`. var _countMask: UInt { return UInt.max >> 2 } /// Bitmask for the flags part of `_countAndFlags`. var _flagMask: UInt { return ~_countMask } /// Value by which to multiply a 2nd byte fetched in order to /// assemble a UTF-16 code unit from our contiguous storage. If we /// store ASCII, this will be zero. Otherwise, it will be 0x100. var _highByteMultiplier: UTF16.CodeUnit { return UTF16.CodeUnit(elementShift) << 8 } /// Returns a pointer to the Nth element of contiguous /// storage. Caveats: The string must have contiguous storage; the /// element may be 1 or 2 bytes wide, depending on elementWidth; the /// result may be null if the string is empty. @warn_unused_result func _pointer(toElementAt n: Int) -> OpaquePointer { _sanityCheck(hasContiguousStorage && n >= 0 && n <= count) return OpaquePointer( UnsafeMutablePointer<_RawByte>(_baseAddress) + (n << elementShift)) } static func _copyElements( _ srcStart: OpaquePointer, srcElementWidth: Int, dstStart: OpaquePointer, dstElementWidth: Int, count: Int ) { // Copy the old stuff into the new storage if _fastPath(srcElementWidth == dstElementWidth) { // No change in storage width; we can use memcpy _memcpy( dest: UnsafeMutablePointer(dstStart), src: UnsafeMutablePointer(srcStart), size: UInt(count << (srcElementWidth - 1))) } else if (srcElementWidth < dstElementWidth) { // Widening ASCII to UTF-16; we need to copy the bytes manually var dest = UnsafeMutablePointer<UTF16.CodeUnit>(dstStart) var src = UnsafeMutablePointer<UTF8.CodeUnit>(srcStart) let srcEnd = src + count while (src != srcEnd) { dest.pointee = UTF16.CodeUnit(src.pointee) dest += 1 src += 1 } } else { // Narrowing UTF-16 to ASCII; we need to copy the bytes manually var dest = UnsafeMutablePointer<UTF8.CodeUnit>(dstStart) var src = UnsafeMutablePointer<UTF16.CodeUnit>(srcStart) let srcEnd = src + count while (src != srcEnd) { dest.pointee = UTF8.CodeUnit(src.pointee) dest += 1 src += 1 } } } //===--------------------------------------------------------------------===// // Initialization public init( baseAddress: OpaquePointer, count: Int, elementShift: Int, hasCocoaBuffer: Bool, owner: AnyObject? ) { _sanityCheck(elementShift == 0 || elementShift == 1) self._baseAddress = baseAddress self._countAndFlags = (UInt(elementShift) << (UInt._sizeInBits - 1)) | ((hasCocoaBuffer ? 1 : 0) << (UInt._sizeInBits - 2)) | UInt(count) self._owner = owner _sanityCheck(UInt(count) & _flagMask == 0, "String too long to represent") _invariantCheck() } /// Create a _StringCore that covers the entire length of the _StringBuffer. init(_ buffer: _StringBuffer) { self = _StringCore( baseAddress: OpaquePointer(buffer.start), count: buffer.usedCount, elementShift: buffer.elementShift, hasCocoaBuffer: false, owner: buffer._anyObject ) } /// Create the implementation of an empty string. /// /// - Note: There is no null terminator in an empty string. public init() { self._baseAddress = _emptyStringBase self._countAndFlags = 0 self._owner = nil _invariantCheck() } //===--------------------------------------------------------------------===// // Properties /// The number of elements stored /// - Complexity: O(1). public var count: Int { get { return Int(_countAndFlags & _countMask) } set(newValue) { _sanityCheck(UInt(newValue) & _flagMask == 0) _countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue) } } /// Left shift amount to apply to an offset N so that when /// added to a UnsafeMutablePointer<_RawByte>, it traverses N elements. var elementShift: Int { return Int(_countAndFlags >> (UInt._sizeInBits - 1)) } /// The number of bytes per element. /// /// If the string does not have an ASCII buffer available (including the case /// when we don't have a utf16 buffer) then it equals 2. public var elementWidth: Int { return elementShift &+ 1 } public var hasContiguousStorage: Bool { #if _runtime(_ObjC) return _fastPath(_baseAddress != nil) #else return true #endif } /// Are we using an `NSString` for storage? public var hasCocoaBuffer: Bool { return Int((_countAndFlags << 1)._value) < 0 } public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> { _sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII") return UnsafeMutablePointer(_baseAddress) } /// True iff a contiguous ASCII buffer available. public var isASCII: Bool { return elementWidth == 1 } public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { _sanityCheck( count == 0 || elementWidth == 2, "String does not contain contiguous UTF-16") return UnsafeMutablePointer(_baseAddress) } /// the native _StringBuffer, if any, or `nil`. public var nativeBuffer: _StringBuffer? { if !hasCocoaBuffer { return _owner.map { unsafeBitCast($0, to: _StringBuffer.self) } } return nil } #if _runtime(_ObjC) /// the Cocoa String buffer, if any, or `nil`. public var cocoaBuffer: _CocoaString? { if hasCocoaBuffer { return _owner.map { unsafeBitCast($0, to: _CocoaString.self) } } return nil } #endif //===--------------------------------------------------------------------===// // slicing /// Returns the given sub-`_StringCore`. public subscript(bounds: Range<Int>) -> _StringCore { _precondition( bounds.startIndex >= 0, "subscript: subrange start precedes String start") _precondition( bounds.endIndex <= count, "subscript: subrange extends past String end") let newCount = bounds.endIndex - bounds.startIndex _sanityCheck(UInt(newCount) & _flagMask == 0) if hasContiguousStorage { return _StringCore( baseAddress: _pointer(toElementAt: bounds.startIndex), _countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount), owner: _owner) } #if _runtime(_ObjC) return _cocoaStringSlice(self, bounds) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } /// Get the Nth UTF-16 Code Unit stored. @_versioned @warn_unused_result func _nthContiguous(_ position: Int) -> UTF16.CodeUnit { let p = UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue) // Always dereference two bytes, but when elements are 8 bits we // multiply the high byte by 0. // FIXME(performance): use masking instead of multiplication. return UTF16.CodeUnit(p.pointee) + UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier } /// Get the Nth UTF-16 Code Unit stored. public subscript(position: Int) -> UTF16.CodeUnit { @inline(__always) get { _precondition( position >= 0, "subscript: index precedes String start") _precondition( position <= count, "subscript: index points past String end") if _fastPath(_baseAddress != nil) { return _nthContiguous(position) } #if _runtime(_ObjC) return _cocoaStringSubscript(self, position) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } } /// Write the string, in the given encoding, to output. func encode< Encoding: UnicodeCodec >(_ encoding: Encoding.Type, @noescape output: (Encoding.CodeUnit) -> Void) { if _fastPath(_baseAddress != nil) { if _fastPath(elementWidth == 1) { for x in UnsafeBufferPointer( start: UnsafeMutablePointer<UTF8.CodeUnit>(_baseAddress), count: count ) { Encoding.encode(UnicodeScalar(UInt32(x)), sendingOutputTo: output) } } else { let hadError = transcode( UnsafeBufferPointer( start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress), count: count ).makeIterator(), from: UTF16.self, to: encoding, stoppingOnError: true, sendingOutputTo: output ) _sanityCheck(!hadError, "Swift.String with native storage should not have unpaired surrogates") } } else if (hasCocoaBuffer) { #if _runtime(_ObjC) _StringCore( _cocoaStringToContiguous( source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0) ).encode(encoding, output: output) #else _sanityCheckFailure("encode: non-native string without objc runtime") #endif } } /// Attempt to claim unused capacity in the String's existing /// native buffer, if any. Return zero and a pointer to the claimed /// storage if successful. Otherwise, returns a suggested new /// capacity and a null pointer. /// /// - Note: If successful, effectively appends garbage to the String /// until it has newSize UTF-16 code units; you must immediately copy /// valid UTF-16 into that storage. /// /// - Note: If unsuccessful because of insufficient space in an /// existing buffer, the suggested new capacity will at least double /// the existing buffer's storage. @warn_unused_result mutating func _claimCapacity( _ newSize: Int, minElementWidth: Int) -> (Int, OpaquePointer) { if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) { var buffer = nativeBuffer! // In order to grow the substring in place, this _StringCore should point // at the substring at the end of a _StringBuffer. Otherwise, some other // String is using parts of the buffer beyond our last byte. let usedStart = _pointer(toElementAt:0) let usedEnd = _pointer(toElementAt:count) // Attempt to claim unused capacity in the buffer if _fastPath( buffer.grow( oldBounds: UnsafePointer(usedStart)..<UnsafePointer(usedEnd), newUsedCount: newSize) ) { count = newSize return (0, usedEnd) } else if newSize > buffer.capacity { // Growth failed because of insufficient storage; double the size return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil) } } return (newSize, nil) } /// Ensure that this String references a _StringBuffer having /// a capacity of at least newSize elements of at least the given width. /// Effectively appends garbage to the String until it has newSize /// UTF-16 code units. Returns a pointer to the garbage code units; /// you must immediately copy valid data into that storage. @warn_unused_result mutating func _growBuffer( _ newSize: Int, minElementWidth: Int ) -> OpaquePointer { let (newCapacity, existingStorage) = _claimCapacity(newSize, minElementWidth: minElementWidth) if _fastPath(existingStorage != nil) { return existingStorage } let oldCount = count _copyInPlace( newSize: newSize, newCapacity: newCapacity, minElementWidth: minElementWidth) return _pointer(toElementAt:oldCount) } /// Replace the storage of self with a native _StringBuffer having a /// capacity of at least newCapacity elements of at least the given /// width. Effectively appends garbage to the String until it has /// newSize UTF-16 code units. mutating func _copyInPlace( newSize: Int, newCapacity: Int, minElementWidth: Int ) { _sanityCheck(newCapacity >= newSize) let oldCount = count // Allocate storage. let newElementWidth = minElementWidth >= elementWidth ? minElementWidth : isRepresentableAsASCII() ? 1 : 2 let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize, elementWidth: newElementWidth) if hasContiguousStorage { _StringCore._copyElements( _baseAddress, srcElementWidth: elementWidth, dstStart: OpaquePointer(newStorage.start), dstElementWidth: newElementWidth, count: oldCount) } else { #if _runtime(_ObjC) // Opaque cocoa buffers might not store ASCII, so assert that // we've allocated for 2-byte elements. // FIXME: can we get Cocoa to tell us quickly that an opaque // string is ASCII? Do we care much about that edge case? _sanityCheck(newStorage.elementShift == 1) _cocoaStringReadAll(cocoaBuffer!, UnsafeMutablePointer(newStorage.start)) #else _sanityCheckFailure("_copyInPlace: non-native string without objc runtime") #endif } self = _StringCore(newStorage) } /// Append `c` to `self`. /// /// - Complexity: O(1) when amortized over repeated appends of equal /// character values. mutating func append(_ c: UnicodeScalar) { let width = UTF16.width(c) append( width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value), width == 2 ? UTF16.trailSurrogate(c) : nil ) } /// Append `u` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(_ u: UTF16.CodeUnit) { append(u, nil) } mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) { _invariantCheck() let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2 let utf16Width = u1 == nil ? 1 : 2 let destination = _growBuffer( count + utf16Width, minElementWidth: minBytesPerCodeUnit) if _fastPath(elementWidth == 1) { _sanityCheck( _pointer(toElementAt:count) == OpaquePointer(UnsafeMutablePointer<_RawByte>(destination) + 1)) UnsafeMutablePointer<UTF8.CodeUnit>(destination)[0] = UTF8.CodeUnit(u0) } else { let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination._rawValue) destination16[0] = u0 if u1 != nil { destination16[1] = u1! } } _invariantCheck() } @inline(never) mutating func append(_ rhs: _StringCore) { _invariantCheck() let minElementWidth = elementWidth >= rhs.elementWidth ? elementWidth : rhs.isRepresentableAsASCII() ? 1 : 2 let destination = _growBuffer( count + rhs.count, minElementWidth: minElementWidth) if _fastPath(rhs.hasContiguousStorage) { _StringCore._copyElements( rhs._baseAddress, srcElementWidth: rhs.elementWidth, dstStart: destination, dstElementWidth:elementWidth, count: rhs.count) } else { #if _runtime(_ObjC) _sanityCheck(elementWidth == 2) _cocoaStringReadAll(rhs.cocoaBuffer!, UnsafeMutablePointer(destination)) #else _sanityCheckFailure("subscript: non-native string without objc runtime") #endif } _invariantCheck() } /// Returns `true` iff the contents of this string can be /// represented as pure ASCII. /// /// - Complexity: O(N) in the worst case. @warn_unused_result func isRepresentableAsASCII() -> Bool { if _slowPath(!hasContiguousStorage) { return false } if _fastPath(elementWidth == 1) { return true } let unsafeBuffer = UnsafeBufferPointer( start: UnsafeMutablePointer<UTF16.CodeUnit>(_baseAddress), count: count) return !unsafeBuffer.contains { $0 > 0x7f } } } extension _StringCore : Collection { public // @testable var startIndex: Int { return 0 } public // @testable var endIndex: Int { return count } } extension _StringCore : RangeReplaceableCollection { /// Replace the elements within `bounds` with `newElements`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange< C: Collection where C.Iterator.Element == UTF16.CodeUnit >( _ bounds: Range<Int>, with newElements: C ) { _precondition( bounds.startIndex >= 0, "replaceSubrange: subrange start precedes String start") _precondition( bounds.endIndex <= count, "replaceSubrange: subrange extends past String end") let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1 let replacementCount = numericCast(newElements.count) as Int let replacedCount = bounds.count let tailCount = count - bounds.endIndex let growth = replacementCount - replacedCount let newCount = count + growth // Successfully claiming capacity only ensures that we can modify // the newly-claimed storage without observably mutating other // strings, i.e., when we're appending. Already-used characters // can only be mutated when we have a unique reference to the // buffer. let appending = bounds.startIndex == endIndex let existingStorage = !hasCocoaBuffer && ( appending || isUniquelyReferencedNonObjC(&_owner) ) ? _claimCapacity(newCount, minElementWidth: width).1 : nil if _fastPath(existingStorage != nil) { let rangeStart = UnsafeMutablePointer<UInt8>( _pointer(toElementAt:bounds.startIndex)) let tailStart = rangeStart + (replacedCount << elementShift) if growth > 0 { (tailStart + (growth << elementShift)).assignBackwardFrom( tailStart, count: tailCount << elementShift) } if _fastPath(elementWidth == 1) { var dst = rangeStart for u in newElements { dst.pointee = UInt8(truncatingBitPattern: u) dst += 1 } } else { var dst = UnsafeMutablePointer<UTF16.CodeUnit>(rangeStart) for u in newElements { dst.pointee = u dst += 1 } } if growth < 0 { (tailStart + (growth << elementShift)).assignFrom( tailStart, count: tailCount << elementShift) } } else { var r = _StringCore( _StringBuffer( capacity: newCount, initialSize: 0, elementWidth: width == 1 ? 1 : isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1 : 2 )) r.append(contentsOf: self[0..<bounds.startIndex]) r.append(contentsOf: newElements) r.append(contentsOf: self[bounds.endIndex..<count]) self = r } } public mutating func reserveCapacity(_ n: Int) { if _fastPath(!hasCocoaBuffer) { if _fastPath(isUniquelyReferencedNonObjC(&_owner)) { let bounds: Range<UnsafePointer<_RawByte>> = UnsafePointer(_pointer(toElementAt:0))..<UnsafePointer(_pointer(toElementAt:count)) if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) { return } } } _copyInPlace( newSize: count, newCapacity: Swift.max(count, n), minElementWidth: 1) } public mutating func append< S : Sequence where S.Iterator.Element == UTF16.CodeUnit >(contentsOf s: S) { var width = elementWidth if width == 1 { if let hasNonAscii = s._preprocessingPass({ s.contains { $0 > 0x7f } }) { width = hasNonAscii ? 2 : 1 } } let growth = s.underestimatedCount var iter = s.makeIterator() if _fastPath(growth > 0) { let newSize = count + growth let destination = _growBuffer(newSize, minElementWidth: width) if elementWidth == 1 { let destination8 = UnsafeMutablePointer<UTF8.CodeUnit>(destination) for i in 0..<growth { destination8[i] = UTF8.CodeUnit(iter.next()!) } } else { let destination16 = UnsafeMutablePointer<UTF16.CodeUnit>(destination) for i in 0..<growth { destination16[i] = iter.next()! } } } // Append any remaining elements for u in IteratorSequence(iter) { self.append(u) } } } // Used to support a tighter invariant: all strings with contiguous // storage have a non-NULL base address. var _emptyStringStorage: UInt32 = 0 var _emptyStringBase: OpaquePointer { return OpaquePointer( UnsafeMutablePointer<UInt16>(Builtin.addressof(&_emptyStringStorage))) }
apache-2.0
2390b48bcbf1cab52869f8fa842c46fb
30.768076
103
0.639011
4.612002
false
false
false
false
KrishMunot/swift
test/1_stdlib/tgmath.swift
3
10701
// RUN: %target-run-simple-swift // REQUIRES: executable_test #if os(Linux) || os(FreeBSD) import Glibc // FIXME: this is a quick hack for non Darwin platforms // where they doesn't have CoreGraphics module. #if arch(i386) || arch(arm) typealias CGFloat = Float #elseif arch(x86_64) || arch(arm64) typealias CGFloat = Double #endif #else import Darwin.C.tgmath import CoreGraphics #endif import StdlibUnittest let MathTests = TestSuite("TGMath") func print3(_ op: String, _ d: Double, _ f: Float, _ g: CGFloat) -> String { #if arch(i386) || arch(arm) if (f != Float(g) && f.isNaN != g.isNaN) { return "\(op)(CGFloat) got \(g) instead of \(f)" } #else if (d != Double(g) && d.isNaN != g.isNaN) { return "\(op)(CGFloat) got \(g) instead of \(d)" } #endif return "\(op) \(d) \(f) \(op)" } func print3(_ op: String, _ d: Bool, _ f: Bool, _ g: Bool) -> String { #if arch(i386) || arch(arm) if (f != g) { return "\(op)(CGFloat) got \(g) instead of \(f)" } #else if (d != g) { return "\(op)(CGFloat) got \(g) instead of \(d)" } #endif return "\(op) \(d) \(f) \(op)" } func print3(_ op: String, _ d: Int, _ f: Int, _ g: Int) -> String { #if arch(i386) || arch(arm) if (f != g) { return "\(op)(CGFloat) got \(g) instead of \(f)" } #else if (d != g) { return "\(op)(CGFloat) got \(g) instead of \(d)" } #endif return "\(op) \(d) \(f) \(op)" } func print6(_ op: String, _ d1: Double, _ d2: Double, _ f1: Float, _ f2: Float, _ g1: CGFloat, _ g2: CGFloat) -> String { #if arch(i386) || arch(arm) if (f1 != Float(g1) || f2 != Float(g2)) { return "\(op)(CGFloat) got \(g1),\(g2) instead of \(f1),\(f2)" } #else if (d1 != Double(g1) || d2 != Double(g2)) { return "\(op)(CGFloat) got \(g1),\(g2) instead of \(d1),\(d2)" } #endif return "\(op) \(d1),\(d2) \(f1),\(f2) \(op)" } func print6(_ op: String, _ d1: Double, _ di: Int, _ f1: Float, _ fi: Int, _ g1: CGFloat, _ gi: Int) -> String { #if arch(i386) || arch(arm) if (f1 != Float(g1) || fi != gi) { return "\(op)(CGFloat) got \(g1),\(gi) instead of \(f1),\(fi)" } #else if (d1 != Double(g1) || di != gi) { return "\(op)(CGFloat) got \(g1),\(gi) instead of \(d1),\(di)" } #endif return "\(op) \(d1),\(di) \(f1),\(fi) \(op)" } // inputs let dx = Double(0.1) let dy = Double(2.2) let dz = Double(3.3) let fx = Float(0.1) let fy = Float(2.2) let fz = Float(3.3) let gx = CGFloat(0.1) let gy = CGFloat(2.2) let gz = CGFloat(3.3) let ix = Int(11) // outputs var d1, d2: Double var f1, f2: Float var g1, g2: CGFloat var i1, i2, i3: Int var b1, b2, b3: Bool MathTests.test("Unary functions") { (d1, f1, g1) = (acos(dx), acos(fx), acos(gx)) expectEqual("acos 1.47062890563334 1.47063 acos", print3("acos", d1, f1, g1)) (d1, f1, g1) = (asin(dx), asin(fx), asin(gx)) expectEqual("asin 0.10016742116156 0.100167 asin", print3("asin", d1, f1, g1)) (d1, f1, g1) = (atan(dx), atan(fx), atan(gx)) expectEqual("atan 0.099668652491162 0.0996687 atan", print3("atan", d1, f1, g1)) (d1, f1, g1) = (cos(dx), cos(fx), cos(gx)) expectEqual("cos 0.995004165278026 0.995004 cos", print3("cos", d1, f1, g1)) (d1, f1, g1) = (sin(dx), sin(fx), sin(gx)) expectEqual("sin 0.0998334166468282 0.0998334 sin", print3("sin", d1, f1, g1)) (d1, f1, g1) = (tan(dx), tan(fx), tan(gx)) expectEqual("tan 0.100334672085451 0.100335 tan", print3("tan", d1, f1, g1)) (d1, f1, g1) = (acosh(dx), acosh(fx), acosh(gx)) expectEqual("acosh nan nan acosh", print3("acosh", d1, f1, g1)) (d1, f1, g1) = (asinh(dx), asinh(fx), asinh(gx)) expectEqual("asinh 0.0998340788992076 0.0998341 asinh", print3("asinh", d1, f1, g1)) (d1, f1, g1) = (atanh(dx), atanh(fx), atanh(gx)) expectEqual("atanh 0.100335347731076 0.100335 atanh", print3("atanh", d1, f1, g1)) (d1, f1, g1) = (cosh(dx), cosh(fx), cosh(gx)) expectEqual("cosh 1.0050041680558 1.005 cosh", print3("cosh", d1, f1, g1)) (d1, f1, g1) = (sinh(dx), sinh(fx), sinh(gx)) expectEqual("sinh 0.100166750019844 0.100167 sinh", print3("sinh", d1, f1, g1)) (d1, f1, g1) = (tanh(dx), tanh(fx), tanh(gx)) expectEqual("tanh 0.0996679946249558 0.099668 tanh", print3("tanh", d1, f1, g1)) (d1, f1, g1) = (exp(dx), exp(fx), exp(gx)) expectEqual("exp 1.10517091807565 1.10517 exp", print3("exp", d1, f1, g1)) (d1, f1, g1) = (exp2(dx), exp2(fx), exp2(gx)) expectEqual("exp2 1.07177346253629 1.07177 exp2", print3("exp2", d1, f1, g1)) (d1, f1, g1) = (expm1(dx), expm1(fx), expm1(gx)) expectEqual("expm1 0.105170918075648 0.105171 expm1", print3("expm1", d1, f1, g1)) (d1, f1, g1) = (log(dx), log(fx), log(gx)) expectEqual("log -2.30258509299405 -2.30259 log", print3("log", d1, f1, g1)) (d1, f1, g1) = (log10(dx), log10(fx), log10(gx)) expectEqual("log10 -1.0 -1.0 log10", print3("log10", d1, f1, g1)) (d1, f1, g1) = (log2(dx), log2(fx), log2(gx)) expectEqual("log2 -3.32192809488736 -3.32193 log2", print3("log2", d1, f1, g1)) (d1, f1, g1) = (log1p(dx), log1p(fx), log1p(gx)) expectEqual("log1p 0.0953101798043249 0.0953102 log1p", print3("log1p", d1, f1, g1)) (d1, f1, g1) = (logb(dx), logb(fx), logb(gx)) expectEqual("logb -4.0 -4.0 logb", print3("logb", d1, f1, g1)) (d1, f1, g1) = (fabs(dx), fabs(fx), fabs(gx)) expectEqual("fabs 0.1 0.1 fabs", print3("fabs", d1, f1, g1)) (d1, f1, g1) = (cbrt(dx), cbrt(fx), cbrt(gx)) expectEqual("cbrt 0.464158883361278 0.464159 cbrt", print3("cbrt", d1, f1, g1)) (d1, f1, g1) = (sqrt(dx), sqrt(fx), sqrt(gx)) expectEqual("sqrt 0.316227766016838 0.316228 sqrt", print3("sqrt", d1, f1, g1)) (d1, f1, g1) = (erf(dx), erf(fx), erf(gx)) expectEqual("erf 0.112462916018285 0.112463 erf", print3("erf", d1, f1, g1)) (d1, f1, g1) = (erfc(dx), erfc(fx), erfc(gx)) expectEqual("erfc 0.887537083981715 0.887537 erfc", print3("erfc", d1, f1, g1)) (d1, f1, g1) = (tgamma(dx), tgamma(fx), tgamma(gx)) expectEqual("tgamma 9.51350769866873 9.51351 tgamma", print3("tgamma", d1, f1, g1)) (d1, f1, g1) = (ceil(dx), ceil(fx), ceil(gx)) expectEqual("ceil 1.0 1.0 ceil", print3("ceil", d1, f1, g1)) (d1, f1, g1) = (floor(dx), floor(fx), floor(gx)) expectEqual("floor 0.0 0.0 floor", print3("floor", d1, f1, g1)) (d1, f1, g1) = (nearbyint(dx), nearbyint(fx), nearbyint(gx)) expectEqual("nearbyint 0.0 0.0 nearbyint", print3("nearbyint", d1, f1, g1)) (d1, f1, g1) = (rint(dx), rint(fx), rint(gx)) expectEqual("rint 0.0 0.0 rint", print3("rint", d1, f1, g1)) (d1, f1, g1) = (round(dx), round(fx), round(gx)) expectEqual("round 0.0 0.0 round", print3("round", d1, f1, g1)) (d1, f1, g1) = (trunc(dx), trunc(fx), trunc(gx)) expectEqual("trunc 0.0 0.0 trunc", print3("trunc", d1, f1, g1)) } MathTests.test("Binary functions") { (d1, f1, g1) = (atan2(dx, dy), atan2(fx, fy), atan2(gx, gy)) expectEqual("atan2 0.045423279421577 0.0454233 atan2", print3("atan2", d1, f1, g1)) (d1, f1, g1) = (hypot(dx, dy), hypot(fx, fy), hypot(gx, gy)) expectEqual("hypot 2.20227155455452 2.20227 hypot", print3("hypot", d1, f1, g1)) (d1, f1, g1) = (pow(dx, dy), pow(fx, fy), pow(gx, gy)) expectEqual("pow 0.00630957344480193 0.00630957 pow", print3("pow", d1, f1, g1)) (d1, f1, g1) = (fmod(dx, dy), fmod(fx, fy), fmod(gx, gy)) expectEqual("fmod 0.1 0.1 fmod", print3("fmod", d1, f1, g1)) (d1, f1, g1) = (remainder(dx, dy), remainder(fx, fy), remainder(gx, gy)) expectEqual("remainder 0.1 0.1 remainder", print3("remainder", d1, f1, g1)) (d1, f1, g1) = (copysign(dx, dy), copysign(fx, fy), copysign(gx, gy)) expectEqual("copysign 0.1 0.1 copysign", print3("copysign", d1, f1, g1)) (d1, f1, g1) = (nextafter(dx, dy), nextafter(fx, fy), nextafter(gx, gy)) expectEqual("nextafter 0.1 0.1 nextafter", print3("nextafter", d1, f1, g1)) (d1, f1, g1) = (fdim(dx, dy), fdim(fx, fy), fdim(gx, gy)) expectEqual("fdim 0.0 0.0 fdim", print3("fdim", d1, f1, g1)) (d1, f1, g1) = (fmax(dx, dy), fmax(fx, fy), fmax(gx, gy)) expectEqual("fmax 2.2 2.2 fmax", print3("fmax", d1, f1, g1)) (d1, f1, g1) = (fmin(dx, dy), fmin(fx, fy), fmin(gx, gy)) expectEqual("fmin 0.1 0.1 fmin", print3("fmin", d1, f1, g1)) } MathTests.test("Other functions") { (i1, i2, i3) = (fpclassify(dx), fpclassify(fx), fpclassify(gx)) expectEqual("fpclassify 4 4 fpclassify", print3("fpclassify", i1, i2, i3)) (b1, b2, b3) = (isnormal(dx), isnormal(fx), isnormal(gx)) expectEqual("isnormal true true isnormal", print3("isnormal", b1, b2, b3)) (b1, b2, b3) = (isfinite(dx), isfinite(fx), isfinite(gx)) expectEqual("isfinite true true isfinite", print3("isfinite", b1, b2, b3)) (b1, b2, b3) = (isinf(dx), isinf(fx), isinf(gx)) expectEqual("isinf false false isinf", print3("isinf", b1, b2, b3)) (b1, b2, b3) = (isnan(dx), isnan(fx), isnan(gx)) expectEqual("isnan false false isnan", print3("isnan", b1, b2, b3)) (i1, i2, i3) = (signbit(dx), signbit(fx), signbit(gx)) expectEqual("signbit 0 0 signbit", print3("signbit", i1, i2, i3)) (d1, d2) = modf(dy) (f1, f2) = modf(fy) (g1, g2) = modf(gy) expectEqual("modf 2.0,0.2 2.0,0.2 modf", print6("modf", d1,d2, f1,f2, g1,g2)) (d1, f1, g1) = (ldexp(dx, ix), ldexp(fx, ix), ldexp(gx, ix)) expectEqual("ldexp 204.8 204.8 ldexp", print3("ldexp", d1, f1, g1)) (d1, i1) = frexp(dy) (f1, i2) = frexp(fy) (g1, i3) = frexp(gy) expectEqual("frexp 0.55,2 0.55,2 frexp", print6("frexp", d1,i1, f1,i2, g1,i3)) (i1, i2, i3) = (ilogb(dy), ilogb(fy), ilogb(gy)) expectEqual("ilogb 1 1 ilogb", print3("ilogb", i1, i2, i3)) (d1, f1, g1) = (scalbn(dx, ix), scalbn(fx, ix), scalbn(gx, ix)) expectEqual("scalbn 204.8 204.8 scalbn", print3("scalbn", d1, f1, g1)) (d1, i1) = lgamma(dx) (f1, i2) = lgamma(fx) (g1, i3) = lgamma(gx) expectEqual("lgamma 2.25271265173421,1 2.25271,1 lgamma", print6("lgamma", d1,i1, f1,i2, g1,i3)) (d1, i1) = remquo(dz, dy) (f1, i2) = remquo(fz, fy) (g1, i3) = remquo(gz, gy) expectEqual("remquo 1.1,1 1.1,1 remquo", print6("remquo", d1,i1, f1,i2, g1,i3)) (d1, f1, g1) = (nan("12345"), nan("12345"), nan("12345")) expectEqual("nan nan nan nan", print3("nan", d1, f1, g1)) (d1, f1, g1) = (fma(dx, dy, dz), fma(fx, fy, fz), fma(gx, gy, gz)) expectEqual("fma 3.52 3.52 fma", print3("fma", d1, f1, g1)) expectEqual("j0 0.99750156206604 j0", "j0 \(j0(dx)) j0") expectEqual("j1 0.049937526036242 j1", "j1 \(j1(dx)) j1") expectEqual("jn 1.22299266103565e-22 jn", "jn \(jn(ix, dx)) jn") expectEqual("y0 -1.53423865135037 y0", "y0 \(y0(dx)) y0") expectEqual("y1 -6.45895109470203 y1", "y1 \(y1(dx)) y1") d1 = yn(ix, dx) expectEqual("yn -2.36620129448696e+20 yn", "yn \(d1) yn") } runAllTests()
apache-2.0
028ac5188ad3c560f8b65efa3633816d
32.440625
81
0.593122
2.332897
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Themes/ThemeBrowserViewController.swift
1
38759
import Foundation import CocoaLumberjack import WordPressShared.WPAnalytics import WordPressShared.WPStyleGuide /** * @brief Support for filtering themes by purchasability * @details Currently purchasing themes via native apps is unsupported */ public enum ThemeType { case all case free case premium static let mayPurchase = false static let types = [all, free, premium] var title: String { switch self { case .all: return NSLocalizedString("All", comment: "Browse all themes selection title") case .free: return NSLocalizedString("Free", comment: "Browse free themes selection title") case .premium: return NSLocalizedString("Premium", comment: "Browse premium themes selection title") } } var predicate: NSPredicate? { switch self { case .all: return nil case .free: return NSPredicate(format: "premium == 0") case .premium: return NSPredicate(format: "premium == 1") } } } /** * @brief Publicly exposed theme interaction support * @details Held as weak reference by owned subviews */ public protocol ThemePresenter: AnyObject { var filterType: ThemeType { get set } var screenshotWidth: Int { get } func currentTheme() -> Theme? func activateTheme(_ theme: Theme?) func presentCustomizeForTheme(_ theme: Theme?) func presentPreviewForTheme(_ theme: Theme?) func presentDetailsForTheme(_ theme: Theme?) func presentSupportForTheme(_ theme: Theme?) func presentViewForTheme(_ theme: Theme?) } /// Invalidates the layout whenever the collection view's bounds change @objc open class ThemeBrowserCollectionViewLayout: UICollectionViewFlowLayout { open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return shouldInvalidateForNewBounds(newBounds) } open override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewFlowLayoutInvalidationContext { let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext context.invalidateFlowLayoutDelegateMetrics = shouldInvalidateForNewBounds(newBounds) return context } fileprivate func shouldInvalidateForNewBounds(_ newBounds: CGRect) -> Bool { guard let collectionView = collectionView else { return false } return (newBounds.width != collectionView.bounds.width || newBounds.height != collectionView.bounds.height) } } @objc open class ThemeBrowserViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchResultsUpdating, ThemePresenter, WPContentSyncHelperDelegate { // MARK: - Constants @objc static let reuseIdentifierForThemesHeader = "ThemeBrowserSectionHeaderViewThemes" @objc static let reuseIdentifierForCustomThemesHeader = "ThemeBrowserSectionHeaderViewCustomThemes" static let themesLoaderFrame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 20.0) // MARK: - Properties: must be set by parent /** * @brief The blog this VC will work with. * @details Must be set by the creator of this VC. */ @objc open var blog: Blog! // MARK: - Properties @IBOutlet weak var collectionView: UICollectionView! fileprivate lazy var customizerNavigationDelegate: ThemeWebNavigationDelegate = { return ThemeWebNavigationDelegate() }() /** * @brief The FRCs this VC will use to display filtered content. */ fileprivate lazy var themesController: NSFetchedResultsController<NSFetchRequestResult> = { return self.createThemesFetchedResultsController() }() fileprivate lazy var customThemesController: NSFetchedResultsController<NSFetchRequestResult> = { return self.createThemesFetchedResultsController() }() fileprivate func createThemesFetchedResultsController() -> NSFetchedResultsController<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Theme.entityName()) fetchRequest.fetchBatchSize = 20 let sort = NSSortDescriptor(key: "order", ascending: true) fetchRequest.sortDescriptors = [sort] let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.themeService.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc } fileprivate var themeCount: NSInteger { return themesController.fetchedObjects?.count ?? 0 } fileprivate var customThemeCount: NSInteger { return blog.supports(BlogFeature.customThemes) ? (customThemesController.fetchedObjects?.count ?? 0) : 0 } // Absolute count of available themes for the site, as it comes from the ThemeService fileprivate var totalThemeCount: NSInteger = 0 { didSet { themesHeader?.themeCount = totalThemeCount } } fileprivate var totalCustomThemeCount: NSInteger = 0 { didSet { customThemesHeader?.themeCount = totalCustomThemeCount } } fileprivate var themesHeader: ThemeBrowserSectionHeaderView? { didSet { themesHeader?.descriptionLabel.text = NSLocalizedString("WordPress.com Themes", comment: "Title for the WordPress.com themes section, should be the same as in Calypso").localizedUppercase themesHeader?.themeCount = totalThemeCount > 0 ? totalThemeCount : themeCount } } fileprivate var customThemesHeader: ThemeBrowserSectionHeaderView? { didSet { customThemesHeader?.descriptionLabel.text = NSLocalizedString("Uploaded themes", comment: "Title for the user uploaded themes section, should be the same as in Calypso").localizedUppercase customThemesHeader?.themeCount = totalCustomThemeCount > 0 ? totalCustomThemeCount : customThemeCount } } fileprivate var hideSectionHeaders: Bool = false fileprivate var searchController: UISearchController! fileprivate var searchName = "" { didSet { if searchName != oldValue { fetchThemes() reloadThemes() } } } fileprivate var suspendedSearch = "" @objc func resumingSearch() -> Bool { return !suspendedSearch.trim().isEmpty } fileprivate var activityIndicator: UIActivityIndicatorView = { let indicatorView = UIActivityIndicatorView(style: .medium) indicatorView.frame = themesLoaderFrame //TODO update color with white headers indicatorView.color = .white indicatorView.startAnimating() return indicatorView }() open var filterType: ThemeType = ThemeType.mayPurchase ? .all : .free /** * @brief Collection view support */ fileprivate enum Section { case search case info case customThemes case themes } fileprivate var sections: [Section]! fileprivate func reloadThemes() { collectionView?.reloadData() updateResults() } fileprivate func themeAtIndexPath(_ indexPath: IndexPath) -> Theme? { if sections[indexPath.section] == .themes { return themesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme } else if sections[indexPath.section] == .customThemes { return customThemesController.object(at: IndexPath(row: indexPath.row, section: 0)) as? Theme } return nil } fileprivate func updateActivateButton(isLoading: Bool) { if isLoading { activateButton?.customView = activityIndicator activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() activateButton?.customView = nil activateButton?.isEnabled = false activateButton?.title = ThemeAction.active.title } } fileprivate var presentingTheme: Theme? private var noResultsViewController: NoResultsViewController? private struct NoResultsTitles { static let noThemes = NSLocalizedString("No themes matching your search", comment: "Text displayed when theme name search has no matches") static let fetchingThemes = NSLocalizedString("Fetching Themes...", comment: "Text displayed while fetching themes") } private var noResultsShown: Bool { return noResultsViewController?.parent != nil } /** * @brief Load theme screenshots at maximum displayed width */ @objc open var screenshotWidth: Int = { let windowSize = UIApplication.shared.mainWindow!.bounds.size let vWidth = Styles.imageWidthForFrameWidth(windowSize.width) let hWidth = Styles.imageWidthForFrameWidth(windowSize.height) let maxWidth = Int(max(hWidth, vWidth)) return maxWidth }() /** * @brief The themes service we'll use in this VC and its helpers */ fileprivate let themeService = ThemeService(managedObjectContext: ContextManager.sharedInstance().mainContext) fileprivate var themesSyncHelper: WPContentSyncHelper! fileprivate var themesSyncingPage = 0 fileprivate var customThemesSyncHelper: WPContentSyncHelper! fileprivate let syncPadding = 5 fileprivate var activateButton: UIBarButtonItem? // MARK: - Private Aliases fileprivate typealias Styles = WPStyleGuide.Themes /** * @brief Convenience method for browser instantiation * * @param blog The blog to browse themes for * * @returns ThemeBrowserViewController instance */ @objc open class func browserWithBlog(_ blog: Blog) -> ThemeBrowserViewController { let storyboard = UIStoryboard(name: "ThemeBrowser", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! ThemeBrowserViewController viewController.blog = blog return viewController } // MARK: - UIViewController open override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Themes", comment: "Title of Themes browser page") WPStyleGuide.configureColors(view: view, collectionView: collectionView) fetchThemes() sections = (themeCount == 0 && customThemeCount == 0) ? [.search, .customThemes, .themes] : [.search, .info, .customThemes, .themes] configureSearchController() updateActiveTheme() setupThemesSyncHelper() if blog.supports(BlogFeature.customThemes) { setupCustomThemesSyncHelper() } syncContent() } fileprivate func configureSearchController() { extendedLayoutIncludesOpaqueBars = true definesPresentationContext = true searchController = UISearchController(searchResultsController: nil) searchController.obscuresBackgroundDuringPresentation = false searchController.delegate = self searchController.searchResultsUpdater = self collectionView.register(ThemeBrowserSearchHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier) collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForThemesHeader) collectionView.register(UINib(nibName: "ThemeBrowserSectionHeaderView", bundle: Bundle(for: ThemeBrowserSectionHeaderView.self)), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader) WPStyleGuide.configureSearchBar(searchController.searchBar) } fileprivate var searchBarHeight: CGFloat { return searchController.searchBar.bounds.height + view.safeAreaInsets.top } open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) collectionView?.collectionViewLayout.invalidateLayout() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) registerForKeyboardNotifications() if resumingSearch() { beginSearchFor(suspendedSearch) suspendedSearch = "" } guard let theme = presentingTheme else { return } presentingTheme = nil if !theme.isCurrentTheme() { // presented page may have activated this theme updateActiveTheme() } } open override func viewWillDisappear(_ animated: Bool) { if searchController.isActive { searchController.isActive = false } super.viewWillDisappear(animated) unregisterForKeyboardNotifications() } fileprivate func registerForKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ThemeBrowserViewController.keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ThemeBrowserViewController.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } fileprivate func unregisterForKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc open func keyboardDidShow(_ notification: Foundation.Notification) { let keyboardFrame = localKeyboardFrameFromNotification(notification) let keyboardHeight = collectionView.frame.maxY - keyboardFrame.origin.y collectionView.contentInset.bottom = keyboardHeight collectionView.verticalScrollIndicatorInsets.top = searchBarHeight collectionView.verticalScrollIndicatorInsets.bottom = keyboardHeight } @objc open func keyboardWillHide(_ notification: Foundation.Notification) { let tabBarHeight = tabBarController?.tabBar.bounds.height ?? 0 collectionView.contentInset.top = view.safeAreaInsets.top collectionView.contentInset.bottom = tabBarHeight collectionView.verticalScrollIndicatorInsets.top = searchBarHeight collectionView.verticalScrollIndicatorInsets.bottom = tabBarHeight } fileprivate func localKeyboardFrameFromNotification(_ notification: Foundation.Notification) -> CGRect { let key = UIResponder.keyboardFrameEndUserInfoKey guard let keyboardFrame = (notification.userInfo?[key] as? NSValue)?.cgRectValue else { return .zero } // Convert the frame from window coordinates return view.convert(keyboardFrame, from: nil) } // MARK: - Syncing the list of themes fileprivate func updateActiveTheme() { let lastActiveThemeId = blog.currentThemeId _ = themeService.getActiveTheme(for: blog, success: { [weak self] (theme: Theme?) in if lastActiveThemeId != theme?.themeId { self?.collectionView?.collectionViewLayout.invalidateLayout() } }, failure: { (error) in DDLogError("Error updating active theme: \(String(describing: error?.localizedDescription))") }) } fileprivate func setupThemesSyncHelper() { themesSyncHelper = WPContentSyncHelper() themesSyncHelper.delegate = self } fileprivate func setupCustomThemesSyncHelper() { customThemesSyncHelper = WPContentSyncHelper() customThemesSyncHelper.delegate = self } fileprivate func syncContent() { if themesSyncHelper.syncContent() && (!blog.supports(BlogFeature.customThemes) || customThemesSyncHelper.syncContent()) { updateResults() } } fileprivate func syncMoreThemesIfNeeded(_ indexPath: IndexPath) { let paddedCount = indexPath.row + syncPadding if paddedCount >= themeCount && themesSyncHelper.hasMoreContent && themesSyncHelper.syncMoreContent() { updateResults() } } fileprivate func syncThemePage(_ page: NSInteger, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { assert(page > 0) themesSyncingPage = page _ = themeService.getThemesFor(blog, page: themesSyncingPage, sync: page == 1, success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in if let success = success { success(hasMore) } self?.totalThemeCount = themeCount }, failure: { (error) in DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))") if let failure = failure, let error = error { failure(error as NSError) } }) } fileprivate func syncCustomThemes(success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { _ = themeService.getCustomThemes(for: blog, sync: true, success: {[weak self](themes: [Theme]?, hasMore: Bool, themeCount: NSInteger) in if let success = success { success(hasMore) } self?.totalCustomThemeCount = themeCount }, failure: { (error) in DDLogError("Error syncing themes: \(String(describing: error?.localizedDescription))") if let failure = failure, let error = error { failure(error as NSError) } }) } @objc open func currentTheme() -> Theme? { guard let themeId = blog.currentThemeId, !themeId.isEmpty else { return nil } for theme in blog.themes as! Set<Theme> { if theme.themeId == themeId { return theme } } return nil } // MARK: - WPContentSyncHelperDelegate func syncHelper(_ syncHelper: WPContentSyncHelper, syncContentWithUserInteraction userInteraction: Bool, success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { if syncHelper == themesSyncHelper { syncThemePage(1, success: success, failure: failure) } else if syncHelper == customThemesSyncHelper { syncCustomThemes(success: success, failure: failure) } } func syncHelper(_ syncHelper: WPContentSyncHelper, syncMoreWithSuccess success: ((_ hasMore: Bool) -> Void)?, failure: ((_ error: NSError) -> Void)?) { if syncHelper == themesSyncHelper { let nextPage = themesSyncingPage + 1 syncThemePage(nextPage, success: success, failure: failure) } } func syncContentEnded(_ syncHelper: WPContentSyncHelper) { updateResults() let lastVisibleTheme = collectionView?.indexPathsForVisibleItems.last ?? IndexPath(item: 0, section: 0) if syncHelper == themesSyncHelper { syncMoreThemesIfNeeded(lastVisibleTheme) } } func hasNoMoreContent(_ syncHelper: WPContentSyncHelper) { if syncHelper == themesSyncHelper { themesSyncingPage = 0 } collectionView?.collectionViewLayout.invalidateLayout() } // MARK: - UICollectionViewDataSource open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch sections[section] { case .search, .info: return 0 case .customThemes: return customThemeCount case .themes: return themeCount } } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ThemeBrowserCell.reuseIdentifier, for: indexPath) as! ThemeBrowserCell cell.presenter = self cell.theme = themeAtIndexPath(indexPath) if sections[indexPath.section] == .themes { syncMoreThemesIfNeeded(indexPath) } return cell } open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionView.elementKindSectionHeader: if sections[indexPath.section] == .search { let searchHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserSearchHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserSearchHeaderView searchHeader.searchBar = searchController.searchBar return searchHeader } else if sections[indexPath.section] == .info { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserHeaderView.reuseIdentifier, for: indexPath) as! ThemeBrowserHeaderView header.presenter = self return header } else { // We don't want the collectionView to reuse the section headers // since we need to keep a reference to them to update the counts if sections[indexPath.section] == .customThemes { customThemesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView) customThemesHeader?.isHidden = customThemeCount == 0 return customThemesHeader! } else { themesHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ThemeBrowserViewController.reuseIdentifierForCustomThemesHeader, for: indexPath) as! ThemeBrowserSectionHeaderView) themesHeader?.isHidden = themeCount == 0 return themesHeader! } } case UICollectionView.elementKindSectionFooter: let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "ThemeBrowserFooterView", for: indexPath) return footer default: fatalError("Unexpected theme browser element") } } open func numberOfSections(in collectionView: UICollectionView) -> Int { return sections.count } // MARK: - UICollectionViewDelegate open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let theme = themeAtIndexPath(indexPath) { if theme.isCurrentTheme() { presentCustomizeForTheme(theme) } else { theme.custom ? presentDetailsForTheme(theme) : presentViewForTheme(theme) } } } // MARK: - UICollectionViewDelegateFlowLayout open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: NSInteger) -> CGSize { switch sections[section] { case .themes, .customThemes: if !hideSectionHeaders && blog.supports(BlogFeature.customThemes) { return CGSize(width: 0, height: ThemeBrowserSectionHeaderView.height) } return .zero case .search: return CGSize(width: 0, height: searchController.searchBar.bounds.height) case .info: let horizontallyCompact = traitCollection.horizontalSizeClass == .compact let height = Styles.headerHeight(horizontallyCompact, includingSearchBar: ThemeType.mayPurchase) return CGSize(width: 0, height: height) } } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let parentViewWidth = collectionView.frame.size.width return Styles.cellSizeForFrameWidth(parentViewWidth) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { guard sections[section] == .themes && themesSyncHelper.isLoadingMore else { return CGSize.zero } return CGSize(width: 0, height: Styles.footerHeight) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { switch sections[section] { case .customThemes: if !blog.supports(BlogFeature.customThemes) { return .zero } return Styles.themeMargins case .themes: return Styles.themeMargins case .info, .search: return Styles.infoMargins } } // MARK: - Search support fileprivate func beginSearchFor(_ pattern: String) { searchController.isActive = true searchController.searchBar.text = pattern searchName = pattern } // MARK: - UISearchControllerDelegate open func willPresentSearchController(_ searchController: UISearchController) { hideSectionHeaders = true if sections[1] == .info { collectionView?.collectionViewLayout.invalidateLayout() setInfoSectionHidden(true) } } open func didPresentSearchController(_ searchController: UISearchController) { WPAppAnalytics.track(.themesAccessedSearch, with: blog) } open func willDismissSearchController(_ searchController: UISearchController) { hideSectionHeaders = false searchName = "" searchController.searchBar.text = "" } open func didDismissSearchController(_ searchController: UISearchController) { if sections[1] == .themes || sections[1] == .customThemes { setInfoSectionHidden(false) } collectionView.verticalScrollIndicatorInsets.top = view.safeAreaInsets.top } fileprivate func setInfoSectionHidden(_ hidden: Bool) { let hide = { self.collectionView?.deleteSections(IndexSet(integer: 1)) self.sections = [.search, .customThemes, .themes] } let show = { self.collectionView?.insertSections(IndexSet(integer: 1)) self.sections = [.search, .info, .customThemes, .themes] } collectionView.performBatchUpdates({ hidden ? hide() : show() }) } // MARK: - UISearchResultsUpdating open func updateSearchResults(for searchController: UISearchController) { searchName = searchController.searchBar.text ?? "" } // MARK: - NSFetchedResultsController helpers fileprivate func searchNamePredicate() -> NSPredicate? { guard !searchName.isEmpty else { return nil } return NSPredicate(format: "name contains[c] %@", searchName) } fileprivate func browsePredicate() -> NSPredicate? { return browsePredicateThemesWithCustomValue(false) } fileprivate func customThemesBrowsePredicate() -> NSPredicate? { return browsePredicateThemesWithCustomValue(true) } fileprivate func browsePredicateThemesWithCustomValue(_ custom: Bool) -> NSPredicate? { let blogPredicate = NSPredicate(format: "blog == %@ AND custom == %d", self.blog, custom ? 1 : 0) let subpredicates = [blogPredicate, searchNamePredicate(), filterType.predicate].compactMap { $0 } switch subpredicates.count { case 1: return subpredicates[0] default: return NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates) } } fileprivate func fetchThemes() { do { themesController.fetchRequest.predicate = browsePredicate() try themesController.performFetch() if self.blog.supports(BlogFeature.customThemes) { customThemesController.fetchRequest.predicate = customThemesBrowsePredicate() try customThemesController.performFetch() } } catch { DDLogError("Error fetching themes: \(error)") } } // MARK: - NSFetchedResultsControllerDelegate open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { reloadThemes() } // MARK: - ThemePresenter // optional closure that will be executed when the presented WebkitViewController closes @objc var onWebkitViewControllerClose: (() -> Void)? @objc open func activateTheme(_ theme: Theme?) { guard let theme = theme, !theme.isCurrentTheme() else { return } updateActivateButton(isLoading: true) _ = themeService.activate(theme, for: blog, success: { [weak self] (theme: Theme?) in WPAppAnalytics.track(.themesChangedTheme, withProperties: ["theme_id": theme?.themeId ?? ""], with: self?.blog) self?.collectionView?.reloadData() let successTitle = NSLocalizedString("Theme Activated", comment: "Title of alert when theme activation succeeds") let successFormat = NSLocalizedString("Thanks for choosing %@ by %@", comment: "Message of alert when theme activation succeeds") let successMessage = String(format: successFormat, theme?.name ?? "", theme?.author ?? "") let manageTitle = NSLocalizedString("Manage site", comment: "Return to blog screen action when theme activation succeeds") let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") self?.updateActivateButton(isLoading: false) let alertController = UIAlertController(title: successTitle, message: successMessage, preferredStyle: .alert) alertController.addActionWithTitle(manageTitle, style: .default, handler: { [weak self] (action: UIAlertAction) in _ = self?.navigationController?.popViewController(animated: true) }) alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }, failure: { [weak self] (error) in DDLogError("Error activating theme \(String(describing: theme.themeId)): \(String(describing: error?.localizedDescription))") let errorTitle = NSLocalizedString("Activation Error", comment: "Title of alert when theme activation fails") let okTitle = NSLocalizedString("OK", comment: "Alert dismissal title") self?.activityIndicator.stopAnimating() self?.activateButton?.customView = nil let alertController = UIAlertController(title: errorTitle, message: error?.localizedDescription, preferredStyle: .alert) alertController.addDefaultActionWithTitle(okTitle, handler: nil) alertController.presentFromRootViewController() }) } @objc open func installThemeAndPresentCustomizer(_ theme: Theme) { _ = themeService.installTheme(theme, for: blog, success: { [weak self] in self?.presentUrlForTheme(theme, url: theme.customizeUrl(), activeButton: !theme.isCurrentTheme()) }, failure: nil) } @objc open func presentCustomizeForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesCustomizeAccessed, with: self.blog) QuickStartTourGuide.shared.visited(.customize) presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: false, modalStyle: .fullScreen) } @objc open func presentPreviewForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesPreviewedSite, with: self.blog) // In order to Try & Customize a theme we first need to install it (Jetpack sites) if let theme = theme, self.blog.supports(.customThemes) && !theme.custom { installThemeAndPresentCustomizer(theme) } else { presentUrlForTheme(theme, url: theme?.customizeUrl(), activeButton: !(theme?.isCurrentTheme() ?? true)) } } @objc open func presentDetailsForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesDetailsAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.detailsUrl()) } @objc open func presentSupportForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesSupportAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.supportUrl()) } @objc open func presentViewForTheme(_ theme: Theme?) { WPAppAnalytics.track(.themesDemoAccessed, with: self.blog) presentUrlForTheme(theme, url: theme?.viewUrl(), onClose: onWebkitViewControllerClose) } @objc open func presentUrlForTheme(_ theme: Theme?, url: String?, activeButton: Bool = true, modalStyle: UIModalPresentationStyle = .pageSheet, onClose: (() -> Void)? = nil) { guard let theme = theme, let url = url.flatMap(URL.init(string:)) else { return } suspendedSearch = searchName presentingTheme = theme let configuration = WebViewControllerConfiguration(url: url) configuration.authenticate(blog: theme.blog) configuration.secureInteraction = true configuration.customTitle = theme.name configuration.navigationDelegate = customizerNavigationDelegate configuration.onClose = onClose let title = activeButton ? ThemeAction.activate.title : ThemeAction.active.title activateButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(ThemeBrowserViewController.activatePresentingTheme)) activateButton?.isEnabled = !theme.isCurrentTheme() let webViewController = WebViewControllerFactory.controller(configuration: configuration, source: "theme_browser") webViewController.navigationItem.rightBarButtonItem = activateButton let navigation = UINavigationController(rootViewController: webViewController) navigation.modalPresentationStyle = modalStyle if searchController != nil && searchController.isActive { searchController.dismiss(animated: true, completion: { self.present(navigation, animated: true) }) } else { present(navigation, animated: true) } } @objc open func activatePresentingTheme() { suspendedSearch = "" activateTheme(presentingTheme) presentingTheme = nil } } // MARK: - NoResults Handling private extension ThemeBrowserViewController { func updateResults() { if themeCount == 0 && customThemeCount == 0 { showNoResults() } else { hideNoResults() } } func showNoResults() { guard !noResultsShown else { return } if noResultsViewController == nil { noResultsViewController = NoResultsViewController.controller() } guard let noResultsViewController = noResultsViewController else { return } if searchController.isActive { noResultsViewController.configureForNoSearchResults(title: NoResultsTitles.noThemes) } else { noResultsViewController.configure(title: NoResultsTitles.fetchingThemes, accessoryView: NoResultsViewController.loadingAccessoryView()) } addChild(noResultsViewController) collectionView.addSubview(noResultsViewController.view) noResultsViewController.view.frame = collectionView.frame // There is a gap between the search bar and the collection view - https://github.com/wordpress-mobile/WordPress-iOS/issues/9730 // This makes the No Results View look vertically off-center. Until that is resolved, we'll adjust the NRV according to the search bar. if searchController.isActive { noResultsViewController.view.frame.origin.y = searchController.searchBar.bounds.height } else { noResultsViewController.view.frame.origin.y -= searchBarHeight } noResultsViewController.didMove(toParent: self) } func hideNoResults() { guard noResultsShown else { return } noResultsViewController?.removeFromView() if searchController.isActive { collectionView?.reloadData() } else { sections = [.search, .info, .customThemes, .themes] collectionView?.collectionViewLayout.invalidateLayout() } } }
gpl-2.0
0131b6c6fb8c01dc551697a414ad5350
38.509684
287
0.652107
6.012876
false
false
false
false
adrfer/swift
test/SILOptimizer/return.swift
1
3352
// RUN: %target-swift-frontend %s -emit-sil -verify func singleBlock() -> Int { _ = 0 } // expected-error {{missing return in a function expected to return 'Int'}} func singleBlock2() -> Int { var y = 0 y += 1 } // expected-error {{missing return in a function expected to return 'Int'}} class MyClassWithClosure { var f : (s: String) -> String = { (s: String) -> String in } // expected-error {{missing return in a closure expected to return 'String'}} } func multipleBlocksSingleMissing(b: Bool) -> (String, Int) { var y = 0 if b { return ("a", 1) } else if (y == 0) { y += 1 } } // expected-error {{missing return in a function expected to return '(String, Int)'}} func multipleBlocksAllMissing(x: Int) -> Int { var y : Int = x + 1 while (y > 0 ) { y -= 1 break } var x = 0 x += 1 } // expected-error {{missing return in a function expected to return 'Int'}} @noreturn func MYsubscriptNonASCII(idx: Int) -> UnicodeScalar { } // no-warning @noreturn @_silgen_name("exit") func exit () -> () @noreturn func tryingToReturn (x: Bool) -> () { if x { return // expected-error {{return from a 'noreturn' function}} } exit() } @noreturn func implicitReturnWithinNoreturn() { _ = 0 }// expected-error {{return from a 'noreturn' function}} func diagnose_missing_return_in_the_else_branch(i: Bool) -> Int { if (i) { exit() } } // expected-error {{missing return in a function expected to return 'Int'}} func diagnose_missing_return_no_error_after_noreturn(i: Bool) -> Int { if (i) { exit() } else { exit() } } // no error class TuringMachine { @noreturn func halt() { repeat { } while true } @noreturn func eatTape() { return // expected-error {{return from a 'noreturn' function}} } } func diagnose_missing_return_no_error_after_noreturn_method() -> Int { TuringMachine().halt() } // no error func whileLoop(flag: Bool) -> Int { var b = 1 while (flag) { if b == 3 { return 3 } b += 1 } } //expected-error {{missing return in a function expected to return 'Int'}} func whileTrueLoop() -> Int { var b = 1 while (true) { if b == 3 { return 3 } b += 1 } // no-error } func testUnreachableAfterNoReturn(x: Int) -> Int { exit(); // expected-note{{a call to a noreturn function}} return x; // expected-warning {{will never be executed}} } func testUnreachableAfterNoReturnInADifferentBlock() -> Int { let x:Int = 5 if true { // expected-note {{condition always evaluates to true}} exit(); } return x; // expected-warning {{will never be executed}} } func testReachableAfterNoReturnInADifferentBlock(x: Int) -> Int { if x == 5 { exit(); } return x; // no warning } func testUnreachableAfterNoReturnFollowedByACall() -> Int { let x:Int = 5 exit(); // expected-note{{a call to a noreturn function}} exit(); // expected-warning {{will never be executed}} return x } func testUnreachableAfterNoReturnMethod() -> Int { TuringMachine().halt(); // expected-note{{a call to a noreturn function}} return 0; // expected-warning {{will never be executed}} } func testCleanupCodeEmptyTuple(@autoclosure fn: () -> Bool = false, message: String = "", file: String = __FILE__, line: Int = __LINE__) { if true { exit() } } // no warning
apache-2.0
4b55d925c76cfa2cf14c71b969d54c44
23.467153
140
0.623508
3.524711
false
false
false
false
Tommy1990/swiftWibo
SwiftWibo/SwiftWibo/Classes/View/Compose/View/EPMComposeView.swift
1
5117
// // EPMComposeView.swift // SwiftWibo // // Created by 马继鵬 on 17/3/27. // Copyright © 2017年 7TH. All rights reserved. // import UIKit import pop class EPMComposeView: UIView { var target:UIViewController? override init(frame: CGRect) { super.init(frame: UIScreen.main.bounds) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { addSubview(imgBack) addSubview(imgAds) addSubBtns() imgBack.snp.makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0)) } imgAds.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self).offset(100) } } //MARKE: 懒加载控件 lazy var imgBack:UIImageView = { let img = UIImageView(image: UIImage.getScreenSnap()?.applyLightEffect()) return img }() lazy var imgAds:UIImageView = UIImageView(image: UIImage(named: "compose_slogan")) lazy var btnArr:[EPMComposeButton] = [EPMComposeButton]() } extension EPMComposeView{ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { btnAnimation(isUP: false) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.4) { self.removeFromSuperview() } } } //MARKE: 对外接口 extension EPMComposeView{ class func showView(target:UIViewController) { let composeView = EPMComposeView() composeView.target = target target.view.addSubview(composeView) composeView.btnAnimation(isUP: true) } } //MARKE: btn按键 extension EPMComposeView{ //MARKE:添加按键 fileprivate func addSubBtns() { let btnWidth:CGFloat = 80 let btnHeight:CGFloat = 120 let btnMargine = (screenWidth - btnWidth*3)/4 let btnModelArr = loadData() for (i,model) in btnModelArr.enumerated() { let row = CGFloat (i / 3) let col = CGFloat (i % 3) let btn = EPMComposeButton() btn.setImage(UIImage(named:model.icon ?? ""), for: .normal) btn.setTitle(model.title!, for: .normal) btn.frame = CGRect(x: btnMargine+(btnMargine+btnWidth)*col, y: (btnMargine+btnHeight)*row+screenHeight, width: btnWidth, height: btnHeight) btn.composeModel = model btnArr.append(btn) btn.addTarget(self, action: #selector(clickBtnAction(btn:)), for: .touchUpInside) addSubview(btn) } } fileprivate func btnAnimation(isUP:Bool) { let msrginY:CGFloat = isUP ? -350 : 350 let btnList = isUP ? btnArr : btnArr.reversed() for (i,button) in btnList.enumerated(){ // 实例化弹簧动画对象 let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)! // 设置toValue anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y + msrginY) // 开始时间 CACurrentMediaTime() 系统绝对时间 anSpring.beginTime = CACurrentMediaTime() + Double(i)*0.025 // 振幅 anSpring.springBounciness = 10.0 // 设置动画 button.pop_add(anSpring, forKey: nil) } } @objc fileprivate func clickBtnAction(btn:EPMComposeButton) { UIView.animate(withDuration: 0.25, animations: { for button in self.btnArr{ button.alpha = 0.2 if btn == button{ btn.transform = CGAffineTransform.init(scaleX: 2, y: 2) }else{ button.transform = CGAffineTransform.init(scaleX: 0.2, y: 0.2) } } }) { (_) in UIView.animate(withDuration: 0.25, animations: { for button in self.btnArr{ button.alpha = 1 button.transform = CGAffineTransform.identity } }, completion: { (_) in guard let className = btn.composeModel?.classname else{ return } guard let classType = NSClassFromString(className) as? UIViewController.Type else{ return } let vc = classType.init() self.target?.present(EPBaseNavigationController(rootViewController:vc), animated: true, completion: { self.removeFromSuperview() }) }) } } } //MARKE: 数据加载 extension EPMComposeView{ fileprivate func loadData()->[EPMComposeModel] { let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)! let tempArray = NSArray(contentsOfFile: path)! let btnArray = NSArray.yy_modelArray(with: EPMComposeModel.self, json: tempArray) as! [EPMComposeModel] return btnArray } }
mit
d54568681475832eb76181b5693173c4
27.662857
151
0.569777
4.462633
false
false
false
false
shuuchen/Swift-Down-Video
source/VideoCollectionViewLayout.swift
1
1047
// // VideoCollectionViewLayout.swift // table_template // // Created by Shuchen Du on 2015/10/12. // Copyright (c) 2015年 Shuchen Du. All rights reserved. // import UIKit protocol PinterestLayoutDelegate { // 1 func collectionView(collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:NSIndexPath, withWidth:CGFloat) -> CGFloat // 2 func collectionView(collectionView: UICollectionView, heightForAnnotationAtIndexPath indexPath: NSIndexPath, withWidth width: CGFloat) -> CGFloat } class VideoCollectionViewLayout: UICollectionViewLayout { // 1 var delegate: PinterestLayoutDelegate! // 2 var numberOfColumns = 2 var cellPadding: CGFloat = 6.0 // 3 private var cache = [UICollectionViewLayoutAttributes]() // 4 private var contentHeight: CGFloat = 0.0 private var contentWidth: CGFloat { let insets = collectionView!.contentInset return CGRectGetWidth(collectionView!.bounds) - (insets.left + insets.right) } }
mit
760af1a5e3c16544079213f183ca682e
26.5
99
0.702392
4.97619
false
false
false
false
bfortunato/aj-framework
platforms/ios/Libs/socket.io-client-swift/SocketIO-MacTests/SocketEngineTest.swift
2
4289
// // SocketEngineTest.swift // Socket.IO-Client-Swift // // Created by Erik Little on 10/15/15. // // import XCTest @testable import SocketIO class SocketEngineTest: XCTestCase { var client: SocketIOClient! var engine: SocketEngine! override func setUp() { super.setUp() client = SocketIOClient(socketURL: URL(string: "http://localhost")!) engine = SocketEngine(client: client, url: URL(string: "http://localhost")!, options: nil) client.setTestable() } func testBasicPollingMessage() { let expect = expectation(description: "Basic polling test") client.on("blankTest") {data, ack in expect.fulfill() } engine.parsePollingMessage("15:42[\"blankTest\"]") waitForExpectations(timeout: 3, handler: nil) } func testTwoPacketsInOnePollTest() { let finalExpectation = expectation(description: "Final packet in poll test") var gotBlank = false client.on("blankTest") {data, ack in gotBlank = true } client.on("stringTest") {data, ack in if let str = data[0] as? String, gotBlank { if str == "hello" { finalExpectation.fulfill() } } } engine.parsePollingMessage("15:42[\"blankTest\"]24:42[\"stringTest\",\"hello\"]") waitForExpectations(timeout: 3, handler: nil) } func testEngineDoesErrorOnUnknownTransport() { let finalExpectation = expectation(description: "Unknown Transport") client.on("error") {data, ack in if let error = data[0] as? String, error == "Unknown transport" { finalExpectation.fulfill() } } engine.parseEngineMessage("{\"code\": 0, \"message\": \"Unknown transport\"}", fromPolling: false) waitForExpectations(timeout: 3, handler: nil) } func testEngineDoesErrorOnUnknownMessage() { let finalExpectation = expectation(description: "Engine Errors") client.on("error") {data, ack in finalExpectation.fulfill() } engine.parseEngineMessage("afafafda", fromPolling: false) waitForExpectations(timeout: 3, handler: nil) } func testEngineDecodesUTF8Properly() { let expect = expectation(description: "Engine Decodes utf8") client.on("stringTest") {data, ack in XCTAssertEqual(data[0] as? String, "lïne one\nlīne \rtwo", "Failed string test") expect.fulfill() } engine.parsePollingMessage("41:42[\"stringTest\",\"lïne one\\nlÄ«ne \\rtwo\"]") waitForExpectations(timeout: 3, handler: nil) } func testEncodeURLProperly() { engine.connectParams = [ "created": "2016-05-04T18:31:15+0200" ] XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&created=2016-05-04T18%3A31%3A15%2B0200") XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&created=2016-05-04T18%3A31%3A15%2B0200") engine.connectParams = [ "forbidden": "!*'();:@&=+$,/?%#[]\" {}" ] XCTAssertEqual(engine.urlPolling.query, "transport=polling&b64=1&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") XCTAssertEqual(engine.urlWebSocket.query, "transport=websocket&forbidden=%21%2A%27%28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%5B%5D%22%20%7B%7D") } func testBase64Data() { let expect = expectation(description: "Engine Decodes base64 data") let b64String = "b4aGVsbG8NCg==" let packetString = "451-[\"test\",{\"test\":{\"_placeholder\":true,\"num\":0}}]" client.on("test") {data, ack in if let data = data[0] as? Data, let string = String(data: data, encoding: .utf8) { XCTAssertEqual(string, "hello") } expect.fulfill() } engine.parseEngineMessage(packetString, fromPolling: false) engine.parseEngineMessage(b64String, fromPolling: false) waitForExpectations(timeout: 3, handler: nil) } }
apache-2.0
dcf3556de46e4b02dacf7e2b1ca9c362
33.540323
154
0.58954
4.098565
false
true
false
false
codepath-volunteer-app/VolunteerMe
VolunteerMe/Pods/ParseLiveQuery/Sources/ParseLiveQuery/Subscription.swift
1
9058
/** * Copyright (c) 2016-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import Parse import BoltsSwift /** This protocol describes the interface for handling events from a liveQuery client. You can use this protocol on any custom class of yours, instead of Subscription, if it fits your use case better. */ public protocol SubscriptionHandling: AnyObject { /// The type of the PFObject subclass that this handler uses. associatedtype PFObjectSubclass: PFObject /** Tells the handler that an event has been received from the live query server. - parameter event: The event that has been recieved from the server. - parameter query: The query that the event occurred on. - parameter client: The live query client which received this event. */ func didReceive(_ event: Event<PFObjectSubclass>, forQuery query: PFQuery<PFObjectSubclass>, inClient client: Client) /** Tells the handler that an error has been received from the live query server. - parameter error: The error that the server has encountered. - parameter query: The query that the error occurred on. - parameter client: The live query client which received this error. */ func didEncounter(_ error: Error, forQuery query: PFQuery<PFObjectSubclass>, inClient client: Client) /** Tells the handler that a query has been successfully registered with the server. - note: This may be invoked multiple times if the client disconnects/reconnects. - parameter query: The query that has been subscribed. - parameter client: The live query client which subscribed this query. */ func didSubscribe(toQuery query: PFQuery<PFObjectSubclass>, inClient client: Client) /** Tells the handler that a query has been successfully deregistered from the server. - note: This is not called unless `unregister()` is explicitly called. - parameter query: The query that has been unsubscribed. - parameter client: The live query client which unsubscribed this query. */ func didUnsubscribe(fromQuery query: PFQuery<PFObjectSubclass>, inClient client: Client) } /** Represents an update on a specific object from the live query server. - Entered: The object has been updated, and is now included in the query. - Left: The object has been updated, and is no longer included in the query. - Created: The object has been created, and is a part of the query. - Updated: The object has been updated, and is still a part of the query. - Deleted: The object has been deleted, and is no longer included in the query. */ public enum Event<T> where T: PFObject { /// The object has been updated, and is now included in the query case entered(T) /// The object has been updated, and is no longer included in the query case left(T) /// The object has been created, and is a part of the query case created(T) /// The object has been updated, and is still a part of the query case updated(T) /// The object has been deleted, and is no longer included in the query case deleted(T) init<V>(event: Event<V>) where V: PFObject { switch event { case .entered(let value as T): self = .entered(value) case .left(let value as T): self = .left(value) case .created(let value as T): self = .created(value) case .updated(let value as T): self = .updated(value) case .deleted(let value as T): self = .deleted(value) default: fatalError() } } } private func == <T: PFObject>(lhs: Event<T>, rhs: Event<T>) -> Bool { switch (lhs, rhs) { case (.entered(let obj1), .entered(let obj2)): return obj1 == obj2 case (.left(let obj1), .left(let obj2)): return obj1 == obj2 case (.created(let obj1), .created(let obj2)): return obj1 == obj2 case (.updated(let obj1), .updated(let obj2)): return obj1 == obj2 case (.deleted(let obj1), .deleted(let obj2)): return obj1 == obj2 default: return false } } /** A default implementation of the SubscriptionHandling protocol, using closures for callbacks. */ open class Subscription<T>: SubscriptionHandling where T: PFObject { fileprivate var errorHandlers: [(PFQuery<T>, Error) -> Void] = [] fileprivate var eventHandlers: [(PFQuery<T>, Event<T>) -> Void] = [] fileprivate var subscribeHandlers: [(PFQuery<T>) -> Void] = [] fileprivate var unsubscribeHandlers: [(PFQuery<T>) -> Void] = [] /** Creates a new subscription that can be used to handle updates. */ public init() { } /** Register a callback for when an error occurs. - parameter handler: The callback to register. - returns: The same subscription, for easy chaining */ @discardableResult open func handleError(_ handler: @escaping (PFQuery<T>, Error) -> Void) -> Subscription { errorHandlers.append(handler) return self } /** Register a callback for when an event occurs. - parameter handler: The callback to register. - returns: The same subscription, for easy chaining. */ @discardableResult open func handleEvent(_ handler: @escaping (PFQuery<T>, Event<T>) -> Void) -> Subscription { eventHandlers.append(handler) return self } /** Register a callback for when a client succesfully subscribes to a query. - parameter handler: The callback to register. - returns: The same subscription, for easy chaining. */ @discardableResult open func handleSubscribe(_ handler: @escaping (PFQuery<T>) -> Void) -> Subscription { subscribeHandlers.append(handler) return self } /** Register a callback for when a query has been unsubscribed. - parameter handler: The callback to register. - returns: The same subscription, for easy chaining. */ @discardableResult open func handleUnsubscribe(_ handler: @escaping (PFQuery<T>) -> Void) -> Subscription { unsubscribeHandlers.append(handler) return self } // --------------- // MARK: SubscriptionHandling // TODO: Move to extension once swift compiler is less crashy // --------------- public typealias PFObjectSubclass = T open func didReceive(_ event: Event<PFObjectSubclass>, forQuery query: PFQuery<T>, inClient client: Client) { eventHandlers.forEach { $0(query, event) } } open func didEncounter(_ error: Error, forQuery query: PFQuery<T>, inClient client: Client) { errorHandlers.forEach { $0(query, error) } } open func didSubscribe(toQuery query: PFQuery<T>, inClient client: Client) { subscribeHandlers.forEach { $0(query) } } open func didUnsubscribe(fromQuery query: PFQuery<T>, inClient client: Client) { unsubscribeHandlers.forEach { $0(query) } } } extension Subscription { /** Register a callback for when an error occcurs of a specific type Example: subscription.handle(LiveQueryErrors.InvalidJSONError.self) { query, error in print(error) } - parameter errorType: The error type to register for - parameter handler: The callback to register - returns: The same subscription, for easy chaining */ @discardableResult public func handle<E: Error>( _ errorType: E.Type = E.self, _ handler: @escaping (PFQuery<T>, E) -> Void ) -> Subscription { errorHandlers.append { query, error in if let error = error as? E { handler(query, error) } } return self } /** Register a callback for when an event occurs of a specific type Example: subscription.handle(Event.Created) { query, object in // Called whenever an object is creaated } - parameter eventType: The event type to handle. You should pass one of the enum cases in `Event` - parameter handler: The callback to register - returns: The same subscription, for easy chaining */ @discardableResult public func handle(_ eventType: @escaping (T) -> Event<T>, _ handler: @escaping (PFQuery<T>, T) -> Void) -> Subscription { return handleEvent { query, event in switch event { case .entered(let obj) where eventType(obj) == event: handler(query, obj) case .left(let obj) where eventType(obj) == event: handler(query, obj) case .created(let obj) where eventType(obj) == event: handler(query, obj) case .updated(let obj) where eventType(obj) == event: handler(query, obj) case .deleted(let obj) where eventType(obj) == event: handler(query, obj) default: return } } } }
mit
fd67e4008af1e7bcc77368a3c92f9720
35.232
145
0.66019
4.535804
false
false
false
false
LamGiauKhongKhoTeam/LGKK
ModulesTests/SwifterSwiftTests/ArrayExtensionsTests.swift
1
7514
// // ArrayExtensionsTests.swift // SwifterSwift // // Created by Omar Albeik on 8/26/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import XCTest @testable import SwifterSwift class ArrayExtensionsTests: XCTestCase { func testRandomItem() { XCTAssert([1, 2, 3].contains([1, 2, 3].randomItem)) } func testAverage() { XCTAssertEqual([1, 2, 3, 4, 5].average(), 3) XCTAssertEqual([1.2, 2.3, 3.4, 4.5, 5.6].average(), 3.4) XCTAssertEqual([Int]().average(), 0) XCTAssertEqual([Double]().average(), 0) } func testFirstIndex() { XCTAssertNotNil([1, 1, 2, 3, 4, 1, 2, 1].firstIndex(of: 2)) XCTAssertEqual([1, 1, 2, 3, 4, 1, 2, 1].firstIndex(of: 2)!, 2) XCTAssertNil([1, 1, 2, 3, 4, 1, 2, 1].firstIndex(of: 7)) } func testIndexes() { XCTAssertEqual([1, 1, 2, 3, 4, 1, 2, 1].indexes(of: 1), [0, 1, 5, 7]) } func testLastIndex() { XCTAssertNotNil([1, 1, 2, 3, 4, 1, 2, 1].lastIndex(of: 2)) XCTAssertEqual([1, 1, 2, 3, 4, 1, 2, 1].lastIndex(of: 2)!, 6) XCTAssertNil([1, 1, 2, 3, 4, 1, 2, 1].lastIndex(of: 7)) } func testPop() { var arr = [1, 2, 3, 4, 5] let item = arr.pop() XCTAssertEqual(arr, [1, 2, 3, 4]) XCTAssertNotNil(item) XCTAssertEqual(item, 5) arr.removeAll() XCTAssertNil(arr.pop()) } func testPrepend() { var arr = [2, 3, 4, 5] arr.prepend(1) XCTAssertEqual(arr, [1, 2, 3, 4, 5]) } func testPush() { var arr = [1, 2, 3, 4] arr.push(5) XCTAssertEqual(arr, [1, 2, 3, 4, 5]) } func testSwap() { var array: [Int] = [1, 2, 3, 4, 5] array.swap(from: 3, to: 0) XCTAssertEqual(array[3], 1) XCTAssertEqual(array[0], 4) } func testSafeSwap() { var array: [Int] = [1, 2, 3, 4, 5] array.safeSwap(from: 3, to: 0) XCTAssertEqual(array[3], 1) XCTAssertEqual(array[0], 4) var newArray = array newArray.safeSwap(from: 1, to: 1) XCTAssertEqual(newArray, array) newArray = array newArray.safeSwap(from: 1, to: 12) XCTAssertEqual(newArray, array) let emptyArray: [Int] = [] var swappedEmptyArray = emptyArray swappedEmptyArray.safeSwap(from: 1, to: 3) XCTAssertEqual(swappedEmptyArray, emptyArray) } func testRemoveAll() { var arr = [0, 1, 2, 0, 3, 4, 5, 0, 0] arr.removeAll(0) XCTAssertEqual(arr, [1, 2, 3, 4, 5]) } func testRemoveAllItems() { var arr = [0, 1, 2, 2, 0, 3, 4, 5, 0, 0] arr.removeAll(0) arr.removeAll(2) XCTAssertEqual(arr, [1, 3, 4, 5]) } func testShuffle() { var arr = ["a"] arr.shuffle() XCTAssertEqual(arr, arr) let original = [1, 2, 3, 4, 5] var array = original while original == array { array.shuffle() } XCTAssertEqual(array.count, 5) XCTAssertNotEqual(original, array) } func testShuffled() { let original = [1, 2, 3, 4, 5] var array = original while original == array { array = array.shuffled() } XCTAssertEqual(array.count, 5) XCTAssertNotEqual(original, array) } func testSum() { XCTAssertEqual([1, 2, 3, 4, 5].sum(), 15) XCTAssertEqual([1.2, 2.3, 3.4, 4.5, 5.6].sum(), 17) } func testRemoveDuplicates() { var array = [1, 1, 2, 2, 3, 3, 3, 4, 5] array.removeDuplicates() XCTAssertEqual(array, [1, 2, 3, 4, 5]) } func testDuplicatesRemoved() { XCTAssertEqual([1, 1, 2, 2, 3, 3, 3, 4, 5].duplicatesRemoved(), [1, 2, 3, 4, 5]) } func testItemAtIndex() { XCTAssertEqual([1, 2, 3].item(at: 0), 1) XCTAssertEqual([1, 2, 3].item(at: 1), 2) XCTAssertEqual([1, 2, 3].item(at: 2), 3) XCTAssertNil([1, 2, 3].item(at: 5)) } func testContains() { XCTAssert([Int]().contains([])) XCTAssertFalse([Int]().contains([1, 2])) XCTAssert([1, 2, 3].contains([1, 2])) XCTAssert([1, 2, 3].contains([2, 3])) XCTAssert([1, 2, 3].contains([1, 3])) XCTAssertFalse([1, 2, 3].contains([4, 5])) } // func testFirstIndexWhere() { // let array = [1, 7, 1, 2, 4, 1, 6] // let index = array.firstIndex { $0 % 2 == 0 } // XCTAssertEqual(index, 3) // XCTAssertNil([Int]().firstIndex { $0 % 2 == 0 }) // } // // func testLastIndexWhere() { // let array = [1, 1, 1, 2, 2, 1, 1, 2, 1] // let index = array.lastIndex { $0 % 2 == 0 } // XCTAssertEqual(index, 7) // XCTAssertNil([Int]().lastIndex { $0 % 2 == 0 }) // } // // func testIndicesWhere() { // let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // let indices = array.indices { $0 % 2 == 0 } // XCTAssertEqual(indices!, [0, 2, 4, 6, 8]) // } // // func testAllMatch() { // let array = [2, 4, 6, 8, 10, 12] // XCTAssert(array.all { $0 % 2 == 0 }) // } // // func testNoneMatch() { // let array = [3, 5, 7, 9, 11, 13] // XCTAssert(array.none { $0 % 2 == 0 }) // } // // func testLastWhere() { // let array = [1, 1, 2, 1, 1, 1, 2, 1, 4, 1] // let element = array.last { $0 % 2 == 0 } // XCTAssertEqual(element, 4) // XCTAssertNil([Int]().last { $0 % 2 == 0 }) // } // // func testReject() { // let input = [1, 2, 3, 4, 5] // let output = input.reject { $0 % 2 == 0 } // XCTAssertEqual(output, [1, 3, 5]) // } // // func testCountWhere() { // let array = [1, 1, 1, 1, 4, 4, 1, 1, 1] // let count = array.count { $0 % 2 == 0 } // XCTAssertEqual(count, 2) // } // // func testForEachReversed() { // let input = [1, 2, 3, 4, 5] // var output: [Int] = [] // input.forEachReversed { output.append($0) } // XCTAssertEqual(output.first, 5) // } // // func testForEachWhere() { // let input = [1, 2, 2, 2, 1, 4, 1] // var output: [Int] = [] // input.forEach(where: {$0 % 2 == 0}) { output.append($0 * 2) } // XCTAssertEqual(output, [4, 4, 4, 8]) // } // // func testAccumulate() { // let input = [1, 2, 3] // let result = input.accumulate(initial: 0, next: +) // XCTAssertEqual([1, 3, 6], result) // } // // func testKeepWhile() { // var input = [2, 4, 6, 7, 8, 9, 10] // input.keep(while: {$0 % 2 == 0 }) // XCTAssertEqual(input, [2, 4, 6]) // // input = [7, 7, 8, 10] // input.keep(while: {$0 % 2 == 0 }) // XCTAssertEqual(input, [Int]()) // } // // func testDropWhile() { // var input = [2, 4, 6, 7, 8, 9, 10] // input.drop(while: { $0 % 2 == 0 }) // XCTAssertEqual(input, [7, 8, 9, 10]) // // input = [7, 7, 8, 10, 7] // input.drop(while: { $0 % 2 == 0 }) // XCTAssertEqual(input, [7, 7, 8, 10, 7]) // } // // func testTakeWhile() { // var input = [2, 4, 6, 7, 8, 9, 10] // var output = input.take(while: {$0 % 2 == 0 }) // XCTAssertEqual(output, [2, 4, 6]) // // input = [7, 7, 8, 10] // output = input.take(while: {$0 % 2 == 0 }) // XCTAssertEqual(output, [Int]()) // } // // func testSkipWhile() { // var input = [2, 4, 6, 7, 8, 9, 10] // var output = input.skip(while: {$0 % 2 == 0 }) // XCTAssertEqual(output, [7, 8, 9, 10]) // // input = [7, 7, 8, 10] // output = input.skip(while: {$0 % 2 == 0 }) // XCTAssertEqual(output, [7, 7, 8, 10]) // } }
mit
c89858d3424dcc15b99151d1e7d78408
26.723247
88
0.500998
2.892953
false
true
false
false
calebd/ReactiveCocoa
ReactiveCocoaTests/InterceptingSpec.swift
1
2395
import Foundation import ReactiveCocoa import ReactiveSwift import enum Result.NoError import Quick import Nimble class InterceptingSpec: QuickSpec { override func spec() { describe("trigger(for:)") { var object: InterceptedObject! weak var _object: InterceptedObject? beforeEach { object = InterceptedObject() _object = object } afterEach { object = nil expect(_object).to(beNil()) } it("should send a value when the selector is invoked") { let signal = object.reactive.trigger(for: #selector(object.increment)) var counter = 0 signal.observeValues { counter += 1 } expect(counter) == 0 expect(object.counter) == 0 object.increment() expect(counter) == 1 expect(object.counter) == 1 object.increment() expect(counter) == 2 expect(object.counter) == 2 } it("should complete when the object deinitializes") { let signal = object.reactive.trigger(for: #selector(object.increment)) var isCompleted = false signal.observeCompleted { isCompleted = true } expect(isCompleted) == false object = nil expect(_object).to(beNil()) expect(isCompleted) == true } it("should multicast") { let signal1 = object.reactive.trigger(for: #selector(object.increment)) let signal2 = object.reactive.trigger(for: #selector(object.increment)) var counter1 = 0 var counter2 = 0 signal1.observeValues { counter1 += 1 } signal2.observeValues { counter2 += 1 } expect(counter1) == 0 expect(counter2) == 0 object.increment() expect(counter1) == 1 expect(counter2) == 1 object.increment() expect(counter1) == 2 expect(counter2) == 2 } it("should not deadlock") { for _ in 1 ... 10 { var isDeadlocked = true func createQueue() -> DispatchQueue { if #available(*, macOS 10.10) { return .global(qos: .userInitiated) } else { return .global(priority: .high) } } createQueue().async { _ = object.reactive.trigger(for: #selector(object.increment)) createQueue().async { _ = object.reactive.trigger(for: #selector(object.increment)) isDeadlocked = false } } expect(isDeadlocked).toEventually(beFalsy()) } } } } } class InterceptedObject: NSObject { var counter = 0 dynamic func increment() { counter += 1 } }
mit
208743414bdccc915e266b13161723b3
20.772727
75
0.637578
3.590705
false
false
false
false
zhuxietong/Eelay
run/test/Regex/Regex.swift
2
6695
import Foundation public struct Regex: CustomStringConvertible, CustomDebugStringConvertible { // MARK: Initialisation internal let regularExpression: NSRegularExpression /// Create a `Regex` based on a pattern string. /// /// If `pattern` is not a valid regular expression, an error is thrown /// describing the failure. /// /// - parameters: /// - pattern: A pattern string describing the regex. /// - options: Configure regular expression matching options. /// For details, see `Regex.Options`. /// /// - throws: A value of `ErrorType` describing the invalid regular expression. public init(string pattern: String, options: Options = []) throws { regularExpression = try NSRegularExpression( pattern: pattern, options: options.toNSRegularExpressionOptions()) } /// Create a `Regex` based on a static pattern string. /// /// Unlike `Regex.init(string:)` this initialiser is not failable. If `pattern` /// is an invalid regular expression, it is considered programmer error rather /// than a recoverable runtime error, so this initialiser instead raises a /// precondition failure. /// /// - requires: `pattern` is a valid regular expression. /// /// - parameters: /// - pattern: A pattern string describing the regex. /// - options: Configure regular expression matching options. /// For details, see `Regex.Options`. public init(_ pattern: StaticString, options: Options = []) { do { regularExpression = try NSRegularExpression( pattern: pattern.description, options: options.toNSRegularExpressionOptions()) } catch { preconditionFailure("unexpected error creating regex: \(error)") } } // MARK: Matching /// Returns `true` if the regex matches `string`, otherwise returns `false`. /// /// - parameter string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. /// /// - note: If the match is successful, `Regex.lastMatch` will be set with the /// result of the match. public func matches(_ string: String) -> Bool { return firstMatch(in: string) != nil } /// If the regex matches `string`, returns a `MatchResult` describing the /// first matched string and any captures. If there are no matches, returns /// `nil`. /// /// - parameter string: The string to match against. /// /// - returns: An optional `MatchResult` describing the first match, or `nil`. /// /// - note: If the match is successful, the result is also stored in `Regex.lastMatch`. public func firstMatch(in string: String) -> MatchResult? { let match = regularExpression .firstMatch(in: string, options: [], range: string.entireRange) .map { MatchResult(string, $0) } Regex._lastMatch = match return match } /// If the regex matches `string`, returns an array of `MatchResult`, describing /// every match inside `string`. If there are no matches, returns an empty /// array. /// /// - parameter string: The string to match against. /// /// - returns: An array of `MatchResult` describing every match in `string`. /// /// - note: If there is at least one match, the first is stored in `Regex.lastMatch`. public func allMatches(in string: String) -> [MatchResult] { let matches = regularExpression .matches(in: string, options: [], range: string.entireRange) .map { MatchResult(string, $0) } if let firstMatch = matches.first { Regex._lastMatch = firstMatch } return matches } // MARK: Accessing the last match /// After any match, the result will be stored in this property for later use. /// This is useful when pattern matching: /// /// switch "hello" { /// case Regex("l+"): /// let count = Regex.lastMatch!.matchedString.characters.count /// print("matched \(count) characters") /// default: /// break /// } /// /// This property uses thread-local storage, and thus is thread safe. public static var lastMatch: MatchResult? { return _lastMatch } private static let _lastMatchKey = "me.sharplet.Regex.lastMatch" private static var _lastMatch: MatchResult? { get { return ThreadLocal(_lastMatchKey).value } set { ThreadLocal(_lastMatchKey).value = newValue } } // MARK: Describing public var description: String { return regularExpression.pattern } public var debugDescription: String { return "/\(description)/" } } // MARK: Pattern matching /// Match `regex` on the left with some `string` on the right. Equivalent to /// `regex.matches(string)`, and allows for the use of a `Regex` in pattern /// matching contexts, e.g.: /// /// switch Regex("hello (\\w+)") { /// case "hello world": /// // successful match /// } /// /// - parameters: /// - regex: The regular expression to match against. /// - string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. public func ~= (regex: Regex, string: String) -> Bool { return regex.matches(string) } /// Match `string` on the left with some `regex` on the right. Equivalent to /// `regex.matches(string)`, and allows for the use of a `Regex` in pattern /// matching contexts, e.g.: /// /// switch "hello world" { /// case Regex("hello (\\w+)"): /// // successful match /// } /// /// - parameters: /// - regex: The regular expression to match against. /// - string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. public func ~= (string: String, regex: Regex) -> Bool { return regex.matches(string) } // MARK: Conformances extension Regex: Equatable { public static func == (lhs: Regex, rhs: Regex) -> Bool { return lhs.regularExpression == rhs.regularExpression } } extension Regex: Hashable { public var hashValue: Int { return regularExpression.hashValue } } #if swift(>=3.2) extension Regex: Codable { public init(from decoder: Decoder) throws { let string = try decoder.singleValueContainer().decode(String.self) try self.init(string: string) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(regularExpression.pattern) } } #endif // MARK: Deprecations / Removals extension Regex { @available(*, unavailable, renamed: "firstMatch(in:)") public func match(_ string: String) -> MatchResult? { fatalError() } @available(*, unavailable, renamed: "allMatches(in:)") public func allMatches(_ string: String) -> [MatchResult] { fatalError() } }
mit
159829be497095f717111b352787929f
29.431818
89
0.658103
4.261617
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/Helpers/Extensions.swift
1
5879
// // Extensions .swift // YoutubeClone // // Created by Pankaj Rawat on 20/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit import SwiftDate extension UIColor { static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } static func appBaseColor() -> UIColor { return rgb(red: 44, green: 62, blue: 80) } static func appCallToActionColor() -> UIColor { return rgb(red: 231, green: 76, blue: 60) } static func appMainBGColor() -> UIColor { return rgb(red: 236, green: 240, blue: 241) } static func appLightBlue() -> UIColor { return rgb(red: 52, green: 152, blue: 219) } static func appDarkBlue() -> UIColor { return rgb(red: 41, green: 128, blue: 185) } } extension UIView { func addConstraintsWithFormat(format: String, views: UIView...){ var viewsDictionary = [String: UIView]() for(index, view) in views.enumerated() { let key = "v\(index)" view.translatesAutoresizingMaskIntoConstraints = false viewsDictionary[key] = view } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary)) } func addBackground(imageName: String) { // screen width and height: let width = UIScreen.main.bounds.size.width let height = UIScreen.main.bounds.size.height let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height)) imageViewBackground.image = UIImage(named: imageName) // you can change the content mode: imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill self.addSubview(imageViewBackground) self.sendSubview(toBack: imageViewBackground) } } let imageCache = NSCache<AnyObject, AnyObject>() class CustomImageView: UIImageView { var imageUrlString: String? func loadImageUsingUrlString(urlString: String, width: Float) { // Change width of image var urlString = urlString let regex = try! NSRegularExpression(pattern: "upload", options: NSRegularExpression.Options.caseInsensitive) let range = NSMakeRange(0, urlString.characters.count) urlString = regex.stringByReplacingMatches(in: urlString, options: [], range: range, withTemplate: "upload/w_\(Int(width * 1.5))") imageUrlString = urlString image = nil backgroundColor = UIColor.gray let url = NSURL(string: urlString) let configuration = URLSessionConfiguration.default let urlRequest = URLRequest(url: url as! URL) let session = URLSession(configuration: configuration) if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage { self.image = imageFromCache return } session.dataTask(with: urlRequest) { (data, response, error) -> Void in if (error != nil) { print(error!) return } else { DispatchQueue.main.async { let imageToCache = UIImage(data: data!) if self.imageUrlString == urlString { self.image = imageToCache } if imageToCache != nil { imageCache.setObject(imageToCache!, forKey: urlString as AnyObject) } } return } }.resume() } } //MARK: - UITextView extension UITextView{ func numberOfLines() -> Int{ if let fontUnwrapped = self.font{ return Int(self.contentSize.height / fontUnwrapped.lineHeight) } return 0 } } extension String { func humanizeDate(format: String = "MM-dd-yyyy HH:mm:ss") -> String { //"yyyy-MM-dd'T'HH:mm:ss.SSSZ" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" dateFormatter.locale = Locale.init(identifier: "en_GB") let dateObj = dateFormatter.date(from: self) dateFormatter.dateFormat = format return dateFormatter.string(from: dateObj!) } func relativeDate() -> String { let date = try! DateInRegion(string: humanizeDate(), format: .custom("MM-dd-yyyy HH:mm:ss")) let relevantTime = try! date.colloquialSinceNow().colloquial return relevantTime } } extension CreateTripController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func handleSelectTripImage() { let picker = UIImagePickerController() picker.delegate = self present(picker, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let imagePicked = info["UIImagePickerControllerOriginalImage"] as? UIImage { self.tripEditForm.thumbnailImageView.image = imagePicked statusBarBackgroundView.alpha = 0 } dismiss(animated: true, completion: nil) } }
mit
4c96149561fb73d18dffa0aecba1640a
32.20904
152
0.585403
5.075993
false
false
false
false
viviancrs/fanboy
FanBoy/Source/Provider/Networking/Base/ServiceBaseSessionProvider.swift
1
9938
// // ServiceNetworkProvider.swift // FanBoy // // Created by SalmoJunior on 8/17/16. // Copyright © 2016 CI&T. All rights reserved. // import Foundation public typealias ServiceURLSessionDictionaryCompletion = (() throws -> [String:AnyObject]?) -> () public typealias ServiceURLSessionArrayCompletion = (() throws -> [AnyObject]?) -> () public typealias ServiceURLSessionParameters = (bodyParameters: [String:AnyObject]?, queryParameters: [String:String]?) class ServiceBaseSessionProvider { let session: URLSession let baseURL: URL init(session: URLSession, baseURL: URL) { self.session = session self.baseURL = baseURL } //MARK: - HTTP Verbs func GET(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String]?, completionWithDictionary completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .get, url: url, parameters: parameters, header: header, completion: completion) } func GET(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String]?, completionWithArray completion: @escaping ServiceURLSessionArrayCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .get, url: url, parameters: parameters, header: header, completion: completion) } func POST(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String], completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .post, url: url, parameters: parameters, header: header, completion: completion) } func HEAD(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String], completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .head, url: url, parameters: parameters, header: header, completion: completion) } func PUT(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String], completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .put, url: url, parameters: parameters, header: header, completion: completion) } func DELETE(_ url: String, parameters: ServiceURLSessionParameters?, header: [String:String], completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { return self.dataTaskFor(httpMethod: .delete, url: url, parameters: parameters, header: header, completion: completion) } //MARK: - Private methods fileprivate func request(_ urlPath: String, parameters: ServiceURLSessionParameters?, header: [String:String]?, httpMethod: ServiceHTTPMethod) throws -> URLRequest { let request = NSMutableURLRequest() request.httpMethod = httpMethod.rawValue guard let completeURL = self.completeURL(urlPath) else { throw TechnicalError.invalidURL } guard var urlComponents : URLComponents = URLComponents(url: completeURL, resolvingAgainstBaseURL: false) else { throw TechnicalError.invalidURL } //checking if parameters are needed if let params = parameters { //adding parameters to body if let bodyParameters = params.bodyParameters { request.httpBody = try JSONSerialization.data(withJSONObject: bodyParameters, options: []) } //adding parameters to query string if let queryParameters = params.queryParameters { let parametersItems: [String] = queryParameters.map({ (par) -> String in let value = par.1 != "" ? par.1 : "null" return "\(par.0)=\(value)" }) urlComponents.query = parametersItems.joined(separator: "&") } } //setting url to request request.url = urlComponents.url request.cachePolicy = .reloadIgnoringCacheData //adding HEAD parameters if header != nil { for parameter in header! { request.addValue(parameter.1, forHTTPHeaderField: parameter.0) } } return request as URLRequest } fileprivate func completeURL(_ componentOrUrl: String) -> URL? { if componentOrUrl.contains("http://") || componentOrUrl.contains("https://") { return URL(string: componentOrUrl) } else { return baseURL.appendingPathComponent(componentOrUrl) } } fileprivate func dataTaskFor(httpMethod: ServiceHTTPMethod, url: String, parameters: ServiceURLSessionParameters?, header: [String:String]?, completion: @escaping ServiceURLSessionDictionaryCompletion) -> URLSessionTask? { do { let request = try self.request(url, parameters: parameters, header: header, httpMethod: httpMethod) let sessionTask: URLSessionTask = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in self.completionHandler(data: data, response:response, error: error, completion: completion) }) sessionTask.resume() return sessionTask } catch let errorRequest { DispatchQueue.main.async(execute: { completion { throw errorRequest } }) } return nil } fileprivate func dataTaskFor(httpMethod: ServiceHTTPMethod, url: String, parameters: ServiceURLSessionParameters?, header: [String:String]?, completion: @escaping ServiceURLSessionArrayCompletion) -> URLSessionTask? { do { let request = try self.request(url, parameters: parameters, header: header, httpMethod: httpMethod) let sessionTask: URLSessionTask = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in self.completionHandler(data, response:response, error: error, completion: completion) }) sessionTask.resume() return sessionTask } catch let errorRequest { DispatchQueue.main.async(execute: { completion { throw errorRequest } }) } return nil } fileprivate func completionHandler(data: Data?, response: URLResponse?, error: Error?, completion: @escaping ServiceURLSessionDictionaryCompletion) { do { //check if there is no error if error != nil { throw error! } //unwraping httpResponse guard let httpResponse = response as? HTTPURLResponse else { throw TechnicalError.parse("The NSHTTPURLResponse could not be parsed") } //check if there is an httpStatus code ~= 200...299 (Success) if 200 ... 299 ~= httpResponse.statusCode { //trying to get the data guard let responseData = data else { throw TechnicalError.parse("Problems on parsing Data from request: \(httpResponse.url)") } //trying to parse guard let json = try JSONSerialization.jsonObject(with: responseData, options: .mutableLeaves) as? NSDictionary else { throw TechnicalError.parse("Problems on parsing JSON from request: \(httpResponse.url)") } DispatchQueue.main.async(execute: { //success completion { json as? [String:AnyObject] } }) } else { //checking status of http throw TechnicalError.httpError(httpResponse.statusCode) } } catch let errorCallback { DispatchQueue.main.async(execute: { completion { throw errorCallback } }) } } fileprivate func completionHandler(_ data: Data?, response: URLResponse?, error: Error?, completion: @escaping ServiceURLSessionArrayCompletion) { do { //check if there is no error if error != nil { throw error! } //unwraping httpResponse guard let httpResponse = response as? HTTPURLResponse else { throw TechnicalError.parse("The NSHTTPURLResponse could not be parsed") } //check if there is an httpStatus code ~= 200...299 (Success) if 200 ... 299 ~= httpResponse.statusCode { //trying to get the data guard let responseData = data else { throw TechnicalError.parse("Problems on parsing Data from request: \(httpResponse.url)") } //trying to parse guard let json = try JSONSerialization.jsonObject(with: responseData, options: .mutableLeaves) as? NSArray else { throw TechnicalError.parse("Problems on parsing JSON from request: \(httpResponse.url)") } DispatchQueue.main.async(execute: { //success completion { (json as [AnyObject]) } }) } else { //checking status of http throw TechnicalError.httpError(httpResponse.statusCode) } } catch let errorCallback { DispatchQueue.main.async(execute: { completion { throw errorCallback } }) } } }
gpl-3.0
5324bbd1a65e6dedb8558d1ce52b7ce7
42.969027
226
0.602395
5.876404
false
false
false
false
meetkei/KxUI
KxUI/Application/KApp.swift
1
8549
// // Copyright (c) 2016 Keun young Kim <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) || os(tvOS) import Foundation import CoreData private let K_FIRST_LAUNCHING_AFTER_INSTALL = "K_FIRST_LAUNCHING_AFTER_INSTALL" private let K_LAST_LAUNCH_DATE = "K_LAST_LAUNCH_DATE" open class KApp: UIResponder, UIApplicationDelegate { open var window: UIWindow? open class var runningOnSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } open var isFirstLaunchAfterInstall = false // open var lastLaunchDate: NSDate { // get { // return KFKeyValueStore.date(forKey: K_LAST_LAUNCH_DATE, defaultValue: Today.now as NSDate) // } // // set { // KFKeyValueStore.save(date: newValue, forKey: K_LAST_LAUNCH_DATE) // } // } open var secondsFromLastLaunch: TimeInterval = 0 ///////////////////////////////////////////////////////////////////// // // MARK: - Life Cycle // #if swift(>=4.2) open func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } #else open func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } #endif ///////////////////////////////////////////////////////////////////// // // MARK: - Notification // open func registerForNotifications(forTypes types: UIUserNotificationType = [.alert, .badge, .sound], categories: Set<UIUserNotificationCategory>? = nil) { deviceTokenString = nil let settings = UIUserNotificationSettings(types: types, categories: categories) UIApplication.shared.registerUserNotificationSettings(settings) UIApplication.shared.registerForRemoteNotifications() } ///////////////////////////////////////////////////////////////////// // // MARK: - Remote Notification // open var deviceTokenString: String? open var pushNotificationRegistered: Bool { return deviceTokenString != nil } open func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data) { let characterSet: CharacterSet = CharacterSet( charactersIn: "<>" ) let tokenString: String = ( token.description as NSString ) .trimmingCharacters( in: characterSet ) .replacingOccurrences( of: " ", with: "" ) as String deviceTokenString = tokenString } ///////////////////////////////////////////////////////////////////// // // MARK: - Commonly Used Directories // public static var documentsDirectoryURL: URL { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls.last! } public static var libraryDirectoryURL: URL { let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask) return urls.last! } public static var applicationSupportDirectoryURL: URL { let urls = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) return urls.last! } public static var cacheDirectoryURL: URL { let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) return urls.last! } public static var temporaryDirectoryURL: URL { return URL(fileURLWithPath: NSTemporaryDirectory()) } ///////////////////////////////////////////////////////////////////// // // MARK: - Core Data stack var modelName: String! var useLightweightMigration = true var storeType = NSSQLiteStoreType open func setupCoreData(modelName name: String, storeType type: String = NSSQLiteStoreType, useLightweightMigration useMigration: Bool = true) { modelName = name useLightweightMigration = useMigration storeType = type } open lazy var managedObjectModel: NSManagedObjectModel = { assert(self.modelName != nil, "EMPTY CORE DATA MODEL NAME: use setupCoreData()") let modelURL = Bundle.main.url(forResource: self.modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() open lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { assert(self.modelName != nil, "EMPTY CORE DATA MODEL NAME: use setupCoreData()") var coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = KApp.documentsDirectoryURL.appendingPathComponent("\(self.modelName ?? "").sqlite") do { var options: [AnyHashable: Any]? = nil if self.useLightweightMigration { options = [NSMigratePersistentStoresAutomaticallyOption:NSNumber(value: true as Bool), NSInferMappingModelAutomaticallyOption:NSNumber(value: true as Bool)] } try coordinator.addPersistentStore(ofType: self.storeType, configurationName: nil, at: url, options: options) } catch { abort() } return coordinator }() open lazy var managedObjectContext: NSManagedObjectContext? = { let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() } extension UIApplication { open var appVersion: String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String } open var buildVersion: String? { return Bundle.main.infoDictionary?["CFBundleVersionString"] as? String } open func moveToAppSetting() { #if swift(>=4.2) if let url = URL(string: UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } #else if let url = URL(string: UIApplicationOpenSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } } #endif } } #endif
mit
1851bc7e8c9b10fb8182f974fcf24869
35.690987
163
0.566382
6.076048
false
false
false
false
ankitthakur/LocationManager
LocationManager/LocationCoordinator.swift
1
7218
// // LocationCoordinator.swift // LocationManager // // Created by Ankit Thakur on 29/08/16. // Copyright © 2016 Ankit Thakur. All rights reserved. // import Foundation import CoreLocation /** LocationCoordinator Class */ let triggerQueue = "com.lm.backgroundTrigger" internal typealias LocationCoorCallback = (_ location:CLLocation?, _ address:String?, _ error:LocationError?, _ eventType:EventType?)->(Void) internal class LocationCoordinator:NSObject, CLLocationManagerDelegate { static let sharedInstance = LocationCoordinator() var eventType:EventType? var manager:CLLocationManager? var currentLocation:CLLocation? var locationCallback:LocationCoorCallback? var isFinalLocation:Bool = false var lastLocationFetchTime:Date? var locationError:LocationError? fileprivate override init(){ manager = CLLocationManager() } func findLocation(_ event:EventType){ DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { [weak self] in self?.eventType = event self?.manager?.desiredAccuracy = kCLLocationAccuracyThreeKilometers logger("event : \(self?.eventType)") self?.startTracking() } } func getLocation(_ event:EventType){ self.stopTracking() DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { [weak self] in self?.eventType = event logger("event : \(self?.eventType)") self?.startTracking() } } func listeningEvent(callback:@escaping LocationCoorCallback){ DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { [weak self] in self?.locationCallback = callback } } func startTracking(){ logger("startTracking") currentLocation = nil isFinalLocation = true manager?.delegate = nil manager?.stopMonitoringVisits() manager?.stopMonitoringSignificantLocationChanges() manager?.requestAlwaysAuthorization(); manager?.requestWhenInUseAuthorization(); if #available(iOS 9.0, *) { self.manager?.allowsBackgroundLocationUpdates = true } else { // Fallback on earlier versions } manager?.desiredAccuracy = kCLLocationAccuracyBest manager?.startUpdatingLocation() manager?.delegate = self } func startSignificantAndVisitTracking(){ logger("startSignificantAndVisitTracking") manager?.requestAlwaysAuthorization(); manager?.requestWhenInUseAuthorization(); manager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters manager?.delegate = self if #available(iOS 9.0, *) { self.manager?.allowsBackgroundLocationUpdates = true } else { // Fallback on earlier versions } manager?.startMonitoringVisits() manager?.startMonitoringSignificantLocationChanges() } func stopTracking(){ logger("stopTracking") manager?.stopUpdatingLocation() startSignificantAndVisitTracking() isFinalLocation = false } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ logger("locationManager didUpdateLocations") if (eventType != nil) { if isFinalLocation == false { startTracking() } else{ if currentLocation == nil { logger("lastLocationFetchTime : \(lastLocationFetchTime)") if (lastLocationFetchTime == nil || Date().timeIntervalSince(lastLocationFetchTime!) > minimumTriggerDuration){ currentLocation = locations.last // currentLocation?.verticalAccuracy if (self.locationCallback != nil) { let coder:Geocoder = Geocoder() coder.geocode(location: self.currentLocation!, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.background), eventType: self.eventType!, callBack: self.locationCallback!) self.currentLocation = nil self.lastLocationFetchTime = Date() logger("updated lastLocationFetchTime : \(self.lastLocationFetchTime)") self.eventType = nil self.stopTracking() } } else{ let duration = (Date().timeIntervalSince(lastLocationFetchTime!))/60 logger("duration since last capture is \(duration) minutes") } } else{ self.currentLocation = nil logger("updated lastLocationFetchTime : \(self.lastLocationFetchTime)") self.eventType = nil self.stopTracking() } } } else{ if (lastLocationFetchTime == nil || Date().timeIntervalSince(lastLocationFetchTime!) > minimumTriggerDuration){ self.currentLocation = nil LocationManager.sharedInstance.getLocation(.backgroundSignificant) } else{ let duration = (Date().timeIntervalSince(lastLocationFetchTime!))/60 logger("locationManager significant event : duration since last capture is \(duration) minutes") } } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){ logger("locationManager didFailWithError error") if (self.locationCallback != nil) { DispatchQueue.main.async { [weak self] in self?.locationError = LocationError(kind: .noLocationFound, message: "no location is found") self?.locationCallback!(nil, nil, self?.locationError, self?.eventType) self?.currentLocation = nil self?.eventType = nil } } } func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit){ logger("locationManager didVisit") if (lastLocationFetchTime == nil || Date().timeIntervalSince(lastLocationFetchTime!) > minimumTriggerDuration){ self.currentLocation = nil LocationManager.sharedInstance.getLocation(.visit) } else{ let duration = (Date().timeIntervalSince(lastLocationFetchTime!))/60 logger("locationManager didVisit event : duration since last capture is \(duration) minutes") } } }
mit
e5633df9ce16fe487089a47ba9d11959
34.204878
203
0.567133
6.645488
false
false
false
false
marekhac/WczasyNadBialym-iOS
WczasyNadBialym/WczasyNadBialym/Models/Network/Event/API+Event.swift
1
1262
// // EventEndpoint.swift // WczasyNadBialym // // Created by Marek Hać on 09.05.2017. // Copyright © 2017 Marek Hać. All rights reserved. // import Foundation extension API { struct Event { // MARK: Controller Keys struct Controller { static let Events = "imprezy/" } // MARK: Methods struct Method { static let List = "lista" static let Details = "details" } // MARK: Method Keys struct ParameterKey { static let Id = "id" } // MARK: JSON Response Keys struct JSONResponseKey { // MARK: List static let Id = "id" static let Name = "wydarzenie" static let Place = "miejsce" static let Date = "termin" static let Time = "godzina" // MARK: Details static let StartDate = "termin" static let StartTime = "godzina" static let Description = "opis" static let MedSizeImgUrl = "img_med_url" static let FullSizeImgUrl = "img_full_url" } } }
gpl-3.0
e7e38b2bf1cd5a3f445284d2394ad505
22.754717
54
0.472597
4.715356
false
false
false
false
voidException/MLSwiftBasic
MLSwiftBasic/Classes/ProgressHUD/MLProgressHUD.swift
10
6679
// // MLProgressHUD.swift // MLSwiftBasic // // Created by 张磊 on 15/7/23. // Copyright (c) 2015年 MakeZL. All rights reserved. // import UIKit enum HUDStatus: Int{ case Message = 0 case Progress = 1 case Waiting = 2 } var hudView:MLProgressHUD! var hudStatus:HUDStatus? var timer:NSTimer? class MLProgressHUD: UIView { // Init Data var progress:CGFloat? { willSet { if self.msgLbl != nil && self.msgView != nil { self.msgLbl!.frame.size.width = self.msgView!.frame.size.width * newValue! } } } var message:String? var duration:CGFloat? var timerIndex:Int! /// View Contatiner var msgView:UIView? var msgLbl:UILabel? override init(frame: CGRect) { super.init(frame: frame) } convenience init(message:String){ self.init() hudView = MLProgressHUD(frame: UIScreen.mainScreen().bounds) hudView.layer.cornerRadius = 5.0; hudView.alpha = 0 hudView.backgroundColor = UIColor.clearColor() UIApplication.sharedApplication().keyWindow?.addSubview(hudView) var maskView = UIView() maskView.frame = UIScreen.mainScreen().bounds maskView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) hudView.addSubview(maskView) var width:CGFloat = 100 var msgView = UIView(frame: CGRectMake(CGFloat(UIScreen.mainScreen().bounds.width - width) * 0.5, CGFloat(UIScreen.mainScreen().bounds.height - width) * 0.5, width, width)) msgView.layer.cornerRadius = 5.0; msgView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2) msgView.clipsToBounds = true hudView.addSubview(msgView) self.msgView = msgView var msgLbl = UILabel(frame: msgView.bounds) msgLbl.font = UIFont.systemFontOfSize(14) msgLbl.textColor = UIColor.whiteColor() msgLbl.textAlignment = .Center msgLbl.text = message msgView.addSubview(msgLbl) self.msgLbl = msgLbl if hudStatus?.rawValue == HUDStatus.Waiting.rawValue { var activityView = UIActivityIndicatorView() if count(message) > 0 { activityView.frame = CGRectMake((msgView.frame.width - 12) * 0.5, (msgView.frame.height - 12) * 0.4, 12, 12) }else{ activityView.frame = CGRectMake((msgView.frame.width - 12) * 0.5, (msgView.frame.height - 12) * 0.5, 12, 12) } activityView.startAnimating() msgView.addSubview(activityView) msgLbl.frame.origin.y = CGRectGetMaxY(activityView.frame) msgLbl.frame.size.height = msgView.frame.height - CGRectGetMaxY(activityView.frame) } UIView.animateWithDuration(0.25, animations: { () -> Void in hudView.alpha = 1 }) } convenience init(message:String, duration:CGFloat){ self.init(message:message) self.timerIndex = 0 if duration > 0 { self.duration = duration self.addTimer() } } convenience init(progress:CGFloat!,message:String!){ self.init(message:message) self.msgLbl?.text = "" self.msgView?.frame.size.width = 200 self.msgLbl?.frame.size.width = self.msgView!.frame.size.width * progress! self.msgLbl?.backgroundColor = UIColor.redColor() self.msgView?.center.x = self.msgView!.frame.size.width } convenience init(progress:CGFloat!,message:String!,duration:CGFloat!){ self.init(progress:progress, message:message) self.timerIndex = 0 if duration > 0 { self.duration = duration self.addTimer() } } func addTimer(){ timer = NSTimer(timeInterval: 1.0, target: self, selector: Selector("startTimer"), userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes) } func removeTimer(){ if timer != nil { timer!.invalidate() } } func startTimer(){ self.timerIndex = self.timerIndex+1 if hudStatus != nil { if hudStatus!.rawValue == HUDStatus.Progress.rawValue{ self.msgLbl?.frame.size.width += 10 } } if CGFloat(self.timerIndex) > self.duration { hudView.dismiss() } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class func showMessage(str:String!) -> MLProgressHUD { return MLProgressHUD(message: str) } class func showMessage(str:String!,durationAfterDismiss duration:CGFloat) -> MLProgressHUD { return MLProgressHUD(message: str, duration: duration) } class func showSuccessMessage(str:String!) -> MLProgressHUD { return MLProgressHUD(message: str) } class func showSuccessMessage(str:String!,durationAfterDismiss duration:CGFloat) -> MLProgressHUD { return MLProgressHUD(message: str, duration: duration) } class func showErrorMessage(str:String!) -> MLProgressHUD { return MLProgressHUD(message: str) } class func showErrorMessage(str:String!,durationAfterDismiss duration:CGFloat) -> MLProgressHUD { return MLProgressHUD(message: str, duration: duration) } class func showProgress(progress:CGFloat!,message:String!) -> MLProgressHUD { hudStatus = HUDStatus.Progress return MLProgressHUD(progress: progress, message: message) } class func showProgress(progress:CGFloat!,message:String!,durationAfterDismiss duration:CGFloat) -> MLProgressHUD { hudStatus = HUDStatus.Progress return MLProgressHUD(progress: progress, message: message,duration: duration) } class func showWaiting(message: String!) -> MLProgressHUD { hudStatus = HUDStatus.Waiting return MLProgressHUD(message: message) } class func showWaiting(message: String!,duration:CGFloat) -> MLProgressHUD { hudStatus = HUDStatus.Waiting return MLProgressHUD(message: message,duration: duration) } func dismiss() { hudStatus = HUDStatus.Message self.removeTimer() UIView.animateWithDuration(0.25, animations: { () -> Void in hudView.alpha = 0 }) { (flag:Bool) -> Void in hudView.removeFromSuperview() } } }
mit
93adedceabe6c8cb863b37f0efd516c5
30.77619
180
0.61037
4.732624
false
false
false
false
dantheli/Neutron
Example/Pods/PromiseKit/Sources/Catchable.swift
1
7913
import Dispatch /// Provides `catch` and `recover` to your object that conforms to `Thenable` public protocol CatchMixin: Thenable {} public extension CatchMixin { /** The provided closure executes when this promise rejects. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. - Parameter on: The queue to which the provided closure dispatches. - Parameter policy: The default policy does not execute your handler for cancellation errors. - Parameter execute: The handler to execute if this promise is rejected. - Returns: A promise finalizer. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ @discardableResult func `catch`(on: DispatchQueue? = conf.Q.return, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) -> Void) -> PMKFinalizer { let finalizer = PMKFinalizer() pipe { switch $0 { case .rejected(let error): guard policy == .allErrors || !error.isCancelled else { fallthrough } on.async { body(error) finalizer.pending.resolve(()) } case .fulfilled: finalizer.pending.resolve(()) } } return finalizer } } public class PMKFinalizer { let pending = Guarantee<Void>.pending() public func finally(_ body: @escaping () -> Void) { pending.guarantee.done(body) } } public extension CatchMixin { /** The provided closure executes when this promise rejects. Unlike `catch`, `recover` continues the chain. Use `recover` in circumstances where recovering the chain from certain errors is a possibility. For example: firstly { CLLocationManager.requestLocation() }.recover { error in guard error == CLError.unknownLocation else { throw error } return .value(CLLocation.chicago) } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ func recover<U: Thenable>(on: DispatchQueue? = conf.Q.map, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> U) -> Promise<T> where U.T == T { let rp = Promise<U.T>(.pending) pipe { switch $0 { case .fulfilled(let value): rp.box.seal(.fulfilled(value)) case .rejected(let error): if policy == .allErrors || !error.isCancelled { on.async { do { let rv = try body(error) guard rv !== rp else { throw PMKError.returnedSelf } rv.pipe(to: rp.box.seal) } catch { rp.box.seal(.rejected(error)) } } } else { rp.box.seal(.rejected(error)) } } } return rp } /** The provided closure executes when this promise rejects. This variant of `recover` requires the handler to return a Guarantee, thus it returns a Guarantee itself and your closure cannot `throw`. Note it is logically impossible for this to take a `catchPolicy`, thus `allErrors` are handled. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, _ body: @escaping(Error) -> Guarantee<T>) -> Guarantee<T> { let rg = Guarantee<T>(.pending) pipe { switch $0 { case .fulfilled(let value): rg.box.seal(value) case .rejected(let error): on.async { body(error).pipe(to: rg.box.seal) } } } return rg } /** The provided closure executes when this promise resolves, whether it rejects or not. firstly { UIApplication.shared.networkActivityIndicatorVisible = true }.done { //… }.ensure { UIApplication.shared.networkActivityIndicatorVisible = false }.catch { //… } - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The closure that executes when this promise resolves. - Returns: A new promise, resolved with this promise’s resolution. */ func ensure(on: DispatchQueue? = conf.Q.return, _ body: @escaping () -> Void) -> Promise<T> { let rp = Promise<T>(.pending) pipe { result in on.async { body() rp.box.seal(result) } } return rp } /** Consumes the Swift unused-result warning. - Note: You should `catch`, but in situations where you know you don’t need a `catch`, `cauterize` makes your intentions clear. */ func cauterize() { self.catch { print("PromiseKit:cauterized-error:", $0) } } } public extension CatchMixin where T == Void { /** The provided closure executes when this promise rejects. This variant of `recover` is specialized for `Void` promises and de-errors your chain returning a `Guarantee`, thus you cannot `throw` and you must handle all errors including cancellation. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ @discardableResult func recover(on: DispatchQueue? = conf.Q.map, _ body: @escaping(Error) -> Void) -> Guarantee<Void> { let rg = Guarantee<Void>(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(()) case .rejected(let error): on.async { body(error) rg.box.seal(()) } } } return rg } /** The provided closure executes when this promise rejects. This variant of `recover` ensures that no error is thrown from the handler and allows specifying a catch policy. - Parameter on: The queue to which the provided closure dispatches. - Parameter body: The handler to execute if this promise is rejected. - SeeAlso: [Cancellation](http://promisekit.org/docs/) */ func recover(on: DispatchQueue? = conf.Q.map, policy: CatchPolicy = conf.catchPolicy, _ body: @escaping(Error) throws -> Void) -> Promise<Void> { let rg = Promise<Void>(.pending) pipe { switch $0 { case .fulfilled: rg.box.seal(.fulfilled(())) case .rejected(let error): if policy == .allErrors || !error.isCancelled { on.async { do { rg.box.seal(.fulfilled(try body(error))) } catch { rg.box.seal(.rejected(error)) } } } else { rg.box.seal(.rejected(error)) } } } return rg } }
mit
288d6d93305dece1ca3cafe1d5cf129e
34.608108
194
0.553953
4.949906
false
false
false
false
austinzheng/swift
stdlib/public/core/ContiguousArray.swift
2
51742
//===--- ContiguousArray.swift --------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `ContiguousArray<Element>` is a fast, contiguous array of `Element` with // a known backing store. // //===----------------------------------------------------------------------===// /// A contiguously stored array. /// /// The `ContiguousArray` type is a specialized array that always stores its /// elements in a contiguous region of memory. This contrasts with `Array`, /// which can store its elements in either a contiguous region of memory or an /// `NSArray` instance if its `Element` type is a class or `@objc` protocol. /// /// If your array's `Element` type is a class or `@objc` protocol and you do /// not need to bridge the array to `NSArray` or pass the array to Objective-C /// APIs, using `ContiguousArray` may be more efficient and have more /// predictable performance than `Array`. If the array's `Element` type is a /// struct or enumeration, `Array` and `ContiguousArray` should have similar /// efficiency. /// /// For more information about using arrays, see `Array` and `ArraySlice`, with /// which `ContiguousArray` shares most properties and methods. @_fixed_layout public struct ContiguousArray<Element>: _DestructorSafeContainer { @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension ContiguousArray { @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.count } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.capacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _buffer = _Buffer(copying: _buffer) } } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _buffer._checkValidSubscript(index) } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "ContiguousArray index is out of range") _precondition(index >= startIndex, "Negative ContiguousArray index is out of range") } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.subscriptBaseAddress + index } } extension ContiguousArray: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 12 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } @inlinable internal var _baseAddress: UnsafeMutablePointer<Element> { return _buffer.firstElementAddress } } extension ContiguousArray: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<ContiguousArray> /// The position of the first element in a nonempty array. /// /// For an instance of `ContiguousArray`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array, in which case /// writing is O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { _checkSubscript_native(index) return _buffer.getElement(index) } _modify { _makeMutableAndUnique() _checkSubscript_native(index) let address = _buffer.subscriptBaseAddress + index yield &address.pointee } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension ContiguousArray: ExpressibleByArrayLiteral { /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new array by using an array /// literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding only /// strings: /// /// let ingredients: ContiguousArray = /// ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self.init(_buffer: ContiguousArray(elements)._buffer) } } extension ContiguousArray: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self = ContiguousArray( _buffer: _Buffer( _buffer: s._copyToContiguousArray()._buffer, shiftedToStartIndex: 0)) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = ContiguousArray._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a ContiguousArray of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct ContiguousArray with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = ContiguousArray._allocateBufferUninitialized(minimumCapacity: count) _buffer.count = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a ContiguousArray of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (ContiguousArray, UnsafeMutablePointer<Element>) { let result = ContiguousArray(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: minimumCapacity) == nil { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: minimumCapacity) _buffer._copyContents( subRange: _buffer.indices, initializing: newBuffer.firstElementAddress) _buffer = _Buffer( _buffer: newBuffer, shiftedToStartIndex: _buffer.startIndex) } _internalInvariant(capacity >= minimumCapacity) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount + 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate( &newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.isMutableAndUniquelyReferenced()) { _copyToNewBuffer(oldCount: _buffer.count) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // This is a performance optimization. This code used to be in an || // statement in the _internalInvariant below. // // _internalInvariant(_buffer.capacity == 0 || // _buffer.isMutableAndUniquelyReferenced()) // // SR-6437 let capacity = _buffer.capacity == 0 // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that preceeds this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. _internalInvariant(capacity || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount + 1 > _buffer.capacity) { _copyToNewBuffer(oldCount: oldCount) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _internalInvariant(_buffer.isMutableAndUniquelyReferenced()) _internalInvariant(_buffer.capacity >= _buffer.count + 1) _buffer.count = oldCount + 1 (_buffer.firstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _getCount() _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { let newElementsCount = newElements.underestimatedCount reserveCapacityForAppend(newElementsCount: newElementsCount) let oldCount = self.count let startNewElements = _buffer.firstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: self.capacity - oldCount) let (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate _buffer.count += writtenCount if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode _buffer._arrayAppendSequence(IteratorSequence(remainder)) } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { let oldCount = self.count let oldCapacity = self.capacity let newCount = oldCount + newElementsCount // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. self.reserveCapacity( newCount > oldCapacity ? Swift.max(newCount, _growArrayCapacity(oldCapacity)) : newCount) } @inlinable public mutating func _customRemoveLast() -> Element? { let newCount = _getCount() - 1 _precondition(newCount >= 0, "Can't removeLast from an empty ContiguousArray") _makeUniqueAndReserveCapacityIfNotUnique() let pointer = (_buffer.firstElementAddress + newCount) let element = pointer.move() _buffer.count = newCount return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult public mutating func remove(at index: Int) -> Element { _precondition(index < endIndex, "Index out of range") _precondition(index >= startIndex, "Index out of range") _makeUniqueAndReserveCapacityIfNotUnique() let newCount = _getCount() - 1 let pointer = (_buffer.firstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.count = newCount return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer { (bufferPointer) -> R in return try body(bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(_buffer) } } extension ContiguousArray: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } extension ContiguousArray: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return _makeCollectionDescription(withTypeName: "ContiguousArray") } } extension ContiguousArray { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension ContiguousArray { /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inlinable // FIXME(inline-always) @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { let count = self.count // Ensure unique storage _buffer._outlinedMakeUniqueBuffer(bufferCount: count) // Ensure that body can't invalidate the storage or its bounds by // moving self into a temporary working array. // NOTE: The stack promotion optimization that keys of the // "array.withUnsafeMutableBufferPointer" semantics annotation relies on the // array buffer not being able to escape in the closure. It can do this // because we swap the array buffer in self with an empty buffer here. Any // escape via the address of self in the closure will therefore escape the // empty array. var work = ContiguousArray() (work, self) = (self, work) // Create an UnsafeBufferPointer over work that we can pass to body let pointer = work._buffer.firstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) // Put the working array back before returning. defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "ContiguousArray withUnsafeMutableBufferPointer: replacing the buffer is not allowed") (work, self) = (self, work) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension ContiguousArray { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "ContiguousArray replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "ContiguousArray replace: subrange extends past the end") let oldCount = _buffer.count let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount if _buffer.requestUniqueMutableBackingBuffer( minimumCapacity: oldCount + growth) != nil { _buffer.replaceSubrange( subrange, with: insertCount, elementsOf: newElements) } else { _buffer._arrayOutOfPlaceReplace(subrange, with: newElements, count: insertCount) } } } extension ContiguousArray: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0) _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension ContiguousArray: Hashable where Element: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension ContiguousArray { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, ...] /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } }
apache-2.0
05d99b895a8467ffb2a1c4ce7e6f9ed7
37.724551
99
0.659425
4.445437
false
false
false
false
mozilla-mobile/firefox-ios
Client/Experiments/Messaging/GleanPlumbMessageManager.swift
2
12655
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import MozillaAppServices import Shared protocol GleanPlumbMessageManagerProtocol { /// Performs the bookkeeping and preparation of messages for their respective surfaces. /// We can build our collection of eligible messages for a surface in here. func onStartup() /// Finds the next message to be displayed out of all showable messages. /// Surface calls. func getNextMessage(for surface: MessageSurfaceId) -> GleanPlumbMessage? /// Report impressions in Glean, and then pass the bookkeeping to increment the impression count and expire to `MessageStore`. /// Surface calls. func onMessageDisplayed(_ message: GleanPlumbMessage) /// Using the helper, this should get the message action string ready for use. /// Surface calls. func onMessagePressed(_ message: GleanPlumbMessage) /// Handles what to do with a message when a user has dismissed it. /// Surface calls. func onMessageDismissed(_ message: GleanPlumbMessage) /// If the message is malformed (missing key elements the surface expects), then /// report the malformed message. /// Manager calls. func onMalformedMessage(messageKey: String) } /// To the surface that requests messages, it provides valid and triggered messages in priority order. /// /// Note: The term "valid" in `GleanPlumbMessage` context means a well-formed, non-expired, priority ordered message. /// /// The `GleanPlumbMessageManager` is responsible for several things including: /// - preparing Messages for a given UI surface /// - reporting telemetry for `GleanPlumbMessage`s: /// - impression counts /// - user dismissal of a message /// - expiration logic /// - exposure /// - malformed message /// - expiration (handled in the store) class GleanPlumbMessageManager: GleanPlumbMessageManagerProtocol { // MARK: - Properties static let shared = GleanPlumbMessageManager() private let messagingUtility: GleanPlumbMessageUtility private let messagingStore: GleanPlumbMessageStoreProtocol private let feature = FxNimbus.shared.features.messaging.value() // MARK: - Inits init(messagingUtility: GleanPlumbMessageUtility = GleanPlumbMessageUtility(), messagingStore: GleanPlumbMessageStoreProtocol = GleanPlumbMessageStore()) { self.messagingUtility = messagingUtility self.messagingStore = messagingStore onStartup() } // MARK: - GleanPlumbMessageManagerProtocol Conformance /// Perform any startup setup if necessary. func onStartup() { } func hasMessage(for surface: MessageSurfaceId) -> Bool { return getNextMessage(for: surface) != nil } /// Returns the next valid and triggered message for the surface, if one exists. func getNextMessage(for surface: MessageSurfaceId) -> GleanPlumbMessage? { /// All these are non-expired, well formed, and descending priority ordered messages for a requested surface. let messages = getAllValidMessagesFor(surface, with: feature) /// If `GleanPlumbHelper` creation fails, we cannot continue with this feature! For that reason, return `nil`. /// We need to recreate the helper for each request to get a message because device context can change. guard let gleanPlumbHelper = messagingUtility.createGleanPlumbHelper() else { return nil } /// Take the first triggered message. guard let message = getNextTriggeredMessage(messages, gleanPlumbHelper) else { return nil } /// If it's a message under experiment, we need to react to whether it's a control or not. if message.isUnderExperimentWith(key: feature.messageUnderExperiment) { guard let nextTriggeredMessage = handleMessageUnderExperiment(message, messages, gleanPlumbHelper, feature.onControl) else { return nil } return nextTriggeredMessage } return message } /// Handle impression reporting and bookkeeping. func onMessageDisplayed(_ message: GleanPlumbMessage) { messagingStore.onMessageDisplayed(message) TelemetryWrapper.recordEvent(category: .information, method: .view, object: .homeTabBanner, value: .messageImpression, extras: [TelemetryWrapper.EventExtraKey.messageKey.rawValue: message.id]) } /// Handle when a user hits the CTA of the surface, and forward the bookkeeping to the store. func onMessagePressed(_ message: GleanPlumbMessage) { messagingStore.onMessagePressed(message) guard let messageUtility = messagingUtility.createGleanPlumbHelper() else { return } /// Make substitutions where they're needed. let template = message.action let uuid = messageUtility.getUuid(template: template) let action = messageUtility.stringFormat(template: template, uuid: uuid) /// Create the message action URL. let urlString = action.hasPrefix("://") ? URL.mozInternalScheme + action : action guard let url = URL(string: urlString) else { self.onMalformedMessage(messageKey: message.id) return } /// With our well-formed URL, we can handle the action here. if url.isWebPage() { let bvc = BrowserViewController.foregroundBVC() bvc.openURLInNewTab(url) } else { UIApplication.shared.open(url, options: [:]) } TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .homeTabBanner, value: .messageInteracted, extras: [TelemetryWrapper.EventExtraKey.messageKey.rawValue: message.id, TelemetryWrapper.EventExtraKey.actionUUID.rawValue: uuid ?? "nil"]) } /// For now, we will assume all dismissed messages should become expired right away. The /// store handles this bookkeeping. func onMessageDismissed(_ message: GleanPlumbMessage) { messagingStore.onMessageDismissed(message) TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .homeTabBanner, value: .messageDismissed, extras: [TelemetryWrapper.EventExtraKey.messageKey.rawValue: message.id]) } func onMalformedMessage(messageKey: String) { TelemetryWrapper.recordEvent(category: .information, method: .application, object: .homeTabBanner, value: .messageMalformed, extras: [TelemetryWrapper.EventExtraKey.messageKey.rawValue: messageKey]) } // MARK: - Misc. Private helpers /// - Returns: All well-formed, non-expired messages for a surface in descending priority order for a specified surface. private func getAllValidMessagesFor(_ surface: MessageSurfaceId, with feature: Messaging) -> [GleanPlumbMessage] { /// All these are non-expired, well formed, and descending priority messages for a requested surface. let messages = feature.messages.compactMap { key, messageData -> GleanPlumbMessage? in guard let message = self.createMessage(messageId: key, message: messageData, lookupTables: feature) else { onMalformedMessage(messageKey: key) return nil } return message }.filter { message in !message.isExpired }.filter { message in message.data.surface == surface }.sorted { message1, message2 in message1.style.priority > message2.style.priority } return messages } /// We assemble one message at a time. If there's any issue with it, return `nil`. /// Reporting a malformed message is done at the call site when reacting to a `nil`. private func createMessage(messageId: String, message: MessageData, lookupTables: Messaging) -> GleanPlumbMessage? { /// Guard against a message with a blank `text` property. guard !message.text.isEmpty else { return nil } /// Ascertain a Message's style, to know priority and max impressions. guard let style = lookupTables.styles[message.style] else { return nil } /// The message action should be either from the lookup table OR a URL. let action = lookupTables.actions[message.action] ?? message.action guard action.contains("://") else { return nil } let triggers = message.trigger.compactMap { trigger in lookupTables.triggers[trigger] } /// Be sure the count on `triggers` and `message.triggers` are equal. /// If these mismatch, that means a message contains a trigger not in the triggers lookup table. /// JEXLS can only be evaluated on supported triggers. Otherwise, consider the message malformed. if triggers.count != message.trigger.count { return nil } let messageMetadata = messagingStore.getMessageMetadata(messageId: messageId) if messageMetadata.impressions >= style.maxDisplayCount || messageMetadata.isExpired { _ = messagingStore.onMessageExpired(messageMetadata, shouldReport: true) return nil } return GleanPlumbMessage(id: messageId, data: message, action: action, triggers: triggers, style: style, metadata: messageMetadata) } /// From the list of messages that are well-formed and non-expired, we return the next / first triggered message. /// /// - Returns: The next triggered message, if one exists. private func getNextTriggeredMessage(_ messages: [GleanPlumbMessage], _ helper: GleanPlumbMessageHelper) -> GleanPlumbMessage? { messages.first( where: { message in do { return try messagingUtility.isMessageEligible(message, messageHelper: helper) } catch { return false } }) } /// If a message is under experiment, we need to handle it a certain way. /// /// First, messages under experiment should always report exposure. /// /// Second, for messages under experiment, there's a chance we may encounter a "control message." If a message /// under experiment IS a control message, we're told how the surface should handle it. /// /// How we handle a control message is provided by `nimbus.fml.yaml`. /// /// The only two options are: /// - showNextMessage /// - showNone /// /// - Returns: The next triggered message, if one exists. private func handleMessageUnderExperiment(_ message: GleanPlumbMessage, _ messages: [GleanPlumbMessage], _ helper: GleanPlumbMessageHelper, _ onControl: ControlMessageBehavior) -> GleanPlumbMessage? { FxNimbus.shared.features.messaging.recordExposure() let onControlActions = onControl if !message.data.isControl { return message } switch onControlActions { case .showNone: return nil case .showNextMessage: return messages.first { message in do { return try messagingUtility.isMessageEligible(message, messageHelper: helper) && !message.data.isControl } catch { onMalformedMessage(messageKey: message.id) return false } } } } }
mpl-2.0
fa0e69c351052a8433d9052e75ae7030
42.940972
132
0.615804
5.584731
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/EndToEnd/Code/TestCredentials.swift
2
2431
// // TestCredentials.swift // edX // // Created by Akiva Leffert on 3/14/16. // Copyright © 2016 edX. All rights reserved. // import Foundation import edXCore private struct Credentials { let username : String let password: String let email: String } private class TestCredentialManager { private static let shared = TestCredentialManager() private let config = OEXConfig(bundle: NSBundle(forClass: TestCredentialManager.self)) private func freshCredentials() -> Credentials { let password = NSUUID().UUIDString let email = config.endToEndConfig.emailTemplate.oex_formatWithParameters(["unique_id": NSUUID().asUsername]) let username = email.componentsSeparatedByString("@").first! return Credentials(username : username, password: password, email: email) } private lazy var defaultCredentials: Credentials = { let credentials = self.freshCredentials() self.registerUser(credentials) return credentials }() func registerUser(credentials: Credentials) { let networkManager = NetworkManager(authorizationHeaderProvider: nil, credentialProvider: nil, baseURL: config.apiHostURL()!, cache: MockResponseCache()) let body = [ "email": credentials.email, "username": credentials.username, "password": credentials.password, "name": "Test Person", "honor_code": "true", "terms_of_service": "true" ] let registrationRequest = RegistrationAPI.registrationRequest(fields: body) let result = networkManager.streamForRequest(registrationRequest).waitForValue() assert(result.value != nil, "failed to register user") } } class TestCredentials { private let credentials : Credentials enum Type { case Fresh // Credentials without an existing account case Default // Standard test credentials. Have an account and registered for at least one course } init(type: Type = .Default) { switch type { case .Fresh: credentials = TestCredentialManager.shared.freshCredentials() case .Default: credentials = TestCredentialManager.shared.defaultCredentials } } var username: String { return credentials.username } var password: String { return credentials.password } var email: String { return credentials.email } }
apache-2.0
300fc7da55724482000b8e4bcc5db1da
32.287671
161
0.676543
5.031056
false
true
false
false
taotao361/swift
FirstSwiftDemo/src/view/YTPhotoBrowserCell.swift
1
3836
// // YTPhotoBrowserCell.swift // FirstSwiftDemo // // Created by yangxutao on 2017/5/23. // Copyright © 2017年 yangxutao. All rights reserved. // import UIKit protocol PhotoBrowserCellDelegate : NSObjectProtocol { func photoBrowserCellDIdClose(_ cell : YTPhotoBrowserCell) } class YTPhotoBrowserCell: UICollectionViewCell { weak var photoBrowserCellDelegate : PhotoBrowserCellDelegate? var imageUrl : URL? { didSet { reset() activityIndicatorView.startAnimating() imageView.kf.setImage(with: imageUrl, placeholder: nil, options: nil, progressBlock: nil) { (image, error, cacheType, url) in self.activityIndicatorView.stopAnimating() self.setImageViewPosition() } } } fileprivate func reset() { scrollView.contentInset = UIEdgeInsets.zero scrollView.contentOffset = CGPoint.zero scrollView.contentSize = CGSize.zero imageView.transform = CGAffineTransform.identity } fileprivate func displaySize(image : UIImage) -> CGSize { let scale = image.size.height / image.size.width let width = UIScreen.main.bounds.width let height = width * scale return CGSize.init(width: width, height: height) } fileprivate func setImageViewPosition () { let size = displaySize(image: imageView.image!) if size.height < UIScreen.main.bounds.height { imageView.frame = CGRect.init(origin: CGPoint.zero, size: size) let y = (UIScreen.main.bounds.height - size.height) * 0.5 self.scrollView.contentInset = UIEdgeInsets.init(top: y, left: 0, bottom: y, right: 0) } else { imageView.frame = CGRect.init(origin: CGPoint.zero, size: size) scrollView.contentSize = size } } override init(frame: CGRect) { super.init(frame: frame) loadUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func loadUI() { contentView.addSubview(scrollView) scrollView.addSubview(imageView) contentView.addSubview(activityIndicatorView) scrollView.frame = UIScreen.main.bounds activityIndicatorView.center = contentView.center scrollView.delegate = self scrollView.maximumZoomScale = 2.0 scrollView.minimumZoomScale = 0.5 let tap = UITapGestureRecognizer.init(target: self, action: #selector(close)) imageView.addGestureRecognizer(tap) imageView.isUserInteractionEnabled = true } func close() { // if self.photoBrowserCellDelegate?.responds(to: photoBrowserCellDelegate?.photoBrowserCellDIdClose(self)) photoBrowserCellDelegate?.photoBrowserCellDIdClose(self) } // fileprivate lazy var scrollView : UIScrollView = UIScrollView.init() lazy var imageView = UIImageView.init() fileprivate lazy var activityIndicatorView : UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) } extension YTPhotoBrowserCell : UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { var offsetX = (UIScreen.main.bounds.width - view!.frame.width) * 0.5 var offsetY = (UIScreen.main.bounds.height - view!.frame.height) * 0.5 offsetX = offsetX < 0 ? 0 : offsetX offsetY = offsetY < 0 ? 0 : offsetY scrollView.contentInset = UIEdgeInsets.init(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX) } }
mit
6ffa47ccf8a99dbbadefce4eba93d470
32.920354
168
0.662927
5.003916
false
false
false
false
sravankumar143/HONDropDownTableView
HONDropDownTableView/Classes/HONButtonView.swift
1
6160
// // HONButtonView.swift // Pods // // Created by Sravan Kumar on 02/08/17. // // import UIKit @objc public protocol HONButtonViewDelegate { @objc optional func buttonViewTapped(forView: HONButtonView) @objc optional func dropDownView(_ dropDown: HONDropDownTableViewController, didSelectedItem item: String, atIndex index: Int) } public class HONButtonView: UIView { let bundle = Bundle(for: HONButtonView.self) ///types of the drop down menu enum DropDownType: Int { case defaultType = 1 case inactiveType } struct DropDownColors { let defaultLayerColor = UIColor(red: 208/255, green: 208/255, blue: 208/255, alpha: 1) let inactiveLayerColor = UIColor(red: 80/255, green: 80/255, blue: 80/255, alpha: 1) let heighlightedLayerColor = UIColor(red: 48/255, green: 181/255, blue: 244/255, alpha: 1) } public var dropDownTable: HONDropDownTableViewController! /// when user sets the menu type it will changes the color of the boaders, text and images. public var menuType = DropDownType.defaultType.rawValue { willSet { if newValue == 2 { self.isUserInteractionEnabled = false self.layer.borderColor = DropDownColors().inactiveLayerColor.cgColor self.titleButton.setTitleColor(DropDownColors().inactiveLayerColor, for: .normal) self.arrowImage.image = UIImage.init(assetIdentifer: "Chevron_Down_Inactive") }else { self.layer.borderColor = DropDownColors().defaultLayerColor.cgColor self.titleButton.setTitleColor(DropDownColors().defaultLayerColor, for: .normal) } } } ///set the list of data to show on the tableview as menu. public var dataSourceArray = [String]() { willSet{ dropDownTable.dataSourceArray = newValue } } /// Selected item can store when user selected on drop down view public var selectedItem: String? = "" { willSet { dropDownTable.selectedItem = newValue self.titleButton.setTitle(newValue, for: .normal) } } /// default text should be displayed on button @IBInspectable public var defaultText: String? = "Recently Computed" { willSet { self.titleButton.setTitle(newValue, for: .normal) } } ///Default image for arrow image. public var defaultArrowImage: UIImage? = UIImage.init(assetIdentifer: "Chevron_Down") { willSet { self.arrowImage.image = newValue } } public var selectArrowImage: UIImage? = UIImage.init(assetIdentifer: "Chevron_Up") public var direction = DropDownDirection.bottom.rawValue { willSet{dropDownTable.direction = newValue} } //MARK:- private properties. @IBOutlet fileprivate weak var titleButton: UIButton! @IBOutlet fileprivate weak var arrowImage: UIImageView! @IBInspectable public var titleButtonTextColor: UIColor = UIColor(red: 48/255, green: 181/255, blue: 244/255, alpha: 1) { willSet{self.titleButton.setTitleColor(newValue, for: .normal)} } @IBOutlet public var delegate: AnyObject? override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } /// intital method to setup the custom components default values. private func setup() { let viewFromNib = viewFromNibForClass() viewFromNib.frame = bounds self.addSubview(viewFromNib) self.layer.borderColor = DropDownColors().defaultLayerColor.cgColor self.layer.borderWidth = 1.5 self.layer.masksToBounds = true titleButton.backgroundColor = UIColor.black let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.openDropDownTableTap)) tapGesture.numberOfTapsRequired = 1 self.addGestureRecognizer(tapGesture) //Create instance of the dropdown table menu dropDownTable = HONDropDownTableViewController(withFrame: CGRect.zero, parentView: self, cellStyle: HONDropDownTableViewController.CustomCellType(rawValue: 1)!) dropDownTable?.dropDownDelegate = self dropDownTable?.dataSourceArray = dataSourceArray dropDownTable?.selectedItem = selectedItem dropDownTable?.direction = direction } /// this method can be used to show the dropdown table when user taps on the view. @objc private func openDropDownTableTap() { dropDownTable?.show() arrowImage.image = selectArrowImage } /// this method can be used to load the xib into the class. /// /// - Returns: custom uiview of the HONButtonView class. private func viewFromNibForClass() -> UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "HONButtonView", bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).last as? UIView return view! } } //MARK:- HONDropDownTableViewControllerProtocol Methods extension HONButtonView: HONDropDownTableViewControllerProtocol { public func didSelectTableViewTapped(index: Int, selectedMenu: String, dropDown: HONDropDownTableViewController) { titleButton.setTitle(selectedMenu, for: .normal) titleButton.setTitleColor(DropDownColors().heighlightedLayerColor, for: .normal) arrowImage.image = defaultArrowImage if let dropDownDelegate = self.delegate?.dropDownView!(dropDown, didSelectedItem: selectedMenu, atIndex: index) { dropDownDelegate } } public func didDismissTableViewController(dropDown: HONDropDownTableViewController) { arrowImage.image = defaultArrowImage } } extension UIImage { convenience init(assetIdentifer: String) { self.init(named : assetIdentifer, in : Bundle(for: HONButtonView.self), compatibleWith : nil)! } }
mit
0c9dc4d963afe1188a033a0c75416f9c
34
168
0.663799
5.020375
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Geometry/Rot3.swift
1
7421
import _Differentiation import TensorFlow /// SO(3) group of 3D Rotations public struct Rot3: LieGroup, Equatable, KeyPathIterable { public typealias TangentVector = Vector3 // MARK: - Manifold conformance public var coordinateStorage: Matrix3Coordinate public init(coordinateStorage: Matrix3Coordinate) { self.coordinateStorage = coordinateStorage } public mutating func move(along direction: Coordinate.LocalCoordinate) { coordinateStorage = coordinateStorage.retract(direction) } /// Construct from a rotation matrix, as doubles in *row-major* order @differentiable public init(_ r11 : Double, _ r12 : Double, _ r13 : Double, _ r21 : Double, _ r22 : Double, _ r23 : Double, _ r31 : Double, _ r32 : Double, _ r33 : Double) { self.init(coordinate: Matrix3Coordinate(r11, r12, r13, r21, r22, r23, r31, r32, r33)) } /// Create Manifold object from element of the tangent (Expmap) @differentiable public static func fromTangent(_ vector: Vector3) -> Self { return Rot3(coordinate: Rot3().coordinate.retract(vector)) } /// Create Manifold object from a quaternion representation /// Using the Eigen convention @differentiable public static func fromQuaternion(_ w: Double, _ x: Double, _ y: Double, _ z: Double) -> Self { let tx = 2.0 * x let ty = 2.0 * y let tz = 2.0 * z let twx = tx * w let twy = ty * w let twz = tz * w let txx = tx * x let txy = ty * x let txz = tz * x let tyy = ty * y let tyz = tz * y let tzz = tz * z return Rot3( 1.0-(tyy+tzz), txy-twz, txz+twy, txy+twz, 1.0-(txx+tzz), tyz-twx, txz-twy, tyz+twx, 1.0-(txx+tyy) ) } } /// Group actions. extension Rot3 { /// Returns the result of acting `self` on `v`. @differentiable public func rotate(_ v: Vector3) -> Vector3 { coordinate.rotate(v) } /// Returns the result of acting the inverse of `self` on `v`. @differentiable public func unrotate(_ v: Vector3) -> Vector3 { coordinate.unrotate(v) } /// Returns the result of acting `aRb` on `bp`. @differentiable public static func * (aRb: Rot3, bp: Vector3) -> Vector3 { aRb.rotate(bp) } } /// determinant for a 3x3 matrix fileprivate func det3(_ M: Tensor<Double>) -> Double { precondition(M.shape[0] == 3) precondition(M.shape[1] == 3) return (M[0, 0].scalar! * (M[1, 1].scalar! * M[2, 2].scalar! - M[2, 1].scalar! * M[1, 2].scalar!) - M[1, 0].scalar! * (M[0, 1].scalar! * M[2, 2].scalar! - M[2, 1].scalar! * M[0, 2].scalar!) + M[2, 0].scalar! * (M[0, 1].scalar! * M[1, 2].scalar! - M[1, 1].scalar! * M[0, 2].scalar!)) } public extension Rot3 { /// Regularize a 3x3 matrix to find the closest rotation matrix in a Frobenius sense static func ClosestTo(mat: Matrix3) -> Rot3 { let M = Tensor<Double>(shape: [3, 3], scalars: [mat[0, 0], mat[0, 1], mat[0, 2], mat[1, 0], mat[1, 1], mat[1, 2], mat[2, 0], mat[2, 1], mat[2, 2]]) let (_, U, V) = M.transposed().svd(computeUV: true, fullMatrices: true) let UVT = matmul(U!, V!.transposed()) let det = det3(UVT) let S = Tensor<Double>(shape: [3], scalars: [1, 1, det]).diagonal() let R = matmul(V!, matmul(S, U!.transposed())) let M_r = Matrix3(R.scalars) return Rot3(coordinate: Matrix3Coordinate(M_r)) } } public struct Matrix3Coordinate: Equatable, KeyPathIterable { public var R: Matrix3 public typealias LocalCoordinate = Vector3 } public extension Matrix3Coordinate { /// Construct from a rotation matrix, as doubles in *row-major* order @differentiable init(_ r11 : Double, _ r12 : Double, _ r13 : Double, _ r21 : Double, _ r22 : Double, _ r23 : Double, _ r31 : Double, _ r32 : Double, _ r33 : Double) { R = Matrix3( r11, r12, r13, r21, r22, r23, r31, r32, r33 ) } } extension Matrix3Coordinate: LieGroupCoordinate { /// Creates the group identity. public init() { self.init( 1, 0, 0, 0, 1, 0, 0, 0, 1 ) } /// Product of two rotations. @differentiable(wrt: (lhs, rhs)) public static func * (lhs: Matrix3Coordinate, rhs: Matrix3Coordinate) -> Matrix3Coordinate { Matrix3Coordinate(matmul(lhs.R, rhs.R)) } /// Inverse of the rotation. @differentiable public func inverse() -> Matrix3Coordinate { Matrix3Coordinate(R.transposed()) } @differentiable(wrt: v) public func Adjoint(_ v: Vector3) -> Vector3 { rotate(v) } @differentiable(wrt: v) public func AdjointTranspose(_ v: Vector3) -> Vector3 { unrotate(v) } } /// Actions. extension Matrix3Coordinate { /// Returns the result of acting `self` on `v`. @differentiable func rotate(_ v: Vector3) -> Vector3 { matvec(R, v) } /// Returns the result of acting the inverse of `self` on `v`. @differentiable func unrotate(_ v: Vector3) -> Vector3 { matvec(R.transposed(), v) } } @differentiable func sqrtWrap(_ v: Double) -> Double { sqrt(v) } @derivative(of: sqrtWrap) func _vjpSqrt(_ v: Double) -> (value: Double, pullback: (Double) -> Double) { let r = sqrt(v) return (r, { 1/(2*r) * $0 }) } extension Matrix3Coordinate: ManifoldCoordinate { /// Compose with the exponential map @differentiable(wrt: local) public func retract(_ local: Vector3) -> Matrix3Coordinate { let theta2 = local.squaredNorm let nearZero = theta2 <= .ulpOfOne let (wx, wy, wz) = (local.x, local.y, local.z) let W = Matrix3(0.0, -wz, wy, wz, 0.0, -wx, -wy, wx, 0.0) let I_3x3 = Matrix3.identity if !nearZero { let theta = sqrtWrap(theta2) let sin_theta = sin(theta) let s2 = sin(theta / 2) let one_minus_cos = 2.0 * s2 * s2 let K = W / theta let KK = matmul(K, K) return self * Matrix3Coordinate( I_3x3 + sin_theta * K + one_minus_cos * KK ) } else { return self * Matrix3Coordinate(I_3x3 + W) } } @differentiable(wrt: global) public func localCoordinate(_ global: Matrix3Coordinate) -> Vector3 { let relative = self.inverse() * global let R = Vector9(relative.R) let (R11, R12, R13) = (R.s0, R.s1, R.s2) let (R21, R22, R23) = (R.s3, R.s4, R.s5) let (R31, R32, R33) = (R.s6, R.s7, R.s8) let tr = R11 + R22 + R33 if tr + 1.0 < 1e-10 { if abs(R33 + 1.0) > 1e-5 { return (.pi / sqrtWrap(2.0 + 2.0 * R33)) * Vector3(R13, R23, 1.0 + R33) } else if abs(R22 + 1.0) > 1e-5 { return (.pi / sqrtWrap(2.0 + 2.0 * R22)) * Vector3(R12, 1.0 + R22, R32) } else { // if(abs(R.r1_.x()+1.0) > 1e-10) This is implicit return (.pi / sqrtWrap(2.0 + 2.0 * R11)) * Vector3(1.0 + R11, R21, R31) } } else { let tr_3 = tr - 3.0; // always negative if tr_3 < -1e-7 { let theta = acos((tr - 1.0) / 2.0) let magnitude = theta / (2.0 * sin(theta)) return magnitude * Vector3(R32 - R23, R13 - R31, R21 - R12) } else { // when theta near 0, +-2pi, +-4pi, etc. (trace near 3.0) // use Taylor expansion: theta \approx 1/2-(t-3)/12 + O((t-3)^2) let magnitude = (0.5 - tr_3 * tr_3 / 12.0) return magnitude * Vector3(R32 - R23, R13 - R31, R21 - R12) } } } /// Construct from Tensor @differentiable init(_ matrix: Matrix3) { R = matrix } }
apache-2.0
2d2a4502adce989c56e53c6a7e22b740
28.101961
151
0.591025
3.050144
false
false
false
false
TomasLinhart/SwiftGtk
Sources/Window.swift
1
2012
// // Copyright © 2015 Tomas Linhart. All rights reserved. // import CGtk public class Window: Bin { public enum WindowType { case topLevel case popUp fileprivate func toGtkWindowType() -> GtkWindowType { switch self { case .topLevel: return GTK_WINDOW_TOPLEVEL case .popUp: return GTK_WINDOW_POPUP } } } public init(windowType: WindowType = .topLevel) { super.init() widgetPointer = gtk_window_new(windowType.toGtkWindowType()) } public var title: String? { get { return String(cString: gtk_window_get_title(castedPointer())) } set { if let title = newValue { gtk_window_set_title(castedPointer(), title) } else { gtk_window_set_title(castedPointer(), nil) } } } public var defaultSize: Size { get { var width: Int32 = 0 var height: Int32 = 0 gtk_window_get_default_size(castedPointer(), &width, &height) return Size(width: Int(width), height: Int(height)) } set (size) { gtk_window_set_default_size(castedPointer(), Int32(size.width), Int32(size.height)) } } public var resizable: Bool { get { return gtk_window_get_resizable(castedPointer()).toBool() } set { gtk_window_set_resizable(castedPointer(), newValue.toGBoolean()) } } public var hideTitlebarWhenMaximized: Bool { get { return gtk_window_get_hide_titlebar_when_maximized(castedPointer()).toBool() } set { gtk_window_set_hide_titlebar_when_maximized(castedPointer(), newValue.toGBoolean()) } } private var _titleBar: Widget? public var titlebar: Widget? { get { return _titleBar } set { gtk_window_set_titlebar(castedPointer(), newValue?.widgetPointer) } } }
mit
0e44e08f6f5a86e381ec5772e95523d1
26.930556
99
0.55992
4.362256
false
false
false
false
svachmic/ios-url-remote
URLRemoteTests/View/ColorSelectorTests.swift
1
1379
// // ColorSelectorTests.swift // URLRemote // // Created by Michal Švácha on 28/05/2017. // Copyright © 2017 Svacha, Michal. All rights reserved. // import XCTest import Material import Bond @testable import URLRemote class ColorSelectorTests: XCTestCase { var view: ColorSelectorView? override func setUp() { super.setUp() view = ColorSelectorView(frame: CGRect(x: 0, y: 0, width: 100, height: 20)) view?.setupViews(with: [.red, .yellow, .green]) } override func tearDown() { super.tearDown() } func testViewConsistency() { let colors = view!.subviews.filter { $0 is FlatButton } let overlappingCount = colors.map { color in return colors .filter { $0 != color } .filter { $0.frame.intersects(color.frame) }.count }.reduce(0, +) XCTAssertEqual(overlappingCount, 0) } func testPublishingSubject() { let observable = Observable<ColorName?>(nil) XCTAssertNil(observable.value) view?.signal.bind(to: observable) let colors = view!.subviews.filter { $0 is FlatButton } XCTAssertTrue(colors.count > 0) let colorButton = colors[0] as! FlatButton colorButton.sendActions(for: .touchUpInside) XCTAssertNotNil(observable.value) } }
apache-2.0
43086ba9051ec8d500eafc464f6512d5
27.081633
83
0.611192
4.382166
false
true
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/FraudDetector/FraudDetector_Shapes.swift
1
126278
//===----------------------------------------------------------------------===// // // 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 Foundation import SotoCore extension FraudDetector { // MARK: Enums public enum DataSource: String, CustomStringConvertible, Codable { case event = "EVENT" case externalModelScore = "EXTERNAL_MODEL_SCORE" case modelScore = "MODEL_SCORE" public var description: String { return self.rawValue } } public enum DataType: String, CustomStringConvertible, Codable { case boolean = "BOOLEAN" case float = "FLOAT" case integer = "INTEGER" case string = "STRING" public var description: String { return self.rawValue } } public enum DetectorVersionStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case draft = "DRAFT" case inactive = "INACTIVE" public var description: String { return self.rawValue } } public enum Language: String, CustomStringConvertible, Codable { case detectorpl = "DETECTORPL" public var description: String { return self.rawValue } } public enum ModelEndpointStatus: String, CustomStringConvertible, Codable { case associated = "ASSOCIATED" case dissociated = "DISSOCIATED" public var description: String { return self.rawValue } } public enum ModelInputDataFormat: String, CustomStringConvertible, Codable { case applicationJson = "APPLICATION_JSON" case textCsv = "TEXT_CSV" public var description: String { return self.rawValue } } public enum ModelOutputDataFormat: String, CustomStringConvertible, Codable { case applicationJsonlines = "APPLICATION_JSONLINES" case textCsv = "TEXT_CSV" public var description: String { return self.rawValue } } public enum ModelSource: String, CustomStringConvertible, Codable { case sagemaker = "SAGEMAKER" public var description: String { return self.rawValue } } public enum ModelTypeEnum: String, CustomStringConvertible, Codable { case onlineFraudInsights = "ONLINE_FRAUD_INSIGHTS" public var description: String { return self.rawValue } } public enum ModelVersionStatus: String, CustomStringConvertible, Codable { case active = "ACTIVE" case inactive = "INACTIVE" public var description: String { return self.rawValue } } public enum RuleExecutionMode: String, CustomStringConvertible, Codable { case allMatched = "ALL_MATCHED" case firstMatched = "FIRST_MATCHED" public var description: String { return self.rawValue } } public enum TrainingDataSourceEnum: String, CustomStringConvertible, Codable { case externalEvents = "EXTERNAL_EVENTS" public var description: String { return self.rawValue } } // MARK: Shapes public struct BatchCreateVariableError: AWSDecodableShape { /// The error code. public let code: Int? /// The error message. public let message: String? /// The name. public let name: String? public init(code: Int? = nil, message: String? = nil, name: String? = nil) { self.code = code self.message = message self.name = name } private enum CodingKeys: String, CodingKey { case code case message case name } } public struct BatchCreateVariableRequest: AWSEncodableShape { /// A collection of key and value pairs. public let tags: [Tag]? /// The list of variables for the batch create variable request. public let variableEntries: [VariableEntry] public init(tags: [Tag]? = nil, variableEntries: [VariableEntry]) { self.tags = tags self.variableEntries = variableEntries } public func validate(name: String) throws { try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) try self.validate(self.variableEntries, name: "variableEntries", parent: name, max: 25) try self.validate(self.variableEntries, name: "variableEntries", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case tags case variableEntries } } public struct BatchCreateVariableResult: AWSDecodableShape { /// Provides the errors for the BatchCreateVariable request. public let errors: [BatchCreateVariableError]? public init(errors: [BatchCreateVariableError]? = nil) { self.errors = errors } private enum CodingKeys: String, CodingKey { case errors } } public struct BatchGetVariableError: AWSDecodableShape { /// The error code. public let code: Int? /// The error message. public let message: String? /// The error name. public let name: String? public init(code: Int? = nil, message: String? = nil, name: String? = nil) { self.code = code self.message = message self.name = name } private enum CodingKeys: String, CodingKey { case code case message case name } } public struct BatchGetVariableRequest: AWSEncodableShape { /// The list of variable names to get. public let names: [String] public init(names: [String]) { self.names = names } public func validate(name: String) throws { try self.validate(self.names, name: "names", parent: name, max: 100) try self.validate(self.names, name: "names", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case names } } public struct BatchGetVariableResult: AWSDecodableShape { /// The errors from the request. public let errors: [BatchGetVariableError]? /// The returned variables. public let variables: [Variable]? public init(errors: [BatchGetVariableError]? = nil, variables: [Variable]? = nil) { self.errors = errors self.variables = variables } private enum CodingKeys: String, CodingKey { case errors case variables } } public struct CreateDetectorVersionRequest: AWSEncodableShape { /// The description of the detector version. public let description: String? /// The ID of the detector under which you want to create a new version. public let detectorId: String /// The Amazon Sagemaker model endpoints to include in the detector version. public let externalModelEndpoints: [String]? /// The model versions to include in the detector version. public let modelVersions: [ModelVersion]? /// The rule execution mode for the rules included in the detector version. You can define and edit the rule mode at the detector version level, when it is in draft status. If you specify FIRST_MATCHED, Amazon Fraud Detector evaluates rules sequentially, first to last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. If you specifiy ALL_MATCHED, Amazon Fraud Detector evaluates all rules and returns the outcomes for all matched rules. The default behavior is FIRST_MATCHED. public let ruleExecutionMode: RuleExecutionMode? /// The rules to include in the detector version. public let rules: [Rule] /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, detectorId: String, externalModelEndpoints: [String]? = nil, modelVersions: [ModelVersion]? = nil, ruleExecutionMode: RuleExecutionMode? = nil, rules: [Rule], tags: [Tag]? = nil) { self.description = description self.detectorId = detectorId self.externalModelEndpoints = externalModelEndpoints self.modelVersions = modelVersions self.ruleExecutionMode = ruleExecutionMode self.rules = rules self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.modelVersions?.forEach { try $0.validate(name: "\(name).modelVersions[]") } try self.rules.forEach { try $0.validate(name: "\(name).rules[]") } try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case detectorId case externalModelEndpoints case modelVersions case ruleExecutionMode case rules case tags } } public struct CreateDetectorVersionResult: AWSDecodableShape { /// The ID for the created version's parent detector. public let detectorId: String? /// The ID for the created detector. public let detectorVersionId: String? /// The status of the detector version. public let status: DetectorVersionStatus? public init(detectorId: String? = nil, detectorVersionId: String? = nil, status: DetectorVersionStatus? = nil) { self.detectorId = detectorId self.detectorVersionId = detectorVersionId self.status = status } private enum CodingKeys: String, CodingKey { case detectorId case detectorVersionId case status } } public struct CreateModelRequest: AWSEncodableShape { /// The model description. public let description: String? /// The name of the event type. public let eventTypeName: String /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, eventTypeName: String, modelId: String, modelType: ModelTypeEnum, tags: [Tag]? = nil) { self.description = description self.eventTypeName = eventTypeName self.modelId = modelId self.modelType = modelType self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case eventTypeName case modelId case modelType case tags } } public struct CreateModelResult: AWSDecodableShape { public init() {} } public struct CreateModelVersionRequest: AWSEncodableShape { /// Details for the external events data used for model version training. Required if trainingDataSource is EXTERNAL_EVENTS. public let externalEventsDetail: ExternalEventsDetail? /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// A collection of key and value pairs. public let tags: [Tag]? /// The training data schema. public let trainingDataSchema: TrainingDataSchema /// The training data source location in Amazon S3. public let trainingDataSource: TrainingDataSourceEnum public init(externalEventsDetail: ExternalEventsDetail? = nil, modelId: String, modelType: ModelTypeEnum, tags: [Tag]? = nil, trainingDataSchema: TrainingDataSchema, trainingDataSource: TrainingDataSourceEnum) { self.externalEventsDetail = externalEventsDetail self.modelId = modelId self.modelType = modelType self.tags = tags self.trainingDataSchema = trainingDataSchema self.trainingDataSource = trainingDataSource } public func validate(name: String) throws { try self.externalEventsDetail?.validate(name: "\(name).externalEventsDetail") try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case externalEventsDetail case modelId case modelType case tags case trainingDataSchema case trainingDataSource } } public struct CreateModelVersionResult: AWSDecodableShape { /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The model version number of the model version created. public let modelVersionNumber: String? /// The model version status. public let status: String? public init(modelId: String? = nil, modelType: ModelTypeEnum? = nil, modelVersionNumber: String? = nil, status: String? = nil) { self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.status = status } private enum CodingKeys: String, CodingKey { case modelId case modelType case modelVersionNumber case status } } public struct CreateRuleRequest: AWSEncodableShape { /// The rule description. public let description: String? /// The detector ID for the rule's parent detector. public let detectorId: String /// The rule expression. public let expression: String /// The language of the rule. public let language: Language /// The outcome or outcomes returned when the rule expression matches. public let outcomes: [String] /// The rule ID. public let ruleId: String /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, detectorId: String, expression: String, language: Language, outcomes: [String], ruleId: String, tags: [Tag]? = nil) { self.description = description self.detectorId = detectorId self.expression = expression self.language = language self.outcomes = outcomes self.ruleId = ruleId self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.expression, name: "expression", parent: name, max: 4096) try self.validate(self.expression, name: "expression", parent: name, min: 1) try self.validate(self.outcomes, name: "outcomes", parent: name, min: 1) try self.validate(self.ruleId, name: "ruleId", parent: name, max: 64) try self.validate(self.ruleId, name: "ruleId", parent: name, min: 1) try self.validate(self.ruleId, name: "ruleId", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case detectorId case expression case language case outcomes case ruleId case tags } } public struct CreateRuleResult: AWSDecodableShape { /// The created rule. public let rule: Rule? public init(rule: Rule? = nil) { self.rule = rule } private enum CodingKeys: String, CodingKey { case rule } } public struct CreateVariableRequest: AWSEncodableShape { /// The source of the data. public let dataSource: DataSource /// The data type. public let dataType: DataType /// The default value for the variable when no value is received. public let defaultValue: String /// The description. public let description: String? /// The name of the variable. public let name: String /// A collection of key and value pairs. public let tags: [Tag]? /// The variable type. For more information see Variable types. Valid Values: AUTH_CODE | AVS | BILLING_ADDRESS_L1 | BILLING_ADDRESS_L2 | BILLING_CITY | BILLING_COUNTRY | BILLING_NAME | BILLING_PHONE | BILLING_STATE | BILLING_ZIP | CARD_BIN | CATEGORICAL | CURRENCY_CODE | EMAIL_ADDRESS | FINGERPRINT | FRAUD_LABEL | FREE_FORM_TEXT | IP_ADDRESS | NUMERIC | ORDER_ID | PAYMENT_TYPE | PHONE_NUMBER | PRICE | PRODUCT_CATEGORY | SHIPPING_ADDRESS_L1 | SHIPPING_ADDRESS_L2 | SHIPPING_CITY | SHIPPING_COUNTRY | SHIPPING_NAME | SHIPPING_PHONE | SHIPPING_STATE | SHIPPING_ZIP | USERAGENT public let variableType: String? public init(dataSource: DataSource, dataType: DataType, defaultValue: String, description: String? = nil, name: String, tags: [Tag]? = nil, variableType: String? = nil) { self.dataSource = dataSource self.dataType = dataType self.defaultValue = defaultValue self.description = description self.name = name self.tags = tags self.variableType = variableType } public func validate(name: String) throws { try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case dataSource case dataType case defaultValue case description case name case tags case variableType } } public struct CreateVariableResult: AWSDecodableShape { public init() {} } public struct DataValidationMetrics: AWSDecodableShape { /// The field-specific model training validation messages. public let fieldLevelMessages: [FieldValidationMessage]? /// The file-specific model training validation messages. public let fileLevelMessages: [FileValidationMessage]? public init(fieldLevelMessages: [FieldValidationMessage]? = nil, fileLevelMessages: [FileValidationMessage]? = nil) { self.fieldLevelMessages = fieldLevelMessages self.fileLevelMessages = fileLevelMessages } private enum CodingKeys: String, CodingKey { case fieldLevelMessages case fileLevelMessages } } public struct DeleteDetectorRequest: AWSEncodableShape { /// The ID of the detector to delete. public let detectorId: String public init(detectorId: String) { self.detectorId = detectorId } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case detectorId } } public struct DeleteDetectorResult: AWSDecodableShape { public init() {} } public struct DeleteDetectorVersionRequest: AWSEncodableShape { /// The ID of the parent detector for the detector version to delete. public let detectorId: String /// The ID of the detector version to delete. public let detectorVersionId: String public init(detectorId: String, detectorVersionId: String) { self.detectorId = detectorId self.detectorVersionId = detectorVersionId } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case detectorId case detectorVersionId } } public struct DeleteDetectorVersionResult: AWSDecodableShape { public init() {} } public struct DeleteEventRequest: AWSEncodableShape { /// The ID of the event to delete. public let eventId: String /// The name of the event type. public let eventTypeName: String public init(eventId: String, eventTypeName: String) { self.eventId = eventId self.eventTypeName = eventTypeName } private enum CodingKeys: String, CodingKey { case eventId case eventTypeName } } public struct DeleteEventResult: AWSDecodableShape { public init() {} } public struct DeleteRuleRequest: AWSEncodableShape { public let rule: Rule public init(rule: Rule) { self.rule = rule } public func validate(name: String) throws { try self.rule.validate(name: "\(name).rule") } private enum CodingKeys: String, CodingKey { case rule } } public struct DeleteRuleResult: AWSDecodableShape { public init() {} } public struct DescribeDetectorRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String /// The maximum number of results to return for the request. public let maxResults: Int? /// The next token from the previous response. public let nextToken: String? public init(detectorId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.detectorId = detectorId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 2500) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1000) } private enum CodingKeys: String, CodingKey { case detectorId case maxResults case nextToken } } public struct DescribeDetectorResult: AWSDecodableShape { /// The detector ARN. public let arn: String? /// The detector ID. public let detectorId: String? /// The status and description for each detector version. public let detectorVersionSummaries: [DetectorVersionSummary]? /// The next token to be used for subsequent requests. public let nextToken: String? public init(arn: String? = nil, detectorId: String? = nil, detectorVersionSummaries: [DetectorVersionSummary]? = nil, nextToken: String? = nil) { self.arn = arn self.detectorId = detectorId self.detectorVersionSummaries = detectorVersionSummaries self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case arn case detectorId case detectorVersionSummaries case nextToken } } public struct DescribeModelVersionsRequest: AWSEncodableShape { /// The maximum number of results to return. public let maxResults: Int? /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The model version number. public let modelVersionNumber: String? /// The next token from the previous results. public let nextToken: String? public init(maxResults: Int? = nil, modelId: String? = nil, modelType: ModelTypeEnum? = nil, modelVersionNumber: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, max: 7) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, min: 3) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, pattern: "^[1-9][0-9]{0,3}\\.[0-9]{1,2}$") } private enum CodingKeys: String, CodingKey { case maxResults case modelId case modelType case modelVersionNumber case nextToken } } public struct DescribeModelVersionsResult: AWSDecodableShape { /// The model version details. public let modelVersionDetails: [ModelVersionDetail]? /// The next token. public let nextToken: String? public init(modelVersionDetails: [ModelVersionDetail]? = nil, nextToken: String? = nil) { self.modelVersionDetails = modelVersionDetails self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case modelVersionDetails case nextToken } } public struct Detector: AWSDecodableShape { /// The detector ARN. public let arn: String? /// Timestamp of when the detector was created. public let createdTime: String? /// The detector description. public let description: String? /// The detector ID. public let detectorId: String? /// The name of the event type. public let eventTypeName: String? /// Timestamp of when the detector was last updated. public let lastUpdatedTime: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, detectorId: String? = nil, eventTypeName: String? = nil, lastUpdatedTime: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.detectorId = detectorId self.eventTypeName = eventTypeName self.lastUpdatedTime = lastUpdatedTime } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case detectorId case eventTypeName case lastUpdatedTime } } public struct DetectorVersionSummary: AWSDecodableShape { /// The detector version description. public let description: String? /// The detector version ID. public let detectorVersionId: String? /// Timestamp of when the detector version was last updated. public let lastUpdatedTime: String? /// The detector version status. public let status: DetectorVersionStatus? public init(description: String? = nil, detectorVersionId: String? = nil, lastUpdatedTime: String? = nil, status: DetectorVersionStatus? = nil) { self.description = description self.detectorVersionId = detectorVersionId self.lastUpdatedTime = lastUpdatedTime self.status = status } private enum CodingKeys: String, CodingKey { case description case detectorVersionId case lastUpdatedTime case status } } public struct Entity: AWSEncodableShape { /// The entity ID. If you do not know the entityId, you can pass unknown, which is areserved string literal. public let entityId: String /// The entity type. public let entityType: String public init(entityId: String, entityType: String) { self.entityId = entityId self.entityType = entityType } public func validate(name: String) throws { try self.validate(self.entityId, name: "entityId", parent: name, max: 64) try self.validate(self.entityId, name: "entityId", parent: name, min: 1) try self.validate(self.entityId, name: "entityId", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case entityId case entityType } } public struct EntityType: AWSDecodableShape { /// The entity type ARN. public let arn: String? /// Timestamp of when the entity type was created. public let createdTime: String? /// The entity type description. public let description: String? /// Timestamp of when the entity type was last updated. public let lastUpdatedTime: String? /// The entity type name. public let name: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, lastUpdatedTime: String? = nil, name: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.lastUpdatedTime = lastUpdatedTime self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case lastUpdatedTime case name } } public struct EventType: AWSDecodableShape { /// The entity type ARN. public let arn: String? /// Timestamp of when the event type was created. public let createdTime: String? /// The event type description. public let description: String? /// The event type entity types. public let entityTypes: [String]? /// The event type event variables. public let eventVariables: [String]? /// The event type labels. public let labels: [String]? /// Timestamp of when the event type was last updated. public let lastUpdatedTime: String? /// The event type name. public let name: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, entityTypes: [String]? = nil, eventVariables: [String]? = nil, labels: [String]? = nil, lastUpdatedTime: String? = nil, name: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.entityTypes = entityTypes self.eventVariables = eventVariables self.labels = labels self.lastUpdatedTime = lastUpdatedTime self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case entityTypes case eventVariables case labels case lastUpdatedTime case name } } public struct ExternalEventsDetail: AWSEncodableShape & AWSDecodableShape { /// The ARN of the role that provides Amazon Fraud Detector access to the data location. public let dataAccessRoleArn: String /// The Amazon S3 bucket location for the data. public let dataLocation: String public init(dataAccessRoleArn: String, dataLocation: String) { self.dataAccessRoleArn = dataAccessRoleArn self.dataLocation = dataLocation } public func validate(name: String) throws { try self.validate(self.dataAccessRoleArn, name: "dataAccessRoleArn", parent: name, max: 256) try self.validate(self.dataAccessRoleArn, name: "dataAccessRoleArn", parent: name, min: 1) try self.validate(self.dataAccessRoleArn, name: "dataAccessRoleArn", parent: name, pattern: "^arn\\:aws[a-z-]{0,15}\\:iam\\:\\:[0-9]{12}\\:role\\/[^\\s]{2,64}$") try self.validate(self.dataLocation, name: "dataLocation", parent: name, max: 512) try self.validate(self.dataLocation, name: "dataLocation", parent: name, min: 1) try self.validate(self.dataLocation, name: "dataLocation", parent: name, pattern: "^s3:\\/\\/(.+)$") } private enum CodingKeys: String, CodingKey { case dataAccessRoleArn case dataLocation } } public struct ExternalModel: AWSDecodableShape { /// The model ARN. public let arn: String? /// Timestamp of when the model was last created. public let createdTime: String? /// The input configuration. public let inputConfiguration: ModelInputConfiguration? /// The role used to invoke the model. public let invokeModelEndpointRoleArn: String? /// Timestamp of when the model was last updated. public let lastUpdatedTime: String? /// The Amazon SageMaker model endpoints. public let modelEndpoint: String? /// The Amazon Fraud Detector status for the external model endpoint public let modelEndpointStatus: ModelEndpointStatus? /// The source of the model. public let modelSource: ModelSource? /// The output configuration. public let outputConfiguration: ModelOutputConfiguration? public init(arn: String? = nil, createdTime: String? = nil, inputConfiguration: ModelInputConfiguration? = nil, invokeModelEndpointRoleArn: String? = nil, lastUpdatedTime: String? = nil, modelEndpoint: String? = nil, modelEndpointStatus: ModelEndpointStatus? = nil, modelSource: ModelSource? = nil, outputConfiguration: ModelOutputConfiguration? = nil) { self.arn = arn self.createdTime = createdTime self.inputConfiguration = inputConfiguration self.invokeModelEndpointRoleArn = invokeModelEndpointRoleArn self.lastUpdatedTime = lastUpdatedTime self.modelEndpoint = modelEndpoint self.modelEndpointStatus = modelEndpointStatus self.modelSource = modelSource self.outputConfiguration = outputConfiguration } private enum CodingKeys: String, CodingKey { case arn case createdTime case inputConfiguration case invokeModelEndpointRoleArn case lastUpdatedTime case modelEndpoint case modelEndpointStatus case modelSource case outputConfiguration } } public struct FieldValidationMessage: AWSDecodableShape { /// The message content. public let content: String? /// The field name. public let fieldName: String? /// The message ID. public let identifier: String? /// The message title. public let title: String? /// The message type. public let type: String? public init(content: String? = nil, fieldName: String? = nil, identifier: String? = nil, title: String? = nil, type: String? = nil) { self.content = content self.fieldName = fieldName self.identifier = identifier self.title = title self.type = type } private enum CodingKeys: String, CodingKey { case content case fieldName case identifier case title case type } } public struct FileValidationMessage: AWSDecodableShape { /// The message content. public let content: String? /// The message title. public let title: String? /// The message type. public let type: String? public init(content: String? = nil, title: String? = nil, type: String? = nil) { self.content = content self.title = title self.type = type } private enum CodingKeys: String, CodingKey { case content case title case type } } public struct GetDetectorVersionRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String /// The detector version ID. public let detectorVersionId: String public init(detectorId: String, detectorVersionId: String) { self.detectorId = detectorId self.detectorVersionId = detectorVersionId } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case detectorId case detectorVersionId } } public struct GetDetectorVersionResult: AWSDecodableShape { /// The detector version ARN. public let arn: String? /// The timestamp when the detector version was created. public let createdTime: String? /// The detector version description. public let description: String? /// The detector ID. public let detectorId: String? /// The detector version ID. public let detectorVersionId: String? /// The Amazon SageMaker model endpoints included in the detector version. public let externalModelEndpoints: [String]? /// The timestamp when the detector version was last updated. public let lastUpdatedTime: String? /// The model versions included in the detector version. public let modelVersions: [ModelVersion]? /// The execution mode of the rule in the dectector FIRST_MATCHED indicates that Amazon Fraud Detector evaluates rules sequentially, first to last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. ALL_MATCHED indicates that Amazon Fraud Detector evaluates all rules and returns the outcomes for all matched rules. You can define and edit the rule mode at the detector version level, when it is in draft status. public let ruleExecutionMode: RuleExecutionMode? /// The rules included in the detector version. public let rules: [Rule]? /// The status of the detector version. public let status: DetectorVersionStatus? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, detectorId: String? = nil, detectorVersionId: String? = nil, externalModelEndpoints: [String]? = nil, lastUpdatedTime: String? = nil, modelVersions: [ModelVersion]? = nil, ruleExecutionMode: RuleExecutionMode? = nil, rules: [Rule]? = nil, status: DetectorVersionStatus? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.detectorId = detectorId self.detectorVersionId = detectorVersionId self.externalModelEndpoints = externalModelEndpoints self.lastUpdatedTime = lastUpdatedTime self.modelVersions = modelVersions self.ruleExecutionMode = ruleExecutionMode self.rules = rules self.status = status } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case detectorId case detectorVersionId case externalModelEndpoints case lastUpdatedTime case modelVersions case ruleExecutionMode case rules case status } } public struct GetDetectorsRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String? /// The maximum number of objects to return for the request. public let maxResults: Int? /// The next token for the subsequent request. public let nextToken: String? public init(detectorId: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.detectorId = detectorId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 5) } private enum CodingKeys: String, CodingKey { case detectorId case maxResults case nextToken } } public struct GetDetectorsResult: AWSDecodableShape { /// The detectors. public let detectors: [Detector]? /// The next page token. public let nextToken: String? public init(detectors: [Detector]? = nil, nextToken: String? = nil) { self.detectors = detectors self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case detectors case nextToken } } public struct GetEntityTypesRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The name. public let name: String? /// The next token for the subsequent request. public let nextToken: String? public init(maxResults: Int? = nil, name: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.name = name self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 5) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case name case nextToken } } public struct GetEntityTypesResult: AWSDecodableShape { /// An array of entity types. public let entityTypes: [EntityType]? /// The next page token. public let nextToken: String? public init(entityTypes: [EntityType]? = nil, nextToken: String? = nil) { self.entityTypes = entityTypes self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case entityTypes case nextToken } } public struct GetEventPredictionRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String /// The detector version ID. public let detectorVersionId: String? /// The entity type (associated with the detector's event type) and specific entity ID representing who performed the event. If an entity id is not available, use "UNKNOWN." public let entities: [Entity] /// The unique ID used to identify the event. public let eventId: String /// Timestamp that defines when the event under evaluation occurred. public let eventTimestamp: String /// The event type associated with the detector specified for the prediction. public let eventTypeName: String /// Names of the event type's variables you defined in Amazon Fraud Detector to represent data elements and their corresponding values for the event you are sending for evaluation. public let eventVariables: [String: String] /// The Amazon SageMaker model endpoint input data blobs. public let externalModelEndpointDataBlobs: [String: ModelEndpointDataBlob]? public init(detectorId: String, detectorVersionId: String? = nil, entities: [Entity], eventId: String, eventTimestamp: String, eventTypeName: String, eventVariables: [String: String], externalModelEndpointDataBlobs: [String: ModelEndpointDataBlob]? = nil) { self.detectorId = detectorId self.detectorVersionId = detectorVersionId self.entities = entities self.eventId = eventId self.eventTimestamp = eventTimestamp self.eventTypeName = eventTypeName self.eventVariables = eventVariables self.externalModelEndpointDataBlobs = externalModelEndpointDataBlobs } public func validate(name: String) throws { try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") try self.entities.forEach { try $0.validate(name: "\(name).entities[]") } try self.eventVariables.forEach { try validate($0.key, name: "eventVariables.key", parent: name, max: 64) try validate($0.key, name: "eventVariables.key", parent: name, min: 1) try validate($0.value, name: "eventVariables[\"\($0.key)\"]", parent: name, max: 1024) try validate($0.value, name: "eventVariables[\"\($0.key)\"]", parent: name, min: 1) } try self.externalModelEndpointDataBlobs?.forEach { try $0.value.validate(name: "\(name).externalModelEndpointDataBlobs[\"\($0.key)\"]") } } private enum CodingKeys: String, CodingKey { case detectorId case detectorVersionId case entities case eventId case eventTimestamp case eventTypeName case eventVariables case externalModelEndpointDataBlobs } } public struct GetEventPredictionResult: AWSDecodableShape { /// The model scores. Amazon Fraud Detector generates model scores between 0 and 1000, where 0 is low fraud risk and 1000 is high fraud risk. Model scores are directly related to the false positive rate (FPR). For example, a score of 600 corresponds to an estimated 10% false positive rate whereas a score of 900 corresponds to an estimated 2% false positive rate. public let modelScores: [ModelScores]? /// The results. public let ruleResults: [RuleResult]? public init(modelScores: [ModelScores]? = nil, ruleResults: [RuleResult]? = nil) { self.modelScores = modelScores self.ruleResults = ruleResults } private enum CodingKeys: String, CodingKey { case modelScores case ruleResults } } public struct GetEventTypesRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The name. public let name: String? /// The next token for the subsequent request. public let nextToken: String? public init(maxResults: Int? = nil, name: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.name = name self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 5) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case name case nextToken } } public struct GetEventTypesResult: AWSDecodableShape { /// An array of event types. public let eventTypes: [EventType]? /// The next page token. public let nextToken: String? public init(eventTypes: [EventType]? = nil, nextToken: String? = nil) { self.eventTypes = eventTypes self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case eventTypes case nextToken } } public struct GetExternalModelsRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The Amazon SageMaker model endpoint. public let modelEndpoint: String? /// The next page token for the request. public let nextToken: String? public init(maxResults: Int? = nil, modelEndpoint: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.modelEndpoint = modelEndpoint self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 5) } private enum CodingKeys: String, CodingKey { case maxResults case modelEndpoint case nextToken } } public struct GetExternalModelsResult: AWSDecodableShape { /// Gets the Amazon SageMaker models. public let externalModels: [ExternalModel]? /// The next page token to be used in subsequent requests. public let nextToken: String? public init(externalModels: [ExternalModel]? = nil, nextToken: String? = nil) { self.externalModels = externalModels self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case externalModels case nextToken } } public struct GetKMSEncryptionKeyResult: AWSDecodableShape { /// The KMS encryption key. public let kmsKey: KMSKey? public init(kmsKey: KMSKey? = nil) { self.kmsKey = kmsKey } private enum CodingKeys: String, CodingKey { case kmsKey } } public struct GetLabelsRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The name of the label or labels to get. public let name: String? /// The next token for the subsequent request. public let nextToken: String? public init(maxResults: Int? = nil, name: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.name = name self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 10) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case name case nextToken } } public struct GetLabelsResult: AWSDecodableShape { /// An array of labels. public let labels: [Label]? /// The next page token. public let nextToken: String? public init(labels: [Label]? = nil, nextToken: String? = nil) { self.labels = labels self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case labels case nextToken } } public struct GetModelVersionRequest: AWSEncodableShape { /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// The model version number. public let modelVersionNumber: String public init(modelId: String, modelType: ModelTypeEnum, modelVersionNumber: String) { self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber } public func validate(name: String) throws { try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, max: 7) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, min: 3) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, pattern: "^[1-9][0-9]{0,3}\\.[0-9]{1,2}$") } private enum CodingKeys: String, CodingKey { case modelId case modelType case modelVersionNumber } } public struct GetModelVersionResult: AWSDecodableShape { /// The model version ARN. public let arn: String? /// The event details. public let externalEventsDetail: ExternalEventsDetail? /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The model version number. public let modelVersionNumber: String? /// The model version status. public let status: String? /// The training data schema. public let trainingDataSchema: TrainingDataSchema? /// The training data source. public let trainingDataSource: TrainingDataSourceEnum? public init(arn: String? = nil, externalEventsDetail: ExternalEventsDetail? = nil, modelId: String? = nil, modelType: ModelTypeEnum? = nil, modelVersionNumber: String? = nil, status: String? = nil, trainingDataSchema: TrainingDataSchema? = nil, trainingDataSource: TrainingDataSourceEnum? = nil) { self.arn = arn self.externalEventsDetail = externalEventsDetail self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.status = status self.trainingDataSchema = trainingDataSchema self.trainingDataSource = trainingDataSource } private enum CodingKeys: String, CodingKey { case arn case externalEventsDetail case modelId case modelType case modelVersionNumber case status case trainingDataSchema case trainingDataSource } } public struct GetModelsRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The next token for the subsequent request. public let nextToken: String? public init(maxResults: Int? = nil, modelId: String? = nil, modelType: ModelTypeEnum? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.modelId = modelId self.modelType = modelType self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 10) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") } private enum CodingKeys: String, CodingKey { case maxResults case modelId case modelType case nextToken } } public struct GetModelsResult: AWSDecodableShape { /// The array of models. public let models: [Model]? /// The next page token to be used in subsequent requests. public let nextToken: String? public init(models: [Model]? = nil, nextToken: String? = nil) { self.models = models self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case models case nextToken } } public struct GetOutcomesRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The name of the outcome or outcomes to get. public let name: String? /// The next page token for the request. public let nextToken: String? public init(maxResults: Int? = nil, name: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.name = name self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 50) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case maxResults case name case nextToken } } public struct GetOutcomesResult: AWSDecodableShape { /// The next page token for subsequent requests. public let nextToken: String? /// The outcomes. public let outcomes: [Outcome]? public init(nextToken: String? = nil, outcomes: [Outcome]? = nil) { self.nextToken = nextToken self.outcomes = outcomes } private enum CodingKeys: String, CodingKey { case nextToken case outcomes } } public struct GetRulesRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String /// The maximum number of rules to return for the request. public let maxResults: Int? /// The next page token. public let nextToken: String? /// The rule ID. public let ruleId: String? /// The rule version. public let ruleVersion: String? public init(detectorId: String, maxResults: Int? = nil, nextToken: String? = nil, ruleId: String? = nil, ruleVersion: String? = nil) { self.detectorId = detectorId self.maxResults = maxResults self.nextToken = nextToken self.ruleId = ruleId self.ruleVersion = ruleVersion } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 50) try self.validate(self.ruleId, name: "ruleId", parent: name, max: 64) try self.validate(self.ruleId, name: "ruleId", parent: name, min: 1) try self.validate(self.ruleId, name: "ruleId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, max: 5) try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, min: 1) try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case detectorId case maxResults case nextToken case ruleId case ruleVersion } } public struct GetRulesResult: AWSDecodableShape { /// The next page token to be used in subsequent requests. public let nextToken: String? /// The details of the requested rule. public let ruleDetails: [RuleDetail]? public init(nextToken: String? = nil, ruleDetails: [RuleDetail]? = nil) { self.nextToken = nextToken self.ruleDetails = ruleDetails } private enum CodingKeys: String, CodingKey { case nextToken case ruleDetails } } public struct GetVariablesRequest: AWSEncodableShape { /// The max size per page determined for the get variable request. public let maxResults: Int? /// The name of the variable. public let name: String? /// The next page token of the get variable request. public let nextToken: String? public init(maxResults: Int? = nil, name: String? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.name = name self.nextToken = nextToken } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 50) } private enum CodingKeys: String, CodingKey { case maxResults case name case nextToken } } public struct GetVariablesResult: AWSDecodableShape { /// The next page token to be used in subsequent requests. public let nextToken: String? /// The names of the variables returned. public let variables: [Variable]? public init(nextToken: String? = nil, variables: [Variable]? = nil) { self.nextToken = nextToken self.variables = variables } private enum CodingKeys: String, CodingKey { case nextToken case variables } } public struct KMSKey: AWSDecodableShape { /// The encryption key ARN. public let kmsEncryptionKeyArn: String? public init(kmsEncryptionKeyArn: String? = nil) { self.kmsEncryptionKeyArn = kmsEncryptionKeyArn } private enum CodingKeys: String, CodingKey { case kmsEncryptionKeyArn } } public struct Label: AWSDecodableShape { /// The label ARN. public let arn: String? /// Timestamp of when the event type was created. public let createdTime: String? /// The label description. public let description: String? /// Timestamp of when the label was last updated. public let lastUpdatedTime: String? /// The label name. public let name: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, lastUpdatedTime: String? = nil, name: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.lastUpdatedTime = lastUpdatedTime self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case lastUpdatedTime case name } } public struct LabelSchema: AWSEncodableShape & AWSDecodableShape { /// The label mapper maps the Amazon Fraud Detector supported model classification labels (FRAUD, LEGIT) to the appropriate event type labels. For example, if "FRAUD" and "LEGIT" are Amazon Fraud Detector supported labels, this mapper could be: {"FRAUD" =&gt; ["0"], "LEGIT" =&gt; ["1"]} or {"FRAUD" =&gt; ["false"], "LEGIT" =&gt; ["true"]} or {"FRAUD" =&gt; ["fraud", "abuse"], "LEGIT" =&gt; ["legit", "safe"]}. The value part of the mapper is a list, because you may have multiple label variants from your event type for a single Amazon Fraud Detector label. public let labelMapper: [String: [String]] public init(labelMapper: [String: [String]]) { self.labelMapper = labelMapper } private enum CodingKeys: String, CodingKey { case labelMapper } } public struct ListTagsForResourceRequest: AWSEncodableShape { /// The maximum number of objects to return for the request. public let maxResults: Int? /// The next token from the previous results. public let nextToken: String? /// The ARN that specifies the resource whose tags you want to list. public let resourceARN: String public init(maxResults: Int? = nil, nextToken: String? = nil, resourceARN: String) { self.maxResults = maxResults self.nextToken = nextToken self.resourceARN = resourceARN } public func validate(name: String) throws { try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 50) try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 256) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) try self.validate(self.resourceARN, name: "resourceARN", parent: name, pattern: "^arn\\:aws[a-z-]{0,15}\\:frauddetector\\:[a-z0-9-]{3,20}\\:[0-9]{12}\\:[^\\s]{2,128}$") } private enum CodingKeys: String, CodingKey { case maxResults case nextToken case resourceARN } } public struct ListTagsForResourceResult: AWSDecodableShape { /// The next token for subsequent requests. public let nextToken: String? /// A collection of key and value pairs. public let tags: [Tag]? public init(nextToken: String? = nil, tags: [Tag]? = nil) { self.nextToken = nextToken self.tags = tags } private enum CodingKeys: String, CodingKey { case nextToken case tags } } public struct MetricDataPoint: AWSDecodableShape { /// The false positive rate. This is the percentage of total legitimate events that are incorrectly predicted as fraud. public let fpr: Float? /// The percentage of fraud events correctly predicted as fraudulent as compared to all events predicted as fraudulent. public let precision: Float? /// The model threshold that specifies an acceptable fraud capture rate. For example, a threshold of 500 means any model score 500 or above is labeled as fraud. public let threshold: Float? /// The true positive rate. This is the percentage of total fraud the model detects. Also known as capture rate. public let tpr: Float? public init(fpr: Float? = nil, precision: Float? = nil, threshold: Float? = nil, tpr: Float? = nil) { self.fpr = fpr self.precision = precision self.threshold = threshold self.tpr = tpr } private enum CodingKeys: String, CodingKey { case fpr case precision case threshold case tpr } } public struct Model: AWSDecodableShape { /// The ARN of the model. public let arn: String? /// Timestamp of when the model was created. public let createdTime: String? /// The model description. public let description: String? /// The name of the event type. public let eventTypeName: String? /// Timestamp of last time the model was updated. public let lastUpdatedTime: String? /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, eventTypeName: String? = nil, lastUpdatedTime: String? = nil, modelId: String? = nil, modelType: ModelTypeEnum? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.eventTypeName = eventTypeName self.lastUpdatedTime = lastUpdatedTime self.modelId = modelId self.modelType = modelType } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case eventTypeName case lastUpdatedTime case modelId case modelType } } public struct ModelEndpointDataBlob: AWSEncodableShape { /// The byte buffer of the Amazon SageMaker model endpoint input data blob. public let byteBuffer: Data? /// The content type of the Amazon SageMaker model endpoint input data blob. public let contentType: String? public init(byteBuffer: Data? = nil, contentType: String? = nil) { self.byteBuffer = byteBuffer self.contentType = contentType } public func validate(name: String) throws { try self.validate(self.contentType, name: "contentType", parent: name, max: 1024) try self.validate(self.contentType, name: "contentType", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case byteBuffer case contentType } } public struct ModelInputConfiguration: AWSEncodableShape & AWSDecodableShape { /// Template for constructing the CSV input-data sent to SageMaker. At event-evaluation, the placeholders for variable-names in the template will be replaced with the variable values before being sent to SageMaker. public let csvInputTemplate: String? /// The event type name. public let eventTypeName: String? /// The format of the model input configuration. The format differs depending on if it is passed through to SageMaker or constructed by Amazon Fraud Detector. public let format: ModelInputDataFormat? /// Template for constructing the JSON input-data sent to SageMaker. At event-evaluation, the placeholders for variable names in the template will be replaced with the variable values before being sent to SageMaker. public let jsonInputTemplate: String? /// The event variables. public let useEventVariables: Bool public init(csvInputTemplate: String? = nil, eventTypeName: String? = nil, format: ModelInputDataFormat? = nil, jsonInputTemplate: String? = nil, useEventVariables: Bool) { self.csvInputTemplate = csvInputTemplate self.eventTypeName = eventTypeName self.format = format self.jsonInputTemplate = jsonInputTemplate self.useEventVariables = useEventVariables } public func validate(name: String) throws { try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, max: 64) try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, min: 1) try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, pattern: "^[0-9a-z_-]+$") } private enum CodingKeys: String, CodingKey { case csvInputTemplate case eventTypeName case format case jsonInputTemplate case useEventVariables } } public struct ModelOutputConfiguration: AWSEncodableShape & AWSDecodableShape { /// A map of CSV index values in the SageMaker response to the Amazon Fraud Detector variables. public let csvIndexToVariableMap: [String: String]? /// The format of the model output configuration. public let format: ModelOutputDataFormat /// A map of JSON keys in response from SageMaker to the Amazon Fraud Detector variables. public let jsonKeyToVariableMap: [String: String]? public init(csvIndexToVariableMap: [String: String]? = nil, format: ModelOutputDataFormat, jsonKeyToVariableMap: [String: String]? = nil) { self.csvIndexToVariableMap = csvIndexToVariableMap self.format = format self.jsonKeyToVariableMap = jsonKeyToVariableMap } private enum CodingKeys: String, CodingKey { case csvIndexToVariableMap case format case jsonKeyToVariableMap } } public struct ModelScores: AWSDecodableShape { /// The model version. public let modelVersion: ModelVersion? /// The model's fraud prediction scores. public let scores: [String: Float]? public init(modelVersion: ModelVersion? = nil, scores: [String: Float]? = nil) { self.modelVersion = modelVersion self.scores = scores } private enum CodingKeys: String, CodingKey { case modelVersion case scores } } public struct ModelVersion: AWSEncodableShape & AWSDecodableShape { /// The model version ARN. public let arn: String? /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// The model version number. public let modelVersionNumber: String public init(arn: String? = nil, modelId: String, modelType: ModelTypeEnum, modelVersionNumber: String) { self.arn = arn self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber } public func validate(name: String) throws { try self.validate(self.arn, name: "arn", parent: name, max: 256) try self.validate(self.arn, name: "arn", parent: name, min: 1) try self.validate(self.arn, name: "arn", parent: name, pattern: "^arn\\:aws[a-z-]{0,15}\\:frauddetector\\:[a-z0-9-]{3,20}\\:[0-9]{12}\\:[^\\s]{2,128}$") try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case arn case modelId case modelType case modelVersionNumber } } public struct ModelVersionDetail: AWSDecodableShape { /// The model version ARN. public let arn: String? /// The timestamp when the model was created. public let createdTime: String? /// The event details. public let externalEventsDetail: ExternalEventsDetail? /// The timestamp when the model was last updated. public let lastUpdatedTime: String? /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The model version number. public let modelVersionNumber: String? /// The status of the model version. public let status: String? /// The training data schema. public let trainingDataSchema: TrainingDataSchema? /// The model version training data source. public let trainingDataSource: TrainingDataSourceEnum? /// The training results. public let trainingResult: TrainingResult? public init(arn: String? = nil, createdTime: String? = nil, externalEventsDetail: ExternalEventsDetail? = nil, lastUpdatedTime: String? = nil, modelId: String? = nil, modelType: ModelTypeEnum? = nil, modelVersionNumber: String? = nil, status: String? = nil, trainingDataSchema: TrainingDataSchema? = nil, trainingDataSource: TrainingDataSourceEnum? = nil, trainingResult: TrainingResult? = nil) { self.arn = arn self.createdTime = createdTime self.externalEventsDetail = externalEventsDetail self.lastUpdatedTime = lastUpdatedTime self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.status = status self.trainingDataSchema = trainingDataSchema self.trainingDataSource = trainingDataSource self.trainingResult = trainingResult } private enum CodingKeys: String, CodingKey { case arn case createdTime case externalEventsDetail case lastUpdatedTime case modelId case modelType case modelVersionNumber case status case trainingDataSchema case trainingDataSource case trainingResult } } public struct Outcome: AWSDecodableShape { /// The outcome ARN. public let arn: String? /// The timestamp when the outcome was created. public let createdTime: String? /// The outcome description. public let description: String? /// The timestamp when the outcome was last updated. public let lastUpdatedTime: String? /// The outcome name. public let name: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, lastUpdatedTime: String? = nil, name: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.lastUpdatedTime = lastUpdatedTime self.name = name } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case lastUpdatedTime case name } } public struct PutDetectorRequest: AWSEncodableShape { /// The description of the detector. public let description: String? /// The detector ID. public let detectorId: String /// The name of the event type. public let eventTypeName: String /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, detectorId: String, eventTypeName: String, tags: [Tag]? = nil) { self.description = description self.detectorId = detectorId self.eventTypeName = eventTypeName self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, max: 64) try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, min: 1) try self.validate(self.eventTypeName, name: "eventTypeName", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case detectorId case eventTypeName case tags } } public struct PutDetectorResult: AWSDecodableShape { public init() {} } public struct PutEntityTypeRequest: AWSEncodableShape { /// The description. public let description: String? /// The name of the entity type. public let name: String /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, name: String, tags: [Tag]? = nil) { self.description = description self.name = name self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case name case tags } } public struct PutEntityTypeResult: AWSDecodableShape { public init() {} } public struct PutEventTypeRequest: AWSEncodableShape { /// The description of the event type. public let description: String? /// The entity type for the event type. Example entity types: customer, merchant, account. public let entityTypes: [String] /// The event type variables. public let eventVariables: [String] /// The event type labels. public let labels: [String]? /// The name. public let name: String /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, entityTypes: [String], eventVariables: [String], labels: [String]? = nil, name: String, tags: [Tag]? = nil) { self.description = description self.entityTypes = entityTypes self.eventVariables = eventVariables self.labels = labels self.name = name self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.entityTypes, name: "entityTypes", parent: name, min: 1) try self.validate(self.eventVariables, name: "eventVariables", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case entityTypes case eventVariables case labels case name case tags } } public struct PutEventTypeResult: AWSDecodableShape { public init() {} } public struct PutExternalModelRequest: AWSEncodableShape { /// The model endpoint input configuration. public let inputConfiguration: ModelInputConfiguration /// The IAM role used to invoke the model endpoint. public let invokeModelEndpointRoleArn: String /// The model endpoints name. public let modelEndpoint: String /// The model endpoint’s status in Amazon Fraud Detector. public let modelEndpointStatus: ModelEndpointStatus /// The source of the model. public let modelSource: ModelSource /// The model endpoint output configuration. public let outputConfiguration: ModelOutputConfiguration /// A collection of key and value pairs. public let tags: [Tag]? public init(inputConfiguration: ModelInputConfiguration, invokeModelEndpointRoleArn: String, modelEndpoint: String, modelEndpointStatus: ModelEndpointStatus, modelSource: ModelSource, outputConfiguration: ModelOutputConfiguration, tags: [Tag]? = nil) { self.inputConfiguration = inputConfiguration self.invokeModelEndpointRoleArn = invokeModelEndpointRoleArn self.modelEndpoint = modelEndpoint self.modelEndpointStatus = modelEndpointStatus self.modelSource = modelSource self.outputConfiguration = outputConfiguration self.tags = tags } public func validate(name: String) throws { try self.inputConfiguration.validate(name: "\(name).inputConfiguration") try self.validate(self.modelEndpoint, name: "modelEndpoint", parent: name, max: 63) try self.validate(self.modelEndpoint, name: "modelEndpoint", parent: name, min: 1) try self.validate(self.modelEndpoint, name: "modelEndpoint", parent: name, pattern: "^[0-9A-Za-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case inputConfiguration case invokeModelEndpointRoleArn case modelEndpoint case modelEndpointStatus case modelSource case outputConfiguration case tags } } public struct PutExternalModelResult: AWSDecodableShape { public init() {} } public struct PutKMSEncryptionKeyRequest: AWSEncodableShape { /// The KMS encryption key ARN. public let kmsEncryptionKeyArn: String public init(kmsEncryptionKeyArn: String) { self.kmsEncryptionKeyArn = kmsEncryptionKeyArn } public func validate(name: String) throws { try self.validate(self.kmsEncryptionKeyArn, name: "kmsEncryptionKeyArn", parent: name, max: 90) try self.validate(self.kmsEncryptionKeyArn, name: "kmsEncryptionKeyArn", parent: name, min: 7) try self.validate(self.kmsEncryptionKeyArn, name: "kmsEncryptionKeyArn", parent: name, pattern: "^\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}|DEFAULT|arn:[a-zA-Z0-9-]+:kms:[a-zA-Z0-9-]+:\\d{12}:key\\/\\w{8}-\\w{4}-\\w{4}-\\w{4}-\\w{12}$") } private enum CodingKeys: String, CodingKey { case kmsEncryptionKeyArn } } public struct PutKMSEncryptionKeyResult: AWSDecodableShape { public init() {} } public struct PutLabelRequest: AWSEncodableShape { /// The label description. public let description: String? /// The label name. public let name: String public let tags: [Tag]? public init(description: String? = nil, name: String, tags: [Tag]? = nil) { self.description = description self.name = name self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case name case tags } } public struct PutLabelResult: AWSDecodableShape { public init() {} } public struct PutOutcomeRequest: AWSEncodableShape { /// The outcome description. public let description: String? /// The name of the outcome. public let name: String /// A collection of key and value pairs. public let tags: [Tag]? public init(description: String? = nil, name: String, tags: [Tag]? = nil) { self.description = description self.name = name self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, max: 64) try self.validate(self.name, name: "name", parent: name, min: 1) try self.validate(self.name, name: "name", parent: name, pattern: "^[0-9a-z_-]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case name case tags } } public struct PutOutcomeResult: AWSDecodableShape { public init() {} } public struct Rule: AWSEncodableShape & AWSDecodableShape { /// The detector for which the rule is associated. public let detectorId: String /// The rule ID. public let ruleId: String /// The rule version. public let ruleVersion: String public init(detectorId: String, ruleId: String, ruleVersion: String) { self.detectorId = detectorId self.ruleId = ruleId self.ruleVersion = ruleVersion } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.ruleId, name: "ruleId", parent: name, max: 64) try self.validate(self.ruleId, name: "ruleId", parent: name, min: 1) try self.validate(self.ruleId, name: "ruleId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, max: 5) try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, min: 1) try self.validate(self.ruleVersion, name: "ruleVersion", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case detectorId case ruleId case ruleVersion } } public struct RuleDetail: AWSDecodableShape { /// The rule ARN. public let arn: String? /// The timestamp of when the rule was created. public let createdTime: String? /// The rule description. public let description: String? /// The detector for which the rule is associated. public let detectorId: String? /// The rule expression. public let expression: String? /// The rule language. public let language: Language? /// Timestamp of the last time the rule was updated. public let lastUpdatedTime: String? /// The rule outcomes. public let outcomes: [String]? /// The rule ID. public let ruleId: String? /// The rule version. public let ruleVersion: String? public init(arn: String? = nil, createdTime: String? = nil, description: String? = nil, detectorId: String? = nil, expression: String? = nil, language: Language? = nil, lastUpdatedTime: String? = nil, outcomes: [String]? = nil, ruleId: String? = nil, ruleVersion: String? = nil) { self.arn = arn self.createdTime = createdTime self.description = description self.detectorId = detectorId self.expression = expression self.language = language self.lastUpdatedTime = lastUpdatedTime self.outcomes = outcomes self.ruleId = ruleId self.ruleVersion = ruleVersion } private enum CodingKeys: String, CodingKey { case arn case createdTime case description case detectorId case expression case language case lastUpdatedTime case outcomes case ruleId case ruleVersion } } public struct RuleResult: AWSDecodableShape { /// The outcomes of the matched rule, based on the rule execution mode. public let outcomes: [String]? /// The rule ID that was matched, based on the rule execution mode. public let ruleId: String? public init(outcomes: [String]? = nil, ruleId: String? = nil) { self.outcomes = outcomes self.ruleId = ruleId } private enum CodingKeys: String, CodingKey { case outcomes case ruleId } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// A tag key. public let key: String /// A value assigned to a tag key. public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try self.validate(self.key, name: "key", parent: name, max: 128) try self.validate(self.key, name: "key", parent: name, min: 1) try self.validate(self.key, name: "key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") try self.validate(self.value, name: "value", parent: name, max: 256) try self.validate(self.value, name: "value", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case key case value } } public struct TagResourceRequest: AWSEncodableShape { /// The resource ARN. public let resourceARN: String /// The tags to assign to the resource. public let tags: [Tag] public init(resourceARN: String, tags: [Tag]) { self.resourceARN = resourceARN self.tags = tags } public func validate(name: String) throws { try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 256) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) try self.validate(self.resourceARN, name: "resourceARN", parent: name, pattern: "^arn\\:aws[a-z-]{0,15}\\:frauddetector\\:[a-z0-9-]{3,20}\\:[0-9]{12}\\:[^\\s]{2,128}$") try self.tags.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case resourceARN case tags } } public struct TagResourceResult: AWSDecodableShape { public init() {} } public struct TrainingDataSchema: AWSEncodableShape & AWSDecodableShape { public let labelSchema: LabelSchema /// The training data schema variables. public let modelVariables: [String] public init(labelSchema: LabelSchema, modelVariables: [String]) { self.labelSchema = labelSchema self.modelVariables = modelVariables } private enum CodingKeys: String, CodingKey { case labelSchema case modelVariables } } public struct TrainingMetrics: AWSDecodableShape { /// The area under the curve. This summarizes true positive rate (TPR) and false positive rate (FPR) across all possible model score thresholds. A model with no predictive power has an AUC of 0.5, whereas a perfect model has a score of 1.0. public let auc: Float? /// The data points details. public let metricDataPoints: [MetricDataPoint]? public init(auc: Float? = nil, metricDataPoints: [MetricDataPoint]? = nil) { self.auc = auc self.metricDataPoints = metricDataPoints } private enum CodingKeys: String, CodingKey { case auc case metricDataPoints } } public struct TrainingResult: AWSDecodableShape { /// The validation metrics. public let dataValidationMetrics: DataValidationMetrics? /// The training metric details. public let trainingMetrics: TrainingMetrics? public init(dataValidationMetrics: DataValidationMetrics? = nil, trainingMetrics: TrainingMetrics? = nil) { self.dataValidationMetrics = dataValidationMetrics self.trainingMetrics = trainingMetrics } private enum CodingKeys: String, CodingKey { case dataValidationMetrics case trainingMetrics } } public struct UntagResourceRequest: AWSEncodableShape { /// The ARN of the resource from which to remove the tag. public let resourceARN: String /// The resource ARN. public let tagKeys: [String] public init(resourceARN: String, tagKeys: [String]) { self.resourceARN = resourceARN self.tagKeys = tagKeys } public func validate(name: String) throws { try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 256) try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1) try self.validate(self.resourceARN, name: "resourceARN", parent: name, pattern: "^arn\\:aws[a-z-]{0,15}\\:frauddetector\\:[a-z0-9-]{3,20}\\:[0-9]{12}\\:[^\\s]{2,128}$") try self.tagKeys.forEach { try validate($0, name: "tagKeys[]", parent: name, max: 128) try validate($0, name: "tagKeys[]", parent: name, min: 1) try validate($0, name: "tagKeys[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$") } try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 50) try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case resourceARN case tagKeys } } public struct UntagResourceResult: AWSDecodableShape { public init() {} } public struct UpdateDetectorVersionMetadataRequest: AWSEncodableShape { /// The description. public let description: String /// The detector ID. public let detectorId: String /// The detector version ID. public let detectorVersionId: String public init(description: String, detectorId: String, detectorVersionId: String) { self.description = description self.detectorId = detectorId self.detectorVersionId = detectorVersionId } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case description case detectorId case detectorVersionId } } public struct UpdateDetectorVersionMetadataResult: AWSDecodableShape { public init() {} } public struct UpdateDetectorVersionRequest: AWSEncodableShape { /// The detector version description. public let description: String? /// The parent detector ID for the detector version you want to update. public let detectorId: String /// The detector version ID. public let detectorVersionId: String /// The Amazon SageMaker model endpoints to include in the detector version. public let externalModelEndpoints: [String] /// The model versions to include in the detector version. public let modelVersions: [ModelVersion]? /// The rule execution mode to add to the detector. If you specify FIRST_MATCHED, Amazon Fraud Detector evaluates rules sequentially, first to last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. If you specifiy ALL_MATCHED, Amazon Fraud Detector evaluates all rules and returns the outcomes for all matched rules. You can define and edit the rule mode at the detector version level, when it is in draft status. The default behavior is FIRST_MATCHED. public let ruleExecutionMode: RuleExecutionMode? /// The rules to include in the detector version. public let rules: [Rule] public init(description: String? = nil, detectorId: String, detectorVersionId: String, externalModelEndpoints: [String], modelVersions: [ModelVersion]? = nil, ruleExecutionMode: RuleExecutionMode? = nil, rules: [Rule]) { self.description = description self.detectorId = detectorId self.detectorVersionId = detectorVersionId self.externalModelEndpoints = externalModelEndpoints self.modelVersions = modelVersions self.ruleExecutionMode = ruleExecutionMode self.rules = rules } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") try self.modelVersions?.forEach { try $0.validate(name: "\(name).modelVersions[]") } try self.rules.forEach { try $0.validate(name: "\(name).rules[]") } } private enum CodingKeys: String, CodingKey { case description case detectorId case detectorVersionId case externalModelEndpoints case modelVersions case ruleExecutionMode case rules } } public struct UpdateDetectorVersionResult: AWSDecodableShape { public init() {} } public struct UpdateDetectorVersionStatusRequest: AWSEncodableShape { /// The detector ID. public let detectorId: String /// The detector version ID. public let detectorVersionId: String /// The new status. public let status: DetectorVersionStatus public init(detectorId: String, detectorVersionId: String, status: DetectorVersionStatus) { self.detectorId = detectorId self.detectorVersionId = detectorVersionId self.status = status } public func validate(name: String) throws { try self.validate(self.detectorId, name: "detectorId", parent: name, max: 64) try self.validate(self.detectorId, name: "detectorId", parent: name, min: 1) try self.validate(self.detectorId, name: "detectorId", parent: name, pattern: "^[0-9a-z_-]+$") try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, max: 5) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, min: 1) try self.validate(self.detectorVersionId, name: "detectorVersionId", parent: name, pattern: "^([1-9][0-9]*)$") } private enum CodingKeys: String, CodingKey { case detectorId case detectorVersionId case status } } public struct UpdateDetectorVersionStatusResult: AWSDecodableShape { public init() {} } public struct UpdateModelRequest: AWSEncodableShape { /// The new model description. public let description: String? /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum public init(description: String? = nil, modelId: String, modelType: ModelTypeEnum) { self.description = description self.modelId = modelId self.modelType = modelType } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") } private enum CodingKeys: String, CodingKey { case description case modelId case modelType } } public struct UpdateModelResult: AWSDecodableShape { public init() {} } public struct UpdateModelVersionRequest: AWSEncodableShape { /// The event details. public let externalEventsDetail: ExternalEventsDetail? /// The major version number. public let majorVersionNumber: String /// The model ID. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// A collection of key and value pairs. public let tags: [Tag]? public init(externalEventsDetail: ExternalEventsDetail? = nil, majorVersionNumber: String, modelId: String, modelType: ModelTypeEnum, tags: [Tag]? = nil) { self.externalEventsDetail = externalEventsDetail self.majorVersionNumber = majorVersionNumber self.modelId = modelId self.modelType = modelType self.tags = tags } public func validate(name: String) throws { try self.externalEventsDetail?.validate(name: "\(name).externalEventsDetail") try self.validate(self.majorVersionNumber, name: "majorVersionNumber", parent: name, max: 5) try self.validate(self.majorVersionNumber, name: "majorVersionNumber", parent: name, min: 1) try self.validate(self.majorVersionNumber, name: "majorVersionNumber", parent: name, pattern: "^([1-9][0-9]*)$") try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case externalEventsDetail case majorVersionNumber case modelId case modelType case tags } } public struct UpdateModelVersionResult: AWSDecodableShape { /// The model ID. public let modelId: String? /// The model type. public let modelType: ModelTypeEnum? /// The model version number of the model version updated. public let modelVersionNumber: String? /// The status of the updated model version. public let status: String? public init(modelId: String? = nil, modelType: ModelTypeEnum? = nil, modelVersionNumber: String? = nil, status: String? = nil) { self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.status = status } private enum CodingKeys: String, CodingKey { case modelId case modelType case modelVersionNumber case status } } public struct UpdateModelVersionStatusRequest: AWSEncodableShape { /// The model ID of the model version to update. public let modelId: String /// The model type. public let modelType: ModelTypeEnum /// The model version number. public let modelVersionNumber: String /// The model version status. public let status: ModelVersionStatus public init(modelId: String, modelType: ModelTypeEnum, modelVersionNumber: String, status: ModelVersionStatus) { self.modelId = modelId self.modelType = modelType self.modelVersionNumber = modelVersionNumber self.status = status } public func validate(name: String) throws { try self.validate(self.modelId, name: "modelId", parent: name, max: 64) try self.validate(self.modelId, name: "modelId", parent: name, min: 1) try self.validate(self.modelId, name: "modelId", parent: name, pattern: "^[0-9a-z_]+$") try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, max: 7) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, min: 3) try self.validate(self.modelVersionNumber, name: "modelVersionNumber", parent: name, pattern: "^[1-9][0-9]{0,3}\\.[0-9]{1,2}$") } private enum CodingKeys: String, CodingKey { case modelId case modelType case modelVersionNumber case status } } public struct UpdateModelVersionStatusResult: AWSDecodableShape { public init() {} } public struct UpdateRuleMetadataRequest: AWSEncodableShape { /// The rule description. public let description: String /// The rule to update. public let rule: Rule public init(description: String, rule: Rule) { self.description = description self.rule = rule } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.rule.validate(name: "\(name).rule") } private enum CodingKeys: String, CodingKey { case description case rule } } public struct UpdateRuleMetadataResult: AWSDecodableShape { public init() {} } public struct UpdateRuleVersionRequest: AWSEncodableShape { /// The description. public let description: String? /// The rule expression. public let expression: String /// The language. public let language: Language /// The outcomes. public let outcomes: [String] /// The rule to update. public let rule: Rule /// The tags to assign to the rule version. public let tags: [Tag]? public init(description: String? = nil, expression: String, language: Language, outcomes: [String], rule: Rule, tags: [Tag]? = nil) { self.description = description self.expression = expression self.language = language self.outcomes = outcomes self.rule = rule self.tags = tags } public func validate(name: String) throws { try self.validate(self.description, name: "description", parent: name, max: 128) try self.validate(self.description, name: "description", parent: name, min: 1) try self.validate(self.expression, name: "expression", parent: name, max: 4096) try self.validate(self.expression, name: "expression", parent: name, min: 1) try self.validate(self.outcomes, name: "outcomes", parent: name, min: 1) try self.rule.validate(name: "\(name).rule") try self.tags?.forEach { try $0.validate(name: "\(name).tags[]") } try self.validate(self.tags, name: "tags", parent: name, max: 200) try self.validate(self.tags, name: "tags", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case description case expression case language case outcomes case rule case tags } } public struct UpdateRuleVersionResult: AWSDecodableShape { /// The new rule version that was created. public let rule: Rule? public init(rule: Rule? = nil) { self.rule = rule } private enum CodingKeys: String, CodingKey { case rule } } public struct UpdateVariableRequest: AWSEncodableShape { /// The new default value of the variable. public let defaultValue: String? /// The new description. public let description: String? /// The name of the variable. public let name: String /// The variable type. For more information see Variable types. public let variableType: String? public init(defaultValue: String? = nil, description: String? = nil, name: String, variableType: String? = nil) { self.defaultValue = defaultValue self.description = description self.name = name self.variableType = variableType } private enum CodingKeys: String, CodingKey { case defaultValue case description case name case variableType } } public struct UpdateVariableResult: AWSDecodableShape { public init() {} } public struct Variable: AWSDecodableShape { /// The ARN of the variable. public let arn: String? /// The time when the variable was created. public let createdTime: String? /// The data source of the variable. public let dataSource: DataSource? /// The data type of the variable. For more information see Variable types. public let dataType: DataType? /// The default value of the variable. public let defaultValue: String? /// The description of the variable. public let description: String? /// The time when variable was last updated. public let lastUpdatedTime: String? /// The name of the variable. public let name: String? /// The variable type of the variable. Valid Values: AUTH_CODE | AVS | BILLING_ADDRESS_L1 | BILLING_ADDRESS_L2 | BILLING_CITY | BILLING_COUNTRY | BILLING_NAME | BILLING_PHONE | BILLING_STATE | BILLING_ZIP | CARD_BIN | CATEGORICAL | CURRENCY_CODE | EMAIL_ADDRESS | FINGERPRINT | FRAUD_LABEL | FREE_FORM_TEXT | IP_ADDRESS | NUMERIC | ORDER_ID | PAYMENT_TYPE | PHONE_NUMBER | PRICE | PRODUCT_CATEGORY | SHIPPING_ADDRESS_L1 | SHIPPING_ADDRESS_L2 | SHIPPING_CITY | SHIPPING_COUNTRY | SHIPPING_NAME | SHIPPING_PHONE | SHIPPING_STATE | SHIPPING_ZIP | USERAGENT public let variableType: String? public init(arn: String? = nil, createdTime: String? = nil, dataSource: DataSource? = nil, dataType: DataType? = nil, defaultValue: String? = nil, description: String? = nil, lastUpdatedTime: String? = nil, name: String? = nil, variableType: String? = nil) { self.arn = arn self.createdTime = createdTime self.dataSource = dataSource self.dataType = dataType self.defaultValue = defaultValue self.description = description self.lastUpdatedTime = lastUpdatedTime self.name = name self.variableType = variableType } private enum CodingKeys: String, CodingKey { case arn case createdTime case dataSource case dataType case defaultValue case description case lastUpdatedTime case name case variableType } } public struct VariableEntry: AWSEncodableShape { /// The data source of the variable. public let dataSource: String? /// The data type of the variable. public let dataType: String? /// The default value of the variable. public let defaultValue: String? /// The description of the variable. public let description: String? /// The name of the variable. public let name: String? /// The type of the variable. For more information see Variable types. Valid Values: AUTH_CODE | AVS | BILLING_ADDRESS_L1 | BILLING_ADDRESS_L2 | BILLING_CITY | BILLING_COUNTRY | BILLING_NAME | BILLING_PHONE | BILLING_STATE | BILLING_ZIP | CARD_BIN | CATEGORICAL | CURRENCY_CODE | EMAIL_ADDRESS | FINGERPRINT | FRAUD_LABEL | FREE_FORM_TEXT | IP_ADDRESS | NUMERIC | ORDER_ID | PAYMENT_TYPE | PHONE_NUMBER | PRICE | PRODUCT_CATEGORY | SHIPPING_ADDRESS_L1 | SHIPPING_ADDRESS_L2 | SHIPPING_CITY | SHIPPING_COUNTRY | SHIPPING_NAME | SHIPPING_PHONE | SHIPPING_STATE | SHIPPING_ZIP | USERAGENT public let variableType: String? public init(dataSource: String? = nil, dataType: String? = nil, defaultValue: String? = nil, description: String? = nil, name: String? = nil, variableType: String? = nil) { self.dataSource = dataSource self.dataType = dataType self.defaultValue = defaultValue self.description = description self.name = name self.variableType = variableType } private enum CodingKeys: String, CodingKey { case dataSource case dataType case defaultValue case description case name case variableType } } }
apache-2.0
e7a0366b763a98b2b08a059c38f9ca91
40.456336
593
0.612761
5.062177
false
false
false
false
SandcastleApps/partyup
PartyUP/NSURL+Mime.swift
1
634
// // NSURL+Mime.swift // MediaMonkey // // Created by Fritz Vander Heide on 2015-09-07. // Copyright © 2015 AppleTrek. All rights reserved. // import Foundation import MobileCoreServices extension NSURL { var mime: String { get{ var mime: String = "application/octet-stream" if let ext = self.pathExtension { if let cfUti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, nil) { if let cfMime = UTTypeCopyPreferredTagWithClass(cfUti.takeRetainedValue() as String, kUTTagClassMIMEType) { mime = cfMime.takeRetainedValue() as String } } } return mime } } }
mit
fd149d496731e7393831b2467776a521
21.607143
112
0.704581
3.745562
false
false
false
false
0x73/SwiftIconFont
SwiftIconFont/Classes/UIKit/SwiftIconFontView.swift
1
1841
// // SwiftIconFontView.swift // SwiftIconFont // // Created by Sedat Gökbek ÇİFTÇİ on 12/07/2017. // Copyright © 2017 Sedat Gökbek ÇİFTÇİ. All rights reserved. // import UIKit @IBDesignable public class SwiftIconFontView: UIView { @IBInspectable public var iconCode: String = "" { didSet { iconFont = GetFontTypeWithSelectedIcon(iconCode) let iconText = GetIconIndexWithSelectedIcon(iconCode) self.iconView.text = String.getIcon(from: iconFont, code: iconText) } } private var iconView = UILabel() private var iconFont = Fonts.fontAwesome5 override init(frame: CGRect) { super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } override public func prepareForInterfaceBuilder() { setupViews() } func setupViews() { iconFont = GetFontTypeWithSelectedIcon(iconCode) let iconText = GetIconIndexWithSelectedIcon(iconCode) self.iconView.textAlignment = NSTextAlignment.center self.iconView.text = String.getIcon(from: iconFont, code: iconText) self.iconView.textColor = self.tintColor self.addSubview(iconView) } override public func tintColorDidChange() { self.iconView.textColor = self.tintColor } override public func layoutSubviews() { super.layoutSubviews() self.clipsToBounds = true self.iconView.font = Font.icon(from: iconFont, ofSize: bounds.size.width < bounds.size.height ? bounds.size.width : bounds.size.height) self.iconView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: bounds.size.width, height: bounds.size.height)) } }
mit
36879fc100da1731dd3cfdbad3b93311
29.5
143
0.651913
4.430993
false
false
false
false
uasys/swift
test/SourceKit/Refactoring/semantic-refactoring/local-rename.swift
3
562
func foo() { var aa = 3 aa = aa + 1 return 1 } // RUN: rm -rf %t.result && mkdir -p %t.result // RUN: %sourcekitd-test -req=local-rename -pos=2:8 -name new_name %s -- %s > %t.result/local-rename.swift.expected // RUN: diff -u %S/local-rename.swift.expected %t.result/local-rename.swift.expected // RUN: %sourcekitd-test -req=find-local-rename-ranges -pos=2:8 %s -- %s > %t.result/local-rename-ranges.swift.expected // RUN: diff -u %S/local-rename-ranges.swift.expected %t.result/local-rename-ranges.swift.expected // REQUIRES-ANY: OS=macosx, OS=linux-gnu
apache-2.0
da98c5ff784209ca3eaccf30619b0989
42.307692
119
0.686833
2.741463
false
true
false
false
LinusLing/LNCodeSet
QuickLookDemo/QuickLookDemoFinal/QuickLookDemo/FileListViewController.swift
1
5603
// // FileListViewController.swift // QuickLookDemo // // Created by Gabriel Theodoropoulos on 3/28/16. // Copyright © 2016 Appcoda. All rights reserved. // import UIKit import QuickLook class FileListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, QLPreviewControllerDataSource, QLPreviewControllerDelegate { @IBOutlet weak var tblFileList: UITableView! let fileNames = ["AppCoda-PDF.pdf", "AppCoda-Pages.pages", "AppCoda-Word.docx", "AppCoda-Keynote.key", "AppCoda-Text.txt", "AppCoda-Image.jpeg"] var fileURLs = [NSURL]() let quickLookController = QLPreviewController() override func viewDidLoad() { super.viewDidLoad() prepareFileURLs() quickLookController.dataSource = self quickLookController.delegate = self configureTableView() navigationItem.title = "Quick Look Demo" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func prepareFileURLs() { for file in fileNames { let fileParts = file.componentsSeparatedByString(".") if let fileURL = NSBundle.mainBundle().URLForResource(fileParts[0], withExtension: fileParts[1]) { if NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) { fileURLs.append(fileURL) } } } } func extractAndBreakFilenameInComponents(fileURL: NSURL) -> (fileName: String, fileExtension: String) { // 将 NSURL 路径分割成零组件,然后创建一个数组将其放置其中 let fileURLParts = fileURL.path!.componentsSeparatedByString("/") // 从上面数组的最后一个元素中得到文件名 let fileName = fileURLParts.last // 将文件名基于符号 . 分割成不同的零组件,并放置在数组中返回 let filenameParts = fileName?.componentsSeparatedByString(".") // 返回最终的元组 return (filenameParts![0], filenameParts![1]) } // MARK: Custom Methods func configureTableView() { tblFileList.delegate = self tblFileList.dataSource = self tblFileList.registerNib(UINib(nibName: "FileListCell", bundle: nil), forCellReuseIdentifier: "idCellFile") tblFileList.reloadData() } func getFileTypeFromFileExtension(fileExtension: String) -> String { var fileType = "" switch fileExtension { case "docx": fileType = "Microsoft Word document" case "pages": fileType = "Pages document" case "jpeg": fileType = "Image document" case "key": fileType = "Keynote document" case "pdf": fileType = "PDF document" default: fileType = "Text document" } return fileType } // MARK: UITableView Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fileURLs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("idCellFile", forIndexPath: indexPath) let currentFileParts = extractAndBreakFilenameInComponents(fileURLs[indexPath.row]) cell.textLabel?.text = currentFileParts.fileName cell.detailTextLabel?.text = getFileTypeFromFileExtension(currentFileParts.fileExtension) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80.0 } // MARK: QLPreviewControllerDataSource func numberOfPreviewItemsInPreviewController(controller: QLPreviewController) -> Int { return fileURLs.count } func previewController(controller: QLPreviewController, previewItemAtIndex index: Int) -> QLPreviewItem { return fileURLs[index] } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if QLPreviewController.canPreviewItem(fileURLs[indexPath.row]) { quickLookController.currentPreviewItemIndex = indexPath.row navigationController?.pushViewController(quickLookController, animated: true) //presentViewController(quickLookController, animated: true, completion: nil) } } // MARK: QLPreviewControllerDelegate func previewControllerWillDismiss(controller: QLPreviewController) { print("The Preview Controller will be dismissed.") } func previewControllerDidDismiss(controller: QLPreviewController) { tblFileList.deselectRowAtIndexPath(tblFileList.indexPathForSelectedRow!, animated: true) print("The Preview Controller has been dismissed.") } func previewController(controller: QLPreviewController, shouldOpenURL url: NSURL, forPreviewItem item: QLPreviewItem) -> Bool { if item as! NSURL == fileURLs[0] { return true } else { print("Will not open URL \(url.absoluteString)") } return false } }
mit
80a660d844fa0d8ed64b368249bea126
31.058824
152
0.637431
5.712788
false
false
false
false
DashiDashCam/iOS-App
Dashi/Dashi/Models/Video.swift
1
12595
// // Video.swift // Dashi // // Created by Chris Henk on 1/25/18. // Copyright © 2018 Senior Design. All rights reserved. // import Foundation import AVKit import SwiftyJSON import Arcane import CoreLocation import MapKit import CoreData class Video { // Protected members var asset: AVURLAsset? var started: Date var length: Int var size: Int var thumbnail: UIImage! var id: String? var storageStat: String! // "cloud", "local", or "both" var startLat: CLLocationDegrees? var endLat: CLLocationDegrees? var startLong: CLLocationDegrees? var endLong: CLLocationDegrees? var uploadProgress: Int! var downloadProgress: Int! var uploadInProgress: Bool! var downloadInProgress: Bool! var locationName: String? var deleted: Bool! = false let appDelegate = UIApplication.shared.delegate as? AppDelegate var managedContext: NSManagedObjectContext /** * Initializes a Video object. Note that ID is initialized * from the SHA256 hash of the content of the video */ init(started: Date, asset: AVURLAsset, startLoc: CLLocationCoordinate2D?, endLoc: CLLocationCoordinate2D?) { managedContext = (appDelegate?.persistentContainer.viewContext)! do { // get the data associated with the video's content and convert it to a string let contentData = try Data(contentsOf: asset.url) let contentString = String(data: contentData, encoding: String.Encoding.ascii) length = Int(Float((asset.duration.value)) / Float((asset.duration.timescale))) size = contentData.count startLat = startLoc?.latitude startLong = startLoc?.longitude endLat = endLoc?.latitude endLong = endLoc?.longitude // hash the video content to produce an ID id = Hash.SHA256(contentString!) let imgGenerator = AVAssetImageGenerator(asset: asset) let cgImage = try! imgGenerator.copyCGImage(at: CMTimeMake(0, 6), actualTime: nil) // !! check the error before proceeding if UIDevice.current.orientation == .portrait { thumbnail = UIImage(cgImage: cgImage, scale: 1.0, orientation: .right) } else if UIDevice.current.orientation == .landscapeLeft { thumbnail = UIImage(cgImage: cgImage, scale: 1.0, orientation: .up) } else if UIDevice.current.orientation == .landscapeRight { thumbnail = UIImage(cgImage: cgImage, scale: 1.0, orientation: .down) } else if UIDevice.current.orientation == .portraitUpsideDown { thumbnail = UIImage(cgImage: cgImage, scale: 1.0, orientation: .left) } else { thumbnail = UIImage(cgImage: cgImage, scale: 1.0, orientation: .up) } } catch let error { print("Could not create video object. \(error)") self.length = -1 self.size = -1 } // initialize other instances variables self.asset = asset self.started = started } init(video: JSON) { managedContext = (appDelegate?.persistentContainer.viewContext)! id = video["id"].stringValue started = DateConv.toDate(timestamp: video["started"].stringValue) length = video["length"].intValue size = video["size"].intValue thumbnail = UIImage(data: Data(base64Encoded: video["thumbnail"].stringValue)!) startLat = video["startLat"].doubleValue startLong = video["startLong"].doubleValue endLat = video["endLat"].doubleValue endLong = video["endLong"].doubleValue } init(started: Date, imageData: Data, id: String, length: Int, size: Int, startLoc: CLLocationCoordinate2D?, endLoc: CLLocationCoordinate2D?, locationName: String? = "") { self.id = id self.started = started thumbnail = UIImage(data: imageData) self.length = length self.size = size startLat = startLoc?.latitude startLong = startLoc?.longitude endLat = endLoc?.latitude endLong = endLoc?.longitude managedContext = (appDelegate?.persistentContainer.viewContext)! if let name = locationName{ self.locationName = name } else{ if let _ = startLoc, let _ = endLoc{ setLocation() } } } public func getUploadProgress() -> Int { updateProgressFromCoreData() return uploadProgress } public func getDownloadProgress() -> Int { updateProgressFromCoreData() return downloadProgress } public func getUploadInProgress() -> Bool { updateProgressFromCoreData() return uploadInProgress } public func getDownloadInProgress() -> Bool { updateProgressFromCoreData() return downloadInProgress } public func getContent() -> Data? { do { return try Data(contentsOf: asset!.url) } catch let error { print("Could not get video content. \(error)") } return nil } public func getImageContent() -> Data? { return UIImageJPEGRepresentation(thumbnail, 0.5) } public func setAsset(asset: AVURLAsset) { self.asset = asset } public func getAsset() -> AVURLAsset { return asset! } public func getStarted() -> Date { return started } public func getLength() -> Int { return length } public func getSize() -> Int { return size } public func getId() -> String { return id! } public func getThumbnail() -> UIImage { return thumbnail } public func getStorageStat() -> String { getStorageStatFromCore() return storageStat! } public func setLocation(){ if let lat = endLat, let long = endLong{ let endLoc = CLLocation(latitude: lat, longitude: long) let geoCoder = CLGeocoder() geoCoder.reverseGeocodeLocation(endLoc) { placemarks, error in if let e = error { print(e) } else { let placeArray = placemarks as [CLPlacemark]! var placeMark: CLPlacemark! placeMark = placeArray![0] self.updateFieldViaCoreDB(key: "locationName", value: placeMark.locality!) DispatchQueue.main.async { self.locationName = placeMark.locality! } } } } } public func changeStorageToBoth() { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Videos") fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id!, (sharedAccount?.getId())!) var result: [NSManagedObject] = [] // 3 do { result = (try managedContext.fetch(fetchRequest)) } catch let error as NSError { print("Could not fetch. \(error), \(error.localizedDescription)") } let setting = result[0] setting.setValue("both", forKey: "storageStat") do { try managedContext.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } storageStat = "both" } public func getStartLat() -> CLLocationDegrees? { return startLat } public func getStartLong() -> CLLocationDegrees? { return startLong } public func getEndLat() -> CLLocationDegrees? { return endLat } public func getEndLong() -> CLLocationDegrees? { return endLong } public func getLocation() -> String{ if let loc = locationName{ return loc } else{ return "" } } public func wasDeleted() -> Bool { var content: [NSManagedObject] let managedContext = appDelegate?.persistentContainer.viewContext // 2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Videos") fetchRequest.propertiesToFetch = ["id"] fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id!, (sharedAccount?.getId())!) // 3 do { content = (try managedContext?.fetch(fetchRequest))! if(content.count > 0){ return false } } catch let error as Error { print("Could not fetch. \(error), \(error.localizedDescription)") } return true } func getStorageStatFromCore() { var content: [NSManagedObject] let managedContext = appDelegate?.persistentContainer.viewContext // 2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Videos") fetchRequest.propertiesToFetch = ["storageStat"] fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id!, (sharedAccount?.getId())!) // 3 do { content = (try managedContext?.fetch(fetchRequest))! storageStat = content[0].value(forKey: "storageStat") as! String // print(storageStat) } catch let error as Error { print("Could not fetch. \(error), \(error.localizedDescription)") } } // gets progress from core data func updateProgressFromCoreData() { var content: [NSManagedObject] let managedContext = appDelegate?.persistentContainer.viewContext // 2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Videos") fetchRequest.propertiesToFetch = ["uploadProgress", "downloadProgress", "uploadInProgress", "downloadInProgress"] fetchRequest.predicate = NSPredicate(format: "id == %@", id!) // 3 do { content = (try managedContext?.fetch(fetchRequest))! var uProg = content[0].value(forKey: "uploadProgress") as? Int if uProg == nil { uProg = 0 } var dProg = content[0].value(forKey: "downloadProgress") as? Int if dProg == nil { dProg = 0 } uploadProgress = uProg! downloadProgress = dProg! uploadInProgress = content[0].value(forKey: "uploadInProgress") as! Bool downloadInProgress = content[0].value(forKey: "downloadInProgress") as! Bool } catch let error as NSError { print("Could not fetch. \(error), \(error.localizedDescription)") } } // helper function for converting seconds to hours func secondsToHoursMinutesSeconds() -> (Int, Int, Int) { return (length / 3600, (length % 3600) / 60, (length % 3600) % 60) } func updateUploadProgress(progress: Int) { updateFieldViaCoreDB(key: "uploadProgress", value: progress) } func updateUploadInProgress(status: Bool) { updateFieldViaCoreDB(key: "uploadInProgress", value: status) } func updateDownloadProgress(progress: Int) { updateFieldViaCoreDB(key: "downloadProgress", value: progress) } func updateDownloadInProgress(status: Bool) { updateFieldViaCoreDB(key: "downloadInProgress", value: status) } private func updateFieldViaCoreDB(key: String, value: Any) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } // coredata context let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Videos") fetchRequest.predicate = NSPredicate(format: "id == %@ && accountID == %d", id!, (sharedAccount?.getId())!) var result: [NSManagedObject] = [] // 3 do { result = (try managedContext.fetch(fetchRequest)) } catch let error as NSError { print("Could not fetch. \(error), \(error.localizedDescription)") } let video = result[0] video.setValue(value, forKey: key) do { try managedContext.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } } }
mit
45ad064922cc7272c88eded1c30fe91b
31.375321
174
0.58647
5.138311
false
false
false
false
jegumhon/URWeatherView
URWeatherView/SpriteAssets/URWeatherScene.swift
1
29249
// // URWeatherScene.swift // URWeatherView // // Created by DongSoo Lee on 2017. 4. 24.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit /// weather type enumeration & each type's the setting options public enum URWeatherType: String { case snow = "MyParticleSnow.sks" case rain = "MyParticleRain.sks" case dust = "MyParticleDust.sks" case dust2 = "MyParticleDust2.sks" case lightning = "0" case hot = "1" case cloudy = "2" case shiny = "3" case comet = "MyParticleBurningComet.sks" case smoke = "MyParticleSmoke.sks" case none = "None" public static let all: [URWeatherType] = [.snow, .rain, .dust, .dust2, .lightning, .hot, .cloudy, .comet // .shiny, // .smoke ] public var name: String { switch self { case .snow: return "Snow" case .rain: return "Rain" case .dust: return "Dust" case .dust2: return "Dust2" case .lightning: return "Lightning" case .hot: return "Hot" case .cloudy: return "Cloudy" case .shiny: return "Shiny" case .comet: return "Comet" case .smoke: return "Smoke" default: return "" } } var ground: URWeatherGroundType { switch self { case .snow: return .snow case .rain: return .rain default: return .none } } public var imageFilterValues: [String: [CGPoint]]? { switch self { case .snow: let r: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.0875816794002757), CGPoint(x: 0.5, y: 0.202614339192708), CGPoint(x: 0.75, y: 0.571241850011489), CGPoint(x: 1.0, y: 1.0)] let g: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.206535967658548), CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0.75, y: 0.945098039215686), CGPoint(x: 1.0, y: 1.0)] let b: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.454902020622702), CGPoint(x: 0.5, y: 0.903268013748468), CGPoint(x: 0.75, y: 0.972549019607843), CGPoint(x: 1.0, y: 1.0)] return ["R": r, "G": g, "B": b ] case .hot: let r: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.281045771580116), CGPoint(x: 0.5, y: 0.596078431372549), CGPoint(x: 0.75, y: 0.920261457854626), CGPoint(x: 1.0, y: 1.0)] let g: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.25), CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0.75, y: 0.75), CGPoint(x: 1.0, y: 1.0)] let b: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.25), CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0.75, y: 0.75), CGPoint(x: 1.0, y: 1.0)] return ["R": r, "G": g, "B": b ] default: return nil } } public var imageFilterValuesSub: [String: [CGPoint]]? { switch self { case .snow: let r: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.20392160851971), CGPoint(x: 0.5, y: 0.377777757831648), CGPoint(x: 0.75, y: 0.670588235294118), CGPoint(x: 1.0, y: 1.0)] let g: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.277124183006536), CGPoint(x: 0.5, y: 0.5), CGPoint(x: 0.75, y: 0.81437908496732), CGPoint(x: 1.0, y: 1.0)] let b: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.25, y: 0.491503287919986), CGPoint(x: 0.5, y: 0.709803961460886), CGPoint(x: 0.75, y: 0.958169914694393), CGPoint(x: 1.0, y: 1.0)] return ["R": r, "G": g, "B": b ] default: return nil } } public var backgroundImage: UIImage? { let bundle = Bundle(for: URWeatherScene.self) switch self { case .dust: return UIImage(named: "yellowDust2", in: bundle, compatibleWith: nil)! case .dust2: return UIImage(named: "dustFrame", in: bundle, compatibleWith: nil)! case .lightning: return UIImage(named: "darkCloud_00000", in: bundle, compatibleWith: nil)! case .hot: return UIImage(named: "sunHot", in: bundle, compatibleWith: nil)! default: return nil } } public var backgroundImageOpacity: CGFloat { switch self { case .hot: return 0.85 default: return 1.0 } } public var startBirthRate: CGFloat? { switch self { case .dust: return 15.0 case .dust2: return 3.0 default: return nil } } public var defaultBirthRate: CGFloat { switch self { case .snow: return 40.0 case .rain: return 150.0 case .dust, .dust2, .smoke: return 200.0 case .cloudy: return 10.0 case .comet: return 455.0 default: return 50.0 } } public var maxBirthRate: CGFloat { switch self { case .snow: return 500.0 case .rain: return 1500.0 case .dust, .dust2: return 300.0 case .cloudy: return 30.0 default: return 300.0 } } } enum URWeatherGroundType: String { case snow = "MyParticleSnowGround.sks" case rain = "MyParticleRainGround.sks" case none = "None" var delayTime: TimeInterval { switch self { case .snow: return 2.0 case .rain: return 2.0 default: return 2.0 } } } public struct URWeatherGroundEmitterOption { var position: CGPoint var rangeRatio: CGFloat = 0.117 var angle: CGFloat public init(position: CGPoint, rangeRatio: CGFloat = 0.117, degree: CGFloat = -29.0) { self.position = position self.rangeRatio = rangeRatio self.angle = degree.degreesToRadians } public init(position: CGPoint, rangeRatio: CGFloat = 0.117, radian: CGFloat) { self.position = position self.rangeRatio = rangeRatio self.angle = radian } } public let URWeatherKeyCloudOption: String = "URWeatherCloudOption" public let URWeatherKeyLightningOption: String = "URWeatherLightningOption" open class URWeatherScene: SKScene, URNodeMovable { fileprivate var emitter: SKEmitterNode! fileprivate var subEmitter: SKEmitterNode! fileprivate var groundEmitter: SKEmitterNode! fileprivate var subGroundEmitters: [SKEmitterNode]! open var subGroundEmitterOptions: [URWeatherGroundEmitterOption]! { didSet { self.stopGroundEmitter() DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { self.startGroundEmitter() } } } private lazy var timers: [Timer] = [Timer]() open var weatherType: URWeatherType = .none var particleColor: UIColor! open var isGraphicsDebugOptionEnabled: Bool = false open var extraEffectBlock: ((UIImage?, CGFloat) -> Void)? var lastLocation: CGPoint = .zero { didSet { self.updateNodePosition() } } var touchedNode: SKNode! lazy var movableNodes: [SKNode] = [SKNode]() override public init(size: CGSize) { super.init(size: size) self.backgroundColor = UIColor.clear } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// switch the SpriteKit debug options open func enableDebugOptions(needToShow: Bool) { self.isGraphicsDebugOptionEnabled = needToShow guard self.emitter != nil else { return } self.view!.showsFPS = self.isGraphicsDebugOptionEnabled self.view!.showsNodeCount = self.isGraphicsDebugOptionEnabled self.view!.showsFields = self.isGraphicsDebugOptionEnabled self.view!.showsPhysics = self.isGraphicsDebugOptionEnabled self.view!.showsDrawCount = self.isGraphicsDebugOptionEnabled } /// setter of the particle birth rate open var birthRate: CGFloat = 0.0 { didSet { if self.emitter != nil { self.emitter.particleBirthRate = self.birthRate DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { if self.groundEmitter != nil { self.groundEmitter.particleBirthRate = self.birthRate / 2.0 } guard let _ = self.subGroundEmitters, self.subGroundEmitters.count > 0 else { return } for subGroundEmitter in self.subGroundEmitters { subGroundEmitter.particleBirthRate = self.birthRate / 13.0 } } } } } /// draw the lightnings func drawLightningEffect(isDirectionInvertable: Bool = false) { var lightningNode: UREffectLigthningNode var lightningNode2: UREffectLigthningNode if isDirectionInvertable { lightningNode = UREffectLigthningNode(frame: CGRect(origin: CGPoint(x: self.size.width * 0.34, y: self.size.height * 0.568), size: CGSize(width: self.size.width * 0.35, height: self.size.height * 0.432)), startPosition: UREffectLigthningPosition.topRight, targetPosition: UREffectLigthningPosition.bottomLeft) lightningNode2 = UREffectLigthningNode(frame: CGRect(origin: CGPoint(x: self.size.width * 0.34, y: self.size.height * 0.568), size: CGSize(width: self.size.width * 0.35, height: self.size.height * 0.432)), startPosition: UREffectLigthningPosition.topRight, targetPosition: UREffectLigthningPosition.bottomLeft) } else { lightningNode = UREffectLigthningNode(frame: CGRect(origin: CGPoint(x: self.size.width * 0.25, y: self.size.height * 0.600), size: CGSize(width: self.size.width * 0.39, height: self.size.height * 0.400)), startPosition: UREffectLigthningPosition.topLeft, targetPosition: UREffectLigthningPosition.bottomRight) lightningNode2 = UREffectLigthningNode(frame: CGRect(origin: CGPoint(x: self.size.width * 0.25, y: self.size.height * 0.600), size: CGSize(width: self.size.width * 0.39, height: self.size.height * 0.400)), startPosition: UREffectLigthningPosition.topLeft, targetPosition: UREffectLigthningPosition.bottomRight) } self.addChild(lightningNode) self.addChild(lightningNode2) lightningNode.startLightning() lightningNode2.startLightning() } open func makeLightningBackgroundEffect(imageView: UIImageView) -> [UIImage] { let cgImage = imageView.image!.cgImage! var rgb: [CGPoint] = [CGPoint(x: 0.0, y: 0.0), CGPoint(x: 0.311631917953491, y: 0.177777817670037), CGPoint(x: 0.512152751286825, y: 0.624836641199449), CGPoint(x: 0.730902751286825, y: 0.997385660807292), CGPoint(x: 1.0, y: 1.0)] let foreCGImage = URToneCurveFilter(cgImage: cgImage, with: rgb).outputCGImage! rgb = [CGPoint(x: 0.0998263756434123, y: 0.0), CGPoint(x: 0.467013875643412, y: 0.0549019607843138), CGPoint(x: 0.714409708976746, y: 0.159477144129136), CGPoint(x: 0.885416666666667, y: 0.355555575501685), CGPoint(x: 1.0, y: 0.661437928442862)] let backCGImage = URToneCurveFilter(cgImage: cgImage, with: rgb).outputCGImage! return [UIImage(cgImage: backCGImage), UIImage(cgImage: foreCGImage)] } /// draw clouds func drawCloudEffect(duration: TimeInterval, interval: TimeInterval = 0.0, index: Int) { var cloudNodes: [UREffectCloudNode] = [UREffectCloudNode]() let makeAction = SKAction.run { cloudNodes = UREffectCloudNode.makeClouds(maxCount: UInt32(self.birthRate), isRandomCountInMax: true, emittableAreaRatio: CGRect(x: -0.8, y: -0.2, width: 1.7, height: 0.3), on: self.view!, movingAngleInDegree: 30.0, movingDuration: duration) cloudNodes = cloudNodes.sorted(by: >) for cloudNode in cloudNodes { self.addChild(cloudNode) cloudNode.makeStreamingAction() } } let waitAction = SKAction.wait(forDuration: duration * 2.0) DispatchQueue.main.asyncAfter(deadline: .now() + interval) { self.run(SKAction.repeatForever(SKAction.sequence([makeAction, waitAction])), withKey: self.weatherType.name + "\(index)") } } /// draw clouds func drawCloudEffect(cloudOption option: UREffectCloudOption, interval: TimeInterval = 0.0, index: Int) { var cloudNodes: [UREffectCloudNode] = [UREffectCloudNode]() let makeAction = SKAction.run { cloudNodes = UREffectCloudNode.makeClouds(maxCount: UInt32(self.birthRate), isRandomCountInMax: true, cloudOption: option, on: self.view!) cloudNodes = cloudNodes.sorted(by: >) for cloudNode in cloudNodes { self.addChild(cloudNode) cloudNode.makeStreamingAction() } } let waitAction = SKAction.wait(forDuration: option.movingDuration * 2.0) DispatchQueue.main.asyncAfter(deadline: .now() + interval) { self.run(SKAction.repeatForever(SKAction.sequence([makeAction, waitAction])), withKey: self.weatherType.name + "\(index)") } } /// make the weather effect scene func makeScene(weather: URWeatherType = .shiny, duration: TimeInterval = 0.0, showTimes times: [Double]! = nil, userInfo: [String: UREffectOption]! = nil) { switch weather { case .lightning: var actions = [SKAction]() for (index, time) in times.enumerated() { var waiting: SKAction if index == 0 { waiting = SKAction.wait(forDuration: duration * time) } else { waiting = SKAction.wait(forDuration: duration * (time - times[index - 1])) } let drawLightning: SKAction = SKAction.run { self.drawLightningEffect(isDirectionInvertable: Double(index) >= (Double(times.count) / 2.0)) } actions.append(waiting) actions.append(drawLightning) if index == times.count - 1 { let waitingForFinish = SKAction.wait(forDuration: duration * (1.0 - time)) actions.append(waitingForFinish) } } self.run(SKAction.repeatForever(SKAction.sequence(actions)), withKey: weather.name) case .cloudy: // self.drawCloudEffect(duration: duration, interval: 0.0, index: 1) // self.drawCloudEffect(duration: duration, interval: duration + 0.5, index: 2) if let option = userInfo[URWeatherKeyCloudOption] as? UREffectCloudOption { self.drawCloudEffect(cloudOption: option, index: 1) self.drawCloudEffect(cloudOption: option, interval: option.movingDuration, index: 2) } default: break } } /// start the whole weather scene open func startScene(_ weather: URWeatherType = .snow, duration: TimeInterval = 0.0, showTimes times: [Double]! = nil, userInfo: [String: UREffectOption]! = nil) { self.weatherType = weather switch weather { case .lightning, .hot, .cloudy, .shiny: self.makeScene(weather: weather, duration: duration, showTimes: times, userInfo: userInfo) default: self.startEmitter(weather: weather) } guard let block = self.extraEffectBlock else { return } block(self.weatherType.backgroundImage, self.weatherType.backgroundImageOpacity) } /// start the particle effects by the weather type func startEmitter(weather: URWeatherType = .snow) { self.emitter = SKEmitterNode(fileNamed: weather.rawValue) var particlePositionRangeX: CGFloat = self.view!.bounds.width if self.weatherType == .rain { particlePositionRangeX *= 2.0 } switch self.weatherType { case .snow: if self.emitter == nil { self.emitter = URSnowEmitterNode() } self.emitter.particlePositionRange = CGVector(dx: particlePositionRangeX, dy: 0) self.emitter.position = CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.height) let timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(changeXAcceleration), userInfo: nil, repeats: true) self.timers.append(timer) case .rain: if self.emitter == nil { self.emitter = URRainEmitterNode() } self.emitter.particlePositionRange = CGVector(dx: particlePositionRangeX, dy: 0) self.emitter.position = CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.height) case .dust, .dust2: if self.emitter == nil { if self.weatherType == .dust { self.emitter = URDustEmitterNode() } else if self.weatherType == .dust2 { self.emitter = URDust2EmitterNode() } } if let startBirthRate = self.weatherType.startBirthRate { self.emitter.particleBirthRate = startBirthRate } self.emitter.particlePositionRange = CGVector(dx: particlePositionRangeX, dy: self.view!.bounds.height) self.emitter.position = CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.midY) let timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(changeXAcceleration), userInfo: nil, repeats: true) self.timers.append(timer) // self.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.2) case .comet: if self.emitter == nil { self.emitter = URBurningCometEmitterNode() } self.emitter.position = CGPoint(x: 0, y: self.view!.bounds.height) self.subEmitter = SKEmitterNode(fileNamed: weatherType.rawValue) if self.subEmitter == nil { self.subEmitter = URBurningCometEmitterNode() } self.subEmitter.position = CGPoint(x: self.view!.bounds.width, y: 0) self.subEmitter.emissionAngle = 330.0 * CGFloat.pi / 180.0 self.subEmitter.yAcceleration = -100 self.subEmitter.targetNode = self self.addChild(self.subEmitter) default: self.emitter.particlePositionRange = CGVector(dx: particlePositionRangeX, dy: 0) self.emitter.position = CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.height) } self.emitter.targetNode = self if self.particleColor != nil { self.emitter.particleColorSequence?.setKeyframeValue(self.particleColor, for: 0) } self.addChild(self.emitter) self.enableDebugOptions(needToShow: self.isGraphicsDebugOptionEnabled) DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { self.startGroundEmitter() } } @objc private func changeXAcceleration() { switch self.weatherType { case .snow: if self.emitter.particleBirthRate <= 40.0 { if self.emitter.xAcceleration == -3 { self.emitter.xAcceleration = 3 } else { self.emitter.xAcceleration = -3 } } else { self.emitter.xAcceleration = 0 } case .dust, .dust2: if self.emitter.yAcceleration == -10 { self.emitter.yAcceleration = 10 } else { self.emitter.yAcceleration = -10 } default: break } } /// start the particle effect around ground func startGroundEmitter() { switch self.weatherType { case .snow: self.subGroundEmitters = [SKEmitterNode]() for i in 0 ..< self.subGroundEmitterOptions.count { let subGroundEmitter = URSnowGroundEmitterNode() subGroundEmitter.particlePositionRange = CGVector(dx: self.size.width * self.subGroundEmitterOptions[i].rangeRatio, dy: subGroundEmitter.particlePositionRange.dy) subGroundEmitter.position = self.subGroundEmitterOptions[i].position subGroundEmitter.targetNode = self subGroundEmitter.particleBirthRate = self.emitter.particleBirthRate / 13.0 subGroundEmitter.zRotation = CGFloat(30.0).degreesToRadians subGroundEmitter.numParticlesToEmit = 0 self.insertChild(subGroundEmitter, at: 0) subGroundEmitter.run(SKAction.rotate(toAngle: self.subGroundEmitterOptions[i].angle, duration: 0.0)) self.subGroundEmitters.insert(subGroundEmitter, at: 0) } case .rain: self.groundEmitter = URRainGroundEmitterNode() self.groundEmitter.particleScaleRange = 0.2 self.subGroundEmitters = [SKEmitterNode]() for i in 0 ..< self.subGroundEmitterOptions.count { let subGroundEmitter = URRainGroundEmitterNode() subGroundEmitter.particlePositionRange = CGVector(dx: self.size.width * self.subGroundEmitterOptions[i].rangeRatio, dy: 7.5) subGroundEmitter.position = self.subGroundEmitterOptions[i].position subGroundEmitter.targetNode = self subGroundEmitter.particleBirthRate = self.emitter.particleBirthRate / 13.0 self.insertChild(subGroundEmitter, at: 0) subGroundEmitter.run(SKAction.rotate(toAngle: self.subGroundEmitterOptions[i].angle, duration: 0.0)) self.subGroundEmitters.insert(subGroundEmitter, at: 0) } default: self.groundEmitter = nil self.subGroundEmitters = nil } guard self.groundEmitter != nil else { return } self.groundEmitter.particlePositionRange = CGVector(dx: self.view!.bounds.width, dy: 0) self.groundEmitter.position = CGPoint(x: self.view!.bounds.midX, y: 5) self.groundEmitter.targetNode = self self.groundEmitter.particleBirthRate = self.emitter.particleBirthRate / 2.0 self.insertChild(self.groundEmitter, at: 0) } /// remove the whole scene open func stopScene() { self.weatherType = .none self.particleColor = nil for weather in URWeatherType.all { self.removeAction(forKey: weather.name) if weather == .cloudy { self.removeAction(forKey: weather.name + "1") self.removeAction(forKey: weather.name + "2") self.removeAllActions() } } for subNode in self.children { subNode.removeFromParent() } guard let _ = self.emitter else { return } self.emitter.particleBirthRate = 0.0 self.emitter.targetNode = nil self.emitter = nil self.enableDebugOptions(needToShow: false) self.stopGroundEmitter() for timer in self.timers { timer.invalidate() } self.backgroundColor = .clear } /// remove the particle effects around ground func stopGroundEmitter() { if self.groundEmitter != nil { self.groundEmitter.particleBirthRate = 0.0 self.groundEmitter.targetNode = nil self.groundEmitter.removeFromParent() self.groundEmitter = nil } guard self.subGroundEmitters != nil else { return } for subGroundEmitter in self.subGroundEmitters { subGroundEmitter.particleBirthRate = 0.0 subGroundEmitter.targetNode = nil subGroundEmitter.removeFromParent() } self.subGroundEmitters.removeAll() self.subGroundEmitters = nil } } extension URWeatherScene { override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if self.weatherType == .cloudy { self.handleTouch(touches) } } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if self.weatherType == .cloudy { self.handleTouch(touches) } } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if self.weatherType == .cloudy { self.handleTouch(touches, isEnded: true) } else if self.weatherType == .comet { if let _ = self.emitter.parent { } else { self.addChild(self.emitter) } if let _ = self.subEmitter.parent { } else { self.addChild(self.subEmitter) } let moveAction: SKAction = SKAction.move(to: CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.midY), duration: 0.5) let action: SKAction = SKAction.customAction(withDuration: 0.5, actionBlock: { (node, elapsedTime) in if node === self.emitter { self.emitter.particlePositionRange = CGVector(dx: 100.0, dy: self.emitter.particlePositionRange.dy * 2.0) self.emitter.emissionAngle = 90.0 * CGFloat.pi / 180.0 } }) let backAction: SKAction = SKAction.move(to: CGPoint(x: 0, y: self.view!.bounds.height), duration: 0.0) let initAction: SKAction = SKAction.customAction(withDuration: 0.0, actionBlock: { (node, elapsedTime) in if node === self.emitter { self.emitter.particlePositionRange = CGVector(dx: 5.0, dy: 5.0) self.emitter.emissionAngle = 150.0 * CGFloat.pi / 180.0 } }) self.emitter.run(SKAction.sequence([moveAction, action, backAction, initAction])) let move1Action: SKAction = SKAction.move(to: CGPoint(x: self.view!.bounds.midX, y: self.view!.bounds.midY), duration: 0.5) let action1: SKAction = SKAction.customAction(withDuration: 0.5, actionBlock: { (node, elapsedTime) in if node === self.emitter { self.emitter.particlePositionRange = CGVector(dx: 100.0, dy: self.emitter.particlePositionRange.dy * 2.0) self.emitter.emissionAngle = 270.0 * CGFloat.pi / 180.0 } }) let back1Action: SKAction = SKAction.move(to: CGPoint(x: self.view!.bounds.width, y: 0), duration: 0.0) self.subEmitter.run(SKAction.sequence([move1Action, action1, back1Action])) } } }
mit
7ac105ddd2a331dc3a49f588f37297bb
38.575101
253
0.550981
4.594815
false
false
false
false
zjjzmw1/speedxSwift
speedxSwift/Pods/RealmSwift/RealmSwift/Results.swift
3
19000
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: MinMaxType /// Types which can be used for min()/max(). public protocol MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /// Types which can be used for average()/sum(). public protocol AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /// :nodoc: /// Internal class. Do not use directly. public class ResultsBase: NSObject, NSFastEnumeration { internal let rlmResults: RLMResults /// Returns a human-readable description of the objects contained in these results. public override var description: String { let type = "Results<\(rlmResults.objectClassName)>" return gsub("RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type } // MARK: Initializers internal init(_ rlmResults: RLMResults) { self.rlmResults = rlmResults } // MARK: Fast Enumeration public func countByEnumeratingWithState(state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { return Int(rlmResults.countByEnumeratingWithState(state, objects: buffer, count: UInt(len))) } } /** Results is an auto-updating container type in Realm returned from object queries. Results can be queried with the same predicates as `List<T>` and you can chain queries to further filter query results. Results always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. Results are initially lazily evaluated, and only run queries when the result of the query is requested. This means that chaining several temporary Results to sort and filter your data does not perform any extra work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results cannot be created directly. */ public final class Results<T: Object>: ResultsBase { /// Element type contained in this collection. public typealias Element = T // MARK: Properties /// Returns the Realm these results are associated with. /// Despite returning an `Optional<Realm>` in order to conform to /// `RealmCollectionType`, it will always return `.Some()` since a `Results` /// cannot exist independently from a `Realm`. public var realm: Realm? { return Realm(rlmResults.realm) } /// Returns the number of objects in these results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal override init(_ rlmResults: RLMResults) { super.init(rlmResults) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the results. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the results. */ public func indexOf(object: T) -> Int? { return notFoundToNil(rlmResults.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return notFoundToNil(rlmResults.indexOfObjectWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return unsafeBitCast(rlmResults[UInt(index)], T.self) } } /// Returns the first object in the results, or `nil` if empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), Optional<T>.self) } /// Returns the last object in the results, or `nil` if empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), Optional<T>.self) } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return rlmResults.valueForKey(key) } /** Returns an Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. - parameter keyPath: The key path to the property. - returns: Array containing the results of invoking `valueForKeyPath(_:)` using keyPath on each of the collection's objects. */ public override func valueForKeyPath(keyPath: String) -> AnyObject? { return rlmResults.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return rlmResults.setValue(value, forKey: key) } // MARK: Filtering /** Filters the results to the objects that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: Results containing objects that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Filters the results to the objects that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: Results containing objects that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` with elements sorted by the given property name. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` with elements sorted by the given property name. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(rlmResults.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the Results, or `nil` if the Results is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return rlmResults.minOfProperty(property) as! U? } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the Results, or `nil` if the Results is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return rlmResults.maxOfProperty(property) as! U? } /** Returns the sum of the given property for objects in the Results. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the Results. */ public func sum<U: AddableType>(property: String) -> U { return rlmResults.sumOfProperty(property) as AnyObject as! U } /** Returns the average of the given property for objects in the Results. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the Results, or `nil` if the Results is empty. */ public func average<U: AddableType>(property: String) -> U? { return rlmResults.averageOfProperty(property) as! U? } // MARK: Notifications /** Register a block to be called each time the Results changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the results, or which objects are in the results. If an error occurs the block will be called with `nil` for the results parameter and a non-`nil` error. Currently the only errors that can occur are when opening the Realm on the background worker thread fails. At the time when the block is called, the Results object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call realm.refresh(), accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial results. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. let results = realm.objects(Dog) print("dogs.count: \(results?.count)") // => 0 let token = results.addNotificationBlock { (dogs, error) in // Only fired once for the example print("dogs.count: \(dogs?.count)") // will only print "dogs.count: 1" } try! realm.write { realm.add(Dog.self, value: ["name": "Rex", "age": 7]) } // end of runloop execution context You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call stop() on the token. - warning: This method cannot be called during a write transaction, or when the source realm is read-only. - parameter block: The block to be called with the evaluated results. - returns: A token which must be held for as long as you want query results to be delivered. */ @available(*, deprecated=1, message="Use addNotificationBlock with changes") @warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock") public func addNotificationBlock(block: (results: Results<T>?, error: NSError?) -> ()) -> NotificationToken { return rlmResults.addNotificationBlock { results, changes, error in if results != nil { block(results: self, error: nil) } else { block(results: nil, error: error) } } } /** Register a block to be called each time the Results changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the results, or which objects are in the results. This version of this method reports which of the objects in the results were added, removed, or modified in each write transaction as indices within the results. See the RealmCollectionChange documentation for more information on the change information supplied and an example of how to use it to update a UITableView. At the time when the block is called, the Results object will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call realm.refresh(), accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial results. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. let dogs = realm.objects(Dog) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { (changes: RealmCollectionChange) in switch changes { case .Initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .Update: // Will not be hit in this example break case .Error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call stop() on the token. - warning: This method cannot be called during a write transaction, or when the source realm is read-only. - parameter block: The block to be called with the evaluated results and change information. - returns: A token which must be held for as long as you want query results to be delivered. */ @warn_unused_result(message="You must hold on to the NotificationToken returned from addNotificationBlock") public func addNotificationBlock(block: (RealmCollectionChange<Results> -> Void)) -> NotificationToken { return rlmResults.addNotificationBlock { results, change, error in block(RealmCollectionChange.fromObjc(self, change: change, error: error)) } } } extension Results: RealmCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the results. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } /// :nodoc: public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(anyCollection, change: change, error: error)) } } }
mit
2e9e7a858ae896d97b66faaf07f8c365
38.915966
120
0.681632
4.976427
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/SpecializedTextInput/BankCardHolderName/BankCardHolderNameUtils.swift
1
5317
// // BankCardHolderNameUtils.swift // TextInputKit // // Created by Artem Starosvetskiy on 15/12/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Foundation struct BankCardHolderNameUtils { private init() {} static let allowedLetterCharacters: CharacterSet = { let latinUppercaseLetters = CharacterSet(charactersIn: UnicodeScalar("A")...UnicodeScalar("Z")) let fullwidthLatinUppercaseLetters = CharacterSet(charactersIn: UnicodeScalar("A")...UnicodeScalar("Z")) return latinUppercaseLetters .union(fullwidthLatinUppercaseLetters) }() static let allowedNonLetterCharacters = CharacterSet(charactersIn: "-. ") static let deniedCharacters: CharacterSet = { return allowedLetterCharacters .union(allowedNonLetterCharacters) .inverted }() } extension BankCardHolderNameUtils { static func stringViewAndIndexAfterFilteringPunctuation( in stringView: String.UnicodeScalarView, withIndex index: String.UnicodeScalarIndex ) -> (String.UnicodeScalarView, String.UnicodeScalarIndex) { var filter = PunctuationFilter(stringView, index) filter.filter() return (filter.resultingStringView, filter.resultingIndex) } private struct PunctuationFilter { private(set) var resultingStringView: String.UnicodeScalarView private(set) var resultingIndex: String.UnicodeScalarIndex init(_ stringView: String.UnicodeScalarView, _ index: String.UnicodeScalarIndex) { self.originalStringView = stringView self.originalIndex = index self.index = stringView.startIndex self.resultingStringView = "".unicodeScalars self.resultingIndex = resultingStringView.endIndex resultingStringView.reserveCapacity(stringView.count) } mutating func filter() { assert(index == originalStringView.startIndex) assert((originalIndex >= originalStringView.startIndex) && (originalIndex <= originalStringView.endIndex)) if index == originalStringView.endIndex { return } skipAnyNonLetterCharacters() while index != originalStringView.endIndex { appendLetterCharacters() if index == originalStringView.endIndex { break } appendAllowedNonLetterCharacterSequence() if index == originalStringView.endIndex { break } skipAnyNonLetterCharacters() } resultingIndex = resultingStringView.index(resultingStringView.startIndex, offsetBy: resultingIndexOffset!) } private typealias Utils = BankCardHolderNameUtils private let originalStringView: String.UnicodeScalarView private let originalIndex: String.UnicodeScalarIndex private var index: String.UnicodeScalarIndex private var resultingIndexOffset: Int? private mutating func skipAnyNonLetterCharacters() { assert(index != originalStringView.endIndex) while (index != originalStringView.endIndex) && !Utils.isLetter(originalStringView[index]) { index = originalStringView.index(after: index) } if (resultingIndexOffset == nil) && (originalIndex <= index) { resultingIndexOffset = resultingStringView.count } } private mutating func appendLetterCharacters() { assert(index != originalStringView.endIndex) assert(Utils.isLetter(originalStringView[index])) repeat { appendCharacter() } while (index != originalStringView.endIndex) && Utils.isLetter(originalStringView[index]) if (resultingIndexOffset == nil) && (originalIndex <= index) { resultingIndexOffset = resultingStringView.count - originalStringView.distance(from: originalIndex, to: index) } } private mutating func appendAllowedNonLetterCharacterSequence() { assert(index != originalStringView.endIndex) assert(!Utils.isLetter(originalStringView[index])) // Copy " ", ". ", "- ". let firstNonLetterCharacter = originalStringView[index] appendCharacter() if (index != originalStringView.endIndex) && (firstNonLetterCharacter != UnicodeScalar(" ")) && (originalStringView[index] == UnicodeScalar(" ")) { appendCharacter() } if (resultingIndexOffset == nil) && (originalIndex <= index) { resultingIndexOffset = resultingStringView.count - originalStringView.distance(from: originalIndex, to: index) } } private mutating func appendCharacter() { assert(index != originalStringView.endIndex) resultingStringView.append(originalStringView[index]) index = originalStringView.index(after: index) } } private static func isLetter(_ unicodeScalar: UnicodeScalar) -> Bool { return allowedLetterCharacters.contains(unicodeScalar) } }
mit
69162c434408d72b997fde12b3a160aa
33.947368
126
0.64119
6.155272
false
false
false
false
digipost/ios
Digipost/AccountViewController.swift
1
10467
// // Copyright (C) Posten Norge AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit class AccountViewController: UIViewController, UIActionSheetDelegate, UIPopoverPresentationControllerDelegate, UITableViewDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var logoutBarButtonItem: UIBarButtonItem! var logoutBarButtonVariable: UIBarButtonItem? var logoutButtonVariable: UIButton? var refreshControl: UIRefreshControl? var dataSource: AccountTableViewDataSource? override func viewDidLoad() { super.viewDidLoad() logoutBarButtonVariable = logoutBarButtonItem logoutButtonVariable = logoutButton if let firstVC: UIViewController = navigationController?.viewControllers[0] { if firstVC.navigationItem.rightBarButtonItem == nil { firstVC.navigationItem.setRightBarButton(logoutBarButtonItem, animated: false) } firstVC.navigationItem.leftBarButtonItem = nil firstVC.navigationItem.rightBarButtonItem = nil firstVC.navigationItem.titleView = nil } refreshControl = UIRefreshControl() refreshControl?.tintColor = UIColor.digipostGreyOne() refreshControl?.addTarget(self, action: #selector(AccountViewController.refreshContentFromServer), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) configureTableView() let appDelegate: SHCAppDelegate = UIApplication.shared.delegate as! SHCAppDelegate appDelegate.initGCM(); } func configureTableView() { // Configure Tableview tableView.register(UINib(nibName: Constants.Account.mainAccountCellNibName, bundle: Bundle.main), forCellReuseIdentifier: Constants.Account.mainAccountCellIdentifier) tableView.register(UINib(nibName: Constants.Account.accountCellNibName, bundle: Bundle.main), forCellReuseIdentifier: Constants.Account.accountCellIdentifier) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 160 tableView.separatorInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) tableView.layoutMargins = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) let tblView = UIView(frame: CGRect.zero) tableView.tableFooterView = tblView tableView.tableFooterView?.isHidden = true tableView.backgroundColor = UIColor.digipostAccountViewBackground() dataSource = AccountTableViewDataSource(asDataSourceForTableView: tableView) tableView.delegate = self } @objc func refreshContentFromServer() { updateContentsFromServerUseInitiateRequest(0) } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.interactivePopGestureRecognizer?.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil) self.navigationController?.isNavigationBarHidden = false let title = NSLocalizedString("Accounts title", comment: "Title for navbar at accounts view") navigationController?.navigationBar.topItem?.title = title logoutButtonVariable?.setTitle(NSLocalizedString("log out button title", comment: "Title for log out button"), for: UIControlState()) logoutButtonVariable?.setTitleColor(UIColor.digipostLogoutButtonTextColor(), for: UIControlState()) logoutBarButtonItem.accessibilityTraits = UIAccessibilityTraitButton if let showingItem: UINavigationItem = navigationController?.navigationBar.backItem { if showingItem.responds(to: #selector(setter: UINavigationItem.rightBarButtonItem)) { showingItem.setRightBarButton(logoutBarButtonVariable, animated: false) } showingItem.title = title } navigationItem.setHidesBackButton(true, animated: false) navigationController?.navigationBar.topItem?.setRightBarButton(logoutBarButtonItem, animated: false) if OAuthToken.isUserLoggedIn(){ updateContentsFromServerUseInitiateRequest(0) } else { userDidConfirmLogout() } } func updateContentsFromServerUseInitiateRequest(_ userDidInitiateRequest: Int) { APIClient.sharedClient.updateRootResource(success: { (responseDictionary) -> Void in POSModelManager.shared().updateRootResource(attributes: responseDictionary) if UIDevice.current.userInterfaceIdiom == .pad { self.configureTableView() } if let actualRefreshControl = self.refreshControl { actualRefreshControl.endRefreshing() } }) { (error) -> () in if(error.code == Constants.Error.Code.noOAuthTokenPresent.rawValue || error.code == Constants.Error.Code.oAuthUnathorized.rawValue){ self.userDidConfirmLogout() } if (userDidInitiateRequest == 1) { UIAlertController.presentAlertControllerWithAPIError(error, presentingViewController: self, didTapOkClosure: nil) } if let actualRefreshControl = self.refreshControl { actualRefreshControl.endRefreshing() } } } // MARK: - TableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell: UITableViewCell = tableView.cellForRow(at: indexPath)! cell.contentView.backgroundColor = UIColor.digipostAccountCellSelectBackground() performSegue(withIdentifier: "PushFolders", sender: self) } func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { let cell: UITableViewCell = tableView.cellForRow(at: indexPath)! cell.contentView.backgroundColor = UIColor.digipostAccountCellSelectBackground() } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.layoutMargins = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) cell.separatorInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PushFolders" { let mailbox: POSMailbox = dataSource?.managedObjectAtIndexPath(tableView.indexPathForSelectedRow!) as! POSMailbox let folderViewController: POSFoldersViewController = segue.destination as! POSFoldersViewController folderViewController.selectedMailBoxDigipostAdress = mailbox.digipostAddress POSModelManager.shared().selectedMailboxDigipostAddress = mailbox.digipostAddress tableView.deselectRow(at: tableView.indexPathForSelectedRow!, animated: true) } else if segue.identifier == "gotoDocumentsFromAccountsSegue" { let documentsView: POSDocumentsViewController = segue.destination as! POSDocumentsViewController let rootResource: POSRootResource = POSRootResource.existingRootResource(in: POSModelManager.shared().managedObjectContext) let nameDescriptor: NSSortDescriptor = NSSortDescriptor(key: "owner", ascending: true) let set = rootResource.mailboxes as NSSet let mailboxes = set.allObjects as NSArray mailboxes.sortedArray(using: [nameDescriptor]) let userMailbox: POSMailbox = mailboxes[0] as! POSMailbox documentsView.mailboxDigipostAddress = userMailbox.digipostAddress documentsView.folderName = kFolderInboxName } } // MARK: - Logout @IBAction func logoutButtonTapped(_ sender: UIButton) { logoutUser() } func logoutUser() { let logoutAlertController = UIAlertController(title: NSLocalizedString("FOLDERS_VIEW_CONTROLLER_LOGOUT_CONFIRMATION_TITLE", comment: "You sure you want to sign out?"), message: "", preferredStyle: UIAlertControllerStyle.actionSheet) logoutAlertController.addAction(UIAlertAction(title: NSLocalizedString("FOLDERS_VIEW_CONTROLLER_LOGOUT_TITLE", comment: "Sign out"), style: .destructive,handler: {(alert: UIAlertAction!) in self.userDidConfirmLogout() })) logoutAlertController.addAction(UIAlertAction(title: NSLocalizedString("GENERIC_CANCEL_BUTTON_TITLE", comment: "Cancel"), style: UIAlertActionStyle.cancel, handler: {(alert: UIAlertAction!) in })) logoutAlertController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem let popPresenter = logoutAlertController.popoverPresentationController popPresenter?.sourceView = self.view popPresenter?.barButtonItem = logoutBarButtonItem present(logoutAlertController, animated: true, completion: nil) } func userDidConfirmLogout() { let appDelegate: SHCAppDelegate = UIApplication.shared.delegate as! SHCAppDelegate appDelegate.revokeGCMToken(); if let letterViewController: POSLetterViewController = appDelegate.letterViewController { letterViewController.attachment = nil } dataSource?.stopListeningToCoreDataChanges() APIClient.sharedClient.logoutThenDeleteAllStoredData() appDelegate.showLoginView() } }
apache-2.0
55dd8157d21fcd94e02d39c39ac09342
45.727679
240
0.694564
5.811771
false
false
false
false
vinsalmont/Movie
Pods/Moya/Source/Plugins/NetworkLoggerPlugin.swift
1
4352
import Foundation import Result /// Logs network activity (outgoing requests and incoming responses). public final class NetworkLoggerPlugin: PluginType { fileprivate let loggerId = "Moya_Logger" fileprivate let dateFormatString = "dd/MM/yyyy HH:mm:ss" fileprivate let dateFormatter = DateFormatter() fileprivate let separator = ", " fileprivate let terminator = "\n" fileprivate let cURLTerminator = "\\\n" fileprivate let output: (_ seperator: String, _ terminator: String, _ items: Any...) -> Void fileprivate let responseDataFormatter: ((Data) -> (Data))? /// If true, also logs response body data. public let verbose: Bool public let cURL: Bool public init(verbose: Bool = false, cURL: Bool = false, output: @escaping (_ seperator: String, _ terminator: String, _ items: Any...) -> Void = NetworkLoggerPlugin.reversedPrint, responseDataFormatter: ((Data) -> (Data))? = nil) { self.cURL = cURL self.verbose = verbose self.output = output self.responseDataFormatter = responseDataFormatter } public func willSendRequest(_ request: RequestType, target: TargetType) { if let request = request as? CustomDebugStringConvertible, cURL { output(separator, terminator, request.debugDescription) return } outputItems(logNetworkRequest(request.request as URLRequest?)) } public func didReceiveResponse(_ result: Result<Moya.Response, Moya.Error>, target: TargetType) { if case .success(let response) = result { outputItems(logNetworkResponse(response.response, data: response.data, target: target)) } else { outputItems(logNetworkResponse(nil, data: nil, target: target)) } } fileprivate func outputItems(_ items: [String]) { if verbose { items.forEach { output(separator, terminator, $0) } } else { output(separator, terminator, items) } } } private extension NetworkLoggerPlugin { var date: String { dateFormatter.dateFormat = dateFormatString dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter.string(from: Date()) } func format(_ loggerId: String, date: String, identifier: String, message: String) -> String { return "\(loggerId): [\(date)] \(identifier): \(message)" } func logNetworkRequest(_ request: URLRequest?) -> [String] { var output = [String]() output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")] if let headers = request?.allHTTPHeaderFields { output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)] } if let bodyStream = request?.httpBodyStream { output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)] } if let httpMethod = request?.httpMethod { output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)] } if let body = request?.httpBody, verbose == true { if let stringOutput = String(data: body, encoding: .utf8) { output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)] } } return output } func logNetworkResponse(_ response: URLResponse?, data: Data?, target: TargetType) -> [String] { guard let response = response else { return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")] } var output = [String]() output += [format(loggerId, date: date, identifier: "Response", message: response.description)] if let data = data, verbose == true { if let stringData = String(data: responseDataFormatter?(data) ?? data, encoding: String.Encoding.utf8) { output += [stringData] } } return output } } fileprivate extension NetworkLoggerPlugin { static func reversedPrint(seperator: String, terminator: String, items: Any...) { print(items, separator: seperator, terminator: terminator) } }
apache-2.0
05cbf705830efd8a3c8b129ca78749c2
37.513274
234
0.639476
4.80884
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/SPopoverViewController.swift
1
5168
// // SPopoverViewController.swift // Telegram-Mac // // Created by keepcoder on 09/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit public struct SPopoverAdditionItemView { let context: Any? let view: NSView let updateIsSelected:((Bool)->Void)? public init(context: Any?, view: NSView, updateIsSelected:((Bool)->Void)? = nil) { self.context = context self.view = view self.updateIsSelected = updateIsSelected } } public struct SPopoverItem : Equatable { public let title:String let image:CGImage? let textColor: NSColor let height: CGFloat public let handler:()->Void let isSeparator: Bool let drawSeparatorBorder: Bool let additionView: SPopoverAdditionItemView? public init(_ title:String, _ handler:@escaping ()->Void, _ image:CGImage? = nil, _ textColor: NSColor = presentation.colors.text, height: CGFloat = 40.0, isSeparator: Bool = false, drawSeparatorBorder: Bool = true, additionView: SPopoverAdditionItemView? = nil) { self.title = title self.image = image self.textColor = textColor self.handler = handler self.height = height self.isSeparator = false self.additionView = additionView self.drawSeparatorBorder = drawSeparatorBorder } public init(_ drawSeparatorBorder: Bool = true) { self.title = "" self.image = nil self.textColor = presentation.colors.text self.handler = {} self.height = 10 self.isSeparator = true self.drawSeparatorBorder = drawSeparatorBorder self.additionView = nil } public static func ==(lhs: SPopoverItem, rhs: SPopoverItem) -> Bool { return lhs.title == rhs.title && lhs.textColor == rhs.textColor } } public class SPopoverViewController: GenericViewController<TableView> { private let items:[TableRowItem] private let disposable = MetaDisposable() public override func viewDidLoad() { super.viewDidLoad() genericView.insert(items: items) genericView.needUpdateVisibleAfterScroll = true genericView.reloadData() readyOnce() } public init(items:[SPopoverItem], visibility:Int = 4, handlerDelay: Double = 0.15, headerItems: [TableRowItem] = []) { weak var controller:SPopoverViewController? let alignAsImage = !items.filter({$0.image != nil}).isEmpty let items = items.map { item -> TableRowItem in if item.isSeparator { return SPopoverSeparatorItem(item.drawSeparatorBorder) } else { return SPopoverRowItem(NSZeroSize, height: item.height, image: item.image, alignAsImage: alignAsImage, title: item.title, textColor: item.textColor, additionView: item.additionView, clickHandler: { Queue.mainQueue().justDispatch { controller?.popover?.hide() if handlerDelay == 0 { item.handler() } else { _ = (Signal<Void, NoError>.single(Void()) |> delay(handlerDelay, queue: Queue.mainQueue())).start(next: { item.handler() }) } } }) } } let width: CGFloat = items.isEmpty ? 200 : items.compactMap({ $0 as? SPopoverRowItem }).max(by: {$0.itemWidth < $1.itemWidth})!.itemWidth for item in headerItems { _ = item.makeSize(width + 48 + 18) } self.items = headerItems + (headerItems.isEmpty ? [] : [SPopoverSeparatorItem(false)]) + items var height: CGFloat = 0 for (i, item) in self.items.enumerated() { if i < visibility { height += item.height } else { height += item.height / 2 break } } // let height = min(visibility * 40 + 20, items.count * 40) super.init(frame: NSMakeRect(0, 0, width + 45 + 18, CGFloat(height))) bar = .init(height: 0) controller = self } deinit { disposable.dispose() } public override func becomeFirstResponder() -> Bool? { return nil } public override func viewWillAppear(_ animated: Bool) { } } //public func presntContextMenu(for event: NSEvent, items: [SPopoverItem]) -> Void { // // // let controller = SPopoverViewController(items: items, visibility: Int.max, handlerDelay: 0) // // let window = Window(contentRect: NSMakeRect(event.locationInWindow.x, event.locationInWindow.y, controller.frame.width, controller.frame.height), styleMask: [], backing: .buffered, defer: true) // window.contentView = controller.view // window.backgroundColor = .clear // event.window?.addChildWindow(window, ordered: .above) // window.makeKeyAndOrderFront(nil) // //}
gpl-2.0
14fcf5666d9af430d84c9c7655ff9ca9
31.910828
268
0.587381
4.736022
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Modal/QModalViewController.swift
1
4173
// // Quickly // open class QModalViewController : QViewController, IQModalViewController { open private(set) var viewController: IQModalContentViewController open var presentAnimation: IQModalViewControllerFixedAnimation? open var dismissAnimation: IQModalViewControllerFixedAnimation? open var interactiveDismissAnimation: IQModalViewControllerInteractiveAnimation? public init( viewController: IQModalContentViewController, presentAnimation: IQModalViewControllerFixedAnimation? = nil, dismissAnimation: IQModalViewControllerFixedAnimation? = nil, interactiveDismissAnimation: IQModalViewControllerInteractiveAnimation? = nil ) { self.viewController = viewController self.presentAnimation = presentAnimation self.dismissAnimation = dismissAnimation self.interactiveDismissAnimation = interactiveDismissAnimation super.init() } open override func setup() { super.setup() self.viewController.parentViewController = self } open override func didLoad() { self.viewController.view.frame = self.view.bounds self.view.addSubview(self.viewController.view) } open override func layout(bounds: CGRect) { self.viewController.view.frame = bounds } open override func prepareInteractivePresent() { super.prepareInteractivePresent() self.viewController.prepareInteractivePresent() } open override func cancelInteractivePresent() { super.cancelInteractivePresent() self.viewController.cancelInteractivePresent() } open override func finishInteractivePresent() { super.finishInteractivePresent() self.viewController.finishInteractivePresent() } open override func willPresent(animated: Bool) { super.willPresent(animated: animated) self.viewController.willPresent(animated: animated) } open override func didPresent(animated: Bool) { super.didPresent(animated: animated) self.viewController.didPresent(animated: animated) } open override func prepareInteractiveDismiss() { super.prepareInteractiveDismiss() self.viewController.prepareInteractiveDismiss() } open override func cancelInteractiveDismiss() { super.cancelInteractiveDismiss() self.viewController.cancelInteractiveDismiss() } open override func finishInteractiveDismiss() { super.finishInteractiveDismiss() self.viewController.finishInteractiveDismiss() } open override func willDismiss(animated: Bool) { super.willDismiss(animated: animated) self.viewController.willDismiss(animated: animated) } open override func didDismiss(animated: Bool) { super.didDismiss(animated: animated) self.viewController.didDismiss(animated: animated) } open override func willTransition(size: CGSize) { super.willTransition(size: size) self.viewController.willTransition(size: size) } open override func didTransition(size: CGSize) { super.didTransition(size: size) self.viewController.didTransition(size: size) } open override func supportedOrientations() -> UIInterfaceOrientationMask { return self.viewController.supportedOrientations() } open override func preferedStatusBarHidden() -> Bool { return self.viewController.preferedStatusBarHidden() } open override func preferedStatusBarStyle() -> UIStatusBarStyle { return self.viewController.preferedStatusBarStyle() } open override func preferedStatusBarAnimation() -> UIStatusBarAnimation { return self.viewController.preferedStatusBarAnimation() } open func shouldInteractive() -> Bool { return self.viewController.modalShouldInteractive() } // MARK: IQContentOwnerViewController open func beginUpdateContent() { } open func updateContent() { } open func finishUpdateContent(velocity: CGPoint) -> CGPoint? { return nil } open func endUpdateContent() { } }
mit
2183306bb5e2343dfca21c4c51a65fb3
29.911111
85
0.708124
5.64682
false
false
false
false
tidepool-org/nutshell-ios
Nutshell/DataModel/CoreData/Upload.swift
1
968
// // Upload.swift // Nutshell // // Created by Brian King on 9/15/15. // Copyright © 2015 Tidepool. All rights reserved. // import Foundation import CoreData import SwiftyJSON class Upload: CommonData { override class func fromJSON(_ json: JSON, moc: NSManagedObjectContext) -> Upload? { if let entityDescription = NSEntityDescription.entity(forEntityName: "Upload", in: moc) { let me = Upload(entity: entityDescription, insertInto: nil) me.timezone = json["timezone"].string me.version = json["version"].string me.byUser = json["byUser"].string me.deviceTagsJSON = json["deviceTags"].string me.deviceManufacturersJSON = json["deviceManufacturers"].string me.deviceModel = json["deviceModel"].string me.deviceSerialNumber = json["deviceSerialNumber"].string return me } return nil } }
bsd-2-clause
35cfd32b8d598afab82b35c927c1afb3
30.193548
97
0.618407
4.787129
false
false
false
false
bazelbuild/tulsi
src/TulsiGenerator/BazelQueryInfoExtractor.swift
1
15116
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation // Provides methods utilizing Bazel query (http://bazel.build/docs/query.html) to extract // information from a workspace. final class BazelQueryInfoExtractor: QueuedLogging { enum ExtractorError: Error { /// A valid Bazel binary could not be located. case invalidBazelPath } /// The location of the bazel binary. var bazelURL: URL /// The location of the directory in which the workspace enclosing this BUILD file can be found. let workspaceRootURL: URL /// Universal flags for all Bazel invocations. private let bazelUniversalFlags: BazelFlags private let localizedMessageLogger: LocalizedMessageLogger private var queuedInfoMessages = [String]() private typealias CompletionHandler = (Process, Data, String?, String) -> Void init(bazelURL: URL, workspaceRootURL: URL, bazelUniversalFlags: BazelFlags, localizedMessageLogger: LocalizedMessageLogger) { self.bazelURL = bazelURL self.workspaceRootURL = workspaceRootURL self.bazelUniversalFlags = bazelUniversalFlags self.localizedMessageLogger = localizedMessageLogger } func extractTargetRulesFromPackages(_ packages: [String]) -> [RuleInfo] { guard !packages.isEmpty else { return [] } let profilingStart = localizedMessageLogger.startProfiling("fetch_rules", message: "Fetching rules for packages \(packages)") var infos = [RuleInfo]() let query = packages.map({ "kind(rule, \($0):all)"}).joined(separator: "+") do { let (process, data, stderr, debugInfo) = try self.bazelSynchronousQueryProcess(query, outputKind: "xml", loggingIdentifier: "bazel_query_fetch_rules") if process.terminationStatus != 0 { showExtractionError(debugInfo, stderr: stderr, displayLastLineIfNoErrorLines: true) } else if let entries = self.extractRuleInfosFromBazelXMLOutput(data) { infos = entries } } catch { // The error has already been displayed to the user. return [] } localizedMessageLogger.logProfilingEnd(profilingStart) return infos } /// Extracts all of the transitive BUILD and skylark (.bzl) files used by the given targets. func extractBuildfiles<T: Collection>(_ targets: T) -> Set<BuildLabel> where T.Iterator.Element == BuildLabel { if targets.isEmpty { return Set() } let profilingStart = localizedMessageLogger.startProfiling("extracting_skylark_files", message: "Finding Skylark files for \(targets.count) rules") let joinedLabels = targets.map { $0.value }.joined(separator: " + ") let query = "buildfiles(deps(\(joinedLabels)))" let buildFiles: Set<BuildLabel> do { // Errors in the BUILD structure being examined should not prevent partial extraction, so this // command is considered successful if it returns any valid data at all. let (_, data, _, debugInfo) = try self.bazelSynchronousQueryProcess(query, outputKind: "xml", additionalArguments: ["--keep_going"], loggingIdentifier: "bazel_query_extracting_skylark_files") self.queuedInfoMessages.append(debugInfo) if let labels = extractSourceFileLabelsFromBazelXMLOutput(data) { buildFiles = Set(labels) } else { localizedMessageLogger.warning("BazelBuildfilesQueryFailed", comment: "Bazel 'buildfiles' query failed to extract information.") buildFiles = Set() } localizedMessageLogger.logProfilingEnd(profilingStart) } catch { // Error will be displayed at the end of project generation. return Set() } return buildFiles } // MARK: - Private methods private func showExtractionError(_ debugInfo: String, stderr: String?, displayLastLineIfNoErrorLines: Bool = false) { localizedMessageLogger.infoMessage(debugInfo) let details: String? if let stderr = stderr { if displayLastLineIfNoErrorLines { details = BazelErrorExtractor.firstErrorLinesOrLastLinesFromString(stderr) } else { details = BazelErrorExtractor.firstErrorLinesFromString(stderr) } } else { details = nil } localizedMessageLogger.error("BazelInfoExtractionFailed", comment: "Error message for when a Bazel extractor did not complete successfully. Details are logged separately.", details: details) } // Generates a Process that will perform a bazel query, capturing the output data and passing it // to the terminationHandler. private func bazelQueryProcess(_ query: String, outputKind: String? = nil, additionalArguments: [String] = [], message: String = "", loggingIdentifier: String? = nil, terminationHandler: @escaping CompletionHandler) throws -> Process { guard FileManager.default.fileExists(atPath: bazelURL.path) else { localizedMessageLogger.error("BazelBinaryNotFound", comment: "Error to show when the bazel binary cannot be found at the previously saved location %1$@.", values: bazelURL as NSURL) throw ExtractorError.invalidBazelPath } var arguments = [ "--max_idle_secs=60", ] arguments.append(contentsOf: bazelUniversalFlags.startup) arguments.append("query") arguments.append(contentsOf: bazelUniversalFlags.build) arguments.append(contentsOf: [ "--announce_rc", // Print the RC files used by this operation. "--noimplicit_deps", "--order_output=no", "--noshow_loading_progress", "--noshow_progress", query ]) arguments.append(contentsOf: additionalArguments) if let kind = outputKind { arguments.append(contentsOf: ["--output", kind]) } var message = message if message != "" { message = "\(message)\n" } let process = TulsiProcessRunner.createProcess(bazelURL.path, arguments: arguments, messageLogger: localizedMessageLogger, loggingIdentifier: loggingIdentifier) { completionInfo in let debugInfoFormatString = NSLocalizedString("DebugInfoForBazelCommand", bundle: Bundle(for: type(of: self)), comment: "Provides general information about a Bazel failure; a more detailed error may be reported elsewhere. The Bazel command is %1$@, exit code is %2$d, stderr %3$@.") let stderr = NSString(data: completionInfo.stderr, encoding: String.Encoding.utf8.rawValue) let debugInfo = String(format: debugInfoFormatString, completionInfo.commandlineString, completionInfo.terminationStatus, stderr ?? "<No STDERR>") terminationHandler(completionInfo.process, completionInfo.stdout, stderr as String?, debugInfo) } return process } /// Performs the given Bazel query synchronously in the workspaceRootURL directory. private func bazelSynchronousQueryProcess(_ query: String, outputKind: String? = nil, additionalArguments: [String] = [], message: String = "", loggingIdentifier: String? = nil) throws -> (bazelProcess: Process, returnedData: Data, stderrString: String?, debugInfo: String) { let semaphore = DispatchSemaphore(value: 0) var data: Data! = nil var stderr: String? = nil var info: String! = nil let process = try bazelQueryProcess(query, outputKind: outputKind, additionalArguments: additionalArguments, message: message, loggingIdentifier: loggingIdentifier) { (_: Process, returnedData: Data, stderrString: String?, debugInfo: String) in data = returnedData stderr = stderrString info = debugInfo semaphore.signal() } process.currentDirectoryPath = workspaceRootURL.path process.launch() _ = semaphore.wait(timeout: DispatchTime.distantFuture) return (process, data, stderr, info) } private func extractRuleInfosWithRuleInputsFromBazelXMLOutput(_ bazelOutput: Data) -> [RuleInfo: Set<BuildLabel>]? { do { var infos = [RuleInfo: Set<BuildLabel>]() let doc = try XMLDocument(data: bazelOutput, options: XMLNode.Options(rawValue: 0)) let rules = try doc.nodes(forXPath: "/query/rule") for ruleNode in rules { guard let ruleElement = ruleNode as? XMLElement else { localizedMessageLogger.error("BazelResponseXMLNonElementType", comment: "General error to show when the XML parser returns something other " + "than an NSXMLElement. This should never happen in practice.") continue } guard let ruleLabel = ruleElement.attribute(forName: "name")?.stringValue else { localizedMessageLogger.error("BazelResponseMissingRequiredAttribute", comment: "Bazel response XML element %1$@ was found but was missing an attribute named %2$@.", values: ruleElement, "name") continue } guard let ruleType = ruleElement.attribute(forName: "class")?.stringValue else { localizedMessageLogger.error("BazelResponseMissingRequiredAttribute", comment: "Bazel response XML element %1$@ was found but was missing an attribute named %2$@.", values: ruleElement, "class") continue } func extractLabelsFromXpath(_ xpath: String) throws -> Set<BuildLabel> { var labelSet = Set<BuildLabel>() let nodes = try ruleElement.nodes(forXPath: xpath) for node in nodes { guard let label = node.stringValue else { localizedMessageLogger.error("BazelResponseLabelAttributeInvalid", comment: "Bazel response XML element %1$@ should have a valid string value but does not.", values: node) continue } labelSet.insert(BuildLabel(label)) } return labelSet } // Retrieve the list of linked targets through the test_host attribute. This provides a // link between the test target and the test host so they can be linked in Xcode. var linkedTargetLabels = Set<BuildLabel>() linkedTargetLabels.formUnion( try extractLabelsFromXpath("./label[@name='test_host']/@value")) let entry = RuleInfo(label: BuildLabel(ruleLabel), type: ruleType, linkedTargetLabels: linkedTargetLabels) infos[entry] = try extractLabelsFromXpath("./rule-input/@name") } return infos } catch let e as NSError { localizedMessageLogger.error("BazelResponseXMLParsingFailed", comment: "Extractor Bazel output failed to be parsed as XML with error %1$@. This may be a Bazel bug or a bad BUILD file.", values: e.localizedDescription) return nil } } private func extractRuleInfosFromBazelXMLOutput(_ bazelOutput: Data) -> [RuleInfo]? { if let infoMap = extractRuleInfosWithRuleInputsFromBazelXMLOutput(bazelOutput) { return [RuleInfo](infoMap.keys) } return nil } private func extractSourceFileLabelsFromBazelXMLOutput(_ bazelOutput: Data) -> Set<BuildLabel>? { do { let doc = try XMLDocument(data: bazelOutput, options: XMLNode.Options(rawValue: 0)) let fileLabels = try doc.nodes(forXPath: "/query/source-file/@name") var extractedLabels = Set<BuildLabel>() for labelNode in fileLabels { guard let value = labelNode.stringValue else { localizedMessageLogger.error("BazelResponseLabelAttributeInvalid", comment: "Bazel response XML element %1$@ should have a valid string value but does not.", values: labelNode) continue } extractedLabels.insert(BuildLabel(value)) } return extractedLabels } catch let e as NSError { localizedMessageLogger.error("BazelResponseXMLParsingFailed", comment: "Extractor Bazel output failed to be parsed as XML with error %1$@. This may be a Bazel bug or a bad BUILD file.", values: e.localizedDescription) return nil } } // MARK: - QueuedLogging func logQueuedInfoMessages() { guard !self.queuedInfoMessages.isEmpty else { return } localizedMessageLogger.debugMessage("Log of Bazel query output follows:") for message in self.queuedInfoMessages { localizedMessageLogger.debugMessage(message) } self.queuedInfoMessages.removeAll() } var hasQueuedInfoMessages: Bool { return !self.queuedInfoMessages.isEmpty } }
apache-2.0
93feacc32c77bfb9da161f4f9c9fa071
43.988095
225
0.591228
5.667792
false
false
false
false
mperovic/my41
SettingsView.swift
1
7582
// // SettingsView.swift // my41 // // Created by Miroslav Perovic on 28.1.21.. // Copyright © 2021 iPera. All rights reserved. // import SwiftUI struct MODsViewStyle: ViewModifier { func body(content: Content) -> some View { return content .overlay( RoundedRectangle(cornerRadius: 8) .stroke(lineWidth: 2) .foregroundColor(.white) ) .shadow( color: Color.gray.opacity(0.4), radius: 3, x: 1, y: 2 ) .padding(5) } } struct SettingsView: View { @EnvironmentObject var calculator: Calculator @ObservedObject var settingsState = SettingsState() @State private var selectedCalculator = UserDefaults.standard.string(forKey: hpCalculatorType) ?? HPCalculator.hp41cx.rawValue @State private var sound = true @State private var syncTime = true @State private var module: MOD? @Binding var showSettings: Bool @State private var showAlert = false @State private var showList1 = false @State private var showList2 = false @State private var showList3 = false @State private var showList4 = false private let mods = MODs.getModFiles() var body: some View { GeometryReader { geometry in VStack(alignment: .leading) { HStack { Text("Calculator") Spacer(minLength: 40) Picker("Calculator", selection: $selectedCalculator) { ForEach(HPCalculator.allCases, id: \.self) { Text($0.rawValue).tag($0.rawValue) } } .pickerStyle(SegmentedPickerStyle()) } Toggle(isOn: $sound){ Text("Sound") } Toggle(isOn: $syncTime){ Text("Synchronyze time with device") } Text("MODs") .padding(.top, 20) VStack { HStack { MODsView(port: .port1, settingsState: settingsState) .onPress {port in showList1 = true } .sheet(isPresented: $showList1) { MODList(settingsState: settingsState, showList: $showList1, port: .port1) } .modifier(MODsViewStyle()) MODsView(port: .port2, settingsState: settingsState) .onPress {port in showList2 = true } .sheet(isPresented: $showList2) { MODList(settingsState: settingsState, showList: $showList2, port: .port2) } .modifier(MODsViewStyle()) } HStack { MODsView(port: .port3, settingsState: settingsState) .onPress {port in showList3 = true } .sheet(isPresented: $showList3) { MODList(settingsState: settingsState, showList: $showList3, port: .port3) } .modifier(MODsViewStyle()) MODsView(port: .port4, settingsState: settingsState) .onPress {port in showList4 = true } .sheet(isPresented: $showList4) { MODList(settingsState: settingsState, showList: $showList4, port: .port4) } .modifier(MODsViewStyle()) } } .padding(.top, 10) .padding(.bottom, 15) .frame(height: geometry.size.height * 0.455) HStack { Spacer() Button(action: { showAlert.toggle() }) { Text("Reset Calculator") } .foregroundColor(.white) .alert(isPresented: $showAlert) { Alert( title: Text("Reset Calculator"), message: Text("This operation will clear all programs and memory registers"), primaryButton: .default(Text("Continue")) { calculator.resetCalculator(restoringMemory: false) showSettings = false }, secondaryButton: .cancel(Text("Cancel")) ) } Spacer() } Spacer() HStack { Spacer() Button(action: { applyChanges() }, label: { Text("Apply") .fontWeight(.semibold) }) .foregroundColor(.white) } } .padding(.all) } } private func applyChanges() { var needsRestart = false let defaults = UserDefaults.standard // Sound settings if sound { SOUND = true } else { SOUND = false } defaults.set(SOUND, forKey: "sound") // Calculator timer if syncTime { SYNCHRONYZE = true } else { SYNCHRONYZE = false } defaults.set(SYNCHRONYZE, forKey: "synchronyzeTime") // Calculator type let calculatorType = defaults.string(forKey: hpCalculatorType) if calculatorType != selectedCalculator { defaults.set(selectedCalculator, forKey: hpCalculatorType) needsRestart = true } // Modules if let module1 = settingsState.module1 { // We have something in Port1 let moduleName = mods.key(from: module1) if let dModuleName = defaults.string(forKey: HPPort.port1.rawValue) { // And we had something in Port1 at the begining if moduleName != dModuleName { // This is different module defaults.set(moduleName, forKey: HPPort.port1.rawValue) needsRestart = true } } else { // Port1 was empty defaults.set(moduleName, forKey: HPPort.port1.rawValue) needsRestart = true } } else { // Port1 is empty now if let _ = defaults.string(forKey: HPPort.port1.rawValue) { // But we had something in Port1 defaults.removeObject(forKey: HPPort.port1.rawValue) } } if let module2 = settingsState.module2 { // We have something in Port2 let moduleName = mods.key(from: module2) if let dModuleName = defaults.string(forKey: HPPort.port2.rawValue) { // And we had something in Port2 at the begining if moduleName != dModuleName { // This is different module defaults.set(moduleName, forKey: HPPort.port2.rawValue) needsRestart = true } } else { // Port2 was empty defaults.set(moduleName, forKey: HPPort.port2.rawValue) needsRestart = true } } else { // Port2 is empty now if let _ = defaults.string(forKey: HPPort.port2.rawValue) { // But we had something in Port2 defaults.removeObject(forKey: HPPort.port2.rawValue) } } if let module3 = settingsState.module3 { // We have something in Port3 let moduleName = mods.key(from: module3) if let dModuleName = defaults.string(forKey: HPPort.port3.rawValue) { // And we had something in Port3 at the begining if moduleName != dModuleName { // This is different module defaults.set(moduleName, forKey: HPPort.port3.rawValue) needsRestart = true } } else { // Port3 was empty defaults.set(moduleName, forKey: HPPort.port3.rawValue) needsRestart = true } } else { // Port3 is empty now if let _ = defaults.string(forKey: HPPort.port3.rawValue) { // But we had something in Port3 defaults.removeObject(forKey: HPPort.port3.rawValue) } } if let module3 = settingsState.module3 { // We have something in Port4 let moduleName = mods.key(from: module3) if let dModuleName = defaults.string(forKey: HPPort.port4.rawValue) { // And we had something in Port4 at the begining if moduleName != dModuleName { // This is different module defaults.set(moduleName, forKey: HPPort.port4.rawValue) needsRestart = true } } else { // Port4 was empty defaults.set(moduleName, forKey: HPPort.port4.rawValue) needsRestart = true } } else { // Port4 is empty now if let _ = defaults.string(forKey: HPPort.port4.rawValue) { // But we had something in Port4 defaults.removeObject(forKey: HPPort.port4.rawValue) } } defaults.synchronize() if needsRestart { calculator.resetCalculator(restoringMemory: true) } showSettings = false } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView(showSettings: .constant(true)) } }
bsd-3-clause
8d33d1a7ae20dd6a32f0538a670b2122
25.6
127
0.646221
3.577631
false
false
false
false
JakeLin/IBAnimatable
Sources/Others/AnimationChainable.swift
2
2811
// // Created by jason akakpo on 01/01/2017. // Copyright © 2017 IBAnimatable. All rights reserved. // import Foundation import UIKit typealias AnimationTuple = (type: AnimationType, configuration: AnimationConfiguration) struct AnimationConfiguration { let damping: CGFloat let velocity: CGFloat let duration: TimeInterval let delay: TimeInterval let force: CGFloat let timingFunction: TimingFunctionType } extension AnimationConfiguration { /// Options for spring animation. var options: UIView.AnimationOptions { if let curveOption = timingFunction.viewAnimationCurveOption { return [ .allowUserInteraction, curveOption, .overrideInheritedCurve, .overrideInheritedOptions, .overrideInheritedDuration] } return [.allowUserInteraction] } } public class AnimationPromise<T: UIView> where T: Animatable { private var view: T private var animationList = [AnimationTuple]() private var delayForNextAnimation = 0.0 private var completion: AnimatableCompletion? init(view: T) { self.view = view } func animationCompleted() { animationList.removeFirst() if let currentAnimation = animationList.first { view.doAnimation(currentAnimation.type, configuration: currentAnimation.configuration, promise: self) } else { completion?() } } public func completion(_ completion: AnimatableCompletion?) { self.completion = completion } @discardableResult public func then(_ animation: AnimationType, duration: TimeInterval? = nil, damping: CGFloat? = nil, velocity: CGFloat? = nil, force: CGFloat? = nil, timingFunction: TimingFunctionType? = nil) -> AnimationPromise { let configuration = AnimationConfiguration(damping: damping ?? view.damping, velocity: velocity ?? view.velocity, duration: duration ?? view.duration, delay: delayForNextAnimation, force: force ?? view.force, timingFunction: timingFunction ?? view.timingFunction) let animTuple = AnimationTuple(type: animation, configuration: configuration) animationList.append(animTuple) if animationList.count == 1 { // If it's the only animation, launch it immediately view.doAnimation(animation, configuration: animTuple.configuration, promise: self) } delayForNextAnimation = 0 return self } @discardableResult public func delay(_ delay: TimeInterval) -> AnimationPromise { delayForNextAnimation = delay return self } }
mit
b27bf29708ceb5fc5f931c4a87be1669
30.931818
109
0.64306
5.477583
false
true
false
false
wiltonlazary/kotlin-native
performance/KotlinVsSwift/ring/src/CastsBenchmark.swift
4
3622
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Foundation struct RunsInfo { static let RUNS = 2_000_000 } protocol I0 {} protocol I1 {} protocol I2: I0 {} protocol I3: I1 {} protocol I4: I0, I2 {} protocol I5: I3 {} protocol I6: I0, I2, I4 {} protocol I9: I0, I2, I4 {} protocol I7: I1 {} protocol I8: I0, I1 {} class CastsBenchmark { class C0: I0 {} class C1: C0, I1 {} class C2: C1, I2 {} class C3: C2, I3 {} class C4: C3, I4 {} class C5: C4, I5 {} class C6: C5, I6 {} class C9: C5, I9 {} class C7: C3, I7 {} class C8: C3, I8 {} private func foo_class(_ c: Any, _ x: Int, _ i: Int) -> Int { var x = x if (c is C0) { x = x &+ i } if (c is C1) { x = x ^ i } if (c is C2) { x = x &+ i } if (c is C3) { x = x ^ i } if (c is C4) { x = x &+ i } if (c is C5) { x = x ^ i } if (c is C6) { x = x &+ i } if (c is C7) { x = x ^ i } if (c is C8) { x = x &+ i } if (c is C9) { x = x ^ i } return x } private func foo_iface(_ c: Any, _ x: Int, _ i: Int) -> Int { var x = x if (c is I0) { x = x &+ i } if (c is I1) { x = x ^ i } if (c is I2) { x = x &+ i } if (c is I3) { x = x ^ i } if (c is I4) { x = x &+ i } if (c is I5) { x = x ^ i } if (c is I6) { x = x &+ i } if (c is I7) { x = x ^ i } if (c is I8) { x = x &+ i } if (c is I9) { x = x ^ i } return x } func classCast() -> Int { let c0: Any = C0() let c1: Any = C1() let c2: Any = C2() let c3: Any = C3() let c4: Any = C4() let c5: Any = C5() let c6: Any = C6() let c7: Any = C7() let c8: Any = C8() let c9: Any = C9() var x = 0 for i in 0..<RunsInfo.RUNS { x = x &+ foo_class(c0, x, i) x = x &+ foo_class(c1, x, i) x = x &+ foo_class(c2, x, i) x = x &+ foo_class(c3, x, i) x = x &+ foo_class(c4, x, i) x = x &+ foo_class(c5, x, i) x = x &+ foo_class(c6, x, i) x = x &+ foo_class(c7, x, i) x = x &+ foo_class(c8, x, i) x = x &+ foo_class(c9, x, i) } return x } func interfaceCast() -> Int { let c0: Any = C0() let c1: Any = C1() let c2: Any = C2() let c3: Any = C3() let c4: Any = C4() let c5: Any = C5() let c6: Any = C6() let c7: Any = C7() let c8: Any = C8() let c9: Any = C9() var x = 0 for i in 0..<RunsInfo.RUNS { x = x &+ foo_iface(c0, x, i) x = x &+ foo_iface(c1, x, i) x = x &+ foo_iface(c2, x, i) x = x &+ foo_iface(c3, x, i) x = x &+ foo_iface(c4, x, i) x = x &+ foo_iface(c5, x, i) x = x &+ foo_iface(c6, x, i) x = x &+ foo_iface(c7, x, i) x = x &+ foo_iface(c8, x, i) x = x &+ foo_iface(c9, x, i) } return x } }
apache-2.0
aecaf04fe3b520cbb27c36eceb027d30
21.6375
101
0.354224
2.858721
false
false
false
false
reidmweber/SwiftCSV
SwiftCSV/CSV.swift
1
3249
// // CSV.swift // SwiftCSV // // Created by naoty on 2014/06/09. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // import Foundation public class CSV { public var headers: [String] = [] public var rows: [Dictionary<String, String>] = [] public var columns = Dictionary<String, [String]>() var delimiter = NSCharacterSet(charactersInString: ",") public init(string: String?, delimiter: NSCharacterSet, encoding: UInt) { if let csvStringToParse = string { self.delimiter = delimiter let newline = NSCharacterSet.newlineCharacterSet() var lines: [String] = [] csvStringToParse.stringByTrimmingCharactersInSet(newline).enumerateLines { line, stop in lines.append(line) } self.headers = self.parseHeaders(fromLines: lines) self.rows = self.parseRows(fromLines: lines) self.columns = self.parseColumns(fromLines: lines) } } public convenience init(contentsOfURL url: NSURL, delimiter: NSCharacterSet, encoding: UInt) throws { let csvString: String? do { csvString = try String(contentsOfURL: url, encoding: encoding) } catch _ { csvString = nil }; self.init(string: csvString, delimiter: delimiter, encoding: encoding) } public convenience init(contentsOfURL url: NSURL) throws { let comma = NSCharacterSet(charactersInString: ",") try self.init(contentsOfURL: url, delimiter: comma, encoding: NSUTF8StringEncoding) } public convenience init(contentsOfURL url: NSURL, encoding: UInt) throws { let comma = NSCharacterSet(charactersInString: ",") try self.init(contentsOfURL: url, delimiter: comma, encoding: encoding) } public convenience init(string: String?) { let comma = NSCharacterSet(charactersInString: ",") self.init(string: string, delimiter: comma, encoding: NSUTF8StringEncoding) } func parseHeaders(fromLines lines: [String]) -> [String] { return lines[0].componentsSeparatedByCharactersInSet(self.delimiter) } func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] { var rows: [Dictionary<String, String>] = [] for (lineNumber, line) in lines.enumerate() { if lineNumber == 0 { continue } var row = Dictionary<String, String>() let values = line.componentsSeparatedByCharactersInSet(self.delimiter) for (index, header) in self.headers.enumerate() { if index < values.count { row[header] = values[index] } else { row[header] = "" } } rows.append(row) } return rows } func parseColumns(fromLines lines: [String]) -> Dictionary<String, [String]> { var columns = Dictionary<String, [String]>() for header in self.headers { let column = self.rows.map { row in row[header] != nil ? row[header]! : "" } columns[header] = column } return columns } }
mit
3fa29f63d5516c48c6a5f0da45b79a1b
34.293478
121
0.595011
4.839046
false
false
false
false
yanfeng0107/ios-charts
Charts/Classes/Charts/BarChartView.swift
45
7397
// // BarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// Chart that draws bars. public class BarChartView: BarLineChartViewBase, BarChartRendererDelegate { /// flag that enables or disables the highlighting arrow private var _drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top private var _drawValueAboveBarEnabled = true /// if set to true, a grey area is darawn behind each bar that indicates the maximum value private var _drawBarShadowEnabled = false internal override func initialize() { super.initialize() renderer = BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler) _xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self) _highlighter = BarChartHighlighter(chart: self) _chartXMin = -0.5 } internal override func calcMinMax() { super.calcMinMax() if (_data === nil) { return } var barData = _data as! BarChartData // increase deltax by 1 because the bars have a width of 1 _deltaX += 0.5 // extend xDelta to make space for multiple datasets (if ther are one) _deltaX *= CGFloat(_data.dataSetCount) var groupSpace = barData.groupSpace _deltaX += CGFloat(barData.xValCount) * groupSpace _chartXMax = Double(_deltaX) - _chartXMin } /// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart. public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set.") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data. public func getBarBounds(e: BarChartDataEntry) -> CGRect! { var set = _data.getDataSetForEntry(e) as! BarChartDataSet! if (set === nil) { return nil } var barspace = set.barSpace var y = CGFloat(e.value) var x = CGFloat(e.xIndex) var barWidth: CGFloat = 0.5 var spaceHalf = barspace / 2.0 var left = x - barWidth + spaceHalf var right = x + barWidth - spaceHalf var top = y >= 0.0 ? y : 0.0 var bottom = y <= 0.0 ? y : 0.0 var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top) getTransformer(set.axisDependency).rectValueToPixel(&bounds) return bounds } public override var lowestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount) var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0) } public override var highestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount) var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom) getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt) return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div)) } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return _drawHighlightArrowEnabled; } set { _drawHighlightArrowEnabled = newValue setNeedsDisplay() } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return _drawValueAboveBarEnabled; } set { _drawValueAboveBarEnabled = newValue setNeedsDisplay() } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return _drawBarShadowEnabled; } set { _drawBarShadowEnabled = newValue setNeedsDisplay() } } /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } // MARK: - BarChartRendererDelegate public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! { return _data as! BarChartData! } public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return getTransformer(which) } public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int { return maxVisibleValueCount } public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! { return valueFormatter } public func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double { return chartYMax } public func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double { return chartYMin } public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double { return chartXMax } public func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double { return chartXMin } public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool { return drawHighlightArrowEnabled } public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool { return drawValueAboveBarEnabled } public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool { return drawBarShadowEnabled } public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted } }
apache-2.0
0f312f54c7286474709dd5dba6749913
31.025974
149
0.634852
5.325414
false
false
false
false
0416354917/FeedMeIOS
SignUpViewController.swift
1
9447
// // SignUpViewController.swift // FeedMeIOS // // Created by Jun Chen on 11/04/2016. // Copyright © 2016 FeedMe. All rights reserved. // import UIKit class SignUpViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! // @IBOutlet weak var verificationCodeTextField: UITextField! // @IBOutlet weak var confirmButton: UIButton! var validEmail: String? var validVerificationCode: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // self.confirmButton.userInteractionEnabled = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancelButtonClicked(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } func displayMessage(messgae: String) { let alert = UIAlertController(title: "Message", message: messgae, preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } @IBAction func signUpButtonClicked(sender: UIButton) { validateSignUp() } //statusCode = 0: validate fail. //statusCode = 1: validate success. //description: validation result description. func validateSignUp() { NSLog("%@", "Validate sign up...") let validateUserInputResult = validateUserInput() if validateUserInputResult.statusCode == 0 { displayMessage(validateUserInputResult.description) } else { let urlString = FeedMe.Path.TEXT_HOST + "/users/checkEmail?email=" + emailTextField.text! let url = NSURL(string: urlString) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in dispatch_async(dispatch_get_main_queue(), { let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) NSLog("response: %@", responseString!) let json: NSDictionary do { json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary if let statusInfo = json["statusInfo"] as? String { if statusInfo == "N" { FeedMeAlert.alertSignUpFailure(self, message: "Email is already taken") } else if statusInfo == "Y" { self.commitSignUp() } else { FeedMeAlert.alertSignUpFailure(self, message: "Unkown Error") } } } catch _ { } }) } task.resume() } } func commitSignUp() { // MARK: TODO // Cache user data in local device settings once signing up successfully. // Prompt user whether allow current account automatically login next time. let hashPassword = Security.md5(string: passwordTextField.text!) let postString = "{\"email\":\"\(emailTextField.text!)\",\"password\":\"\(hashPassword)\"}" NSLog("post data: %@", postString) // Use EVReflection: let user = User(email: emailTextField.text!, password: hashPassword) user.setFirstName("default_firstname") user.setLastName("default_lastname") // user.setMachineCode(UIDevice.currentDevice().identifierForVendor!.UUIDString) let jsonString = user.toJsonString(ConvertionOptions.None) NSLog("json string: %@", jsonString) let url = FeedMe.Path.TEXT_HOST + "users/register" let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) request.setValue("application/json", forHTTPHeaderField: "Content-Type") // NSLog("reuqest body: %@", request.HTTPBody!) let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil else { // check for fundamental networking error NSLog("error: %@", error!) FeedMeAlert.alertSignUpFailure(self, message: "Unknown error") return } if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors NSLog("statusCode should be 200, but is: %@", httpStatus.statusCode) NSLog("response: %@", response!) FeedMeAlert.alertSignUpFailure(self, message: "Unknown error") return } let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) NSLog("response string: %@", responseString!) FeedMe.user = user FeedMe.Variable.userInLoginState = true self.dismissViewControllerAnimated(true, completion: nil) } task.resume() } func validateUserInput() -> (statusCode: Int, description: String) { NSLog("Validate user input...") let validateEmailResult = validateEmail() if validateEmailResult.statusCode == 0 { return validateEmailResult } let validatePasswordResult = validatePassword() if validatePasswordResult.statusCode == 0 { return validatePasswordResult } return (1, "") } func validateEmail() -> (statusCode: Int, description: String) { let email = emailTextField.text! NSLog("Validate email: %@", email) var statusCode = 1 var description = "" // MARK: to be fixed! if email.length == 0 { // clear current input: passwordTextField.text = "" confirmPasswordTextField.text = "" statusCode = 0 description = "Not a valid Email." } return (statusCode, description) } func validatePassword() -> (statusCode: Int, description: String) { let password = passwordTextField.text! let confirmPassword = confirmPasswordTextField.text! NSLog("Validate password: %@, confirm password: %@", password, confirmPassword) var statusCode = 1 var description = "" if password.length == 0 || confirmPassword.length == 0 || password != confirmPassword { // clear current input: passwordTextField.text = "" confirmPasswordTextField.text = "" statusCode = 0 description = "Password mismatch, enter again." } return (statusCode, description) } // MARK: - Not implemented now. To be implemented in the future. /* @IBAction func sendAgainButtonClicked(sender: UIButton) { sendVerificationCode(emailTextField.text!) } */ /* @IBAction func confirmButtonClicked(sender: UIButton) { // let validateVerificationCodeResult = validateVerificationCode(verificationCodeTextField.text) // if validateVerificationCodeResult.statusCode == 0 { // displayMessage(validateVerificationCodeResult) // } else { // commitSignUp() // } } */ /* func sendVerificationCode(phone: String) { // clear current input if any: verificationCodeTextField.text = "" verificationCodeTextField.becomeFirstResponder() // MARK: TODO: HTTP POST. // From the http response: get verification code and store in self.validVerificationCode. // uncomment the statement below and put it into callback handler: // self.confirmButton.userInteractionEnabled = true } */ /* func validateVerificationCode(verificationCode: String?) -> (statusCode: Int, description: String) { var statusCode = 1 var description = "" if verificationCode!.length == 0 || verificationCode! != self.validVerificationCode! { statusCode = 0 description = "Wrong verification code." } return (statusCode, description) } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bsd-3-clause
f34668bd217d97b5e59dca69d8f4e58e
36.633466
123
0.586492
5.652902
false
false
false
false
sublimter/Meijiabang
KickYourAss/KickYourAss/MainViewController.swift
3
5703
// // MainViewController.swift // KickYourAss // // Created by eagle on 15/1/19. // Copyright (c) 2015年 Li Chaoyi. All rights reserved. // import UIKit class MainViewController: UITabBarController { var picker : UIImagePickerController! = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() self.delegate = self // Do any additional setup after loading the view. // 搜索 let SearchStoryboard = UIStoryboard(name: "Search", bundle: nil) let SearchVC = SearchStoryboard.instantiateInitialViewController() as UINavigationController // 首页 let HomeStoryboard = UIStoryboard(name: "Home", bundle: nil) let HomeVC = HomeStoryboard.instantiateInitialViewController() as UINavigationController // 美甲师 let ArtistStoryboard = UIStoryboard(name: "Artist", bundle: nil) let ArtistVC = ArtistStoryboard.instantiateInitialViewController() as UINavigationController // 晒美甲 let placeHolderVC = UINavigationController() // 我的 let AboutMeStoryboard = UIStoryboard(name: "AboutMe", bundle: nil) let AboutMeVC = AboutMeStoryboard.instantiateInitialViewController() as UINavigationController self.setViewControllers([SearchVC,HomeVC,ArtistVC,placeHolderVC,AboutMeVC], animated: false) let itemPlist: NSArray! = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("HomeItemsPList", ofType: "plist")!) self.tabBar.selectedImageTintColor = UIColor(red: 249.0/255.0, green: 97.0/255.0, blue: 104.0/255.0, alpha: 1) for var i = 0 ; i < self.tabBar.items?.count ; i++ { var item : UITabBarItem = self.tabBar.items![i] as UITabBarItem var fileItemDic : Dictionary<String,String> = itemPlist[i] as Dictionary<String,String> item.title = fileItemDic["itemName"] item.selectedImage = UIImage(named: fileItemDic["itemImage"]!) item.image = UIImage(named: fileItemDic["itemUpImage"]!) //item.image = UIImage(named: fileItemDic[""])) } } 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. } */ } extension MainViewController : UITabBarControllerDelegate , ZXY_PictureTakeDelegate , ZXY_ImagePickerDelegate , UINavigationControllerDelegate,UIImagePickerControllerDelegate { func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { if(viewController == (tabBarController.viewControllers![3] as UIViewController)) { var story = UIStoryboard(name: "ZXYTakePic", bundle: nil) var vc = story.instantiateInitialViewController() as ZXY_PictureTakeVC vc.delegate = self vc.presentView() return false } else { return true } } func clickChoosePictureBtn() { var currentVC: UIViewController = self.viewControllers![self.selectedIndex] as UIViewController var zxy_imgPick = ZXY_ImagePickerTableVC() zxy_imgPick.setMaxNumOfSelect(1) zxy_imgPick.delegate = self zxy_imgPick.presentZXYImagePicker(currentVC) } func clickTakePhotoBtn() { var currentVC: UIViewController = self.viewControllers![self.selectedIndex] as UIViewController var photoPicker = UIImagePickerController() photoPicker.sourceType = UIImagePickerControllerSourceType.Camera photoPicker.delegate = self currentVC.presentViewController(photoPicker, animated: true) { () -> Void in } } func ZXY_ImagePicker(imagePicker: ZXY_ImagePickerTableVC, didFinishPicker assetArr: [ALAsset]) { var currentVC: UINavigationController = self.viewControllers![self.selectedIndex] as UINavigationController var story = UIStoryboard(name: "ZXYTakePic", bundle: nil) var vc = story.instantiateViewControllerWithIdentifier("ZXY_AfterPickImgVCID") as ZXY_AfterPickImgVC vc.setAssetArr(assetArr) //currentVC.presentViewController(vc, animated: true) { () -> Void in currentVC.pushViewController(vc, animated: true) //} } func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { picker.dismissViewControllerAnimated(true, completion: { () -> Void in var currentVC: UINavigationController = self.viewControllers![self.selectedIndex] as UINavigationController var story = UIStoryboard(name: "ZXYTakePic", bundle: nil) var vc = story.instantiateViewControllerWithIdentifier("ZXY_AfterPickImgVCID") as ZXY_AfterPickImgVC vc.setPhoto([image]) currentVC.pushViewController(vc, animated: true) }) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: { () -> Void in }) } }
mit
7e4f77ae38bc5df64ab333f94fa09e5a
40.137681
174
0.666902
5.345574
false
false
false
false
m-alani/contests
hackerrank/TheGridSearch.swift
1
2043
// // TheGridSearch.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/the-grid-search // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // import Foundation // Helper function to check if a matrix is contained in another matrix at specific coordenates func does(thisMatrix main: [[Int]], containThisOne sub: [[Int]], atThisRow x: Int, andColumn y: Int) -> Bool { for checkX in 0..<sub.count { for checkY in 0..<sub[checkX].count { if sub[checkX][checkY] != main[checkX+x][checkY+y] { return false } } } return true } /***** MAIN STARTS HERE *****/ if let cases = Int(readLine() ?? "0") { var output = [String]() // Process Input for _ in 1...cases { // Read the case's input matrix var dimensions = String(readLine()!)! var rows = Int(dimensions.components(separatedBy: " ")[0])! var columns = Int(dimensions.components(separatedBy: " ")[1])! var input = [[Int]]() for row in 0..<rows { if let line: String = readLine() { input.append(line.utf8.map({Int($0) - 48;})) } } // Read the case's smaller matrix to find dimensions = String(readLine()!)! rows = Int(dimensions.components(separatedBy: " ")[0])! columns = Int(dimensions.components(separatedBy: " ")[1])! var search = [[Int]]() for row in 0..<rows { if let line: String = readLine() { search.append(line.utf8.map({Int($0) - 48;})) } } // Process this case var found = "NO" mainLoop: for x in 0...input.count-search.count { for y in 0...input[x].count-search[0].count { if does(thisMatrix: input, containThisOne: search, atThisRow: x, andColumn: y) { found = "YES" break mainLoop } } } output.append(found) } // Print Output for line in output { print(line) } } /***** MAIN ENDS HERE *****/
mit
e7e2ab679a3d95f971ee51bab8a780b3
27.375
118
0.602056
3.596831
false
false
false
false
lucaslouca/swift-concurrency
app-ios/Fluxcapacitor/FXCOrder.swift
1
783
// // FXCOrder.swift // Fluxcapacitor // // Created by Lucas Louca on 30/05/15. // Copyright (c) 2015 Lucas Louca. All rights reserved. // import UIKit enum FXCOrderState { case New, Downloaded, Failed, Parsed } class FXCOrder: NSObject { var state = FXCOrderState.New let url:NSURL var data: NSData? let id:Int var title: String = "" var info: String = "" var price:Int = 0 var itemCount: Int = 0 var address: String = "a" var radius:Int = 0 var radiusUnit: String = "" var latitude: Double = 0.0 var longitude: Double = 0.0 var deliveryDate = "" var currency = "" var items:[FXCOrderItem] = [FXCOrderItem]() init(id: Int, url:NSURL) { self.id = id self.url = url } }
mit
678869585f6b111b1fcec22136603dd8
19.076923
56
0.592593
3.449339
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Background/Crypto/MXLegacyBackgroundCrypto.swift
1
8988
// // Copyright 2022 The Matrix.org Foundation C.I.C // // 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 class MXLegacyBackgroundCrypto: MXBackgroundCrypto { private let credentials: MXCredentials private let cryptoStore: MXBackgroundCryptoStore private let olmDevice: MXOlmDevice init(credentials: MXCredentials, resetBackgroundCryptoStore: Bool) { self.credentials = credentials cryptoStore = MXBackgroundCryptoStore(credentials: credentials, resetBackgroundCryptoStore: resetBackgroundCryptoStore) olmDevice = MXOlmDevice(store: cryptoStore) } func handleSyncResponse(_ syncResponse: MXSyncResponse) { for event in syncResponse.toDevice?.events ?? [] { handleToDeviceEvent(event) } } func canDecryptEvent(_ event: MXEvent) -> Bool { if !event.isEncrypted { return true } guard let senderKey = event.content["sender_key"] as? String, let sessionId = event.content["session_id"] as? String else { return false } return cryptoStore.inboundGroupSession(withId: sessionId, andSenderKey: senderKey) != nil } func decryptEvent(_ event: MXEvent) throws { if !event.isEncrypted { return } guard let senderKey = event.content["sender_key"] as? String, let algorithm = event.content["algorithm"] as? String else { throw MXBackgroundSyncServiceError.unknown } guard let decryptorClass = MXCryptoAlgorithms.shared()?.decryptorClass(forAlgorithm: algorithm) else { throw MXBackgroundSyncServiceError.unknownAlgorithm } if decryptorClass == MXMegolmDecryption.self { guard let ciphertext = event.content["ciphertext"] as? String, let sessionId = event.content["session_id"] as? String else { throw MXBackgroundSyncServiceError.unknown } let olmResult = try olmDevice.decryptGroupMessage(ciphertext, isEditEvent: event.isEdit(), roomId: event.roomId, inTimeline: nil, sessionId: sessionId, senderKey: senderKey) let decryptionResult = MXEventDecryptionResult() decryptionResult.clearEvent = olmResult.payload decryptionResult.senderCurve25519Key = olmResult.senderKey decryptionResult.claimedEd25519Key = olmResult.keysClaimed["ed25519"] as? String decryptionResult.forwardingCurve25519KeyChain = olmResult.forwardingCurve25519KeyChain decryptionResult.isUntrusted = olmResult.isUntrusted event.setClearData(decryptionResult) } else if decryptorClass == MXOlmDecryption.self { guard let ciphertextDict = event.content["ciphertext"] as? [AnyHashable: Any], let deviceCurve25519Key = olmDevice.deviceCurve25519Key, let message = ciphertextDict[deviceCurve25519Key] as? [AnyHashable: Any], let payloadString = decryptMessageWithOlm(message: message, theirDeviceIdentityKey: senderKey) else { throw MXBackgroundSyncServiceError.decryptionFailure } guard let payloadData = payloadString.data(using: .utf8), let payload = try? JSONSerialization.jsonObject(with: payloadData, options: .init(rawValue: 0)) as? [AnyHashable: Any], let recipient = payload["recipient"] as? String, recipient == credentials.userId, let recipientKeys = payload["recipient_keys"] as? [AnyHashable: Any], let ed25519 = recipientKeys["ed25519"] as? String, ed25519 == olmDevice.deviceEd25519Key, let sender = payload["sender"] as? String, sender == event.sender else { throw MXBackgroundSyncServiceError.decryptionFailure } if let roomId = event.roomId { guard payload["room_id"] as? String == roomId else { throw MXBackgroundSyncServiceError.decryptionFailure } } let claimedKeys = payload["keys"] as? [AnyHashable: Any] let decryptionResult = MXEventDecryptionResult() decryptionResult.clearEvent = payload decryptionResult.senderCurve25519Key = senderKey decryptionResult.claimedEd25519Key = claimedKeys?["ed25519"] as? String event.setClearData(decryptionResult) } else { throw MXBackgroundSyncServiceError.unknownAlgorithm } } func reset() { cryptoStore.reset() } // MARK: - Private private func handleToDeviceEvent(_ event: MXEvent) { // only handle supported events guard MXTools.isSupportedToDeviceEvent(event) else { MXLog.debug("[MXLegacyBackgroundCrypto] handleToDeviceEvent: ignore unsupported event") return } if event.isEncrypted { do { try decryptEvent(event) } catch let error { MXLog.debug("[MXLegacyBackgroundCrypto] handleToDeviceEvent: Could not decrypt to-device event: \(error)") return } } guard let userId = credentials.userId else { MXLog.error("[MXLegacyBackgroundCrypto] handleToDeviceEvent: Cannot get userId") return } let factory = MXRoomKeyInfoFactory(myUserId: userId, store: cryptoStore) guard let key = factory.roomKey(for: event) else { MXLog.error("[MXLegacyBackgroundCrypto] handleToDeviceEvent: Cannot create megolm key from event") return } switch key.type { case .safe: olmDevice.addInboundGroupSession( key.info.sessionId, sessionKey: key.info.sessionKey, roomId: key.info.roomId, senderKey: key.info.senderKey, forwardingCurve25519KeyChain: key.info.forwardingKeyChain, keysClaimed: key.info.keysClaimed, exportFormat: key.info.exportFormat, sharedHistory: key.info.sharedHistory, untrusted: key.type != .safe ) case .unsafe: MXLog.warning("[MXLegacyBackgroundCrypto] handleToDeviceEvent: Ignoring unsafe keys") case .unrequested: MXLog.warning("[MXLegacyBackgroundCrypto] handleToDeviceEvent: Ignoring unrequested keys") } } private func decryptMessageWithOlm(message: [AnyHashable: Any], theirDeviceIdentityKey: String) -> String? { let sessionIds = olmDevice.sessionIds(forDevice: theirDeviceIdentityKey) let messageBody = message[kMXMessageBodyKey] as? String let messageType = message["type"] as? UInt ?? 0 for sessionId in sessionIds ?? [] { if let payload = olmDevice.decryptMessage(messageBody, withType: messageType, sessionId: sessionId, theirDeviceIdentityKey: theirDeviceIdentityKey) { return payload } else { let foundSession = olmDevice.matchesSession(theirDeviceIdentityKey, sessionId: sessionId, messageType: messageType, ciphertext: messageBody) if foundSession { return nil } } } if messageType != 0 { return nil } var payload: NSString? guard let _ = olmDevice.createInboundSession(theirDeviceIdentityKey, messageType: messageType, cipherText: messageBody, payload: &payload) else { return nil } return payload as String? } }
apache-2.0
5965d884a5d08d995de891fcfa415409
43.49505
185
0.585336
5.90927
false
false
false
false
benlangmuir/swift
test/IRGen/opaque_result_type_private_underlying.swift
16
4501
// RUN: %target-swift-frontend -disable-availability-checking -emit-ir -primary-file %s -primary-file %S/Inputs/opaque_result_type_private_underlying_2.swift | %FileCheck %s --check-prefix=SINGLEMODULE // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-availability-checking -emit-module -emit-module-path=%t/Repo1.swiftmodule -module-name=Repo1 %S/Inputs/opaque_result_type_private_underlying_2.swift // RUN: %target-swift-frontend -disable-availability-checking -I %t -emit-ir -primary-file %s -DUSEMODULE | %FileCheck %s --check-prefix=NONRESILIENT // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-availability-checking -enable-library-evolution -emit-module -emit-module-path=%t/Repo1.swiftmodule -module-name=Repo1 %S/Inputs/opaque_result_type_private_underlying_2.swift // RUN: %target-swift-frontend -disable-availability-checking -I %t -emit-ir -primary-file %s -DUSEMODULE | %FileCheck %s --check-prefix=RESILIENT // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-availability-checking -enable-library-evolution -emit-module -emit-module-path=%t/Repo1.swiftmodule -module-name=Repo1 %S/Inputs/opaque_result_type_private_underlying_2.swift // RUN: %target-swift-frontend -disable-availability-checking -I %t -emit-ir -primary-file %s -primary-file %S/Inputs/opaque_result_type_private_underlying_3.swift -DUSEMODULE -DUSESECONDFILE | %FileCheck %s --check-prefix=RESILIENT #if USEMODULE import Repo1 #endif // SINGLEMODULE: s37opaque_result_type_private_underlying18UsePublicInlinableVAA1AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}37opaque_result_type_private_underlying7PublicSV // NONRESILIENT: s37opaque_result_type_private_underlying18UsePublicInlinableV5Repo11AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}5Repo17PublicSV // RESILIENT: s37opaque_result_type_private_underlying18UsePublicInlinableV5Repo11AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}5Repo17PublicSV public struct UsePublicInlinable : A { public init() {} public func bindAssoc() -> some Q { return PublicUnderlyingInlinable().bindAssoc() } } // SINGLEMODULE: s37opaque_result_type_private_underlying9UsePublicVAA1AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}37opaque_result_type_private_underlying7PublicSV // NONRESILIENT: s37opaque_result_type_private_underlying9UsePublicV5Repo11AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}5Repo17PublicSV // RESILIENT: s37opaque_result_type_private_underlying9UsePublicV5Repo11AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 5Repo116PublicUnderlyingV9bindAssocQryFQO public struct UsePublic : A { public init() {} public func bindAssoc() -> some Q { return PublicUnderlying().bindAssoc() } } // SINGLEMODULE: s37opaque_result_type_private_underlying11UseInternalVAA1AAAMA" = internal constant { {{.*}}symbolic {{(_____ )?}}37opaque_result_type_private_underlying9InternalSV // NONRESILIENT: s37opaque_result_type_private_underlying11UseInternalV5Repo11AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 5Repo118InternalUnderlyingV9bindAssocQryFQO // RESILIENT: s37opaque_result_type_private_underlying11UseInternalV5Repo11AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 5Repo118InternalUnderlyingV9bindAssocQryFQO public struct UseInternal: A { public init() {} public func bindAssoc() -> some Q { return InternalUnderlying().bindAssoc() } } // SINGLEMODULE: s37opaque_result_type_private_underlying10UsePrivateVAA1AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 37opaque_result_type_private_underlying17PrivateUnderlyingV9bindAssocQryFQO // NONRESILIENT: s37opaque_result_type_private_underlying10UsePrivateV5Repo11AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 5Repo117PrivateUnderlyingV9bindAssocQryFQO // RESILIENT: s37opaque_result_type_private_underlying10UsePrivateV5Repo11AAAMA" = internal constant { {{.*}}symbolic _____y_Qo_ 5Repo117PrivateUnderlyingV9bindAssocQryFQO public struct UsePrivate: A { public init() {} public func bindAssoc() -> some Q { return PrivateUnderlying().bindAssoc() } } #if USESECONDFILE public struct MyThing { public let which: MyEnum public init(_ which: MyEnum) { self.which = which } public var body: some Q { self.thing } public var thing: some Q { self.which.thing } } #endif public struct E<V> { var body : some P { var r = R(V.self, getSome()) r.modify() return r } }
apache-2.0
9a0828351150e2a37dc0a018233694eb
56.705128
232
0.74539
3.710635
false
false
false
false
benlangmuir/swift
test/Parse/try.swift
14
16584
// RUN: %target-typecheck-verify-swift -swift-version 4 // Intentionally has lower precedence than assignments and ?: infix operator %%%% : LowPrecedence precedencegroup LowPrecedence { associativity: none lowerThan: AssignmentPrecedence } func %%%%<T, U>(x: T, y: U) -> Int { return 0 } // Intentionally has lower precedence between assignments and ?: infix operator %%% : MiddlingPrecedence precedencegroup MiddlingPrecedence { associativity: none higherThan: AssignmentPrecedence lowerThan: TernaryPrecedence } func %%%<T, U>(x: T, y: U) -> Int { return 1 } func foo() throws -> Int { return 0 } func bar() throws -> Int { return 0 } var x = try foo() + bar() x = try foo() + bar() x += try foo() + bar() x += try foo() %%%% bar() // expected-error {{'try' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }} x += try foo() %%% bar() x = foo() + try bar() // expected-error {{'try' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} var y = true ? try foo() : try bar() + 0 var z = true ? try foo() : try bar() %%% 0 // expected-error {{'try' following conditional operator does not cover everything to its right}} var a = try! foo() + bar() a = try! foo() + bar() a += try! foo() + bar() a += try! foo() %%%% bar() // expected-error {{'try!' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{22-22=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{22-22=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{22-22=try! }} a += try! foo() %%% bar() a = foo() + try! bar() // expected-error {{'try!' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} var b = true ? try! foo() : try! bar() + 0 var c = true ? try! foo() : try! bar() %%% 0 // expected-error {{'try!' following conditional operator does not cover everything to its right}} infix operator ?+= : AssignmentPrecedence func ?+=(lhs: inout Int?, rhs: Int?) { lhs = lhs! + rhs! } var i = try? foo() + bar() let _: Double = i // expected-error {{cannot convert value of type 'Int?' to specified type 'Double'}} i = try? foo() + bar() i ?+= try? foo() + bar() i ?+= try? foo() %%%% bar() // expected-error {{'try?' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{23-23=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{23-23=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{23-23=try! }} i ?+= try? foo() %%% bar() _ = foo() == try? bar() // expected-error {{'try?' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = (try? foo()) == bar() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }} _ = foo() == (try? bar()) // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = (try? foo()) == (try? bar()) let j = true ? try? foo() : try? bar() + 0 let k = true ? try? foo() : try? bar() %%% 0 // expected-error {{'try?' following conditional operator does not cover everything to its right}} try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }} try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }} try let uninit: Int // expected-error {{'try' must be placed on the initial value expression}} try let (destructure1, destructure2) = (foo(), bar()) // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{40-40=try }} try let multi1 = foo(), multi2 = bar() // expected-error {{'try' must be placed on the initial value expression}} expected-error 2 {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{18-18=try }} expected-note@-1 {{did you mean to use 'try'?}} {{34-34=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{18-18=try? }} expected-note@-2 {{did you mean to handle error as optional value?}} {{34-34=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{18-18=try! }} expected-note@-3 {{did you mean to disable error propagation?}} {{34-34=try! }} class TryDecl { // expected-note {{in declaration of 'TryDecl'}} try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }} // expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}} try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }} // expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}} try // expected-error {{expected declaration}} func method() {} } func test() throws -> Int { try while true { // expected-error {{'try' cannot be used with 'while'}} try break // expected-error {{'try' cannot be used with 'break'}} } try throw // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{3-3=try }} expected-error {{expected expression in 'throw' statement}} ; // Reset parser. try return // expected-error {{'try' cannot be used with 'return'}} expected-error {{non-void function should return a value}} ; // Reset parser. try throw foo() // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{13-13=try }} // expected-error@-1 {{thrown expression type 'Int' does not conform to 'Error'}} try return foo() // expected-error {{'try' must be placed on the returned expression}} {{3-7=}} {{14-14=try }} } // Test operators. func *(a : String, b : String) throws -> Int { return 42 } let _ = "foo" * // expected-error {{operator can throw but expression is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }} "bar" let _ = try! "foo"*"bar" let _ = try? "foo"*"bar" let _ = (try? "foo"*"bar") ?? 0 // <rdar://problem/21414023> Assertion failure when compiling function that takes throwing functions and rethrows func rethrowsDispatchError(handleError: ((Error) throws -> ()), body: () throws -> ()) rethrows { do { body() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} } catch { } } // <rdar://problem/21432429> Calling rethrows from rethrows crashes Swift compiler struct r21432429 { func x(_ f: () throws -> ()) rethrows {} func y(_ f: () throws -> ()) rethrows { x(f) // expected-error {{call can throw but is not marked with 'try'}} expected-note {{call is to 'rethrows' function, but argument function can throw}} } } // <rdar://problem/21427855> Swift 2: Omitting try from call to throwing closure in rethrowing function crashes compiler func callThrowingClosureWithoutTry(closure: (Int) throws -> Int) rethrows { closure(0) // expected-error {{call can throw but is not marked with 'try'}} expected-warning {{result of call to function returning 'Int' is unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{3-3=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{3-3=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{3-3=try! }} } func producesOptional() throws -> Int? { return nil } let _: String = try? producesOptional() // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} let _ = (try? foo())!! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} func producesDoubleOptional() throws -> Int?? { return 3 } let _: String = try? producesDoubleOptional() // expected-error {{cannot convert value of type 'Int???' to specified type 'String'}} func maybeThrow() throws {} try maybeThrow() // okay try! maybeThrow() // okay try? maybeThrow() // okay since return type of maybeThrow is Void _ = try? maybeThrow() // okay let _: () -> Void = { try! maybeThrow() } // okay let _: () -> Void = { try? maybeThrow() } // okay since return type of maybeThrow is Void if try? maybeThrow() { // expected-error {{cannot be used as a boolean}} {{4-4=((}} {{21-21=) != nil)}} } let _: Int = try? foo() // expected-error {{value of optional type 'Int?' not unwrapped; did you mean to use 'try!' or chain with '?'?}} {{14-18=try!}} class X {} func test(_: X) {} func producesObject() throws -> AnyObject { return X() } test(try producesObject()) // expected-error {{'AnyObject' is not convertible to 'X'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{26-26= as! X}} _ = "a\(try maybeThrow())b" _ = try "a\(maybeThrow())b" _ = "a\(maybeThrow())" // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }} extension DefaultStringInterpolation { mutating func appendInterpolation() throws {} } _ = try "a\()b" _ = "a\()b" // expected-error {{interpolation can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} _ = try "\() \(1)" func testGenericOptionalTry<T>(_ call: () throws -> T ) { let _: String = try? call() // expected-error {{cannot convert value of type 'T?' to specified type 'String'}} } func genericOptionalTry<T>(_ call: () throws -> T ) -> T? { let x = try? call() // no error expected return x } // Test with a non-optional type let _: String = genericOptionalTry({ () throws -> Int in return 3 }) // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} // Test with an optional type let _: String = genericOptionalTry({ () throws -> Int? in return nil }) // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} func produceAny() throws -> Any { return 3 } let _: Int? = try? produceAny() as? Int // expected-error {{value of optional type 'Int??' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int?? = (try? produceAny()) as? Int // good let _: String = try? produceAny() as? Int // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} let _: String = (try? produceAny()) as? Int // expected-error {{cannot convert value of type 'Int?' to specified type 'String'}} struct ThingProducer { func produceInt() throws -> Int { return 3 } func produceIntNoThrowing() -> Int { return 3 } func produceAny() throws -> Any { return 3 } func produceOptionalAny() throws -> Any? { return 3 } func produceDoubleOptionalInt() throws -> Int?? { return 3 } } let optProducer: ThingProducer? = ThingProducer() let _: Int? = try? optProducer?.produceInt() // expected-error {{value of optional type 'Int??' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int = try? optProducer?.produceInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'Int'}} let _: String = try? optProducer?.produceInt() // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} let _: Int?? = try? optProducer?.produceInt() // good let _: Int? = try? optProducer?.produceIntNoThrowing() // expected-error {{value of optional type 'Int??' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int?? = try? optProducer?.produceIntNoThrowing() // expected-warning {{no calls to throwing functions occur within 'try' expression}} let _: Int? = (try? optProducer?.produceAny()) as? Int // good let _: Int? = try? optProducer?.produceAny() as? Int // expected-error {{value of optional type 'Int??' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int?? = try? optProducer?.produceAny() as? Int // good let _: String = try? optProducer?.produceAny() as? Int // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}} let _: String = try? optProducer?.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int???' to specified type 'String'}} let producer = ThingProducer() let _: Int = try? producer.produceDoubleOptionalInt() // expected-error {{value of optional type 'Int???' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int? = try? producer.produceDoubleOptionalInt() // expected-error {{value of optional type 'Int???' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int?? = try? producer.produceDoubleOptionalInt() // expected-error {{value of optional type 'Int???' not unwrapped; did you mean to use 'try!' or chain with '?'?}} let _: Int??? = try? producer.produceDoubleOptionalInt() // good let _: String = try? producer.produceDoubleOptionalInt() // expected-error {{cannot convert value of type 'Int???' to specified type 'String'}} // rdar://problem/46742002 protocol Dummy : class {} class F<T> { func wait() throws -> T { fatalError() } } func bar(_ a: F<Dummy>, _ b: F<Dummy>) { _ = (try? a.wait()) === (try? b.wait()) }
apache-2.0
c861308680e6d0f57f278aac9e90353a
59.970588
251
0.615292
3.893872
false
false
false
false
Tiger-Coding/gameofthronescountdown
GOTCountdown/Countdown.swift
1
1628
// // Countdown.swift // GOTCountdown // // Created by user on 4/13/16. // Copyright © 2016 Javoid. All rights reserved. // import Foundation import SwiftDate /** An encapsulated struct that calculates the amount of time remaining until the show starts. */ struct Countdown { /** Made estRegion static because startDateEst depends on this for init, and this way avoids an unecessary optional. */ static private let estRegion = Region(calendarName: nil, timeZoneName: TimeZoneName.AmericaNewYork, localeName: nil) /** The exact global release time the show starts. */ private let startDateEst: DateInRegion = DateInRegion(era: 1, year: 2016, month: 4, day: 24, hour: 21, minute: 0, second: 0, nanosecond: 0, region: Countdown.estRegion) /** create calendar units here so we don't have to re-create them every call. */ private let calendarUnits: NSCalendarUnit = [.Day, .Minute, .Hour, .Second] func remainingTime() -> RemainingTime { // get a local region so we can compare it let localRegion = Region() let localDateInRegion = DateInRegion(absoluteTime: NSDate(), region: localRegion) // difference returns an optional, so guard it guard let difference = localDateInRegion.difference(startDateEst, unitFlags: calendarUnits) else { return RemainingTime() } return RemainingTime(days: difference.day, hours: difference.hour, minutes: difference.minute, seconds: difference.second) } func showStartDate() -> NSDate { return startDateEst.absoluteTime } }
mit
f0bb11032d6356d119e9bac68fdfe6a3
36.837209
172
0.682852
4.622159
false
false
false
false
ACChe/eidolon
Kiosk/Auction Listings/ListingsViewModel.swift
1
11487
import Foundation import ReactiveCocoa typealias ShowDetailsClosure = (SaleArtwork) -> Void typealias PresentModalClosure = (SaleArtwork) -> Void protocol ListingsViewModelType { var auctionID: String { get } var syncInterval: NSTimeInterval { get } var pageSize: Int { get } var schedule: (RACSignal, RACScheduler) -> RACSignal { get } var logSync: (AnyObject!) -> Void { get } var numberOfSaleArtworks: Int { get } var showSpinnerSignal: RACSignal! { get } var gridSelectedSignal: RACSignal! { get } var updatedContentsSignal: RACSignal! { get } func saleArtworkViewModelAtIndexPath(indexPath: NSIndexPath) -> SaleArtworkViewModel func showDetailsForSaleArtworkAtIndexPath(indexPath: NSIndexPath) func presentModalForSaleArtworkAtIndexPath(indexPath: NSIndexPath) func imageAspectRatioForSaleArtworkAtIndexPath(indexPath: NSIndexPath) -> CGFloat? } class ListingsViewModel: NSObject, ListingsViewModelType { // These are private to the view model – should not be accessed directly private dynamic var saleArtworks = Array<SaleArtwork>() private dynamic var sortedSaleArtworks = Array<SaleArtwork>() let auctionID: String let pageSize: Int let syncInterval: NSTimeInterval let logSync: (AnyObject!) -> Void var schedule: (RACSignal, RACScheduler) -> RACSignal var numberOfSaleArtworks: Int { return saleArtworks.count } var showSpinnerSignal: RACSignal! var gridSelectedSignal: RACSignal! var updatedContentsSignal: RACSignal! { return RACObserve(self, "sortedSaleArtworks").distinctUntilChanged().mapArrayLengthExistenceToBool().ignore(false).map { _ -> AnyObject! in NSDate() } } let showDetails: ShowDetailsClosure let presentModal: PresentModalClosure init(selectedIndexSignal: RACSignal, showDetails: ShowDetailsClosure, presentModal: PresentModalClosure, pageSize: Int = 10, syncInterval: NSTimeInterval = SyncInterval, logSync: (AnyObject!) -> Void = ListingsViewModel.DefaultLogging, schedule: (signal: RACSignal, scheduler: RACScheduler) -> RACSignal = ListingsViewModel.DefaultScheduler, auctionID: String = AppSetup.sharedState.auctionID) { self.auctionID = auctionID self.showDetails = showDetails self.presentModal = presentModal self.pageSize = pageSize self.syncInterval = syncInterval self.logSync = logSync self.schedule = schedule super.init() setup(selectedIndexSignal) } // MARK: Private Methods private func setup(selectedIndexSignal: RACSignal) { RAC(self, "saleArtworks") <~ recurringListingsRequestSignal().takeUntil(self.rac_willDeallocSignal()) showSpinnerSignal = RACObserve(self, "saleArtworks").mapArrayLengthExistenceToBool().not() gridSelectedSignal = selectedIndexSignal.map { return ListingsViewModel.SwitchValues(rawValue: $0 as! Int) == .Some(.Grid) } let sortedSaleArtworksSignal = RACSignal.combineLatest([RACObserve(self, "saleArtworks").distinctUntilChanged(), selectedIndexSignal]).map { let tuple = $0 as! RACTuple let saleArtworks = tuple.first as! [SaleArtwork] let selectedIndex = tuple.second as! Int if let switchValue = ListingsViewModel.SwitchValues(rawValue: selectedIndex) { return switchValue.sortSaleArtworks(saleArtworks) } else { // Necessary for compiler – won't execute return saleArtworks } } RAC(self, "sortedSaleArtworks") <~ sortedSaleArtworksSignal } private func listingsRequestSignalForPage(page: Int) -> RACSignal { return XAppRequest(.AuctionListings(id: auctionID, page: page, pageSize: self.pageSize)).filterSuccessfulStatusCodes().mapJSON() } // Repeatedly calls itself with page+1 until the count of the returned array is < pageSize. private func retrieveAllListingsRequestSignal(page: Int) -> RACSignal { return RACSignal.createSignal { [weak self] (subscriber) -> RACDisposable! in self?.listingsRequestSignalForPage(page).subscribeNext { (object) -> () in if let array = object as? Array<AnyObject> { var nextPageSignal = RACSignal.empty() if array.count >= (self?.pageSize ?? 0) { // Infer we have more results to retrieve nextPageSignal = self?.retrieveAllListingsRequestSignal(page+1) ?? RACSignal.empty() } RACSignal.`return`(object).concat(nextPageSignal).subscribe(subscriber) } } return nil } } // Fetches all pages of the auction private func allListingsRequestSignal() -> RACSignal { return schedule(schedule(retrieveAllListingsRequestSignal(1), RACScheduler(priority: RACSchedulerPriorityDefault)).collect().map({ (object) -> AnyObject! in // object is an array of arrays (thanks to collect()). We need to flatten it. let array = object as? Array<Array<AnyObject>> return (array ?? []).reduce(Array<AnyObject>(), combine: +) }).mapToObjectArray(SaleArtwork.self).`catch`({ (error) -> RACSignal! in logger.log("Sale Artworks: Error handling thing: \(error.artsyServerError())") return RACSignal.empty() }), RACScheduler.mainThreadScheduler()) } private func recurringListingsRequestSignal() -> RACSignal { let recurringSignal = RACSignal.interval(syncInterval, onScheduler: RACScheduler.mainThreadScheduler()).startWith(NSDate()).takeUntil(rac_willDeallocSignal()) return recurringSignal.doNext(logSync).map { [weak self] _ -> AnyObject! in return self?.allListingsRequestSignal() ?? RACSignal.empty() }.switchToLatest().map { [weak self] (newSaleArtworks) -> AnyObject! in guard self != nil else { return [] } // Now safe to use self! let currentSaleArtworks = self!.saleArtworks func update(currentSaleArtworks: [SaleArtwork], newSaleArtworks: [SaleArtwork]) -> Bool { assert(currentSaleArtworks.count == newSaleArtworks.count, "Arrays' counts must be equal.") // Updating the currentSaleArtworks is easy. Both are already sorted as they came from the API (by lot #). // Because we assume that their length is the same, we just do a linear scan through and // copy values from the new to the existing. let saleArtworksCount = currentSaleArtworks.count for var i = 0; i < saleArtworksCount; i++ { if currentSaleArtworks[i].id == newSaleArtworks[i].id { currentSaleArtworks[i].updateWithValues(newSaleArtworks[i]) } else { // Failure: the list was the same size but had different artworks. return false } } return true } // So we want to do here is pretty simple – if the existing and new arrays are of the same length, // then update the individual values in the current array and return the existing value. // If the array's length has changed, then we pass through the new array if let newSaleArtworks = newSaleArtworks as? Array<SaleArtwork> { if newSaleArtworks.count == currentSaleArtworks.count { if update(currentSaleArtworks, newSaleArtworks: newSaleArtworks) { return currentSaleArtworks } } } return newSaleArtworks } } // MARK: Private class methods private class func DefaultLogging(date: AnyObject!) { #if (arch(i386) || arch(x86_64)) && os(iOS) logger.log("Syncing on \(date)") #endif } private class func DefaultScheduler(signal: RACSignal, _ scheduler: RACScheduler) -> RACSignal { return signal.deliverOn(scheduler) } // MARK: Public methods func saleArtworkViewModelAtIndexPath(indexPath: NSIndexPath) -> SaleArtworkViewModel { return sortedSaleArtworks[indexPath.item].viewModel } func imageAspectRatioForSaleArtworkAtIndexPath(indexPath: NSIndexPath) -> CGFloat? { return sortedSaleArtworks[indexPath.item].artwork.defaultImage?.aspectRatio } func showDetailsForSaleArtworkAtIndexPath(indexPath: NSIndexPath) { showDetails(sortedSaleArtworks[indexPath.item]) } func presentModalForSaleArtworkAtIndexPath(indexPath: NSIndexPath) { presentModal(sortedSaleArtworks[indexPath.item]) } // MARK: - Switch Values enum SwitchValues: Int { case Grid = 0 case LeastBids case MostBids case HighestCurrentBid case LowestCurrentBid case Alphabetical var name: String { switch self { case .Grid: return "Grid" case .LeastBids: return "Least Bids" case .MostBids: return "Most Bids" case .HighestCurrentBid: return "Highest Bid" case .LowestCurrentBid: return "Lowest Bid" case .Alphabetical: return "A–Z" } } func sortSaleArtworks(saleArtworks: [SaleArtwork]) -> [SaleArtwork] { switch self { case Grid: return saleArtworks case LeastBids: return saleArtworks.sort(leastBidsSort) case MostBids: return saleArtworks.sort(mostBidsSort) case HighestCurrentBid: return saleArtworks.sort(highestCurrentBidSort) case LowestCurrentBid: return saleArtworks.sort(lowestCurrentBidSort) case Alphabetical: return saleArtworks.sort(alphabeticalSort) } } static func allSwitchValues() -> [SwitchValues] { return [Grid, LeastBids, MostBids, HighestCurrentBid, LowestCurrentBid, Alphabetical] } static func allSwitchValueNames() -> [String] { return allSwitchValues().map{$0.name.uppercaseString} } } } // MARK: - Sorting Functions func leastBidsSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return (lhs.bidCount ?? 0) < (rhs.bidCount ?? 0) } func mostBidsSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return !leastBidsSort(lhs, rhs) } func lowestCurrentBidSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return (lhs.highestBidCents ?? 0) < (rhs.highestBidCents ?? 0) } func highestCurrentBidSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return !lowestCurrentBidSort(lhs, rhs) } func alphabeticalSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return lhs.artwork.sortableArtistID().caseInsensitiveCompare(rhs.artwork.sortableArtistID()) == .OrderedAscending } func sortById(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool { return lhs.id.caseInsensitiveCompare(rhs.id) == .OrderedAscending }
mit
c5d62c4a6b455c63205c4f0cd44d9b56
38.582759
166
0.637076
5.453207
false
false
false
false
sudiptasahoo/IVP-Luncheon
IVP Luncheon/SSCommonUtilities.swift
1
1242
// // SSCommonUtilities.swift // IVP Luncheon // // Created by Sudipta Sahoo on 23/05/17. // Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved. // import UIKit class SSCommonUtilities: NSObject { //MARK: Network Indicator Related Utilities static var networkQueue = 0; class func addTaskToNetworkQueue() -> Void{ networkQueue += 1 updateNetworkIndicatorStatus() } class func removeTaskFromNetworkQueue() -> Void{ networkQueue -= 1 updateNetworkIndicatorStatus() } class func updateNetworkIndicatorStatus(){ if(networkQueue > 0){ UIApplication.shared.isNetworkActivityIndicatorVisible = true } else if (networkQueue <= 0){ UIApplication.shared.isNetworkActivityIndicatorVisible = false } } class func instantiateViewController(_ withName: String) -> Any{ let storyboard = UIStoryboard(name: "Main", bundle: nil) return storyboard.instantiateViewController(withIdentifier: withName) } }
apache-2.0
97d96ac84fc1e92c6f5823cd2941bc6c
29.268293
236
0.680902
5.024291
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
AwesomeAdsDemo/CreativeViewModel.swift
1
3038
import UIKit import SuperAwesome class CreativeViewModel: NSObject { private let cdnUrl: String = "https://s3-eu-west-1.amazonaws.com/beta-ads-video-transcoded-thumbnails/" private var adFormat: AdFormat = .unknown private var ad: DemoAd! private var index: Int = 0 private var remoteUrl: String? private var localUrl: String! init (withAd ad: DemoAd, atIndex index: Int) { self.index = index self.ad = ad self.adFormat = AdFormat.fromCreative(ad.creative) switch adFormat { case .unknown: localUrl = "icon_placeholder"; break; case .smallbanner: localUrl = "smallbanner"; break; case .banner: localUrl = "banner"; break case .smallleaderboard: localUrl = "imac468x60"; break; case .leaderboard: localUrl = "leaderboard"; break case .pushdown: localUrl = "imac970x90"; break; case .billboard: localUrl = "imac970x250"; break; case .skinnysky: localUrl = "imac120x600"; break case .sky: localUrl = "imac300x600"; break; case .mpu: localUrl = "mpu"; break; case .doublempu: localUrl = "imac300x600"; break; case .mobile_portrait_interstitial: localUrl = "small_inter_port"; break; case .mobile_landscape_interstitial: localUrl = "small_inter_land"; break; case .tablet_portrait_interstitial: localUrl = "large_inter_port"; break; case .tablet_landscape_interstitial: localUrl = "large_inter_land"; break; case .video: localUrl = "video"; break; case .gamewall: localUrl = "appwall"; break; } } var name: String { return ad.creative.name } var source: String { var source = "Source: " switch ad.creative.format { case .imageWithLink: source += "Image" break case .video: source += "MP4 Video" break case .richMedia: source += "Rich Media" break case .tag: source += "3rd Party Tag" break default: source += "Unknown" break } return source } func getFormat () -> AdFormat { return adFormat } var creativeFormat: String { return "Format: \(self.adFormat.toString())" } func getLocalUrl () -> String { return localUrl! } func getRemoteUrl () -> URL? { if let url = remoteUrl { return URL(string: url) } else { return nil } } func getAd () -> DemoAd { return ad } var osTarget: String { var os = "System: " if let targets = ad.creative.osTarget { os += targets.count == 0 ? "All" : targets.joined(separator: ",") } else { os += "N/A" } return os } var backgroundColor: UIColor { return index % 2 == 0 ? UIColor(rgb: 0xf7f7f7) : .white } }
apache-2.0
215afd688021ef94b0c8a960d7d94180
28.495146
107
0.553654
4.321479
false
false
false
false
natecook1000/swift-compiler-crashes
fixed/27135-swift-patternbindingdecl-setpattern.swift
4
2231
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{{ let : T:a<T where f enum b {struct A enum B}protocol a{ let a=f:A{var" let a { let c{ class d{{ }typealias d {func f g class A { struct d<S where B{ let : N < where h:a var f _}}}} struct S<T where g:d {{{ class B{ var b{ <f {let:d { class b:d{ " { var b{ let : d:A struct d:d { B{ struct B<T where " {{a enum B<T where f: T> : a{var b=Swift.h =1 func f g < where " "" {}struct B<T where f: d< where B : T.h =1 < where h:A func f g:a func let a = " " class d func g a<T {var b { class B<f=1 var b{ var f= let : d:P { class A class A class A{ class A { }}protocol a= func aA} "" class b<f= struct B<T> : { B<T where B{var b:e}}struct S<f:P { let a = " { func foo}typealias d<T where f func aA} struct S<T where " { let : T:e let:d{var" var b { " func a <T {let:d< {func a{{let:A }}} < where h: d B{{ " " " " func a=1 class A var b{ { where =1 class b<T where a = f: a= protocol B:a = " [ 1 {{{ protocol B{ let a func < where h: { class A {}} protocol a{var b {b{{ protocol B:a func struct S<T where =f: { { enum :a<T where g:e let:d struct S<T { func A protocol B{var f= let c{ enum B:P { enum S<T where B : d where a func let a = " {var b:d where g:a<{{var"""" class B<f:A struct S<h {var b {}typealias d< where h: d where f class d<T where g:d<T where g struct B{{ enum b { protocol B{ protocol a class A class B{ class A { { let a<T where B{ let : d:P { struct A enum S<f:d:e}}struct S<T where h:e class d let a func class A<T where f=Swift.E let a = f:d { func g a enum B<T where B : a{ func g a<T where g:d where g:d func a class a<T where " [ 1 class A {var b:d {b<T:a{ }protocol B} class d{} _}}typealias d let a {var f=1 let c{var b { class A { func aA}}}typealias d func f g:a=f:P {{ class A { protocol B} func foo}} let c<f=1 class A class {{ let : T:A{func g a{struct B{ <T { class A { class d<T where g:a var b<T where g func f g:a protocol a<T where g:d<T where h:A class A{ { class d<S where f: {{ protocol a{ class a<T.e}}}} let a{ { enum S<f class a{let:T {b {{ func g a var b:T>: T func foo} let a{ let : d:d enum B{var b{a{struct S<T:A<T <T
mit
fd333d10e1c913ecc9e25fda8f2347c7
13.677632
87
0.619005
2.253535
false
false
false
false
Olinguito/YoIntervengoiOS
Yo Intervengo/Views/Filter/FilterVC.swift
1
1411
// // FilterVC.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 1/21/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit class FilterVC: GenericViewController,UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var segmented: UISegmentedControl! @IBOutlet weak var container: UIView! @IBOutlet weak var btnSearch: UIButton! @IBOutlet weak var btnErase: UIButton! override func viewDidLoad() { super.viewDidLoad() btnErase.titleLabel?.font = UIFont(name: "Roboto-Light", size: 18) btnErase.setTitleColor(UIColor.addThemeContrast(), forState: UIControlState.Normal) btnErase.layer.borderColor = UIColor.addThemeContrast().CGColor btnErase.layer.borderWidth = 1 btnSearch.titleLabel?.font = UIFont(name: "Roboto-Light", size: 18) btnSearch.setTitleColor(UIColor.addThemeContrast(), forState: UIControlState.Normal) btnSearch.layer.borderColor = UIColor.addThemeContrast().CGColor btnSearch.layer.borderWidth = 1 searchBar.backgroundColor = UIColor.clearColor() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = "" searchBar.resignFirstResponder() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
73ffb2932456a088c3f2e88835790dda
34.275
92
0.705174
4.766892
false
false
false
false
digitalsurgeon/SwiftWebSocket
websocketserver/websockethandler.swift
1
11751
// // websockethandler.swift // websocketserver // // Created by Ahmad Mushtaq on 17/05/15. // Copyright (c) 2015 Ahmad Mushtaq. All rights reserved. // Portions of this code from the Qt Websockets library // qwebsockets git at http://code.qt.io/cgit/qt/qtwebsockets.git/ import Foundation @objc(WebSocketHandler) class WebSocketHandler: Handler { enum ProcessingState { case PS_READ_HEADER case PS_READ_PAYLOAD_LENGTH case PS_READ_BIG_PAYLOAD_LENGTH case PS_READ_MASK case PS_READ_PAYLOAD case PS_DISPATCH_RESULT case PS_WAIT_FOR_MORE_DAT } enum OpCode: UInt8 { case OpCodeContinue = 0x0 case OpCodeText = 0x1 case OpCodeBinary = 0x2 case OpCodeReserved3 = 0x3 case OpCodeReserved4 = 0x4 case OpCodeReserved5 = 0x5 case OpCodeReserved6 = 0x6 case OpCodeReserved7 = 0x7 case OpCodeClose = 0x8 case OpCodePing = 0x9 case OpCodePong = 0xA case OpCodeReservedB = 0xB case OpCodeReservedC = 0xC case OpCodeReservedD = 0xD case OpCodeReservedE = 0xE case OpCodeReservedF = 0xF } func messageReceived(var frame: WebSocketFrame) { Swell.info("Message received: \(frame.payLoad)") } func messageSent(var tag:Int, success: Bool) { Swell.info("Message with tag \(tag) sent: \(success)") } func connected() { Swell.info("Connected") } func disconnected() { Swell.info("Disconnected") } func send(var data:NSData, var tag: Int) { //maximum size of a frame when sending a message let FRAME_SIZE_IN_BYTES = 512 * 512 * 2; //currently only support text messages let firstOpCode:OpCode = .OpCodeText var numFrames = (data.length / FRAME_SIZE_IN_BYTES) if numFrames == 0 { numFrames = 1 } var bytesWritten = 0 for (var i = 0; i < numFrames; ++i) { var maskingKey:UInt32 = 0 //generateMaskingKey(); let isLastFrame = (i == (numFrames - 1)) let isFirstFrame = (i == 0) let opcode = isFirstFrame ? firstOpCode : .OpCodeContinue; var header: NSMutableData = NSMutableData(data: getFrameHeader(opcode, payloadLength: UInt64(data.length), maskingKey: maskingKey, lastFrame: isLastFrame)) var buffer:[UInt8] = [UInt8] (count: data.length, repeatedValue: 0) data.getBytes(&buffer, length: buffer.count) //web socket server does not mask the data it sends. //applyMask(&buffer, payloadSize: buffer.count, maskingKey: maskingKey) header.appendBytes(&buffer, length: buffer.count) socket!.writeData(header, withTimeout: 10, tag: tag) } } override func handle(var request:Request, var socket: GCDAsyncSocket) { super.handle(request, socket: socket) Swell.info("WSH - Handling web socket") if let webSocketKey = request.headers["Sec-WebSocket-Key"] { var webSocketResponseKey = generateWebSocketAcceptKey(webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") Swell.info("websocket response key:" + webSocketResponseKey) var response = Response(socket: socket) response.setCode(Response.Code.WebSocketHandShake) response.addHeader("Sec-WebSocket-Accept", value: webSocketResponseKey) response.addHeader("Connection", value: "Upgrade") response.addHeader("Upgrade", value: "websocket") response.generateResponse() socket.readDataWithTimeout(-1, tag: 0) } } func generateWebSocketAcceptKey(var s:String) -> String { let str = s.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(s.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_SHA1_DIGEST_LENGTH) let result = UnsafeMutablePointer<UInt8>.alloc(digestLen) CC_SHA1(str!, strLen, result) var ns:NSData = NSData(bytes: result, length: digestLen) var key = ns.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0)) result.destroy() return key } func getFrameHeader(var opCode:OpCode, var payloadLength:UInt64, var maskingKey:UInt32, var lastFrame:Bool) -> NSData { var header = NSMutableData() var byte:UInt8 = (opCode.rawValue & 0x0F) | (lastFrame ? 0x80 : 0x00) header.appendBytes(&byte, length: 1) byte = 0x00 if maskingKey != 0 { byte |= 0x80 } if payloadLength <= 125 { byte |= UInt8(payloadLength) header.appendBytes(&byte, length:1) } else if payloadLength <= 0xFFFF { byte |= 126 header.appendBytes(&byte, length: 1) var swapped = UInt16(payloadLength).bigEndian header.appendBytes(&swapped, length:2); } else if payloadLength <= 0x7FFFFFFFFFFFFFFF { byte |= 127 header.appendBytes(&byte, length: 1) var swapped = UInt64(payloadLength).bigEndian header.appendBytes(&swapped, length: 8); } if maskingKey != 0 { var mask = maskingKey.bigEndian header.appendBytes(&mask, length: 4) } return header } func generateMaskingKey() -> UInt32 { return UInt32(arc4random_uniform(UInt32.max)+1) } func applyMask( inout payload: [UInt8], var payloadSize: Int, var maskingKey:UInt32 ) { var mask: [UInt8] = [ UInt8((maskingKey & 0xFF000000) >> 24), UInt8((maskingKey & 0x00FF0000) >> 16), UInt8((maskingKey & 0x0000FF00) >> 8), UInt8((maskingKey & 0x000000FF)) ] for var i = 0; i < payloadSize; ++i { payload[i] ^= mask[i % 4] } } struct WebSocketFrame { var isFinalFrame: Bool var opCode: OpCode var payLoad: NSData? } func parseWebSocketIncomingFrame(data: NSData) -> WebSocketFrame? { var processingState = ProcessingState.PS_READ_HEADER; var payloadLength:UInt64 = 0 var mask : UInt32 = 0 var index: Int = 0 var isFinalFrame: Bool = false var hasMask: Bool = false var payload: NSData? = nil var opCode:OpCode = OpCode.OpCodeText while processingState != .PS_DISPATCH_RESULT { switch processingState { case .PS_READ_HEADER: var buffer = [UInt8](count: 2, repeatedValue: 0); data.getBytes(&buffer, range: NSRange(location: index, length:buffer.count)) index += buffer.count isFinalFrame = (buffer[0] & 0x80) != 0 // don't care about rsv values. //var rsv1 = (buffer[0] & 0x40); //var rsv2 = (buffer[0] & 0x20); //var rsv3 = (buffer[0] & 0x10); opCode = OpCode(rawValue: buffer[0] & 0x0F)!; hasMask = (buffer[1] & 0x80) != 0; var frame_length:UInt8 = (buffer[1] & 0x7F); switch frame_length { case 126: processingState = .PS_READ_PAYLOAD_LENGTH; case 127: processingState = .PS_READ_BIG_PAYLOAD_LENGTH; default: payloadLength = UInt64 (frame_length); processingState = hasMask ? .PS_READ_MASK : .PS_READ_PAYLOAD; } case .PS_READ_PAYLOAD_LENGTH: var buffer = [UInt8](count: 2, repeatedValue: 0); data.getBytes(&buffer, range: NSRange(location: index, length:buffer.count)) index += buffer.count let u16 = UnsafePointer<UInt16>(buffer).memory.bigEndian payloadLength = UInt64(u16) if payloadLength < 126 { //see http://tools.ietf.org/html/rfc6455#page-28 paragraph 5.2 //"in all cases, the minimal number of bytes MUST be used to encode //the length, for example, the length of a 124-byte-long string //can't be encoded as the sequence 126, 0, 124" // some error situation. but I dont care about this. processingState = .PS_DISPATCH_RESULT } else { processingState = hasMask ? .PS_READ_MASK : .PS_READ_PAYLOAD; } case .PS_READ_BIG_PAYLOAD_LENGTH: var buffer = [UInt8](count: 8, repeatedValue: 0); data.getBytes(&buffer, range: NSRange(location: index, length:buffer.count)) index += buffer.count let u64 = UnsafePointer<UInt64>(buffer).memory.bigEndian payloadLength = UInt64(u64) case .PS_READ_MASK: var buffer = [UInt8](count: 4, repeatedValue: 0); data.getBytes(&buffer, range: NSRange(location: index, length:buffer.count)) index += buffer.count let u32 = UnsafePointer<UInt32>(buffer).memory.bigEndian mask = UInt32(u32) processingState = .PS_READ_PAYLOAD case .PS_READ_PAYLOAD: var buffer = [UInt8](count: Int(payloadLength), repeatedValue: 0) data.getBytes(&buffer, range: NSRange(location: index, length:buffer.count)) applyMask(&buffer, payloadSize: buffer.count, maskingKey: mask) payload = NSData(bytes: &buffer, length: buffer.count) processingState = .PS_DISPATCH_RESULT default: Swell.info("default case in parseWebSocketIncomingFrame") return nil } } return WebSocketFrame(isFinalFrame: isFinalFrame, opCode: opCode, payLoad: payload) } func socket(socket: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { Swell.info("WSH - Read some data. length:\(data.length)") let frame: WebSocketFrame? = parseWebSocketIncomingFrame(data) if let f = frame { switch f.opCode { case .OpCodeClose: disconnect() default: messageReceived(f) socket.readDataWithTimeout(-1, tag: 0) } } } func socket(socket:GCDAsyncSocket, didWriteDataWithTag: Int) { Swell.info("WSH - Did write data witg tag " + String(didWriteDataWithTag)) messageSent(didWriteDataWithTag, success: true) } func socket(sock: GCDAsyncSocket!, shouldTimeoutWriteWithTag tag: Int, elapsed: NSTimeInterval, bytesDone length: UInt) -> NSTimeInterval { messageSent(tag, success: false) return 0 } func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) { disconnected() } }
mit
4e78359ce964dee9cbffa1253ff4bc60
35.607477
167
0.547783
4.687276
false
false
false
false
yulingtianxia/Spiral
Spiral/ZenHelpScene.swift
1
1859
// // ZenHelpScene.swift // Spiral // // Created by 杨萧玉 on 15/5/3. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import SpriteKit class ZenHelpScene: SKScene { func lightWithFinger(_ point:CGPoint){ if let light = self.childNode(withName: "light") as? SKLightNode { light.lightColor = SKColor.white light.position = self.convertPoint(fromView: point) } } func turnOffLight() { (self.childNode(withName: "light") as? SKLightNode)?.lightColor = SKColor.brown } func back() { if !Data.sharedData.gameOver { return } DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { () -> Void in Data.sharedData.currentMode = .zen Data.sharedData.gameOver = false Data.sharedData.reset() let gvc = UIApplication.shared.keyWindow?.rootViewController as! GameViewController gvc.startRecordWithHandler { () -> Void in DispatchQueue.main.async(execute: { () -> Void in if self.scene is ZenHelpScene { gvc.addGestureRecognizers() let scene = ZenModeScene(size: self.size) let push = SKTransition.push(with: SKTransitionDirection.right, duration: 1) push.pausesIncomingScene = false self.scene?.view?.presentScene(scene, transition: push) } }) } } } override func didMove(to view: SKView) { let bg = childNode(withName: "background") as! SKSpriteNode let w = bg.size.width let h = bg.size.height let scale = max(view.frame.width/w, view.frame.height/h) bg.xScale = scale bg.yScale = scale } }
apache-2.0
83a7547df2c098f258bdb013a1e1dda3
33.166667
100
0.564228
4.600998
false
false
false
false
MrAlek/Swift-NSFetchedResultsController-Trickery
CoreDataTrickerySwift/ToDoListController.swift
1
8272
// // ToDoListController.swift // CoreDataTrickerySwift // // Created by Alek Astrom on 2014-07-30. // Copyright (c) 2014 Apps and Wonders. All rights reserved. // import CoreData /// Class used to display ToDo's in a table view class ToDoListController: NSObject { // // MARK: - Internal properties // /// Array of ControllerSectionInfo objects, each object representing a section in a table view fileprivate(set) var sections: [ControllerSectionInfo] = [] /// Set to true to enable empty sections to be shown, delegate will be noticed of these changes var showsEmptySections: Bool = false { didSet { if showsEmptySections == oldValue { return } delegate!.controllerWillChangeContent!(toDosController as! NSFetchedResultsController<NSFetchRequestResult>) let changedEmptySections = sectionInfoWithEmptySections(true) notifyDelegateOfChangedEmptySections(changedEmptySections, changeType: showsEmptySections ? .insert : .delete) sections = sectionInfoWithEmptySections(showsEmptySections) delegate?.controllerDidChangeContent?(toDosController as! NSFetchedResultsController<NSFetchRequestResult>) } } /// Used to receive updates about changes in sections and rows var delegate: NSFetchedResultsControllerDelegate? // // MARK: - Private properties // fileprivate var oldSectionsDuringFetchUpdate: [ControllerSectionInfo] = [] fileprivate lazy var toDosController: NSFetchedResultsController<ToDoMetaData> = { let fetchRequest = NSFetchRequest<ToDoMetaData>(entityName: ToDoMetaData.entityName) fetchRequest.relationshipKeyPathsForPrefetching = ["toDo"] fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "sectionIdentifier", ascending: true), NSSortDescriptor(key: "internalOrder", ascending: false)] let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: "sectionIdentifier", cacheName: nil) try! controller.performFetch() controller.delegate = self return controller }() fileprivate var managedObjectContext: NSManagedObjectContext fileprivate var listConfiguration: ToDoListConfiguration // // MARK: - Internal methods // /** Initializes a ToDoListController with a given managed object context - parameter managedObjectContext: The context to fetch ToDo's from */ init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext self.listConfiguration = ToDoListConfiguration.defaultConfiguration(managedObjectContext) super.init() sections = sectionInfoWithEmptySections(false) } /** Used to get all the fetched ToDo's - returns: All fetched ToDo's in provided managed object context */ func fetchedToDos() -> [ToDo] { return toDosController.fetchedObjects?.map { $0.toDo } ?? [] } /** Used to get a single ToDo for a given index path - parameter indexPath: The index path for a ToDo in the table view - returns: An optional ToDo if a ToDo was found at the provided index path */ func toDoAtIndexPath(_ indexPath: IndexPath) -> ToDo? { let sectionInfo = sections[indexPath.section] guard let section = sectionInfo.fetchedIndex else { return nil } let indexPath = IndexPath(row: indexPath.row, section: section) return toDosController.object(at: indexPath).toDo } /// Reloads all data internally, does not notify delegate of eventual changes in sections or rows func reloadData() { try! toDosController.performFetch() sections = sectionInfoWithEmptySections(showsEmptySections) } // // MARK: - Private methods // fileprivate func sectionInfoWithEmptySections(_ includeEmptySections: Bool) -> [ControllerSectionInfo] { guard let fetchedSectionNames = toDosController.sections?.map({$0.name}) else { return [] } if includeEmptySections { let configuration = ToDoListConfiguration.defaultConfiguration(managedObjectContext) // Map sections to sectionInfo structs with each section and its fetched index return configuration.sections.map { section in let fetchedIndex = fetchedSectionNames.firstIndex(of: section.rawValue) return ControllerSectionInfo(section: section, fetchedIndex: fetchedIndex, fetchController: (toDosController as! NSFetchedResultsController<NSFetchRequestResult>) ) } } else { // Just get all the sections from the fetched results controller let rawSectionValuesIndexes = fetchedSectionNames.map { ($0, fetchedSectionNames.firstIndex(of: $0)) } return rawSectionValuesIndexes.map { ControllerSectionInfo(section: ToDoSection(rawValue: $0.0)!, fetchedIndex: $0.1, fetchController: (toDosController as! NSFetchedResultsController<NSFetchRequestResult>)) } } } fileprivate func notifyDelegateOfChangedEmptySections(_ changedSections: [ControllerSectionInfo], changeType: NSFetchedResultsChangeType) { for (index, sectionInfo) in changedSections.enumerated() { if sectionInfo.fetchedIndex == nil { delegate?.controller?((toDosController as! NSFetchedResultsController<NSFetchRequestResult>), didChange: sectionInfo, atSectionIndex: index, for: changeType) } } } fileprivate func displayedIndexPathForFetchedIndexPath(_ fetchedIndexPath: IndexPath, sections: [ControllerSectionInfo]) -> IndexPath? { // Ugh, I hate this implementation but as of Swift 2, other options are just less intuitive and needs more code for (sectionIndex, sectionInfo) in sections.enumerated() { if sectionInfo.fetchedIndex == fetchedIndexPath.section { return IndexPath(row: fetchedIndexPath.row, section: sectionIndex) } } return nil } } // // MARK: - NSFetchedResultsControllerDelegate extension // extension ToDoListController: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { oldSectionsDuringFetchUpdate = sections // Backup delegate?.controllerWillChangeContent?(controller) } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { // Regenerate section info sections = sectionInfoWithEmptySections(showsEmptySections) // When we show empty sections, fetched section changes don't affect our delegate if !showsEmptySections { delegate?.controller?(controller, didChange: sectionInfo, atSectionIndex: sectionIndex, for: type) } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { let metaData = anObject as! ToDoMetaData // Convert fetched indexpath to displayed index paths let displayedOldIndexPath = indexPath.flatMap { displayedIndexPathForFetchedIndexPath($0, sections: oldSectionsDuringFetchUpdate) } let displayedNewIndexPath = newIndexPath.flatMap { displayedIndexPathForFetchedIndexPath($0, sections: sections) } delegate?.controller?(controller, didChange: metaData.toDo, at: displayedOldIndexPath, for: type, newIndexPath: displayedNewIndexPath) } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { delegate?.controllerDidChangeContent?(controller) } }
mit
ea3db3804a5d865971a141d59415e0cb
42.767196
210
0.692336
6.082353
false
false
false
false
Palleas/Rewatch
Rewatch/Settings/ShowTableViewCell.swift
1
1982
// // ShowTableViewCell.swift // Rewatch // // Created by Romain Pouclet on 2016-03-27. // Copyright © 2016 Perfectly-Cooked. All rights reserved. // import UIKit protocol ShowTableViewCellDelegate: class { func didToggleCell(cell: ShowTableViewCell, on: Bool) } class ShowTableViewCell: UITableViewCell { private let titleLabel = UILabel() private let showCheckmark = UIImageView(image: UIImage(named: "check")) weak var delegate: ShowTableViewCellDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .Default, reuseIdentifier: reuseIdentifier) titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) showCheckmark.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(showCheckmark) titleLabel.leftAnchor.constraintEqualToAnchor(contentView.leftAnchor, constant: 10).active = true titleLabel.centerYAnchor.constraintEqualToAnchor(contentView.centerYAnchor).active = true titleLabel.rightAnchor.constraintEqualToAnchor(showCheckmark.leftAnchor, constant: 5).active = true titleLabel.textColor = Stylesheet.settingsTintColor titleLabel.highlightedTextColor = Stylesheet.settingsHighlightedTintColor titleLabel.font = Stylesheet.showCellTitleFont showCheckmark.rightAnchor.constraintEqualToAnchor(contentView.rightAnchor, constant: -10).active = true showCheckmark.centerYAnchor.constraintEqualToAnchor(contentView.centerYAnchor).active = true showCheckmark.widthAnchor.constraintEqualToConstant(22).active = true selectedBackgroundView = UIView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configureWithTitle(title: String, includeInRandom: Bool) { titleLabel.text = title showCheckmark.hidden = !includeInRandom } }
mit
20e0c4ba6b7580b7323e519b79ff9158
37.843137
111
0.75265
5.518106
false
false
false
false
TangentW/PhotosSheet
PhotosSheet/PhotosSheet/Classes/ProgressViewController.swift
1
5404
// // ProgressViewController.swift // PhotosSheet // // Created by Tan on 2017/8/14. // import UIKit fileprivate let progressContentViewSize = CGSize(width: 140, height: 140) fileprivate let progressViewSize = CGSize(width: 100, height: 100) final class ProgressViewController: UIViewController { init() { super.init(nibName: nil, bundle: nil) modalPresentationStyle = .overCurrentContext modalTransitionStyle = .crossDissolve } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate lazy var _contentView: UIVisualEffectView = { let view = UIVisualEffectView(effect: self._contentViewEffect) view.backgroundColor = UIColor.white.withAlphaComponent(0.3) view.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin] view.layer.masksToBounds = true view.layer.cornerRadius = 9 return view }() fileprivate lazy var _cancelBtn: UIButton = { let button = UIButton() button.setTitle("Cancel".localizedString, for: .normal) button.setTitleColor(.white, for: .normal) button.titleLabel?.font = .systemFont(ofSize: 16) button.addTarget(self, action: #selector(ProgressViewController._cancel), for: .touchUpInside) button.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] return button }() fileprivate lazy var _contentViewEffect: UIVisualEffect = { return UIBlurEffect(style: .light) }() fileprivate lazy var _progressView = DownloadProgressView(frame: CGRect(origin: .zero, size: progressViewSize), lineWidth: 5) fileprivate lazy var _blurView: UIView = { let view = UIView() view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.backgroundColor = .black view.alpha = 0.4 return view }() var progress: Double = 0 { didSet { _progressView.progress = progress } } var cancelCallback: ((ProgressViewController) -> ())? @objc fileprivate func _cancel() { cancelCallback?(self) } } extension ProgressViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear view.addSubview(_blurView) view.addSubview(_contentView) view.addSubview(_cancelBtn) _contentView.contentView.addSubview(_progressView) _contentView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() _blurView.frame = view.bounds _contentView.frame.size = progressContentViewSize _contentView.center = CGPoint(x: 0.5 * view.bounds.width, y: 0.5 * view.bounds.height) _progressView.center = CGPoint(x: 0.5 * _contentView.bounds.width, y: 0.5 * _contentView.bounds.height) _cancelBtn.sizeToFit() _cancelBtn.center.x = 0.5 * view.bounds.width _cancelBtn.frame.origin.y = _contentView.frame.maxY + 8 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIView.animate(withDuration: 0.25) { self._contentView.transform = .identity } } } // MARK: - DownloadProgressView extension ProgressViewController { final class DownloadProgressView: UIView { fileprivate let _lineWidth: CGFloat init(frame: CGRect, lineWidth: CGFloat) { _lineWidth = lineWidth super.init(frame: frame) backgroundColor = .clear layer.shadowColor = UIColor.black.cgColor layer.shadowRadius = 2 layer.shadowOpacity = 0.2 layer.shadowOffset = CGSize(width: 1, height: 1) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layer.addSublayer(_circle) } var progress: Double = 0 { didSet { _circle.strokeEnd = CGFloat(self.progress) } } fileprivate lazy var _circlePath: UIBezierPath = { return UIBezierPath(arcCenter: CGPoint(x: 0.5 * self.bounds.size.width, y: 0.5 * self.bounds.size.height), radius: 0.5 * (self.bounds.size.width - 2 * self._lineWidth), startAngle: -0.5 * CGFloat.pi, endAngle: 2 * CGFloat.pi - 0.5 * CGFloat.pi, clockwise: true) }() fileprivate lazy var _circle: CAShapeLayer = { let circle = CAShapeLayer() circle.frame = self.layer.bounds circle.path = self._circlePath.cgPath circle.lineCap = kCALineCapRound circle.fillColor = UIColor.clear.cgColor circle.strokeColor = UIColor.white.cgColor circle.strokeStart = 0 circle.strokeEnd = 0 circle.zPosition = 1 circle.lineWidth = self._lineWidth return circle }() } }
mit
6a3e3949af5148aec020caeca7e52943
33.641026
129
0.621021
4.890498
false
false
false
false
mkaply/firefox-ios
Client/Frontend/Settings/AppSettingsOptions.swift
4
49748
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import SwiftKeychainWrapper import LocalAuthentication import Glean // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 private var disclosureIndicator: UIImageView { let disclosureIndicator = UIImageView() disclosureIndicator.image = UIImage(named: "menu-Disclosure")?.withRenderingMode(.alwaysTemplate) disclosureIndicator.tintColor = UIColor.theme.tableView.accessoryViewTint disclosureIndicator.sizeToFit() return disclosureIndicator } // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryView: UIImageView? { return disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var accessibilityIdentifier: String? { return "SignInToSync" } override func onClick(_ navigationController: UINavigationController?) { let viewController = FirefoxAccountSignInViewController(profile: profile, parentType: .settings, deepLinkParams: nil) TelemetryWrapper.recordEvent(category: .firefoxAccount, method: .view, object: .settings) navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.imageView?.image = UIImage.templateImageNamed("FxA-Default") cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 cell.imageView?.layer.masksToBounds = true } } class SyncNowSetting: WithAccountSetting { let imageView = UIImageView(frame: CGRect(width: 30, height: 30)) let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear) let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20)) let syncIcon: UIImage? = { let image = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20)) return ThemeManager.instance.currentName == .dark ? image?.tinted(withColor: .white) : image }() // Animation used to rotate the Sync icon 360 degrees while syncing is in progress. let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation") override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil) } fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { if !DeviceInfo.hasConnectivity() { return NSAttributedString( string: Strings.FxANoInternetConnection, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultMediumFont ] ) } return NSAttributedString( string: Strings.FxASyncNow, attributes: [ NSAttributedString.Key.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)]) func startRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey") } } @objc func stopRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.removeAllAnimations() } } override var accessoryType: UITableViewCell.AccessoryType { return .none } override var image: UIImage? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncIcon } switch syncStatus { case .inProgress: return syncBlueIcon default: return syncIcon } } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var hidden: Bool { return !enabled } override var enabled: Bool { get { if !DeviceInfo.hasConnectivity() { return false } return profile.hasSyncableAccount() } set { } } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: .roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity() // Animation that loops continously until stopped continuousRotateAnimation.fromValue = 0.0 continuousRotateAnimation.toValue = CGFloat(Double.pi) continuousRotateAnimation.isRemovedOnCompletion = true continuousRotateAnimation.duration = 0.5 continuousRotateAnimation.repeatCount = .infinity // To ensure sync icon is aligned properly with user's avatar, an image is created with proper // dimensions and color, then the scaled sync icon is added as a subview. imageView.contentMode = .center imageView.image = image cell.imageView?.subviews.forEach({ $0.removeFromSuperview() }) cell.imageView?.image = syncIconWrapper cell.imageView?.addSubview(imageView) if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .inProgress: self.startRotateSyncIcon() default: self.stopRotateSyncIcon() } } } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { if !DeviceInfo.hasConnectivity() { return } NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil) } @objc func updateAccount(notification: Notification) { DispatchQueue.main.async { self.settings.tableView.reloadData() } } override var accessoryView: UIImageView? { return disclosureIndicator } override var title: NSAttributedString? { if let displayName = RustFirefoxAccounts.shared.userProfile?.displayName { return NSAttributedString(string: displayName, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } if let email = RustFirefoxAccounts.shared.userProfile?.email { return NSAttributedString(string: email, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } return nil } override var status: NSAttributedString? { if RustFirefoxAccounts.shared.isActionNeeded { let string = Strings.FxAAccountVerifyPassword let orange = UIColor.theme.tableView.warningText let range = NSRange(location: 0, length: string.count) let attrs = [NSAttributedString.Key.foregroundColor: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } return nil } override func onClick(_ navigationController: UINavigationController?) { guard !profile.rustFxA.accountNeedsReauth() else { let vc = FirefoxAccountSignInViewController(profile: profile, parentType: .settings, deepLinkParams: nil) TelemetryWrapper.recordEvent(category: .firefoxAccount, method: .view, object: .settings) navigationController?.pushViewController(vc, animated: true) return } let viewController = SyncContentSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let imageView = cell.imageView { imageView.subviews.forEach({ $0.removeFromSuperview() }) imageView.frame = CGRect(width: 30, height: 30) imageView.layer.cornerRadius = (imageView.frame.height) / 2 imageView.layer.masksToBounds = true imageView.image = UIImage(named: "placeholder-avatar")!.createScaled(CGSize(width: 30, height: 30)) RustFirefoxAccounts.shared.avatar?.image.uponQueue(.main) { image in imageView.image = image.createScaled(CGSize(width: 30, height: 30)) } } } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.hasPrefix("browser.") || file.hasPrefix("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } class ExportLogDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Logger.copyPreviousLogsToDocuments() } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Sentry.shared.crash() } } class ChangeToChinaSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: toggle China version (needs restart)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { if UserDefaults.standard.bool(forKey: debugPrefIsChinaEdition) { UserDefaults.standard.removeObject(forKey: debugPrefIsChinaEdition) } else { UserDefaults.standard.set(true, forKey: debugPrefIsChinaEdition) } } } class SlowTheDatabase: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: simulate slow database operations", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { debugSimulateSlowDBOperations = !debugSimulateSlowDBOperations } } class ForgetSyncAuthStateDebugSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: forget Sync auth state", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { settings.profile.rustFxA.syncAuthState.invalidate() settings.tableView.reloadData() } } class SentryIDSetting: HiddenSetting { let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: "SentryDeviceAppHash") ?? "0000000000000000000000000000000000000000" override var title: NSAttributedString? { return NSAttributedString(string: "Sentry ID: \(deviceAppHash)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10)]) } override func onClick(_ navigationController: UINavigationController?) { copyAppDeviceIDAndPresentAlert(by: navigationController) } func copyAppDeviceIDAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = deviceAppHash navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } class ShowEtpCoverSheet: HiddenSetting { let profile: Profile override var title: NSAttributedString? { return NSAttributedString(string: "Debug: ETP Cover Sheet On", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { BrowserViewController.foregroundBVC().hasTriedToPresentETPAlready = false // ETP is shown when user opens app for 3rd time on clean install. // Hence setting session to 2 (0,1,2) for 3rd install as it starts from 0 being 1st session self.profile.prefs.setInt(2, forKey: PrefsKeys.KeyInstallSession) self.profile.prefs.setString(ETPCoverSheetShowType.CleanInstall.rawValue, forKey: PrefsKeys.KeyETPCoverSheetShowType) } } class ToggleOnboarding: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Toggle onboarding type", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let onboardingResearch = OnboardingUserResearch() let type = onboardingResearch.onboardingScreenType var newOnboardingType: OnboardingScreenType = .versionV2 if type == nil { newOnboardingType = .versionV1 } else if type == .versionV2 { newOnboardingType = .versionV1 } OnboardingUserResearch().onboardingScreenType = newOnboardingType } } class LeanplumStatus: HiddenSetting { let lplumSetupType = LeanPlumClient.shared.lpSetupType() override var title: NSAttributedString? { return NSAttributedString(string: "LP Setup: \(lplumSetupType) | Started: \(LeanPlumClient.shared.isRunning()) | Device ID: \(LeanPlumClient.shared.leanplumDeviceId ?? "")", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { copyLeanplumDeviceIDAndPresentAlert(by: navigationController) } func copyLeanplumDeviceIDAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) UIPasteboard.general.string = "\(LeanPlumClient.shared.leanplumDeviceId ?? "")" navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } } class ClearOnboardingABVariables: HiddenSetting { override var title: NSAttributedString? { // If we are running an A/B test this will also fetch the A/B test variables from leanplum. Re-open app to see the effect. return NSAttributedString(string: "Debug: Clear onboarding AB variables", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { settings.profile.prefs.removeObjectForKey(PrefsKeys.IntroSeen) OnboardingUserResearch().onboardingScreenType = nil } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController override var accessibilityIdentifier: String? { return "FxVersion" } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), VersionSetting.appVersion, VersionSetting.appBuildNumber), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } public static var appVersion: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } public static var appBuildNumber: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } override func onLongPress(_ navigationController: UINavigationController?) { copyAppVersionAndPresentAlert(by: navigationController) } func copyAppVersionAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = self.title?.string navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } // Opens the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "\(InternalURL.baseUrl)/\(AboutLicenseHandler.path)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { BrowserViewController.foregroundBVC().presentIntroViewController(true) }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { let statusText = NSMutableAttributedString() statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight])) statusText.append(NSAttributedString(string: " ")) statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.general.highlightBlue])) super.init( prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle), attributedStatusText: statusText, settingDidChange: { AdjustIntegration.setEnabled($0) LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0]) LeanPlumClient.shared.set(enabled: $0) Glean.shared.setUploadEnabled($0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController super.init(title: NSAttributedString(string: Strings.LoginsAndPasswordsTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { deselectRow() guard let navController = navigationController else { return } LoginListViewController.create(authenticateInNavigationController: navController, profile: profile, settingsDelegate: BrowserViewController.foregroundBVC()).uponQueue(.main) { loginsVC in guard let loginsVC = loginsVC else { return } LeanPlumClient.shared.track(event: .openedLogins) navController.pushViewController(loginsVC, animated: true) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let localAuthContext = LAContext() let title: String if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { if localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class ContentBlockerSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "TrackingProtection" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ContentBlockerSettingViewController(prefs: profile.prefs) viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsDataManagementSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: Setting { override var accessoryType: UITableViewCell.AccessoryType { return .none } var prefs: Prefs { return profile.prefs } let prefKey = PrefsKeys.KeyEnableChinaSyncService let profile: Profile let settings: UIViewController override var hidden: Bool { return !AppInfo.isChinaEdition } override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight]) } init(settings: SettingsTableViewController) { self.profile = settings.profile self.settings = settings } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? AppInfo.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .chinaServerSwitch) guard profile.rustFxA.hasAccount() else { prefs.setObject(toggle.isOn, forKey: prefKey) RustFirefoxAccounts.reconfig(prefs: profile.prefs) return } // Show confirmation dialog for the user to sign out of FxA let msg = "更改此设置后,再次登录您的帐户" // "Sign-in again to your account after changing this setting" let alert = UIAlertController(title: "", message: msg, preferredStyle: .alert) let ok = UIAlertAction(title: Strings.OKString, style: .default) { _ in self.prefs.setObject(toggle.isOn, forKey: self.prefKey) self.profile.removeAccount() RustFirefoxAccounts.reconfig(prefs: self.profile.prefs) } let cancel = UIAlertAction(title: Strings.CancelString, style: .default) { _ in toggle.setOn(!toggle.isOn, animated: true) } alert.addAction(ok) alert.addAction(cancel) settings.present(alert, animated: true) } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getNewTabPage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabContentSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } fileprivate func getDisclosureIndicator() -> UIImageView { let disclosureIndicator = UIImageView() disclosureIndicator.image = UIImage(named: "menu-Disclosure")?.withRenderingMode(.alwaysTemplate) disclosureIndicator.tintColor = UIColor.theme.tableView.accessoryViewTint disclosureIndicator.sizeToFit() return disclosureIndicator } class HomeSetting: Setting { let profile: Profile override var accessoryView: UIImageView { getDisclosureIndicator() } override var accessibilityIdentifier: String? { return "Home" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getHomePage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.AppMenuOpenHomePageTitleString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 12.0, *) class SiriPageSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "SiriSettings" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SiriSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } override var status: NSAttributedString { guard let provider = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), provider != "mailto:" else { return NSAttributedString(string: "") } if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { let mailProvider = dictRoot.compactMap({$0 as? NSDictionary }).first { (dict) -> Bool in return (dict["scheme"] as? String) == provider } return NSAttributedString(string: (mailProvider?["name"] as? String) ?? "") } return NSAttributedString(string: "") } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class AdvancedAccountSetting: HiddenSetting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var accessibilityIdentifier: String? { return "AdvancedAccount.Setting" } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsAdvancedAccountTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdvancedAccountSettingViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override var hidden: Bool { return !ShowDebugSettings || profile.hasAccount() } } class ThemeSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "DisplayThemeOption" } override var status: NSAttributedString { if ThemeManager.instance.systemThemeIsOn { return NSAttributedString(string: Strings.SystemThemeSectionHeader) } else if !ThemeManager.instance.automaticBrightnessIsOn { return NSAttributedString(string: Strings.DisplayThemeManualStatusLabel) } else if ThemeManager.instance.automaticBrightnessIsOn { return NSAttributedString(string: Strings.DisplayThemeAutomaticStatusLabel) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(ThemeSettingsController(), animated: true) } } class TranslationSetting: Setting { let profile: Profile override var accessoryView: UIImageView? { return disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "TranslationOption" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingTranslateSnackBarTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(TranslationSettingsController(profile), animated: true) } }
mpl-2.0
1c44ecfb3c6c78b13cfaec28aa67adc6
41.680412
329
0.710407
5.584532
false
false
false
false
LeoMobileDeveloper/ImageMaskTransition
ImageMaskTransition/DetailViewController.swift
1
1779
// // DetailViewController.swift // ImageMaskTransition // // Created by huangwenchen on 16/8/18. // Copyright © 2016年 Leo. All rights reserved. // import UIKit class DetailViewController: UIViewController { let imageView = UIImageView() let button = UIButton(type: .custom) let scrollView = UIScrollView() var topView = UIImageView() override func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) view.backgroundColor = UIColor.white scrollView.frame = self.view.bounds scrollView.contentSize = CGSize(width: self.view.bounds.size.width , height: self.view.bounds.size.height * 2) topView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width,height: 200) topView.image = UIImage(named: "topImage.jpg") scrollView.addSubview(topView) imageView.image = UIImage(named: "movie.jpg") imageView.frame = CGRect(x: 0, y: 0, width: 80, height: 124) imageView.center = CGPoint(x: 60, y: 200) scrollView.addSubview(imageView) button.setTitle("Back", for: UIControlState()) button.setTitleColor(UIColor.white, for: UIControlState()) button.sizeToFit() button.center = CGPoint(x: self.view.frame.width - 30, y: 25) view.addSubview(button) button.addTarget(self, action: #selector(DetailViewController.dismissController), for: UIControlEvents.touchUpInside) // Do any additional setup after loading the view. } func dismissController(){ if self.navigationController != nil { _ = self.navigationController?.popViewController(animated: true) }else{ self.dismiss(animated: true, completion: nil) } } }
mit
8d0f8391516e50002a8a634ef2ab930f
36
125
0.653153
4.363636
false
false
false
false
zhouxj6112/ARKit
ARHome/ARHome/ViewController.swift
1
16620
// // ViewController.swift // ARHome // // Created by MrZhou on 2017/11/15. // Copyright © 2017年 vipme. All rights reserved. // import ARKit import SceneKit import UIKit class ViewController: UIViewController { // MARK: IBOutlets @IBOutlet var sceneView: VirtualObjectARView! @IBOutlet weak var addObjectButton: UIButton! @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var spinner: UIActivityIndicatorView! // MARK: - UI Elements var focusSquare = FocusSquare() var planes = [UUID:Plane]() // 字典,存储场景中当前渲染的所有平面 (有可能检测到多个平面) /// The view controller that displays the status and "restart experience" UI. lazy var statusViewController: StatusViewController = { return childViewControllers.lazy.flatMap({ $0 as? StatusViewController }).first! }() // 底部弹出的选择模型viewcontroller public var popNav:UINavigationController? // MARK: - ARKit Configuration Properties /// A type which manages gesture manipulation of virtual content in the scene. lazy var virtualObjectInteraction = { () -> VirtualObjectInteraction in let interaction = VirtualObjectInteraction(sceneView: self.sceneView) interaction.viewController = self interaction.objectManager = virtualObjectLoader return interaction }() /// Coordinates the loading and unloading of reference nodes for virtual objects. let virtualObjectLoader = VirtualObjectLoader() /// Marks if the AR experience is available for restart. var isRestartAvailable = true /// A serial queue used to coordinate adding or removing nodes from the scene. let updateQueue = DispatchQueue(label: "com.example.apple-samplecode.arkitexample.serialSceneKitQueue") var screenCenter: CGPoint { let bounds = sceneView.bounds return CGPoint(x: bounds.midX, y: bounds.midY) } /// Convenience accessor for the session owned by ARSCNView. var session: ARSession { return sceneView.session } // MARK: - View Controller Life Cycle override func loadView() { super.loadView() } override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.session.delegate = self //#if DEBUG // sceneView.showsStatistics = true // sceneView.allowsCameraControl = false // sceneView.antialiasingMode = .multisampling4X //// sceneView.debugOptions = SCNDebugOptions.showBoundingBoxes // sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints] //#endif // Set up scene content. setupCamera() sceneView.scene.rootNode.addChildNode(focusSquare) /* The `sceneView.automaticallyUpdatesLighting` option creates an ambient light source and modulates its intensity. This sample app instead modulates a global lighting environment map for use with physically based materials, so disable automatic lighting. */ sceneView.automaticallyUpdatesLighting = false if let environmentMap = UIImage(named: "Models.scnassets/sharedImages/environment_blur.exr") { sceneView.scene.lightingEnvironment.contents = environmentMap } // Hook up status view controller callback(s). statusViewController.restartExperienceHandler = { [unowned self] in self.restartExperience() } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showVirtualObjectSelectionViewController)) // Set the delegate to ensure this gesture is only used when there are no virtual objects in the scene. tapGesture.delegate = self sceneView.addGestureRecognizer(tapGesture) // 监听通知 NotificationCenter.default.addObserver(self, selector: #selector(self.resetAR), name: NSNotification.Name(rawValue: "kNotificationResetAR"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.recoverLasted), name: NSNotification.Name(rawValue: "kNotificationRecoverLasted"), object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Prevent the screen from being dimmed to avoid interuppting the AR experience. UIApplication.shared.isIdleTimerDisabled = true // Start the `ARSession`. resetTracking() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // session.pause() debugPrint("AR进入暂停状态") } // MARK: - Scene content setup func setupCamera() { guard let camera = sceneView.pointOfView?.camera else { fatalError("Expected a valid `pointOfView` from the scene.") } /* Enable HDR camera settings for the most realistic appearance with environmental lighting and physically based materials. */ camera.wantsHDR = true camera.exposureOffset = -1 camera.minimumExposure = -1 camera.maximumExposure = 3 } // MARK: - Session management /// Creates a new AR configuration to run on the `session`. @objc func resetTracking() { let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal session.run(configuration, options: [.resetTracking, .removeExistingAnchors]) statusViewController.scheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", inSeconds: 7.5, messageType: .planeEstimation) } // 关闭窗口 func dismissViewController() { dismiss(animated: true, completion: { debugPrint("关闭AR视图ViewController完成") }) } // 弹出设置界面 func toSettingViewController() { let vc = SettingViewController(); vc.preferredContentSize = CGSize.init(width: self.view.frame.size.width, height: self.view.frame.size.height-180) vc.modalPresentationStyle = .popover let popover = vc.popoverPresentationController popover?.sourceView = self.statusViewController.view popover?.sourceRect = CGRect.init(x: 10, y: 10, width: 120, height: 300) popover?.permittedArrowDirections = .any popover?.delegate = self present(vc, animated: true) { // } } @objc func resetAR(sender:Notification) { statusViewController.showMessage("重置成功", autoHide: true) // virtualObjectLoader.removeAllVirtualObjects(); self.resetTracking(); } @objc func recoverLasted(sender:Notification) { let oper = sender.userInfo!["oper"] as! String; if oper == "save" { self.saveCurrentARForHistory(); } else { let index = sender.userInfo!["index"] as? NSNumber; self.recoverARFromHistory(index) } } // MARK: - Focus Square func updateFocusSquare() { let isObjectVisible = virtualObjectLoader.loadedObjects.contains { object in return sceneView.isNode(object, insideFrustumOf: sceneView.pointOfView!) } if isObjectVisible { focusSquare.hide() } else { focusSquare.unhide() statusViewController.scheduleMessage("TRY MOVING LEFT OR RIGHT", inSeconds: 5.0, messageType: .focusSquare) } // We should always have a valid world position unless the sceen is just being initialized. guard let (worldPosition, planeAnchor, _) = sceneView.worldPosition(fromScreenPosition: screenCenter, objectPosition: focusSquare.lastPosition) else { updateQueue.async { self.focusSquare.state = .initializing self.sceneView.pointOfView?.addChildNode(self.focusSquare) } addObjectButton.isHidden = true return } updateQueue.async { self.sceneView.scene.rootNode.addChildNode(self.focusSquare) let camera = self.session.currentFrame?.camera if let planeAnchor = planeAnchor { self.focusSquare.state = .planeDetected(anchorPosition: worldPosition, planeAnchor: planeAnchor, camera: camera) } else { self.focusSquare.state = .featuresDetected(anchorPosition: worldPosition, camera: camera) } } addObjectButton.isHidden = false statusViewController.cancelScheduledMessage(for: .focusSquare) } // MARK: - Error handling func displayErrorMessage(title: String, message: String) { // Blur the background. blurView.isHidden = false // Present an alert informing about the error that has occurred. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let restartAction = UIAlertAction(title: "Restart Session", style: .default) { _ in alertController.dismiss(animated: true, completion: nil) // self.blurView.isHidden = true // self.resetTracking() } alertController.addAction(restartAction) present(alertController, animated: true, completion: nil) } public var modelList:NSArray = [] func resetModelList(array:NSArray) -> Void { modelList = array } func saveCurrentARForHistory() { let alertController = UIAlertController.init(title: "", message: "请输入标题", preferredStyle: .alert) let okAction = UIAlertAction.init(title: "确定", style: .default) { (alertAction:UIAlertAction) in // 开始保存 let inputTitle = alertController.textFields![0].text; let array = NSMutableArray.init(capacity: 1); for obj in self.virtualObjectLoader.loadedObjects { if obj.isShadowObj { continue; } let dic = NSMutableDictionary.init(capacity: 10); dic.setValue(obj.zipFileUrl, forKey: "zipFileUrl"); dic.setValue(obj.signID, forKey: "signID"); dic.setValue(obj.signName, forKey: "signName"); // 标记位置 do { // 取底部阴影模型的坐标 let shadowObj = obj.shadowObject; if shadowObj != nil { let posString = String.init(format: "%f|%f|%f", (shadowObj?.simdPosition.x)!, (shadowObj?.simdPosition.y)!, (shadowObj?.simdPosition.z)!); dic.setValue(posString, forKey: "simdPosition"); } else { let posString = String.init(format: "%f|%f|%f", (obj.simdPosition.x), (obj.simdPosition.y), (obj.simdPosition.z)); dic.setValue(posString, forKey: "simdPosition"); } } // let scaleString = String.init(format: "%f|%f|%f", obj.scale.x, obj.scale.y, obj.scale.z) dic.setValue(scaleString, forKey: "scale"); // let rotationString = String.init(format: "%f|%f|%f|%f", (obj.simdRotation.x), (obj.simdRotation.y), (obj.simdRotation.z), obj.simdRotation.w); dic.setValue(rotationString, forKey: "simdRotation"); // let oriString = String.init(format: "%f", obj.simdWorldOrientation.angle); dic.setValue(oriString, forKey: "simdWorldOrientation"); // dic.setValue(NSNumber.init(value: array.count), forKey: "index"); // 标记位置 array.add(dic); } if array.count == 0 { self.displayErrorMessage(title: "温馨提示", message: "当前场景为空,不需要保存"); return; } let filePath = NSHomeDirectory() + "/Documents/" + "his.txt" // 读取历史文件 var arraySrc = NSMutableArray.init(contentsOfFile: filePath); if arraySrc == nil { arraySrc = NSMutableArray.init(); } let newDic = NSMutableDictionary.init(capacity: 1); newDic.setValue((arraySrc?.count)!+1, forKey: "index"); newDic.setValue(inputTitle, forKey: "title") newDic.setValue(array, forKey: "array"); newDic.setValue(NSDate.init(), forKey: "createTime"); arraySrc?.add(newDic); // let bRet = arraySrc?.write(toFile: filePath, atomically: true); if !bRet! { debugPrint("追加保存失败"); } else { debugPrint("追加保存成功"); } } alertController.addAction(okAction) alertController.addTextField { (textField:UITextField) in textField.placeholder = "标题" } self.present(alertController, animated: true, completion: nil) } func recoverARFromHistory(_ atIndex:NSNumber?) { if atIndex == nil { let vc = ChooseHistoryViewController(); vc.preferredContentSize = CGSize.init(width: self.view.frame.size.width, height: self.view.frame.size.height-180) vc.modalPresentationStyle = .popover let popover = vc.popoverPresentationController popover?.sourceView = self.statusViewController.view popover?.sourceRect = CGRect.init(x: 10, y: 10, width: 120, height: 300) popover?.permittedArrowDirections = .any popover?.delegate = self present(vc, animated: true) { // } return; } let filePath = NSHomeDirectory() + "/Documents/" + "his.txt" if FileManager.default.fileExists(atPath: filePath) { let array = NSArray.init(contentsOfFile: filePath); debugPrint("文件:\(String(describing: array))"); let index = (array?.count)! - 1 - (atIndex?.intValue)!; // 要倒序 let objDic = array?.object(at: index) as! NSDictionary; // 倒序的 let objList:NSArray = objDic["array"] as! NSArray; for obj in objList { let dic = obj as! NSDictionary; // let zipFileUrl = dic["zipFileUrl"] as! String; if zipFileUrl.count == 0 { continue; } let zipFileUrlEnc = zipFileUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) let objectFileUrl = URL.init(string: zipFileUrlEnc!); let didSelectObjectID = dic["signID"] as! String; let posString = dic["simdPosition"] as! String; let posArr = posString.split(separator: "|"); let simdPosition = float3(Float(posArr[0])!, Float(posArr[1])!, Float(posArr[2])!); let simdWorldOrientation = dic["simdWorldOrientation"] as! String; virtualObjectLoader.loadVirtualObject(objectFileUrl!, loadedHandler: { [unowned self] loadedObject, shadowObject in DispatchQueue.main.async { self.hideObjectLoadingUI() // if (loadedObject != nil) { loadedObject?.signID = didSelectObjectID; self.placeVirtualObject(loadedObject!) loadedObject?.simdPosition = simdPosition; let ori = simd_quatf(ix: 0, iy: 0, iz: 0, r: Float(simdWorldOrientation)!); loadedObject?.simdWorldOrientation = ori; // 放置阴影模型在底部 if shadowObject != nil { self.placeVirtualObject(shadowObject!) // 跟主模型的中心重合 shadowObject?.simdPosition = simdPosition; } } } }); } } } deinit { virtualObjectLoader.release(); debugPrint("ViewController释放"); } }
apache-2.0
dffeb37aa84eee2c186a92d8ed554236
40.57398
173
0.596674
5.116797
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCFactoryDetailsTableViewCell.swift
2
3765
// // NCFactoryDetailsTableViewCell.swift // Neocom // // Created by Artem Shimanski on 16.08.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import Dgmpp class NCFactoryDetailsTableViewCell: NCTableViewCell { @IBOutlet weak var efficiencyLabel: UILabel! @IBOutlet weak var extrapolatedEfficiencyLabel: UILabel! @IBOutlet weak var inputRatioLabel: UILabel! @IBOutlet weak var inputRatioTitleLabel: UILabel! } extension Prototype { enum NCFactoryDetailsTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCFactoryDetailsTableViewCell", bundle: nil), reuseIdentifier: "NCFactoryDetailsTableViewCell") } } class NCFactoryDetailsRow: TreeRow { let currentTime: Date let productionTime: TimeInterval? let idleTime: TimeInterval? let efficiency: Double? let extrapolatedProductionTime: TimeInterval? let extrapolatedIdleTime: TimeInterval? let extrapolatedEfficiency: Double? let identifier: Int64 let inputRatio: [Double] init(factory: DGMFactory, inputRatio: [Double], currentTime: Date) { self.currentTime = currentTime self.inputRatio = inputRatio identifier = factory.identifier let states = factory.states let lastState = states.reversed().first {$0.cycle == nil} let firstProductionState = states.first {$0.cycle?.start == $0.timestamp} // let lastProductionState = states?.reversed().first {$0.currentCycle?.launchTime == $0.timestamp} let currentState = states.reversed().first {$0.timestamp < currentTime} ?? states.last efficiency = currentState?.efficiency extrapolatedEfficiency = lastState?.efficiency (productionTime, idleTime) = { guard let currentState = currentState, let firstProductionState = firstProductionState else {return (nil, nil)} let duration = currentState.timestamp.timeIntervalSince(firstProductionState.timestamp) let productionTime = currentState.efficiency * duration let idleTime = duration - productionTime return (productionTime, idleTime) }() (extrapolatedProductionTime, extrapolatedIdleTime) = { guard let lastState = lastState, let firstProductionState = firstProductionState else {return (nil, nil)} let duration = lastState.timestamp.timeIntervalSince(firstProductionState.timestamp) let productionTime = lastState.efficiency * duration let idleTime = duration - productionTime return (productionTime, idleTime) }() super.init(prototype: Prototype.NCFactoryDetailsTableViewCell.default) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCFactoryDetailsTableViewCell else {return} if let productionTime = productionTime, let idleTime = idleTime, productionTime + idleTime > 0 { let duration = productionTime + idleTime cell.efficiencyLabel.text = String(format: "%.0f%%", productionTime / duration * 100) } else { cell.efficiencyLabel.text = "0%" } if let productionTime = extrapolatedProductionTime, let idleTime = extrapolatedIdleTime, productionTime + idleTime > 0 { let duration = productionTime + idleTime cell.extrapolatedEfficiencyLabel.text = String(format: "%.0f%%", productionTime / duration * 100) } else { cell.extrapolatedEfficiencyLabel.text = "0%" } if inputRatio.count > 1 { cell.inputRatioLabel.text = inputRatio.map{$0 == 0 ? "0" : $0 == 1 ? "1" : String(format: "%.1f", $0)}.joined(separator: ":") cell.inputRatioLabel.isHidden = false cell.inputRatioTitleLabel.isHidden = false } else { cell.inputRatioLabel.isHidden = true cell.inputRatioTitleLabel.isHidden = true } } override var hash: Int { return identifier.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCFactoryDetailsRow)?.hashValue == hashValue } }
lgpl-2.1
4ed0b7d4db3a0dc928252287ff80e769
32.90991
151
0.74814
4.205587
false
false
false
false
mrr1vfe/FBLA
userViewController.swift
1
16334
// // userViewController.swift // FBLA // // Created by Yi Chen on 15/11/7. // Copyright © 2015年 Yi Chen. All rights reserved. // import UIKit import Parse class userViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var blurView: UIVisualEffectView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var blurViewTitle: UILabel! @IBOutlet weak var blurDoneButton: UIButton! @IBOutlet weak var changeImageButton: UIButton! @IBOutlet weak var currentUserId: UILabel! @IBOutlet weak var loggedInVIew: UIVisualEffectView! @IBOutlet weak var currentUserAvatar: UIImageView! @IBOutlet weak var modeChangeButton: UIButton! @IBOutlet weak var currentUserUsername: UILabel! var movedRange:CGFloat? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.623822, green: 0.835422, blue: 0.916207, alpha: 1) self.navigationController?.navigationBar.opaque navigationController?.navigationBar.tintColor = UIColor.whiteColor() //set the corner at the 4 vertices blurView.layer.cornerRadius = 10 blurView.layer.masksToBounds = true loggedInVIew.layer.cornerRadius = 10 loggedInVIew.layer.masksToBounds = true currentUserAvatar.layer.cornerRadius = currentUserAvatar.frame.width/2 currentUserAvatar.layer.masksToBounds = true changeImageButton.layer.cornerRadius = changeImageButton.frame.width/2 changeImageButton.layer.masksToBounds = true //enable the button first doneButton.enabled = false UITextField.appearance().tintColor = UIColor.whiteColor() movedRange = self.view.frame.height * 0.125 if PFUser.currentUser() != nil { self.currentUserUsername.text = PFUser.currentUser()?.username self.currentUserId.text = PFUser.currentUser()?.objectId PFUser.currentUser()!.valueForKey("userAvatar")?.getDataInBackgroundWithBlock({ (data, error) -> Void in if let downloadedImage = UIImage(data: data!){ self.currentUserAvatar.image = downloadedImage; } }) loggedInVIew.hidden = false blurView.hidden = true } else { blurView.hidden = false loggedInVIew.hidden = true } } @IBAction func clickChangeImage(sender: AnyObject) { let image = UIImagePickerController() image.delegate = self image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary image.allowsEditing = true self.presentViewController(image, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { dismissViewControllerAnimated(true, completion: nil) currentUserAvatar.image = image let userPicData = UIImageJPEGRepresentation(currentUserAvatar.image!, 0.2) let userPicFile = PFFile(name: "avatar.png", data: userPicData!) let user = PFUser.currentUser() user?.setObject(userPicFile!, forKey: "userAvatar") SwiftLoader.show(title: "Loading...", animated: true) user?.saveInBackgroundWithBlock({ (success, error) -> Void in SwiftLoader.hide() if success { print("success") self.currentUserId.text = PFUser.currentUser()?.objectId self.currentUserUsername.text = PFUser.currentUser()?.username PFUser.currentUser()!.valueForKey("userAvatar")?.getDataInBackgroundWithBlock({ (data, error) -> Void in if let downloadedImage = UIImage(data: data!){ self.currentUserAvatar.image = downloadedImage; } }) } else { if let error = error { var errorString = "" if error.code == PFErrorCode.ErrorObjectNotFound.rawValue { errorString = "Uh oh, we couldn't find the object!" } else { errorString = (error.userInfo["error"] as? String)! print("Error: \(errorString)") } JCAlertView.showOneButtonWithTitle("Could not Update", message: errorString, buttonType: JCAlertViewButtonType.Warn, buttonTitle: "OK", click: nil) } } }) } @IBAction func beginUsername(sender: AnyObject) { //Animation if view.frame.origin.y == 0 { UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.frame.origin.y -= self.movedRange! }, completion: nil) } } @IBAction func endUsername(sender: AnyObject) { //Animation UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.frame.origin.y = 0 }, completion: nil) //reisgnFR usernameTextField.resignFirstResponder() //Check the completivity if usernameTextField.text != "" && passwordTextField.text != "" { doneButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) doneButton.enabled = true }else { doneButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) doneButton.enabled = false } } @IBAction func beginPassword(sender: AnyObject) { //Animation if view.frame.origin.y == 0 { UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.frame.origin.y -= self.movedRange! }, completion: nil) } } @IBAction func endPassword(sender: AnyObject) { //Animation UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.view.frame.origin.y = 0 }, completion: nil) //reisgnFR passwordTextField.resignFirstResponder() //Check the completivity if usernameTextField.text != "" && passwordTextField.text != "" { doneButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) doneButton.enabled = true } else { doneButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) doneButton.enabled = false } } @IBAction func clickDone(sender: AnyObject) { if blurViewTitle.text == "Sign Up" { // sign up in to the Parse server let user = PFUser() user.username = usernameTextField.text user.password = passwordTextField.text SwiftLoader.show(title: "Loading...", animated: true) user.signUpInBackgroundWithBlock { (success, error) -> Void in if success != false { let userPicData = UIImageJPEGRepresentation(UIImage(named: "avatarPlaceholder.jpg")!, 1) let userPicFile = PFFile(name: "avatar.png", data: userPicData!) let user = PFUser.currentUser() user?.setObject(userPicFile!, forKey: "userAvatar") user?.saveInBackgroundWithBlock({ (success, error) -> Void in SwiftLoader.hide() if success { self.blurView.hidden = true self.loggedInVIew.hidden = false print("success") self.currentUserId.text = PFUser.currentUser()?.objectId self.currentUserUsername.text = PFUser.currentUser()?.username PFUser.currentUser()!.valueForKey("userAvatar")?.getDataInBackgroundWithBlock({ (data, error) -> Void in if let downloadedImage = UIImage(data: data!){ self.currentUserAvatar.image = downloadedImage; } }) } else { if let error = error { var errorString = "" if error.code == PFErrorCode.ErrorObjectNotFound.rawValue { errorString = "Uh oh, we couldn't find the object!" } else { errorString = (error.userInfo["error"] as? String)! print("Error: \(errorString)") } JCAlertView.showOneButtonWithTitle("Could not sign up", message: errorString, buttonType: JCAlertViewButtonType.Warn, buttonTitle: "OK", click: nil) } } }) } else { SwiftLoader.hide() if let error = error { var errorString = "" if error.code == PFErrorCode.ErrorObjectNotFound.rawValue { errorString = "Uh oh, we couldn't find the object!" } else { errorString = (error.userInfo["error"] as? String)! print("Error: \(errorString)") } JCAlertView.showOneButtonWithTitle("Could not sign up", message: errorString, buttonType: JCAlertViewButtonType.Warn, buttonTitle: "OK", click: nil) } } } } else { SwiftLoader.hide() UIApplication.sharedApplication().beginIgnoringInteractionEvents() SwiftLoader.show(title: "Loading...", animated: true) PFUser.logInWithUsernameInBackground(usernameTextField.text!, password: passwordTextField.text!, block: { (user, error) -> Void in UIApplication.sharedApplication().endIgnoringInteractionEvents() SwiftLoader.hide() if user != nil { self.currentUserId.text = PFUser.currentUser()?.objectId self.currentUserUsername.text = PFUser.currentUser()?.username PFUser.currentUser()!.valueForKey("userAvatar")?.getDataInBackgroundWithBlock({ (data, error) -> Void in if let downloadedImage = UIImage(data: data!){ self.currentUserAvatar.image = downloadedImage; } }) print("success") self.blurView.hidden = true self.loggedInVIew.hidden = false } else { let errorString = error!.userInfo["error"] as? String JCAlertView.showOneButtonWithTitle("Could not sign in", message: errorString, buttonType: JCAlertViewButtonType.Warn, buttonTitle: "OK", click: nil) } }) } } @IBAction func clickLogout(sender: AnyObject) { PFUser.logOut() loggedInVIew.hidden = true blurView.hidden = false } @IBAction func clickModeChangeButton(sender: AnyObject) { UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.usernameTextField.alpha = 0 self.passwordTextField.alpha = 0 self.blurViewTitle.alpha = 0 self.blurDoneButton.alpha = 0 self.modeChangeButton.alpha = 0 if self.blurViewTitle.text == "Sign Up" { print("2") UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.usernameTextField.alpha = 1 self.passwordTextField.alpha = 1 self.blurViewTitle.alpha = 1 self.blurDoneButton.alpha = 1 self.modeChangeButton.alpha = 1 self.blurViewTitle.text = "Sign In" self.modeChangeButton.setTitle("Sign Up", forState: UIControlState.Normal) }, completion: nil) } else { print("3") UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.usernameTextField.alpha = 1 self.passwordTextField.alpha = 1 self.blurViewTitle.alpha = 1 self.blurDoneButton.alpha = 1 self.modeChangeButton.alpha = 1 self.blurViewTitle.text = "Sign Up" self.modeChangeButton.setTitle("Sign In", forState: UIControlState.Normal) }, completion: nil) } }, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
92978ba6b6880ae67b9f57691f769455
35.453125
184
0.495989
6.622466
false
false
false
false
andrewcar/hoods
Project/hoods/hoods/RadioView.swift
1
4863
// // RadioView.swift // hoods // // Created by Andrew Carvajal on 1/25/18. // Copyright © 2018 YugeTech. All rights reserved. // import UIKit import UIImageColors class RadioView: UIView { var radioConstraints = [NSLayoutConstraint]() var whiteViewConstraints = [NSLayoutConstraint]() var labelsImageView = UIImageView() var whiteView = UIView() var albumImageView = UIImageView() var button = UIButton() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .black labelsImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height)) labelsImageView.translatesAutoresizingMaskIntoConstraints = false whiteView = UIView(frame: CGRect(x: 30, y: 30, width: frame.width - 60, height: frame.height - 40)) whiteView.translatesAutoresizingMaskIntoConstraints = false whiteView.backgroundColor = .white albumImageView = UIImageView(frame: CGRect(x: 2, y: 2, width: whiteView.frame.width - 4, height: whiteView.frame.height - 4)) albumImageView.translatesAutoresizingMaskIntoConstraints = false button.translatesAutoresizingMaskIntoConstraints = false addSubview(labelsImageView) addSubview(whiteView) whiteView.addSubview(albumImageView) addSubview(button) activateConstraints() } func activateConstraints() { NSLayoutConstraint.deactivate(radioConstraints) radioConstraints = [ labelsImageView.topAnchor.constraint(equalTo: topAnchor), labelsImageView.leftAnchor.constraint(equalTo: leftAnchor), labelsImageView.rightAnchor.constraint(equalTo: rightAnchor), labelsImageView.bottomAnchor.constraint(equalTo: bottomAnchor), whiteView.topAnchor.constraint(equalTo: topAnchor, constant: 30), whiteView.leftAnchor.constraint(equalTo: leftAnchor, constant: 30), whiteView.rightAnchor.constraint(equalTo: rightAnchor, constant: -30), whiteView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -30), button.topAnchor.constraint(equalTo: topAnchor), button.leftAnchor.constraint(equalTo: leftAnchor), button.rightAnchor.constraint(equalTo: rightAnchor), button.bottomAnchor.constraint(equalTo: bottomAnchor), ] NSLayoutConstraint.activate(radioConstraints) NSLayoutConstraint.deactivate(whiteViewConstraints) whiteViewConstraints = [ albumImageView.leftAnchor.constraint(equalTo: whiteView.leftAnchor, constant: 2), albumImageView.rightAnchor.constraint(equalTo: whiteView.rightAnchor, constant: -2), albumImageView.topAnchor.constraint(equalTo: whiteView.topAnchor, constant: 2), albumImageView.bottomAnchor.constraint(equalTo: whiteView.bottomAnchor, constant: -2), ] NSLayoutConstraint.activate(whiteViewConstraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateLabelsImageView(songName: String, artistName: String, radioFrame: CGRect, albumImage: UIImage) { let size = self.bounds.size UIGraphicsBeginImageContextWithOptions(size, true, 0.0) guard let context = UIGraphicsGetCurrentContext() else { return } // ******************************************************************* // Scale & translate the context to have 0,0 // at the centre of the screen maths convention // Obviously change your origin to suit... // ******************************************************************* context.translateBy (x: size.width / 2, y: size.height / 2) context.scaleBy (x: 1, y: -1) context.setAlpha(1) let colors = albumImage.getColors() context.setFillColor(colors.background.cgColor) context.fill(CGRect(x: -2000, y: -2000, width: 4000, height: 4000)) Frames.si.centreArcPerpendicular(text: songName, context: context, radius: self.whiteView.frame.width / 2 + 16, angle: CGFloat(Double.pi / 2), colour: colors.primary, font: UIFont(name: Fonts.HelveticaNeue.bold, size: 13)!, clockwise: true) Frames.si.centreArcPerpendicular(text: artistName, context: context, radius: self.whiteView.frame.width / 2 + 13, angle: CGFloat(-Double.pi / 2), colour: colors.secondary, font: UIFont(name: Fonts.HelveticaNeue.bold, size: 16)!, clockwise: false) whiteView.backgroundColor = colors.detail let image = UIGraphicsGetImageFromCurrentImageContext() self.labelsImageView.image = image UIGraphicsEndImageContext() } }
mit
6d5666e3a54c4318c95da1b7f11a3eca
44.867925
254
0.655697
5.239224
false
false
false
false
kalia-akkad/uSpy
ClarifaiApiDemo/SwiftRecognitionViewController.swift
1
7386
// // SwiftRecognitionViewController.swift // ClarifaiApiDemo // import UIKit /** * This view controller performs recognition using the Clarifai API. */ class SwiftRecognitionViewController : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { // IMPORTANT NOTE: you should replace these keys with your own App ID and secret. // These can be obtained at https://developer.clarifai.com/applications static let appID = "vM05qo55uhZard2dL4BixmMm4WsHIl6CsGCTgS_7" static let appSecret = "rx4oPPiXiCWNRVcoJ0huLz02cKiQUZtq5JPVrhjM" // Custom Training (Alpha): to predict against a custom concept (instead of the standard // tag model), set this to be the name of the concept you wish to predict against. You must // have previously trained this concept using the same app ID and secret as above. For more // info on custom training, see https://github.com/Clarifai/hackathon static let conceptName: String? = nil static let conceptNamespace = "default" @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var button: UIButton! @IBOutlet weak var tag1: UILabel! @IBOutlet weak var tag2: UILabel! @IBOutlet weak var tag3: UILabel! @IBOutlet weak var scoreF: UILabel! private lazy var client : ClarifaiClient = { let c = ClarifaiClient(appID: appID, appSecret: appSecret) // Uncomment this to request embeddings. Contact us to enable embeddings for your app: // c.enableEmbed = true return c }() override func viewDidLoad() { super.viewDidLoad() self.textView.hidden = true let url = NSURL(string: "https://www.wolframcloud.com/objects/d5484999-7deb-421c-a7a7-8b74bb382fc3?x=3")! let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in // Will happen when task completes let urlContent = data let webContent = NSString(data: urlContent!, encoding: NSUTF8StringEncoding) let stringwithoutquotes = webContent!.stringByReplacingOccurrencesOfString("\"", withString: "") let removeBracket1 = stringwithoutquotes.stringByReplacingOccurrencesOfString("{", withString: "") let removeBracket2 = removeBracket1.stringByReplacingOccurrencesOfString("}", withString: "") let removeSpace = removeBracket2.stringByReplacingOccurrencesOfString(" ", withString: "") let thisArray = removeSpace.characters.split{$0 == ","}.map(String.init) self.tag1.text = thisArray[0] self.tag2.text = thisArray[1] self.tag3.text = thisArray[2] } task.resume() } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = true } @IBAction func buttonPressed(sender: UIButton) { // Show a UIImagePickerController to let the user pick an image from their library. let picker = UIImagePickerController() picker.sourceType = .PhotoLibrary picker.allowsEditing = false picker.delegate = self presentViewController(picker, animated: true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) { dismissViewControllerAnimated(true, completion: nil) if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { // The user picked an image. Send it Clarifai for recognition. imageView.image = image textView.text = "Recognizing..." button.enabled = false recognizeImage(image) } } private func recognizeImage(image: UIImage!) { // Scale down the image. This step is optional. However, sending large images over the // network is slow and does not significantly improve recognition performance. let size = CGSizeMake(320, 320 * image.size.height / image.size.width) UIGraphicsBeginImageContext(size) image.drawInRect(CGRectMake(0, 0, size.width, size.height)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Encode as a JPEG. let jpeg = UIImageJPEGRepresentation(scaledImage, 0.9)! if SwiftRecognitionViewController.conceptName == nil { // Standard Recognition: Send the JPEG to Clarifai for standard image tagging. client.recognizeJpegs([jpeg]) { (results: [ClarifaiResult]?, error: NSError?) in if error != nil { print("Error: \(error)\n") self.textView.text = "Sorry, there was an error recognizing your image." } else { self.textView.text = results![0].tags.joinWithSeparator(",") let tagStr = self.textView.text let tagArr = tagStr.characters.split{$0 == ","}.map(String.init) let score: String var counter = 0 for score: String in tagArr { if score == self.tag1.text { counter = counter + 1 } if score == self.tag2.text { counter = counter + 1 } if score == self.tag3.text { counter = counter + 1 } } var finalScore = 0 if counter == 0 { finalScore = 0 }else if counter == 1{ finalScore = 1 }else if counter == 2{ finalScore = 4 }else if counter == 3{ finalScore = 9 } self.scoreF.text = String(Int(self.scoreF.text!)! + finalScore) } self.textView.hidden = true self.button.enabled = true } } else { // Custom Training: Send the JPEG to Clarifai for prediction against a custom model. client.predictJpegs([jpeg], conceptNamespace: SwiftRecognitionViewController.conceptNamespace, conceptName: SwiftRecognitionViewController.conceptName) { (results: [ClarifaiPredictionResult]?, error: NSError?) in if error != nil { print("Error: \(error)\n") self.textView.text = "Sorry, there was an error running prediction on your image." } else { self.textView.text = "Prediction score for \(SwiftRecognitionViewController.conceptName!):\n\(results![0].score)" } self.button.enabled = true } } } }
mit
fc6f081a1e108b24d2f883186a26ae1e
44.036585
165
0.584484
5.336705
false
false
false
false
neotron/SwiftBot-Discord
DiscordAPI/Source/API/Users/PrivateChannelRequest.swift
1
1580
// // Created by David Hedbor on 2/14/16. // Copyright (c) 2016 NeoTron. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper import ObjectMapper // Not exposed private class PrivateChannelResponseModel : MappableBase { var channelId: String? override func mapping(map: Map) { channelId <- map["id"] } } open class PrivateChannelRequest { fileprivate var recipientId: String public init(recipientId: String) { self.recipientId = recipientId } open func execute(_ callback: @escaping (String?)->Void) { guard let token = Registry.instance.token else { LOG_ERROR("No authorization token found.") return } guard let userId = Registry.instance.user?.id else { LOG_ERROR("No authorization token found.") return } Alamofire.request(Endpoints.User(userId, endpoint: .Channel), method: .post, parameters:["recipient_id": recipientId], encoding: JSONEncoding.default, headers: ["Authorization": token]).responseObject { (response: DataResponse<PrivateChannelResponseModel>) in print("Private channel is \(response.result.value)") if let channelId = response.result.value?.channelId { callback(channelId) } else { if let error = response.result.error { LOG_ERROR("Failed to create private channel: \(error)") } callback(nil) } } } }
gpl-3.0
0bcdc44058bc9ee248e9ec37cbdb4dfd
30.6
126
0.608228
4.906832
false
false
false
false
ericmarkmartin/Nightscouter2
Nightscouter/AppDelegate.swift
1
10634
// // AppDelegate.swift // Nightscouter // // Created by Peter Ina on 1/11/16. // Copyright © 2016 Nothingonline. All rights reserved. // import UIKit import NightscouterKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? /// Saved shortcut item used as a result of an app launch, used later when app is activated. var launchedShortcutItem: String? override init() { //SitesDataSource.sharedInstance.sites super.init() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Theme.customizeAppAppearance(sharedApplication: UIApplication.sharedApplication(), forWindow: window) // Register for intial settings. let userDefaults = NSUserDefaults.standardUserDefaults() registerInitialSettings(userDefaults) // Register for settings changes as store might have changed NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("userDefaultsDidChange:"), name: NSUserDefaultsDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserverForName(DataUpdatedNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (_) -> Void in self.dataManagerDidChange() } // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem { launchedShortcutItem = shortcutItem.type } return true } func applicationDidBecomeActive(application: UIApplication) { #if DEBUG print(">>> Entering \(__FUNCTION__) <<<") #endif } 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 applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Save data. } func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool { #if DEBUG print(">>> Entering \(__FUNCTION__) <<<") print("Recieved URL: \(url) with options: \(options)") #endif // If the incoming scheme is not contained within the array of supported schemes return false. guard let schemes = LinkBuilder.supportedSchemes where schemes.contains(url.scheme) else { return false } // We now have an acceptable scheme. Pass the URL to the deep linking handler. deepLinkToURL(url) return true } func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { print(shortcutItem) guard let type = CommonUseCasesForShortcuts(rawValue: shortcutItem.type) else { completionHandler(false) return } switch type { case .AddNew: let url = type.linkForUseCase() deepLinkToURL(url) case .ShowDetail: let siteIndex = shortcutItem.userInfo!["siteIndex"] as! Int SitesDataSource.sharedInstance.lastViewedSiteIndex = siteIndex #if DEDBUG println("User tapped on notification for site: \(site) at index \(siteIndex) with UUID: \(uuid)") #endif let url = type.linkForUseCase() deepLinkToURL(url) default: completionHandler(false) } completionHandler(true) } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // TODO: Background fetch new data and update watch. completionHandler(.NewData) } } extension AppDelegate { func deepLinkToURL(url: NSURL) { // Maybe this can be expanded to handle icomming messages from remote or local notifications. guard let pathComponents = url.pathComponents else { return } if let queryItems = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)?.queryItems { #if DEBUG print("queryItems: \(queryItems)") // Not handling queries at that moment, but might want to. #endif } guard let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window else { return } if let navController = window.rootViewController as? UINavigationController { // Get the root view controller's navigation controller. navController.popToRootViewControllerAnimated(false) // Return to root viewcontroller without animation. navController.dismissViewControllerAnimated(false, completion: { () -> Void in // }) let storyboard = window .rootViewController?.storyboard // Grab the storyboard from the rootview. var viewControllers = navController.viewControllers // Grab all the current view controllers in the stack. for pathComponent in pathComponents { // iterate through all the path components. Currently the app only has one level of deep linking. // Attempt to create a storyboard identifier out of the string. guard let storyboardIdentifier = StoryboardIdentifier(rawValue: pathComponent) else { continue } let linkIsAllowed = StoryboardIdentifier.deepLinkable.contains(storyboardIdentifier) // Check to see if this is an allowed viewcontroller. if linkIsAllowed { let newViewController = storyboard!.instantiateViewControllerWithIdentifier(storyboardIdentifier.rawValue) switch (storyboardIdentifier) { case .SiteListPageViewController: if let UUIDString = pathComponents[safe: 2], uuid = NSUUID(UUIDString: UUIDString), site = (SitesDataSource.sharedInstance.sites.filter { $0.uuid == uuid }.first), index = SitesDataSource.sharedInstance.sites.indexOf(site) { SitesDataSource.sharedInstance.lastViewedSiteIndex = index } viewControllers.append(newViewController) // Create the view controller and append it to the navigation view controller stack case .FormViewNavigationController, .FormViewController: navController.presentViewController(newViewController, animated: false, completion: { () -> Void in // ... }) default: viewControllers.append(newViewController) // Create the view controller and append it to the navigation view controller stack } } } navController.viewControllers = viewControllers // Apply the updated list of view controller to the current navigation controller. } } // MARK: Notifications func userDefaultsDidChange(notification: NSNotification) { if let userDefaults = notification.object as? NSUserDefaults { print("Defaults Changed") } } private func registerInitialSettings(userDefaults: NSUserDefaults) { } func setupNotificationSettings() { print(">>> Entering \(__FUNCTION__) <<<") // Specify the notification types. let notificationTypes: UIUserNotificationType = [.Alert, .Sound, .Badge] // Register the notification settings. let newNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(newNotificationSettings) // TODO: Enabled remote notifications... need to get a server running. // UIApplication.sharedApplication().registerForRemoteNotifications() UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) UIApplication.sharedApplication().applicationIconBadgeNumber = 0 UIApplication.sharedApplication().cancelAllLocalNotifications() } // TODO: Datasource needs to produce a signal, notification or callback so that the delegate can request premissions. // AppDataManagerNotificationDidChange Handler func dataManagerDidChange(notification: NSNotification? = nil) { // let sites = SitesDataSource.sharedInstance.sites // // if UIApplication.sharedApplication().currentUserNotificationSettings()?.types == .None || !sites.isEmpty { // setupNotificationSettings() // } // // UIApplication.sharedApplication().shortcutItems = nil // // let useCase = CommonUseCasesForShortcuts.ShowDetail.applicationShortcutItemType // // for (index, site) in sites.enumerate() { // // let mvm = site.generateSummaryModelViewModel() // // UIApplication.sharedApplication().shortcutItems?.append(UIApplicationShortcutItem(type: useCase, localizedTitle: mvm.nameLabel, localizedSubtitle: mvm.urlLabel, icon: nil, userInfo: ["uuid": site.uuid.UUIDString, "siteIndex": index])) // } } }
mit
e845b6fbf6230f5363b5a60c69b33aeb
42.048583
285
0.63538
6.291716
false
false
false
false
mattjgalloway/emoncms-ios
EmonCMSiOS/ViewModel/FeedListHelper.swift
1
1780
// // FeedListHelper.swift // EmonCMSiOS // // Created by Matt Galloway on 10/10/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import Foundation import RxSwift import RxCocoa import RealmSwift final class FeedListHelper { struct FeedListItem { let feedId: String let name: String } private let account: Account private let api: EmonCMSAPI private let realm: Realm private let feedUpdateHelper: FeedUpdateHelper private let disposeBag = DisposeBag() // Inputs let refresh = ReplaySubject<()>.create(bufferSize: 1) // Outputs private(set) var feeds: Driver<[FeedListItem]> private(set) var isRefreshing: Driver<Bool> init(account: Account, api: EmonCMSAPI) { self.account = account self.api = api self.realm = account.createRealm() self.feedUpdateHelper = FeedUpdateHelper(account: account, api: api) self.feeds = Driver.never() self.isRefreshing = Driver.never() self.feeds = Observable.arrayFrom(self.realm.objects(Feed.self)) .map(self.feedsToListItems) .asDriver(onErrorJustReturn: []) let isRefreshing = ActivityIndicator() self.isRefreshing = isRefreshing.asDriver() self.refresh .flatMapLatest { [weak self] () -> Observable<()> in guard let strongSelf = self else { return Observable.empty() } return strongSelf.feedUpdateHelper.updateFeeds() .catchErrorJustReturn(()) .trackActivity(isRefreshing) } .subscribe() .addDisposableTo(self.disposeBag) } private func feedsToListItems(_ feeds: [Feed]) -> [FeedListItem] { let sortedFeedItems = feeds.sorted { $0.name < $1.name }.map { FeedListItem(feedId: $0.id, name: $0.name) } return sortedFeedItems } }
mit
66d06e6235fa36c3bd58a3ae24e409f4
23.708333
72
0.679033
4.185882
false
false
false
false
crazytonyli/GeoNet-iOS
GeoNet/Volcanoes/VolcanoesViewController.swift
1
4410
// // VolcanoesViewController.swift // GeoNet // // Created by Tony Li on 18/11/16. // Copyright © 2016 Tony Li. All rights reserved. // import UIKit import SafariServices import GeoNetAPI private class VolcanoCell: UITableViewCell { let alertColorLayer: CAGradientLayer override init(style: UITableViewCellStyle, reuseIdentifier: String?) { alertColorLayer = CAGradientLayer() alertColorLayer.locations = [0, 0.2, 1] alertColorLayer.startPoint = CGPoint(x: 0, y: 0) alertColorLayer.endPoint = CGPoint(x: 1, y: 0) super.init(style: .value1, reuseIdentifier: reuseIdentifier) backgroundView = UIView() backgroundView!.layer.insertSublayer(alertColorLayer, at: 0) textLabel?.backgroundColor = .clear detailTextLabel?.backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() alertColorLayer.frame = alertColorLayer.superlayer!.bounds } func update(with volcano: Volcano) { textLabel?.text = volcano.title detailTextLabel?.text = volcano.level.rawValue.description alertColorLayer.isHidden = volcano.level == .noUnrest detailTextLabel?.textColor = alertColorLayer.isHidden ? .lightGray : .white let startLevel = VolcanoAlertLevel(rawValue: volcano.level.rawValue - 1) ?? .noUnrest alertColorLayer.colors = [UIColor.white.cgColor, startLevel.color.cgColor, volcano.level.color.cgColor] } } class VolcanoesViewController: UITableViewController { fileprivate weak var loadVolcanoesTask: URLSessionTask? fileprivate var volcanoes = [Volcano]() { didSet { tableView.reloadData() } } init() { super.init(style: .grouped) title = "Volcanoes" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(loadVolcanoes), for: .valueChanged) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "info") tableView.register(VolcanoCell.self, forCellReuseIdentifier: "volcano") loadVolcanoes() } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 1 ? "Volcanoes" : nil } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : volcanoes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) cell.textLabel?.text = "Volcanic Alert Levels" cell.accessoryType = .disclosureIndicator return cell } // swiftlint:disable force_cast let cell = tableView.dequeueReusableCell(withIdentifier: "volcano", for: indexPath) as! VolcanoCell cell.update(with: volcanoes[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return indexPath.section == 0 ? indexPath : nil } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == 0 else { return } let controller = SFSafariViewController(url: URL(string: "http://info.geonet.org.nz/m/display/volc/Volcanic+Alert+Levels")!) present(controller, animated: true, completion: nil) } } private extension VolcanoesViewController { @objc func loadVolcanoes() { loadVolcanoesTask = URLSession.API.volcanoes { [weak self] result in guard let `self` = self else { return } self.refreshControl?.endRefreshing() switch result { case .success(let volcanoes): self.volcanoes = volcanoes.sorted() case .failure(let error): break } } } }
mit
18dca60c26a15f880208745dc83576e8
32.150376
132
0.667045
4.829135
false
false
false
false
glock45/swifter
Sources/Swifter/Socket+Server.swift
1
4555
// // Socket+Server.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // #if os(Linux) import Glibc #else import Foundation #endif extension Socket { public class func tcpSocketForListen(_ port: in_port_t, _ forceIPv4: Bool = false, _ maxPendingConnection: Int32 = SOMAXCONN) throws -> Socket { #if os(Linux) let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, Int32(SOCK_STREAM.rawValue), 0) #else let socketFileDescriptor = socket(forceIPv4 ? AF_INET : AF_INET6, SOCK_STREAM, 0) #endif if socketFileDescriptor == -1 { throw SocketError.socketCreationFailed(Process.lastErrno) } var value: Int32 = 1 if setsockopt(socketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 { let details = Process.lastErrno Socket.release(socketFileDescriptor) throw SocketError.socketSettingReUseAddrFailed(details) } Socket.setNoSigPipe(socketFileDescriptor) #if os(Linux) var bindResult: Int32 = -1 if forceIPv4 { var addr = sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: port.bigEndian, sin_addr: in_addr(s_addr: in_addr_t(0)), sin_zero:(0, 0, 0, 0, 0, 0, 0, 0)) bindResult = withUnsafePointer(&addr) { bind(socketFileDescriptor, UnsafePointer<sockaddr>($0), socklen_t(sizeof(sockaddr_in))) } } else { var addr = sockaddr_in6(sin6_family: sa_family_t(AF_INET6), sin6_port: port.bigEndian, sin6_flowinfo: 0, sin6_addr: in6addr_any, sin6_scope_id: 0) bindResult = withUnsafePointer(&addr) { bind(socketFileDescriptor, UnsafePointer<sockaddr>($0), socklen_t(sizeof(sockaddr_in6))) } } #else var bindResult: Int32 = -1 if forceIPv4 { var addr = sockaddr_in(sin_len: UInt8(MemoryLayout<sockaddr_in>.stride), sin_family: UInt8(AF_INET), sin_port: port.bigEndian, sin_addr: in_addr(s_addr: in_addr_t(0)), sin_zero:(0, 0, 0, 0, 0, 0, 0, 0)) bindResult = withUnsafePointer(to: &addr) { bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size)) } } else { var addr = sockaddr_in6(sin6_len: UInt8(MemoryLayout<sockaddr_in6>.stride), sin6_family: UInt8(AF_INET6), sin6_port: port.bigEndian, sin6_flowinfo: 0, sin6_addr: in6addr_any, sin6_scope_id: 0) bindResult = withUnsafePointer(to: &addr) { bind(socketFileDescriptor, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in6>.size)) } } #endif if bindResult == -1 { let details = Process.lastErrno Socket.release(socketFileDescriptor) throw SocketError.bindFailed(details) } if listen(socketFileDescriptor, maxPendingConnection) == -1 { let details = Process.lastErrno Socket.release(socketFileDescriptor) throw SocketError.listenFailed(details) } return Socket(socketFileDescriptor: socketFileDescriptor) } public func acceptClientSocket() throws -> Socket { var addr = sockaddr() var len: socklen_t = 0 let clientSocket = accept(self.socketFileDescriptor, &addr, &len) if clientSocket == -1 { throw SocketError.acceptFailed(Process.lastErrno) } Socket.setNoSigPipe(clientSocket) return Socket(socketFileDescriptor: clientSocket) } }
bsd-3-clause
aaca1febdf2d41882f198af631dafb58
41.166667
148
0.507466
4.923243
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectRisksDisclaimerCell.swift
1
3604
import KsApi import Library import Prelude import UIKit protocol ProjectRisksDisclaimerCellDelegate: AnyObject { func projectRisksDisclaimerCell(_ cell: ProjectRisksDisclaimerCell, didTapURL: URL) } final class ProjectRisksDisclaimerCell: UITableViewCell, ValueCell { // MARK: - Properties weak var delegate: ProjectRisksDisclaimerCellDelegate? private let viewModel = ProjectRisksDisclaimerCellViewModel() private lazy var descriptionLabel: UILabel = { UILabel(frame: .zero) }() private lazy var rootStackView = { UIStackView(frame: .zero) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() // MARK: - Lifecycle override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.bindStyles() self.configureViews() self.bindViewModel() let descriptionLabelTapGesture = UITapGestureRecognizer( target: self, action: #selector(self.descriptionLabelTapped) ) self.descriptionLabel.addGestureRecognizer(descriptionLabelTapGesture) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Bindings override func bindViewModel() { super.bindViewModel() self.viewModel.outputs.notifyDelegateDescriptionLabelTapped .observeForControllerAction() .observeValues { [weak self] url in guard let self = self else { return } self.delegate?.projectRisksDisclaimerCell(self, didTapURL: url) } } override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() |> \.separatorInset .~ .init(leftRight: Styles.projectPageLeftRightInset) _ = self.contentView |> \.layoutMargins .~ .init(topBottom: Styles.projectPageTopBottomInset, leftRight: Styles.projectPageLeftRightInset) _ = self.descriptionLabel |> descriptionLabelStyle |> \.attributedText .~ self.attributedTextForFootnoteLabel() _ = self.rootStackView |> rootStackViewStyle } // MARK: - Configuration func configureWith(value _: Void) { return } private func configureViews() { _ = (self.rootStackView, self.contentView) |> ksr_addSubviewToParent() |> ksr_constrainViewToMarginsInParent() _ = ([self.descriptionLabel], self.rootStackView) |> ksr_addArrangedSubviewsToStackView() } // MARK: - Helpers private func attributedTextForFootnoteLabel() -> NSAttributedString { let attributes: String.Attributes = [ .font: UIFont.ksr_subhead(), .underlineStyle: NSUnderlineStyle.single.rawValue ] return NSMutableAttributedString( string: Strings.Learn_about_accountability_on_Kickstarter(), attributes: attributes ) } // MARK: - Actions @objc private func descriptionLabelTapped() { guard let url = HelpType.trust .url(withBaseUrl: AppEnvironment.current.apiService.serverConfig.webBaseUrl) else { return } self.viewModel.inputs.descriptionLabelTapped(url: url) } } // MARK: - Styles private let descriptionLabelStyle: LabelStyle = { label in label |> \.adjustsFontForContentSizeCategory .~ true |> \.isUserInteractionEnabled .~ true |> \.lineBreakMode .~ .byWordWrapping |> \.numberOfLines .~ 0 |> \.textColor .~ .ksr_create_700 } private let rootStackViewStyle: StackViewStyle = { stackView in stackView |> \.axis .~ .vertical |> \.insetsLayoutMarginsFromSafeArea .~ false |> \.isLayoutMarginsRelativeArrangement .~ true |> \.spacing .~ Styles.grid(3) }
apache-2.0
51b5d663dbe63ceb39fbcca09a4554ed
26.723077
101
0.705882
5.090395
false
false
false
false
zybug/firefox-ios
Client/Frontend/Widgets/ToggleButton.swift
15
4951
/* 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 private struct UX { static let TopColor = UIColor(red: 179 / 255, green: 83 / 255, blue: 253 / 255, alpha: 1) static let BottomColor = UIColor(red: 146 / 255, green: 16 / 255, blue: 253, alpha: 1) // The amount of pixels the toggle button will expand over the normal size. This results in the larger -> contract animation. static let ExpandDelta: CGFloat = 5 static let ShowDuration: NSTimeInterval = 0.4 static let HideDuration: NSTimeInterval = 0.2 static let BackgroundSize = CGSize(width: 32, height: 32) } class ToggleButton: UIButton { func setSelected(selected: Bool, animated: Bool = true) { self.selected = selected if animated { animateSelection(selected) } } private func updateMaskPathForSelectedState(selected: Bool) { let path = CGPathCreateMutable() if selected { var rect = CGRect(origin: CGPointZero, size: UX.BackgroundSize) rect.center = maskShapeLayer.position CGPathAddEllipseInRect(path, nil, rect) } else { CGPathAddEllipseInRect(path, nil, CGRect(origin: maskShapeLayer.position, size: CGSizeZero)) } self.maskShapeLayer.path = path } private func animateSelection(selected: Bool) { var endFrame = CGRect(origin: CGPointZero, size: UX.BackgroundSize) endFrame.center = maskShapeLayer.position if selected { let animation = CAKeyframeAnimation(keyPath: "path") let startPath = CGPathCreateMutable() CGPathAddEllipseInRect(startPath, nil, CGRect(origin: maskShapeLayer.position, size: CGSizeZero)) let largerPath = CGPathCreateMutable() let largerBounds = CGRectInset(endFrame, -UX.ExpandDelta, -UX.ExpandDelta) CGPathAddEllipseInRect(largerPath, nil, largerBounds) let endPath = CGPathCreateMutable() CGPathAddEllipseInRect(endPath, nil, endFrame) animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) animation.values = [ startPath, largerPath, endPath ] animation.duration = UX.ShowDuration self.maskShapeLayer.path = endPath self.maskShapeLayer.addAnimation(animation, forKey: "grow") } else { let animation = CABasicAnimation(keyPath: "path") animation.duration = UX.HideDuration animation.fillMode = kCAFillModeForwards let fromPath = CGPathCreateMutable() CGPathAddEllipseInRect(fromPath, nil, endFrame) animation.fromValue = fromPath animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let toPath = CGPathCreateMutable() CGPathAddEllipseInRect(toPath, nil, CGRect(origin: self.maskShapeLayer.bounds.center, size: CGSizeZero)) self.maskShapeLayer.path = toPath self.maskShapeLayer.addAnimation(animation, forKey: "shrink") } } lazy private var backgroundView: UIView = { let view = UIView() view.userInteractionEnabled = false view.layer.addSublayer(self.gradientLayer) return view }() lazy private var maskShapeLayer: CAShapeLayer = { let circle = CAShapeLayer() return circle }() lazy private var gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UX.TopColor.CGColor, UX.BottomColor.CGColor] gradientLayer.mask = self.maskShapeLayer return gradientLayer }() override init(frame: CGRect) { super.init(frame: frame) contentMode = UIViewContentMode.Redraw insertSubview(backgroundView, belowSubview: imageView!) } override func layoutSubviews() { super.layoutSubviews() let zeroFrame = CGRect(origin: CGPointZero, size: frame.size) backgroundView.frame = zeroFrame // Make the gradient larger than normal to allow the mask transition to show when it blows up // a little larger than the resting size gradientLayer.bounds = CGRectInset(backgroundView.frame, -UX.ExpandDelta, -UX.ExpandDelta) maskShapeLayer.bounds = backgroundView.frame gradientLayer.position = CGPoint(x: CGRectGetMidX(zeroFrame), y: CGRectGetMidY(zeroFrame)) maskShapeLayer.position = CGPoint(x: CGRectGetMidX(zeroFrame), y: CGRectGetMidY(zeroFrame)) updateMaskPathForSelectedState(selected) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
8e95daa0cc499cf0a2e0cde4c166111b
38.301587
129
0.663098
5.195173
false
false
false
false