repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rain2540/RGAppTools
refs/heads/master
Sources/RGBuild/RGToast.swift
mpl-2.0
1
// // RGToast.swift // RGAppTools // // Created by RAIN on 2017/8/22. // Copyright © 2017年 Smartech. All rights reserved. // import UIKit // MARK: RGToast public class RGToast: NSObject { public static let shared = RGToast() private var toastContents: Array<[CanBeToast]> = [] private var active = false private var toastView: RGToastView? private var toastFrame = UIScreen.main.bounds // MARK: Lifecycle override private init() { super.init() NotificationCenter.default .addObserver(self, selector: #selector(RGToast.keyboardWillAppear(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default .addObserver(self, selector: #selector(RGToast.keyboardWillDisappear(notification:)), name: UIResponder.keyboardDidHideNotification, object: nil) NotificationCenter.default .addObserver(self, selector: #selector(RGToast.orientationWillChange(notification:)), name: UIApplication.willChangeStatusBarOrientationNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Public Method public func toast(message: String?, image: UIImage? = nil) { if message != nil && image != nil { toastContents.append([message!, image!]) } else if message != nil { toastContents.append([message!]) } else if image != nil { toastContents.append([image!]) } if !active { showToast() } } // MARK: Show Toast Message private func showToast() { if toastContents.count < 1 { active = false return } active = true toastView = RGToastView() let contents = toastContents[0] var img: UIImage? = nil if contents.count > 1 { img = toastContents[0][1] as? UIImage toastView?.image = img } if contents.count > 0 { toastView?.messageText = toastContents[0][0] as? String } toastView?.transform = CGAffineTransform.identity toastView?.alpha = 0.0 toastView?.center = CGPoint(x: toastFrame.midX, y: toastFrame.midY) UIApplication.shared.keyWindow?.addSubview(toastView!) let orientation = UIApplication.shared.statusBarOrientation let degress = rotationDegress(orientation: orientation) toastView?.transform = CGAffineTransform(rotationAngle: degress * .pi / 180.0) toastView?.transform.scaledBy(x: 2.0, y: 2.0) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.15) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(RGToast.animationStep2)) toastView?.transform = CGAffineTransform(rotationAngle: degress * .pi / 180.0) toastView?.frame = (toastView?.frame.integral)! toastView?.alpha = 1.0 UIView.commitAnimations() } @objc private func animationStep2() { UIView.beginAnimations(nil, context: nil) let words = (toastContents[0][0] as! String).components(separatedBy: CharacterSet.whitespaces) let duration = max(Double(words.count) * 60.0 / 200.0, 1.4) UIView.setAnimationDelay(duration) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(RGToast.animationStep3)) let orientation = UIApplication.shared.statusBarOrientation let degress = rotationDegress(orientation: orientation) toastView?.transform = CGAffineTransform(rotationAngle: degress * .pi / 180.0) toastView?.transform.scaledBy(x: 0.5, y: 0.5) toastView?.alpha = 0.0 UIView.commitAnimations() } @objc private func animationStep3() { toastView?.removeFromSuperview() toastContents.remove(at: 0) showToast() } // MARK: System Observation Changes private func subtractRect(screenFrame: CGRect, keyboardFrame: CGRect) -> CGRect { var vKeyboardFrame = keyboardFrame if CGPoint.zero != vKeyboardFrame.origin { if vKeyboardFrame.origin.x > 0 { vKeyboardFrame.size.width = keyboardFrame.origin.x } if vKeyboardFrame.origin.y > 0 { vKeyboardFrame.size.height = keyboardFrame.origin.y } vKeyboardFrame.origin = CGPoint.zero } else { vKeyboardFrame.origin.x = abs(keyboardFrame.size.width - screenFrame.size.width) vKeyboardFrame.origin.y = abs(keyboardFrame.size.height - screenFrame.size.height) if vKeyboardFrame.origin.x > 0 { let temp = vKeyboardFrame.origin.x vKeyboardFrame.origin.x = vKeyboardFrame.size.width vKeyboardFrame.size.width = temp } else if vKeyboardFrame.origin.y > 0 { let temp = vKeyboardFrame.origin.y vKeyboardFrame.origin.y = vKeyboardFrame.size.height vKeyboardFrame.size.height = temp } } return screenFrame.intersection(vKeyboardFrame) } // MARK: Target - Action @objc private func keyboardWillAppear(notification: Notification) { let userInfo = notification.userInfo let aValue = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue let keyboardFrame = aValue.cgRectValue let screenFrame = UIScreen.main.bounds UIView.beginAnimations(nil, context: nil) toastFrame = subtractRect(screenFrame: screenFrame, keyboardFrame: keyboardFrame) toastView?.center = CGPoint(x: toastFrame.midX, y: toastFrame.midY) UIView.commitAnimations() } @objc private func keyboardWillDisappear(notification: Notification) { toastFrame = UIScreen.main.bounds } @objc private func orientationWillChange(notification: Notification) { let userInfo = notification.userInfo let v = userInfo?[UIApplication.statusBarOrientationUserInfoKey] as! NSNumber let o = UIInterfaceOrientation(rawValue: v.intValue) let degress = rotationDegress(orientation: o!) UIView.beginAnimations(nil, context: nil) toastView?.transform = CGAffineTransform(rotationAngle: degress * .pi / 180.0) toastView?.frame = CGRect(x: (toastView?.frame.minX)!, y: (toastView?.frame.minY)!, width: (toastView?.frame.width)!, height: (toastView?.frame.height)!) UIView.commitAnimations() } // MARK: Callback private func rotationDegress(orientation: UIInterfaceOrientation) -> CGFloat { var degress: CGFloat = 0.0 if orientation == .landscapeLeft { degress = -90.0 } else if orientation == .landscapeRight { degress = 90.0 } else if orientation == .portraitUpsideDown { degress = 180.0 } return degress } } // MARK: - RGToastView fileprivate class RGToastView: UIView { private var messageRect: CGRect? private var _image: UIImage? private var _messageText: String? fileprivate var image: UIImage? { get { return _image } set { _image = newValue adjust() } } fileprivate var messageText: String? { get { return _messageText } set { _messageText = newValue adjust() } } fileprivate init() { super.init(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0)) self.messageRect = bounds.insetBy(dx: 10.0, dy: 10.0) self.backgroundColor = UIColor.clear self.messageText = "" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func drawRoundRectangle(in rect: CGRect, radius: CGFloat) { let context = UIGraphicsGetCurrentContext() let rRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.width, height: rect.height) let minX = rRect.minX, midX = rRect.midX, maxX = rRect.maxX let minY = rRect.minY, midY = rRect.midY, maxY = rRect.maxY context?.move(to: CGPoint(x: minX, y: midY)) context?.addArc(tangent1End: CGPoint(x: minX, y: minY), tangent2End: CGPoint(x: midX, y: minY), radius: radius) context?.addArc(tangent1End: CGPoint(x: maxX, y: minY), tangent2End: CGPoint(x: maxX, y: midY), radius: radius) context?.addArc(tangent1End: CGPoint(x: maxX, y: maxY), tangent2End: CGPoint(x: midX, y: maxY), radius: radius) context?.addArc(tangent1End: CGPoint(x: minX, y: maxY), tangent2End: CGPoint(x: minX, y: midY), radius: radius) context?.closePath() context?.drawPath(using: .fill) } override func draw(_ rect: CGRect) { UIColor(white: 0.0, alpha: 0.8).set() drawRoundRectangle(in: rect, radius: 10.0) UIColor.white.set() let paragraphStyle = NSMutableParagraphStyle.default.mutableCopy() (paragraphStyle as! NSMutableParagraphStyle).lineBreakMode = .byWordWrapping (paragraphStyle as! NSMutableParagraphStyle).alignment = .center let dict = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14.0), NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.foregroundColor: UIColor.white] (messageText! as NSString).draw(in: messageRect!, withAttributes: dict) if let image = image { var imageRect = CGRect.zero imageRect.origin.y = 15.0 imageRect.origin.x = (rect.width - image.size.width) / 2.0 imageRect.size = image.size image.draw(in: imageRect) } } // MARK: Setter Methods private func adjust() { let size = messageText?.boundingRect(with: CGSize(width: 160.0, height: 200.0), options: [.usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14.0)], context: nil).size messageText?.size(withAttributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14.0)]) var imageAdjustment: CGFloat = 0.0 if image != nil { imageAdjustment = 7.0 + (image?.size.height)! } bounds = CGRect(x: 0.0, y: 0.0, width: (size?.width)! + 40.0, height: (size?.height)! + 15.0 + 15.0 + imageAdjustment) messageRect?.size = size! messageRect?.size.height += 5 messageRect?.origin.x = 20.0 messageRect?.origin.y = 15.0 + imageAdjustment setNeedsLayout() setNeedsDisplay() } } // MARK: fileprivate protocol CanBeToast { } extension UIImage: CanBeToast { } extension String: CanBeToast { }
83f80b0c487f9453af32ac1056fe0c7f
37.080268
161
0.604426
false
false
false
false
Coledunsby/TwitterClient
refs/heads/master
TwitterClientTests/LoginViewModelTests.swift
mit
1
// // LoginViewModelTests.swift // TwitterClient // // Created by Cole Dunsby on 2017-06-20. // Copyright © 2017 Cole Dunsby. All rights reserved. // import RealmSwift import RxCocoa import RxSwift import RxTest import XCTest @testable import TwitterClient final class LoginViewModelTests: XCTestCase { private var viewModel: LoginViewModelIO! private var scheduler: TestScheduler! private var disposeBag = DisposeBag() override func setUp() { super.setUp() Realm.Configuration.defaultConfiguration.inMemoryIdentifier = "test database" Cache.shared.clear() viewModel = LoginViewModel() scheduler = TestScheduler(initialClock: 0) disposeBag = DisposeBag() } func testInvalidEmail() { let email = scheduler.createHotObservable([next(50, "")]) let password = scheduler.createHotObservable([next(50, "password")]) let login = scheduler.createHotObservable([next(100, ())]) let tweetsViewModel = scheduler.createObserver(TweetsViewModel.self) let errors = scheduler.createObserver(Error.self) bindInputs(email: email, password: password, login: login) viewModel.outputs.tweetsViewModel.bind(to: tweetsViewModel).disposed(by: disposeBag) viewModel.outputs.errors.bind(to: errors).disposed(by: disposeBag) scheduler.start() XCTAssertEqual(tweetsViewModel.events.count, 0) XCTAssertEqual(errors.events.count, 1) XCTAssertEqual(errors.events.first?.value.element as? LoginError, .invalidEmail) } func testInvalidPassword() { let email = scheduler.createHotObservable([next(50, "[email protected]")]) let password = scheduler.createHotObservable([next(50, "")]) let login = scheduler.createHotObservable([next(100, ())]) let tweetsViewModel = scheduler.createObserver(TweetsViewModel.self) let errors = scheduler.createObserver(Error.self) bindInputs(email: email, password: password, login: login) viewModel.outputs.tweetsViewModel.bind(to: tweetsViewModel).disposed(by: disposeBag) viewModel.outputs.errors.bind(to: errors).disposed(by: disposeBag) scheduler.start() XCTAssertEqual(tweetsViewModel.events.count, 0) XCTAssertEqual(errors.events.count, 1) XCTAssertEqual(errors.events.first?.value.element as? LoginError, .invalidPassword) } func testInvalidCredentials() { Cache.shared.addUser(User(email: "[email protected]", password: "password")) let email = scheduler.createHotObservable([next(50, "[email protected]")]) let password = scheduler.createHotObservable([next(50, "notpassword")]) let login = scheduler.createHotObservable([next(100, ())]) let tweetsViewModel = scheduler.createObserver(TweetsViewModel.self) let errors = scheduler.createObserver(Error.self) bindInputs(email: email, password: password, login: login) viewModel.outputs.tweetsViewModel.bind(to: tweetsViewModel).disposed(by: disposeBag) viewModel.outputs.errors.bind(to: errors).disposed(by: disposeBag) scheduler.start() XCTAssertEqual(tweetsViewModel.events.count, 0) XCTAssertEqual(errors.events.count, 1) XCTAssertEqual(errors.events.first?.value.element as? LoginError, .invalidCredentials) } func testValidSignup() { let email = scheduler.createHotObservable([next(50, "[email protected]")]) let password = scheduler.createHotObservable([next(50, "password")]) let login = scheduler.createHotObservable([next(100, ())]) let tweetsViewModel = scheduler.createObserver(TweetsViewModel.self) let errors = scheduler.createObserver(Error.self) bindInputs(email: email, password: password, login: login) viewModel.outputs.tweetsViewModel.bind(to: tweetsViewModel).disposed(by: disposeBag) viewModel.outputs.errors.bind(to: errors).disposed(by: disposeBag) scheduler.start() XCTAssertEqual(tweetsViewModel.events.count, 1) XCTAssertEqual(errors.events.count, 0) } func testValidLogin() { Cache.shared.addUser(User(email: "[email protected]", password: "password")) let email = scheduler.createHotObservable([next(50, "[email protected]")]) let password = scheduler.createHotObservable([next(50, "password")]) let login = scheduler.createHotObservable([next(100, ())]) let tweetsViewModel = scheduler.createObserver(TweetsViewModel.self) let errors = scheduler.createObserver(Error.self) bindInputs(email: email, password: password, login: login) viewModel.outputs.tweetsViewModel.bind(to: tweetsViewModel).disposed(by: disposeBag) viewModel.outputs.errors.bind(to: errors).disposed(by: disposeBag) scheduler.start() XCTAssertEqual(tweetsViewModel.events.count, 1) XCTAssertEqual(errors.events.count, 0) } // MARK: - Private Helper Functions private func bindInputs(email: TestableObservable<String>, password: TestableObservable<String>, login: TestableObservable<()>) { email.bind(to: viewModel.inputs.email).disposed(by: disposeBag) password.bind(to: viewModel.inputs.password).disposed(by: disposeBag) login.bind(to: viewModel.inputs.login).disposed(by: disposeBag) } }
9548396102ba0b4f53b36aa5e84ead9b
40.664179
133
0.675802
false
true
false
false
gabmarfer/CucumberPicker
refs/heads/master
CucumberPicker/CucumberPicker/Commons/Extensions/UIImageSwiftExtension/UIImage+Alpha.swift
mit
2
// // UIImage+Alpha.swift // // Created by Trevor Harmon on 09/20/09. // Swift 3 port by Giacomo Boccardo on 09/15/2016. // // Free for personal or commercial use, with or without modification // No warranty is expressed or implied. // import UIKit public extension UIImage { public func hasAlpha() -> Bool { let alpha: CGImageAlphaInfo = (self.cgImage)!.alphaInfo return alpha == CGImageAlphaInfo.first || alpha == CGImageAlphaInfo.last || alpha == CGImageAlphaInfo.premultipliedFirst || alpha == CGImageAlphaInfo.premultipliedLast } public func imageWithAlpha() -> UIImage { if self.hasAlpha() { return self } let imageRef:CGImage = self.cgImage! let width = imageRef.width let height = imageRef.height // The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error let offscreenContext: CGContext = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: imageRef.colorSpace!, bitmapInfo: 0 /*CGImageByteOrderInfo.orderMask.rawValue*/ | CGImageAlphaInfo.premultipliedFirst.rawValue )! // Draw the image into the context and retrieve the new image, which will now have an alpha layer offscreenContext.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let imageRefWithAlpha:CGImage = offscreenContext.makeImage()! return UIImage(cgImage: imageRefWithAlpha) } public func transparentBorderImage(_ borderSize: Int) -> UIImage { let image = self.imageWithAlpha() let newRect = CGRect( x: 0, y: 0, width: image.size.width + CGFloat(borderSize) * 2, height: image.size.height + CGFloat(borderSize) * 2 ) // Build a context that's the same dimensions as the new size let bitmap: CGContext = CGContext( data: nil, width: Int(newRect.size.width), height: Int(newRect.size.height), bitsPerComponent: (self.cgImage)!.bitsPerComponent, bytesPerRow: 0, space: (self.cgImage)!.colorSpace!, bitmapInfo: (self.cgImage)!.bitmapInfo.rawValue )! // Draw the image in the center of the context, leaving a gap around the edges let imageLocation = CGRect(x: CGFloat(borderSize), y: CGFloat(borderSize), width: image.size.width, height: image.size.height) bitmap.draw(self.cgImage!, in: imageLocation) let borderImageRef: CGImage = bitmap.makeImage()! // Create a mask to make the border transparent, and combine it with the image let maskImageRef: CGImage = self.newBorderMask(borderSize, size: newRect.size) let transparentBorderImageRef: CGImage = borderImageRef.masking(maskImageRef)! return UIImage(cgImage:transparentBorderImageRef) } fileprivate func newBorderMask(_ borderSize: Int, size: CGSize) -> CGImage { let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray() // Build a context that's the same dimensions as the new size let maskContext: CGContext = CGContext( data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, // 8-bit grayscale bytesPerRow: 0, space: colorSpace, bitmapInfo: CGBitmapInfo().rawValue | CGImageAlphaInfo.none.rawValue )! // Start with a mask that's entirely transparent maskContext.setFillColor(UIColor.black.cgColor) maskContext.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) // Make the inner part (within the border) opaque maskContext.setFillColor(UIColor.white.cgColor) maskContext.fill(CGRect( x: CGFloat(borderSize), y: CGFloat(borderSize), width: size.width - CGFloat(borderSize) * 2, height: size.height - CGFloat(borderSize) * 2) ) // Get an image of the context return maskContext.makeImage()! } }
f1e40daccaf4354e09e2bf50f32911d5
39.773585
134
0.625636
false
false
false
false
nahive/SnapKit-Keyboard
refs/heads/master
Example/snapkitkeyboard/ViewController.swift
unlicense
1
// // ViewController.swift // snapkitkeyboard // // Created by Szymon Maślanka on 03/01/2017. // Copyright © 2017 Szymon Maślanka. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { let topView: UIView = { let view = UIView() view.backgroundColor = .red return view }() let topViewReplacement: UIView = { let view = UIView() view.backgroundColor = .blue return view }() let topMiddleView: UITextField = { let view = UITextField() view.backgroundColor = .green return view }() let bottomMiddleView: UITextField = { let view = UITextField() view.backgroundColor = .gray return view }() let bottomView: UIView = { let view = UIView() view.backgroundColor = .black return view }() override func viewDidLoad() { super.viewDidLoad() setup() } private func setup(){ setupSubviews() setupObservers() } private func setupSubviews(){ view.addSubview(topView) view.addSubview(topViewReplacement) view.addSubview(topMiddleView) view.addSubview(bottomMiddleView) view.addSubview(bottomView) } private func setupObservers(){ view.registerAutomaticKeyboardConstraints() } private func setupRegularConstraints(){ topView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.top.equalTo(view.snp.top).keyboard(false, in: view) make.height.equalTo(100) } topView.snp.prepareConstraints { (make) in make.bottom.equalTo(view.snp.top).keyboard(true, in: view) } topViewReplacement.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.bottom.equalTo(view.snp.top).keyboard(false, in: view) make.height.equalTo(100) } topViewReplacement.snp.prepareConstraints { (make) in make.top.equalTo(view.snp.top).keyboard(true, in: view) } topMiddleView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) make.centerX.equalTo(view.snp.centerX) make.centerY.equalTo(view.snp.centerY).offset(-44).keyboard(false, in: view) } topMiddleView.snp.prepareConstraints { (make) in make.centerY.equalTo(view.snp.centerY).offset(-144).keyboard(true, in: view) } bottomMiddleView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.right).offset(-20) make.height.equalTo(44) make.centerX.equalTo(view.snp.centerX) make.top.equalTo(topMiddleView.snp.bottom).offset(44) } bottomView.snp.remakeConstraints { (make) in make.bottom.equalTo(view.snp.bottom).offset(-44).keyboard(false, in: view) make.centerX.equalTo(view.snp.centerX) make.width.equalTo(100) make.height.equalTo(55) } bottomView.snp.prepareConstraints { (make) in make.top.equalTo(bottomMiddleView.snp.bottom).offset(20).keyboard(true, in: view) } } private func setupCompactConstraints(){ topView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.top.equalTo(view.snp.top).keyboard(false, in: view) make.height.equalTo(100) } topView.snp.prepareConstraints { (make) in make.bottom.equalTo(view.snp.top).keyboard(true, in: view) } topViewReplacement.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left) make.right.equalTo(view.snp.right) make.bottom.equalTo(view.snp.top).keyboard(false, in: view) make.height.equalTo(100) } topViewReplacement.snp.prepareConstraints { (make) in make.top.equalTo(view.snp.top).keyboard(true, in: view) } topMiddleView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.left).offset(20) make.right.equalTo(view.snp.centerX).offset(-20).keyboard(false, in: view) make.height.equalTo(44) make.centerY.equalTo(view.snp.centerY).keyboard(false, in: view) } topMiddleView.snp.prepareConstraints { (make) in make.right.equalTo(view.snp.centerX).offset(-64).keyboard(true, in: view) make.centerY.equalTo(view.snp.centerY).offset(-44).keyboard(true, in: view) } bottomMiddleView.snp.remakeConstraints { (make) in make.left.equalTo(view.snp.centerX).offset(20).keyboard(false, in: view) make.right.equalTo(view.snp.right).offset(-20).keyboard(false, in: view) make.height.equalTo(44) make.centerY.equalTo(topMiddleView.snp.centerY) } bottomMiddleView.snp.prepareConstraints { (make) in make.left.equalTo(topMiddleView.snp.right).offset(16).keyboard(true, in: view) } bottomView.snp.remakeConstraints { (make) in make.bottom.equalTo(view.snp.bottom).offset(-44).keyboard(false, in: view) make.centerX.equalTo(view.snp.centerX).keyboard(false, in: view) make.width.equalTo(100) make.height.equalTo(55) } bottomView.snp.prepareConstraints { (make) in make.centerY.equalTo(bottomMiddleView.snp.centerY).keyboard(true, in: view) make.left.equalTo(bottomMiddleView.snp.right).offset(8).keyboard(true, in: view) make.right.equalTo(view.snp.right).offset(-8).keyboard(true, in: view) } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { guard traitCollection != previousTraitCollection else { return } switch traitCollection.verticalSizeClass { case .regular: setupRegularConstraints() case .compact: setupCompactConstraints() case .unspecified: print("unspecified vertical size class") } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } }
f0cdee8b92da28843fe6338a8c9e6988
33.963918
93
0.602388
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Content Display Logic/Controllers/SegmentedViewController.swift
apache-2.0
1
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class SegmentedViewController: UIViewController { @IBOutlet private weak var segmentedControl: UISegmentedControl! @IBOutlet private weak var infoContainerView: UIView! @IBOutlet private weak var codeContainerView: UIView! var filenames = [String]() var readmeURL: URL? // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SourceCodeSegue" { let controller = segue.destination as! SourceCodeViewController controller.filenames = filenames } else if segue.identifier == "SampleInfoSegue" { let controller = segue.destination as! SampleInfoViewController controller.readmeURL = readmeURL } } // MARK: - Actions @IBAction func valueChanged(_ sender: UISegmentedControl) { self.infoContainerView.isHidden = (sender.selectedSegmentIndex == 1) } }
9b145db10049e93ff74c7e815b90ee8b
35.833333
76
0.700065
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Settings/WebsiteDataSearchResultsViewController.swift
mpl-2.0
2
// 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 SnapKit import Shared import WebKit class WebsiteDataSearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, Themeable { var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol private enum Section: Int { case sites = 0 case clearButton = 1 static let count = 2 } let viewModel: WebsiteDataManagementViewModel private var tableView: UITableView! private var filteredSiteRecords = [WKWebsiteDataRecord]() private var currentSearchText = "" init(viewModel: WebsiteDataManagementViewModel, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default) { self.viewModel = viewModel self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.isEditing = true tableView.allowsMultipleSelectionDuringEditing = true tableView.register(ThemedTableViewCell.self, forCellReuseIdentifier: "Cell") tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: ThemedTableSectionHeaderFooterView.cellIdentifier) view.addSubview(tableView) let footer = ThemedTableSectionHeaderFooterView(frame: CGRect(width: tableView.bounds.width, height: SettingsUX.TableViewHeaderFooterHeight)) footer.applyTheme(theme: themeManager.currentTheme) footer.showBorder(for: .top, true) tableView.tableFooterView = footer tableView.snp.makeConstraints { make in make.edges.equalTo(view) } KeyboardHelper.defaultHelper.addDelegate(self) listenForThemeChange() applyTheme() } func reloadData() { guard tableView != nil else { return } // to update filteredSiteRecords before reloading the tableView filterContentForSearchText(currentSearchText) } func numberOfSections(in tableView: UITableView) -> Int { return Section.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = Section(rawValue: section)! switch section { case .sites: return filteredSiteRecords.count case .clearButton: return 1 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ThemedTableViewCell(style: .default, reuseIdentifier: nil) cell.applyTheme(theme: themeManager.currentTheme) let section = Section(rawValue: indexPath.section)! switch section { case .sites: if let record = filteredSiteRecords[safe: indexPath.row] { cell.textLabel?.text = record.displayName if viewModel.selectedRecords.contains(record) { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } else { tableView.deselectRow(at: indexPath, animated: false) } } case .clearButton: cell.textLabel?.text = viewModel.clearButtonTitle cell.textLabel?.textAlignment = .center cell.textLabel?.textColor = themeManager.currentTheme.colors.textWarning cell.accessibilityTraits = UIAccessibilityTraits.button cell.accessibilityIdentifier = "ClearAllWebsiteData" } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = Section(rawValue: indexPath.section)! switch section { case .sites: guard let item = filteredSiteRecords[safe: indexPath.row] else { return } viewModel.selectItem(item) break case .clearButton: let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() let alert = viewModel.createAlertToRemove() present(alert, animated: true, completion: nil) } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let section = Section(rawValue: indexPath.section)! switch section { case .sites: guard let item = filteredSiteRecords[safe: indexPath.row] else { return } viewModel.deselectItem(item) break default: break } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { let section = Section(rawValue: indexPath.section)! switch section { case .sites: return true case .clearButton: return false } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ThemedTableSectionHeaderFooterView.cellIdentifier) as? ThemedTableSectionHeaderFooterView else { return nil } headerView.titleLabel.text = section == Section.sites.rawValue ? .SettingsWebsiteDataTitle : nil headerView.showBorder(for: .top, true) headerView.showBorder(for: .bottom, true) // top section: no top border (this is a plain table) guard let section = Section(rawValue: section) else { return headerView } if section == .sites { headerView.showBorder(for: .top, false) // no records: no bottom border (would make 2 with the one from the clear button) let emptyRecords = viewModel.siteRecords.isEmpty if emptyRecords { headerView.showBorder(for: .bottom, false) } } return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let section = Section(rawValue: section)! switch section { case .clearButton: return 10 // Controls the space between the site list and the button case .sites: return UITableView.automaticDimension } } func filterContentForSearchText(_ searchText: String) { filteredSiteRecords = viewModel.siteRecords.filter({ siteRecord in return siteRecord.displayName.lowercased().contains(searchText.lowercased()) }) tableView.reloadData() } func applyTheme() { tableView.separatorColor = themeManager.currentTheme.colors.borderPrimary tableView.backgroundColor = themeManager.currentTheme.colors.layer1 } } extension WebsiteDataSearchResultsViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { currentSearchText = searchController.searchBar.text ?? "" filterContentForSearchText(currentSearchText) } } extension WebsiteDataSearchResultsViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(view) tableView.contentInset.bottom = coveredHeight tableView.verticalScrollIndicatorInsets.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } }
35bb800a4bf1c193771ea6a1fade3024
37.642857
198
0.672458
false
false
false
false
brodie20j/Reunion-iOS
refs/heads/master
NSW/RSSManager.swift
mit
1
// // RSSManager.swift // Carleton Reunion // // Created by Jonathan Brodie on 6/1/15. // Copyright (c) 2015 BTIN. All rights reserved. // // Manages the RSS Feed for Carleton Reunion. // -keeps track of posts // -parses RSS feed from url to get the title and description // -this is accessed in EventListViewController.m, as that is when we check for updates import Foundation @objc class RSSManager: NSObject { var currentFeed:String="" let feedURL:String="https://apps.carleton.edu/reunion/feeds/blogs/reunionupdates" var feedLog: [String: String]=[:] var log=["DUMMY"] var updates=false override init() { super.init() //since we're being initialized, go get the latest RSS Feed self.getLatestFeed() } func getLatestFeed() { var html : NSString = NSString(contentsOfURL: NSURL(string:self.feedURL)!, encoding: NSUTF8StringEncoding, error: nil)! as NSString self.currentFeed=html as! String self.scrapeUpdates() } func scrapeUpdates() { var rawHTML:String=self.currentFeed var titleString:String="" var descriptionString:String="" var dateString:String="" var linkString:String="" //Warning: The following is a non-versatile way to parse HTML. This approach is very narrow and prevents further expansions. If we had needed to directly access HTML more, I would have looked into constructing a better approach. while (rawHTML.rangeOfString("<item>") != nil) { var titleString:String="" var descriptionString:String="" var dateString:String="" var linkString:String="" var range=rawHTML.rangeOfString("<item>")! //get the substring from the <item> tag to the rest of the page var jankystr=rawHTML.substringWithRange(Range<String.Index>(start: advance(range.endIndex,8), end: rawHTML.endIndex)) var counter=0 for char in jankystr { if char=="<" { break } else { titleString.append(char) counter=counter+1 } } rawHTML=rawHTML.substringWithRange(Range<String.Index>(start: advance(range.endIndex,8+counter),end: rawHTML.endIndex)) range=rawHTML.rangeOfString("<description>")! //get the substring from the <description> tag to the rest of the page jankystr=rawHTML.substringWithRange(Range<String.Index>(start: range.endIndex, end: rawHTML.endIndex)) counter=0 for char in jankystr { if char=="<" { break } else { descriptionString.append(char) counter=counter+1 } } self.feedLog[titleString]=descriptionString rawHTML=jankystr } } func getCurrentFeed() -> String { return self.currentFeed; } //checks the current feed for logs we have seen before, filters those out, and returns a dictionary of the remaining values func getFeedLog() -> [String: String] { for i in self.log { if let val = self.feedLog[i] { self.feedLog.removeValueForKey(i) } } var newLog:[String:String]=[:] for title in self.feedLog.keys { if self.feedLog[title] != nil { newLog[title]=self.feedLog[title] } //now add these values to our old log if !contains(self.log,title) { self.log+=[title] } } return newLog } func clearLog() { self.feedLog=[:] } }
c248386874cb57f8f7a9ae2470459d70
32.220339
238
0.563409
false
false
false
false
minimoog/filters
refs/heads/master
filters/CarnivalMirror.swift
mit
1
// // CarnivalMirror.swift // filters // // Created by Toni Jovanoski on 2/14/17. // Copyright © 2017 Antonie Jovanoski. All rights reserved. // import Foundation import CoreImage class CarnivalMirror: CIFilter { var inputImage: CIImage? var inputHorWavelength: CGFloat = 10 var inputHorAmount: CGFloat = 20 var inputVerWavelength: CGFloat = 10 var inputVerAmount: CGFloat = 20 override func setDefaults() { inputHorWavelength = 10 inputHorAmount = 20 inputVerWavelength = 10 inputVerAmount = 20 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Carnival Mirror", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputHorizontalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Horizontal Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputHorizontalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Horizontal Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalWavelength": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Vertical Wavelength", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar], "inputVerticalAmount": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 20, kCIAttributeDisplayName: "Vertical Amount", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } let carnivalMirrorKernel = CIWarpKernel(string: "kernel vec2 carnivalMirror(float xWavelength, float xAmount, float yWavelength, float yAmount)" + "{" + " float y = destCoord().y + sin(destCoord().y / yWavelength) * yAmount; " + " float x = destCoord().x + sin(destCoord().x / xWavelength) * xAmount; " + " return vec2(x, y);" + "}") override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = carnivalMirrorKernel else { return nil } let arguments = [inputHorWavelength, inputHorAmount, inputVerWavelength, inputVerAmount] let extent = inputImage.extent return kernel.apply(withExtent: extent, roiCallback: { (index, rect) -> CGRect in return rect }, inputImage: inputImage, arguments: arguments) } }
bc1bdc38089ccd3fd17f23b901095f5c
35.302083
106
0.584505
false
false
false
false
Seanalair/GreenAR
refs/heads/master
Example/GreenAR/MultipeerManager.swift
mit
1
// // MultipeerManager.swift // GreenAR_Example // // Created by Daniel Grenier on 10/23/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import MultipeerConnectivity class MultipeerManager: NSObject, MCSessionDelegate, MCNearbyServiceAdvertiserDelegate, MCNearbyServiceBrowserDelegate { let kServiceName = "RoomShare" let kAdvertiserName = "RoomSource" let kBrowserName = "Roommate" var fileName: String var completionHandler: (_ success: Bool) -> Void var sending: Bool var peerID: MCPeerID? var session: MCSession? var browser: MCNearbyServiceBrowser? var advertiser: MCNearbyServiceAdvertiser? public init(fileToSend:String, completion: @escaping (_ success: Bool) -> Void) { sending = true fileName = fileToSend completionHandler = completion super.init() connect() } public init(targetFileLocation: String, completion: @escaping (_ success: Bool) -> Void) { sending = false fileName = targetFileLocation completionHandler = completion super.init() connect() } public func connect() { if (sending) { peerID = MCPeerID(displayName: kAdvertiserName) session = MCSession(peer: peerID!, securityIdentity: nil, encryptionPreference: .none) session!.delegate = self advertiser = MCNearbyServiceAdvertiser(peer: peerID!, discoveryInfo: nil, serviceType: kServiceName) advertiser!.delegate = self advertiser!.startAdvertisingPeer() } else { peerID = MCPeerID(displayName: kBrowserName) session = MCSession(peer: peerID!, securityIdentity: nil, encryptionPreference: .none) session!.delegate = self browser = MCNearbyServiceBrowser(peer: peerID!, serviceType: kServiceName) browser!.delegate = self browser!.startBrowsingForPeers() } } public func disconnect() { if (sending) { session!.disconnect() advertiser!.stopAdvertisingPeer() session = nil peerID = nil advertiser = nil } else { session!.disconnect() browser!.stopBrowsingForPeers() session = nil peerID = nil browser = nil } } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { if (peerID.displayName == kBrowserName && state == .connected) { guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let fileUrl = documentsDirectoryUrl.appendingPathComponent("\(fileName).json") do { let data = try Data(contentsOf: fileUrl, options: []) try session.send(data, toPeers: [peerID], with: .reliable) completionHandler(true) } catch { print(error) completionHandler(false) } } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { do { if let _ = try JSONSerialization.jsonObject(with: data,options: []) as? [String : Any] { guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let fileUrl = documentDirectoryUrl.appendingPathComponent("\(fileName).json") try data.write(to: fileUrl, options: []) completionHandler(true) disconnect() } } catch { print(error) completionHandler(false) disconnect() } } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { print("Received stream named:\(streamName) from peer:\(peerID.displayName)") } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { print("Started receiving resource named:\(resourceName) from peer:\(peerID.displayName)") } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { print("Finished receiving resource named:\(resourceName) from peer:\(peerID.displayName)") } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { if (peerID.displayName == kBrowserName) { invitationHandler(true, session!) } } func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) { print("Found peer:\(peerID.displayName) with discovery info: \(String(describing:info))") if (peerID.displayName == kAdvertiserName) { browser.invitePeer(peerID, to: session!, withContext: nil, timeout: 5) } } func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { print("Lost Connection with peer:\(peerID.displayName)") } }
7e20c9a69152860750cbcf9855349ae4
35.647059
141
0.553451
false
false
false
false
Urinx/SublimeCode
refs/heads/master
Sublime/Sublime/SSHAddNewServerViewController.swift
gpl-3.0
1
// // SSHAddNewServerViewController.swift // Sublime // // Created by Eular on 3/28/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import Gifu class SSHAddNewServerViewController: UITableViewController, UITextFieldDelegate { let settingList = [ ["ssh_server", "host"], ["ssh_port", "port"], ["ssh_user", "username"], ["ssh_password", "password"] ] var textFieldList = [UITextField]() override func viewDidLoad() { super.viewDidLoad() title = "New Server" tableView.backgroundColor = Constant.CapeCod tableView.separatorColor = Constant.TableCellSeparatorColor tableView.tableFooterView = UIView() Global.Notifi.addObserver(self, selector: #selector(self.keyboardDidShow), name: UIKeyboardDidShowNotification, object: nil) Global.Notifi.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIKeyboardDidHideNotification, object: nil) let header = UIView(frame: CGRectMake(0, 0, view.width, 80)) let gif = AnimatableImageView() gif.frame = CGRectMake(0, 20, view.width, 60) gif.contentMode = .ScaleAspectFit gif.animateWithImageData(NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("animation", ofType: "gif")!)!) gif.startAnimatingGIF() header.addSubview(gif) tableView.tableHeaderView = header } func keyboardDidShow() { navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ssh_keyboard"), style: .Plain, target: self, action: #selector(self.dismissKeyboard)) } func keyboardWillHide() { navigationItem.rightBarButtonItem = nil } func dismissKeyboard() { self.view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [settingList.count, 1][section] } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return Constant.FilesTableSectionHight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } let headerView = UIView() headerView.frame = CGRectMake(0, 0, view.width, Constant.FilesTableSectionHight) headerView.backgroundColor = Constant.CapeCod return headerView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: nil) cell.backgroundColor = Constant.NavigationBarAndTabBarColor cell.selectedBackgroundView = UIView(frame: cell.frame) cell.selectedBackgroundView?.backgroundColor = Constant.NavigationBarAndTabBarColor if indexPath.section == 0 { let tf = UITextField() tf.frame = CGRectMake(70, 3, cell.frame.width - 80, cell.frame.height) tf.attributedPlaceholder = NSAttributedString(string: settingList[indexPath.row][1], attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) tf.textColor = UIColor.whiteColor() tf.delegate = self if tf.placeholder == "port" { tf.keyboardType = .NumberPad } else if tf.placeholder == "host" { tf.keyboardType = .URL } tf.autocorrectionType = .No tf.autocapitalizationType = .None cell.addSubview(tf) cell.imageView?.image = UIImage(named: settingList[indexPath.row][0]) textFieldList.append(tf) } else { let doneImg = UIImageView() doneImg.frame = CGRectMake(0, 0, 40, 40) doneImg.image = UIImage(named: "ssh_done") cell.addSubview(doneImg) doneImg.atCenter() } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 1 { var serverInfo = [String:String]() for tf in textFieldList { if tf.text!.isEmpty { view.Toast(message: "\(tf.placeholder!) can't be empty", hasNavigationBar: true) return } else { serverInfo[tf.placeholder!] = tf.text } } let serverPlist = Plist(path: Constant.SublimeRoot+"/etc/ssh_list.plist") do { try serverPlist.appendToPlistFile(serverInfo) navigationController?.popViewControllerAnimated(true) } catch { view.Toast(message: "Save failed!", hasNavigationBar: true) } } } }
e9abe6839e98a6001a72a52be79db9b7
37.7
168
0.626061
false
false
false
false
ninjaprawn/BigStats
refs/heads/master
BigStats/SwiftRegex.swift
mit
1
// // SwiftRegex.swift // SwiftRegex // // Created by John Holdsworth on 26/06/2014. // Copyright (c) 2014 John Holdsworth. // // $Id: //depot/SwiftRegex/SwiftRegex.swift#37 $ // // This code is in the public domain from: // https://github.com/johnno1962/SwiftRegex // import Foundation var swiftRegexCache = Dictionary<String,NSRegularExpression>() public class SwiftRegex: NSObject, BooleanType { var target: NSString var regex: NSRegularExpression init(target:NSString, pattern:String, options:NSRegularExpressionOptions = nil) { self.target = target if let regex = swiftRegexCache[pattern] { self.regex = regex } else { var error: NSError? if let regex = NSRegularExpression(pattern: pattern, options:options, error:&error) { swiftRegexCache[pattern] = regex self.regex = regex } else { SwiftRegex.failure("Error in pattern: \(pattern) - \(error)") self.regex = NSRegularExpression() } } super.init() } class func failure(message: String) { println("SwiftRegex: "+message) //assert(false,"SwiftRegex: failed") } final var targetRange: NSRange { return NSRange(location: 0,length: target.length) } final func substring(range: NSRange) -> NSString! { if ( range.location != NSNotFound ) { return target.substringWithRange(range) } else { return nil } } public func doesMatch(options: NSMatchingOptions = nil) -> Bool { return range(options: options).location != NSNotFound } public func range(options: NSMatchingOptions = nil) -> NSRange { return regex.rangeOfFirstMatchInString(target, options: nil, range: targetRange) } public func match(options: NSMatchingOptions = nil) -> String! { return substring(range(options: options)) } public func groups(options: NSMatchingOptions = nil) -> [String]! { return groupsForMatch( regex.firstMatchInString(target, options: options, range: targetRange) ) } func groupsForMatch(match: NSTextCheckingResult!) -> [String]! { if match != nil { var groups = [String]() for groupno in 0...regex.numberOfCaptureGroups { if let group = substring(match.rangeAtIndex(groupno)) as String! { groups += [group] } else { groups += ["_"] // avoids bridging problems } } return groups } else { return nil } } public subscript(groupno: Int) -> String! { get { return groups()[groupno] } set(newValue) { if let mutableTarget = target as? NSMutableString { for match in matchResults().reverse() { let replacement = regex.replacementStringForResult( match, inString: target, offset: 0, template: newValue ) mutableTarget.replaceCharactersInRange(match.rangeAtIndex(groupno), withString: replacement) } } else { SwiftRegex.failure("Group modify on non-mutable") } } } func matchResults(options: NSMatchingOptions = nil) -> [NSTextCheckingResult] { return regex.matchesInString(target, options: options, range: targetRange) as [NSTextCheckingResult] } public func ranges(options: NSMatchingOptions = nil) -> [NSRange] { return matchResults(options: options).map { $0.range } } public func matches(options: NSMatchingOptions = nil) -> [String] { return matchResults(options: options).map { self.substring($0.range) } } public func allGroups(options: NSMatchingOptions = nil) -> [[String]] { return matchResults(options: options).map { self.groupsForMatch($0) } } public func dictionary(options: NSMatchingOptions = nil) -> Dictionary<String,String> { var out = Dictionary<String,String>() for match in matchResults(options: options) { out[substring(match.rangeAtIndex(1))] = substring(match.rangeAtIndex(2)) } return out } func substituteMatches(substitution: (NSTextCheckingResult, UnsafeMutablePointer<ObjCBool>) -> String, options:NSMatchingOptions = nil) -> NSMutableString { let out = NSMutableString() var pos = 0 regex.enumerateMatchesInString(target, options: options, range: targetRange ) { (match: NSTextCheckingResult!, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in let matchRange = match.range out.appendString( self.substring( NSRange(location:pos, length:matchRange.location-pos) ) ) out.appendString( substitution(match, stop) ) pos = matchRange.location + matchRange.length } out.appendString( substring( NSRange(location:pos, length:targetRange.length-pos) ) ) if let mutableTarget = target as? NSMutableString { mutableTarget.setString(out) return mutableTarget } else { SwiftRegex.failure("Modify on non-mutable") return out } } /* removed Beta6 public func __conversion() -> Bool { return doesMatch() } public func __conversion() -> NSRange { return range() } public func __conversion() -> String { return match() } public func __conversion() -> [String] { return matches() } public func __conversion() -> [[String]] { return allGroups() } public func __conversion() -> [String:String] { return dictionary() } */ public var boolValue: Bool { return doesMatch() } } extension NSString { public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex { return SwiftRegex(target: self, pattern: pattern, options: options) } } extension NSString { public subscript(pattern: String) -> SwiftRegex { return SwiftRegex(target: self, pattern: pattern) } } extension String { public subscript(pattern: String, options: NSRegularExpressionOptions) -> SwiftRegex { return SwiftRegex(target: self, pattern: pattern, options: options) } } extension String { public subscript(pattern: String) -> SwiftRegex { return SwiftRegex(target: self, pattern: pattern) } } public func RegexMutable(string: NSString) -> NSMutableString { return NSMutableString(string:string) } public func ~= (left: SwiftRegex, right: String) -> NSMutableString { return left.substituteMatches { (match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in return left.regex.replacementStringForResult( match, inString: left.target, offset: 0, template: right ) } } public func ~= (left: SwiftRegex, right: [String]) -> NSMutableString { var matchNumber = 0 return left.substituteMatches { (match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in if ++matchNumber == right.count { stop.memory = true } return left.regex.replacementStringForResult( match, inString: left.target, offset: 0, template: right[matchNumber-1] ) } } public func ~= (left: SwiftRegex, right: (String) -> String) -> NSMutableString { return left.substituteMatches { (match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in return right(left.substring(match.range)) } } public func ~= (left: SwiftRegex, right: ([String]) -> String) -> NSMutableString { return left.substituteMatches { (match: NSTextCheckingResult, stop: UnsafeMutablePointer<ObjCBool>) in return right(left.groupsForMatch(match)) } } // my take on custom threading operators from // http://ijoshsmith.com/2014/07/05/custom-threading-operator-in-swift/ private let _queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) public func | (left: () -> Void, right: () -> Void) { dispatch_async(_queue) { left() dispatch_async(dispatch_get_main_queue(), right) } } public func | <R> (left: () -> R, right: (result:R) -> Void) { dispatch_async(_queue) { let result = left() dispatch_async(dispatch_get_main_queue(), { right(result:result) }) } } // dispatch groups { block } & { block } | { completion } public func & (left: () -> Void, right: () -> Void) -> [() -> Void] { return [left, right]; } public func & (left: [() -> Void], right: () -> Void) -> [() -> Void] { var out = left out.append( right ) return out } public func | (left: [() -> Void], right: () -> Void) { let group = dispatch_group_create() for block in left { dispatch_group_async(group, _queue, block) } dispatch_group_notify(group, dispatch_get_main_queue(), right) } // parallel blocks with returns public func & <R> (left: () -> R, right: () -> R) -> [() -> R] { return [left, right] } public func & <R> (left: [() -> R], right: () -> R) -> [() -> R] { var out = left out.append( right ) return out } public func | <R> (left: [() -> R], right: (results:[R!]) -> Void) { let group = dispatch_group_create() var results = Array<R!>() for t in 0..<left.count { results += [nil] } for t in 0..<left.count { //dispatch_retain(group) dispatch_group_enter(group) dispatch_async(_queue, { results[t] = left[t]() dispatch_group_leave(group) //dispatch_release(group) }) } dispatch_group_notify(group, dispatch_get_main_queue(), { right(results: results) }) }
2bcd9862dec3672d597091aa95042d62
29.701538
112
0.603327
false
false
false
false
uphold/uphold-sdk-ios
refs/heads/master
Tests/UtilTests/MockSessionManager.swift
mit
1
import Foundation import KeychainSwift import UpholdSdk /// Mock session manager. open class MockSessionManager { /// The singleton's shared instance. static let sharedInstance = MockSessionManager() /// The mocked keychain key to access the bearer token. private static let MOCK_KEYCHAIN_TOKEN_KEY: String = "com.uphold.sdk.mock.token" /// The mocked keychain access object. let keychain: MockKeychain /// Queue to manage concurrency. let lockQueue: DispatchQueue /** Constructor. */ init() { self.keychain = MockKeychain() self.lockQueue = DispatchQueue(label: GlobalConfigurations.BUNDLE_NAME, attributes: []) self.invalidateSession() } /** Gets the bearer token. - returns: The bearer token. */ func getBearerToken() -> String? { guard let token = self.keychain.get(key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) else { return nil } return token } /** Sets the bearer token. - parameter token: The bearer token. */ func setBearerToken(token: String) { self.invalidateSession() _ = self.lockQueue.sync { self.keychain.set(token: token, key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) } } /** Deletes the bearer token from the keychain. */ func invalidateSession() { _ = self.lockQueue.sync { self.keychain.delete(key: MockSessionManager.MOCK_KEYCHAIN_TOKEN_KEY) } } }
c53e70998c595d0d5ec6597df723baaf
23.125
99
0.626943
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/HCILEReadRemoteUsedFeaturesComplete.swift
mit
1
// // HCILEReadRemoteUsedFeaturesComplete.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// LE Read Remote Features Complete Event /// /// The event is used to indicate the completion of the process of the Controller /// obtaining the features used on the connection and the features supported by the remote Blu @frozen public struct HCILEReadRemoteUsedFeaturesComplete: HCIEventParameter { public static let event = LowEnergyEvent.readRemoteUsedFeaturesComplete // 0x04 public static let length: Int = 11 public typealias Status = HCIStatus /// `0x00` if Connection successfully completed. /// `HCIError` value otherwise. public let status: Status /// Connection Handle /// /// Range: 0x0000-0x0EFF (all other values reserved for future use) public let handle: UInt16 // Connection_Handle /// LE features of the remote controller. public let features: LowEnergyFeatureSet public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let statusByte = data[0] let handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) let featuresRawValue = UInt64(littleEndian: UInt64(bytes: (data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10]))) guard let status = Status(rawValue: statusByte) else { return nil } self.status = status self.handle = handle self.features = LowEnergyFeatureSet(rawValue: featuresRawValue) } }
eda6d850a61c02d6fea580826d4c3614
34.606557
94
0.51105
false
false
false
false
malaonline/iOS
refs/heads/master
mala-ios/View/TeacherTableView/TeacherTableViewCell.swift
mit
1
// // TeacherTableViewCell.swift // mala-ios // // Created by Elors on 1/14/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit class TeacherTableViewCell: UITableViewCell { // MARK: - Property /// 老师简介模型 var model: TeacherModel? { didSet{ guard let model = model else { return } courseLabel.setTitle((model.grades_shortname ?? "")+" • "+(model.subject ?? ""), for: UIControlState()) nameLabel.text = model.name levelLabel.text = String(format: " T%d ", model.level) avatarView.setImage(withURL: model.avatar) let string = String(MinPrice: model.min_price.money, MaxPrice: model.max_price.money) let attrString: NSMutableAttributedString = NSMutableAttributedString(string: string) let rangeLocation = (string as NSString).range(of: "元").location attrString.addAttribute( NSForegroundColorAttributeName, value: UIColor(named: .ThemeBlue), range: NSMakeRange(0, rangeLocation) ) attrString.addAttribute( NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, rangeLocation) ) attrString.addAttribute( NSForegroundColorAttributeName, value: UIColor(named: .ArticleSubTitle), range: NSMakeRange(rangeLocation, 4) ) attrString.addAttribute( NSFontAttributeName, value: UIFont.systemFont(ofSize: 12), range: NSMakeRange(rangeLocation, 4) ) priceLabel.attributedText = attrString tagsLabel.text = model.tags?.joined(separator: "|") } } // MARK: - Components /// 布局视图(卡片式Cell白色背景) private lazy var content: UIView = { let view = UIView(UIColor.white) return view }() /// 授课年级及科目label private lazy var courseLabel: UIButton = { let courseLabel = UIButton() courseLabel.setBackgroundImage(UIImage(asset: .tagsTitle), for: UIControlState()) courseLabel.titleLabel?.font = UIFont.systemFont(ofSize: 11) courseLabel.titleEdgeInsets = UIEdgeInsets(top: -1, left: 0, bottom: 1, right: 0) courseLabel.isUserInteractionEnabled = false return courseLabel }() /// 老师姓名label private lazy var nameLabel: UILabel = { let nameLabel = UILabel() nameLabel.font = FontFamily.HelveticaNeue.Thin.font(17) nameLabel.textColor = UIColor(named: .ArticleTitle) return nameLabel }() /// 老师级别label private lazy var levelLabel: UILabel = { let levelLabel = UILabel() levelLabel.font = FontFamily.HelveticaNeue.Thin.font(13) levelLabel.backgroundColor = UIColor.white levelLabel.textColor = UIColor(named: .ThemeRed) return levelLabel }() /// 级别所在分割线 private lazy var separator: UIView = { let separator = UIView(UIColor(named: .SeparatorLine)) return separator }() /// 老师头像ImageView private lazy var avatarView: UIImageView = { let avatarView = UIImageView() avatarView.frame = CGRect(x: 0, y: 0, width: MalaLayout_AvatarSize, height: MalaLayout_AvatarSize) avatarView.layer.cornerRadius = MalaLayout_AvatarSize * 0.5 avatarView.layer.masksToBounds = true avatarView.image = UIImage(asset: .avatarPlaceholder) avatarView.contentMode = .scaleAspectFill return avatarView }() /// 授课价格label private lazy var priceLabel: UILabel = { let priceLabel = UILabel() priceLabel.font = UIFont.systemFont(ofSize: 14) priceLabel.textColor = UIColor(named: .ArticleSubTitle) return priceLabel }() /// 风格标签label private lazy var tagsLabel: UILabel = { let tagsLabel = UILabel() tagsLabel.font = FontFamily.HelveticaNeue.Thin.font(11) tagsLabel.textColor = UIColor(named: .CardTag) return tagsLabel }() // MARK: - Constructed override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private Method private func setupUserInterface() { // Style contentView.backgroundColor = UIColor(named: .themeLightBlue) selectionStyle = .none // SubViews contentView.addSubview(content) contentView.addSubview(courseLabel) content.addSubview(nameLabel) content.addSubview(levelLabel) content.insertSubview(separator, belowSubview: levelLabel) content.addSubview(avatarView) content.addSubview(priceLabel) content.addSubview(tagsLabel) // Autolayout content.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView).offset(4) maker.left.equalTo(contentView).offset(12) maker.bottom.equalTo(contentView).offset(-4) maker.right.equalTo(contentView).offset(-12) } courseLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(contentView).offset(4) maker.left.equalTo(contentView) maker.height.equalTo(24) maker.width.equalTo(100) } nameLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(content).offset(15) maker.centerX.equalTo(content) maker.height.equalTo(17) } levelLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(nameLabel.snp.bottom).offset(10) maker.centerX.equalTo(content) maker.height.equalTo(13) } separator.snp.makeConstraints { (maker) -> Void in maker.centerX.equalTo(content) maker.centerY.equalTo(levelLabel) maker.left.equalTo(content).offset(10) maker.right.equalTo(content).offset(-10) maker.height.equalTo(MalaScreenOnePixel) } avatarView.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(levelLabel.snp.bottom).offset(12) maker.centerX.equalTo(content) maker.width.equalTo(MalaLayout_AvatarSize) maker.height.equalTo(MalaLayout_AvatarSize) } priceLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(avatarView.snp.bottom).offset(11) maker.centerX.equalTo(content) maker.height.equalTo(14) } tagsLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(priceLabel.snp.bottom).offset(12) maker.centerX.equalTo(content) maker.height.equalTo(11) maker.bottom.equalTo(content).offset(-15) } } override func prepareForReuse() { super.prepareForReuse() avatarView.image = UIImage(asset: .avatarPlaceholder) } }
9f14d103f19a6f43c2cd14c3434b62ef
36.317949
115
0.611653
false
false
false
false
egnwd/ic-bill-hack
refs/heads/master
quick-split/quick-split/DemoFriends.swift
mit
1
// // DemoFriends.swift // quick-split // // Created by Elliot Greenwood on 02.20.2016. // Copyright © 2016 stealth-phoenix. All rights reserved. // import Foundation import UIKit class DemoFriends { var friends: [Friend] static let sharedInstance = DemoFriends() init() { let alice = Friend(name: "Alice", pictureName: "alice.jpg", mondoId: "acc_1") let bob = Friend(name: "Bob", pictureName: "bob.jpg", mondoId: "acc_2") let clare = Friend(name: "Clare", pictureName: "clare.jpg", mondoId: "acc_3") let david = Friend(name: "David", pictureName: "david.jpg", mondoId: "acc_4") let elliot = Friend(name: "Elliot", pictureName: "elliot.jpg", mondoId: "acc_000094cjbHqqTaBqC8CQMb") let fred = Friend(name: "Fred", pictureName: "fred.jpg", mondoId: "acc_6") let george = Friend(name: "George", pictureName: "george.jpg", mondoId: "acc_7") let harry = Friend(name: "Harry", pictureName: "harry.jpg", mondoId: "acc_8") let isaac = Friend(name: "Isaac", pictureName: "isaac.jpg", mondoId: "acc_9") let jonathan = Friend(name: "Jonathan", pictureName: "jonathan.jpg", mondoId: "acc_10") friends = [alice, bob, clare, david, elliot, fred, george, harry, isaac, jonathan] } static func getFriends() -> [Friend] { return sharedInstance.friends } static func demoFriends() -> DemoFriends { return sharedInstance } }
bf30ebf1066239f1e03128105666fff3
34.769231
105
0.662123
false
false
false
false
ntwf/TheTaleClient
refs/heads/1.2/stable
TheTale/Controllers/StartScreen/StartViewController.swift
mit
1
// // StartViewController.swift // the-tale // // Created by Mikhail Vospennikov on 21/05/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import UIKit protocol SegueHandlerDelegate: class { func segueHandler(identifier: String) } protocol AuthPathDelegate: class { var authPath: String? { get set } } final class StartViewController: UIViewController, AuthPathDelegate { // MARK: - AuthPathDelegate var authPath: String? // MARK: - Outlets @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var loginContainer: UIView! @IBOutlet weak var registrationContainer: UIView! @IBOutlet var startingViewsCollection: [UIView]! // MARK: - Load controller override func viewDidLoad() { super.viewDidLoad() startingViewsCollection.forEach { $0.isHidden = true } setupGesture() addNotification() } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override var shouldAutorotate: Bool { return false } func setupGesture() { let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) segmentedControl.selectedSegmentIndex = 0 checkAuthorisation() } // MARK: - Notification func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(catchNotification(sender:)), name: .TaleAPINonblockingOperationStatusChanged, object: nil) } func catchNotification(sender: Notification) { guard let userInfo = sender.userInfo, let status = userInfo[TaleAPI.UserInfoKey.nonblockingOperationStatus] as? TaleAPI.StatusOperation else { return } switch status { case .ok: checkAuthorisation() case .error: print("error") default: break } } func checkAuthorisation() { TaleAPI.shared.getAuthorisationState { [weak self] (result) in guard let strongSelf = self else { return } switch result { case .success: strongSelf.performSegue(withIdentifier: AppConfiguration.Segue.toJournal, sender: self) case .failure(let error as NSError): debugPrint("checkAuthorisation", error) strongSelf.segmentedControl.isHidden = false strongSelf.loginContainer.isHidden = true strongSelf.registrationContainer.isHidden = false default: break } } } // MARK: - Prepare segue data override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == AppConfiguration.Segue.toWeb { if let navigationViewController = segue.destination as? UINavigationController, let webViewController = navigationViewController.topViewController as? WebViewController, let authPath = authPath { webViewController.authPath = authPath } } else if segue.identifier == AppConfiguration.Segue.toLogin, let loginViewController = segue.destination as? LoginViewController { loginViewController.segueHandlerDelegate = self loginViewController.authPathDelegate = self } } // MARK: - Outlets action @IBAction func showComponents(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { loginContainer.isHidden = true registrationContainer.isHidden = false } else { loginContainer.isHidden = false registrationContainer.isHidden = true } } } // MARK: - SegueHandlerDelegate extension StartViewController: SegueHandlerDelegate { func segueHandler(identifier: String) { performSegue(withIdentifier: identifier, sender: nil) } }
4d78da97628654657dab6b90266e7529
27.725352
116
0.68154
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/TableViewController/Tasks/HabitTableViewController.swift
gpl-3.0
1
// // HabitTableViewController.swift // Habitica // // Created by Elliot Schrock on 6/7/18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import UIKit class HabitTableViewController: TaskTableViewController { var lastLoggedPredicate: String? override func viewDidLoad() { readableName = L10n.Tasks.habit typeName = "habit" dataSource = HabitTableViewDataSource(predicate: self.getPredicate()) super.viewDidLoad() dataSource?.emptyDataSource = SingleItemTableViewDataSource<EmptyTableViewCell>(cellIdentifier: "emptyCell", styleFunction: EmptyTableViewCell.habitsStyle) self.tutorialIdentifier = "habits" configureTitle(L10n.Tasks.habits) } override func getDefinitonForTutorial(_ tutorialIdentifier: String) -> [AnyHashable: Any]! { if tutorialIdentifier == "habits" { let localizedStringArray = [L10n.Tutorials.habits1, L10n.Tutorials.habits2, L10n.Tutorials.habits3, L10n.Tutorials.habits4] return ["textList": localizedStringArray] } return super.getDefinitonForTutorial(tutorialIdentifier) } override func getCellNibName() -> String { return "HabitTableViewCell" } }
ab5144ac5d834088ad85d5111977990a
34.027778
163
0.691515
false
false
false
false
tryolabs/TLSphinx
refs/heads/master
TLSphinx/Config.swift
mit
1
// // Config.swift // TLSphinx // // Created by Bruno Berisso on 5/29/15. // Copyright (c) 2015 Bruno Berisso. All rights reserved. // import Foundation import Sphinx.Base public final class Config { var cmdLnConf: OpaquePointer? fileprivate var cArgs: [UnsafeMutablePointer<Int8>?] public init?(args: (String,String)...) { // Create [UnsafeMutablePointer<Int8>]. cArgs = args.flatMap { (name, value) -> [UnsafeMutablePointer<Int8>?] in //strdup move the strings to the heap and return a UnsageMutablePointer<Int8> return [strdup(name),strdup(value)] } cmdLnConf = cmd_ln_parse_r(nil, ps_args(), CInt(cArgs.count), &cArgs, STrue32) if cmdLnConf == nil { return nil } } deinit { for cString in cArgs { free(cString) } cmd_ln_free_r(cmdLnConf) } public var showDebugInfo: Bool { get { if cmdLnConf != nil { return cmd_ln_str_r(cmdLnConf, "-logfn") == nil } else { return false } } set { if cmdLnConf != nil { if newValue { cmd_ln_set_str_r(cmdLnConf, "-logfn", nil) } else { cmd_ln_set_str_r(cmdLnConf, "-logfn", "/dev/null") } } } } }
5d642428645343a6ae3c3c427093e293
23.830508
89
0.493515
false
false
false
false
Antowkos/Rosberry-Vapor
refs/heads/master
Sources/App/Models/App.swift
mit
1
import Vapor import FluentProvider final class App: Model { let storage = Storage() var name: String var icon: String var rank: Int var score: Int func usage() throws -> Usage? { return try children().first() } /// Creates a new Post init(name: String, icon: String, rank: Int, score: Int) { self.name = name self.icon = icon self.rank = rank self.score = score } convenience init(request: Request) throws { guard let json = request.json else { throw Abort.badRequest } try self.init(json: json) } // MARK: Fluent Serialization /// Initializes the Post from the /// database row init(row: Row) throws { name = try row.get("name") icon = try row.get("icon") rank = try row.get("rank") score = try row.get("score") } // Serializes the Post to the database func makeRow() throws -> Row { var row = Row() try row.set("icon", icon) try row.set("name", name) try row.set("rank", rank) try row.set("score", score) return row } } extension App: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.string("name") builder.string("icon") builder.string("rank") builder.string("score") } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } extension App: JSONConvertible { convenience init(json: JSON) throws { try self.init(name: json.get("name"), icon: json.get("icon"), rank: json.get("rank"), score: json.get("score")) } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("name", name) try json.set("icon", icon) try json.set("rank", rank) try json.set("score", score) return json } } extension App: ResponseRepresentable { } extension App: Updateable { static var updateableKeys: [UpdateableKey<App>] { return [ UpdateableKey("name", String.self) { app, name in app.name = name } ] } }
0699f85a592b8b8b5fa921efad0e8f3e
24.364583
69
0.535934
false
false
false
false
mumbler/PReVo-iOS
refs/heads/trunk
ReVoModeloj/Komunaj/Modeloj/Lingvo.swift
mit
1
// // Lingvo.swift // PoshReVo // // Created by Robin Hill on 5/4/20. // Copyright © 2020 Robin Hill. All rights reserved. // import Foundation /* Reprezentas lingvon ekzistantan en la vortaro. Uzata en serĉado kaj listigado de tradukoj en artikoloj. */ public final class Lingvo : NSObject, NSSecureCoding { public let kodo: String public let nomo: String public init(kodo: String, nomo: String) { self.kodo = kodo self.nomo = nomo } // MARK: - NSSecureCoding public static var supportsSecureCoding = true public required convenience init?(coder aDecoder: NSCoder) { if let enkodo = aDecoder.decodeObject(forKey: "kodo") as? String, let ennomo = aDecoder.decodeObject(forKey: "nomo") as? String { self.init(kodo: enkodo, nomo: ennomo) } else { return nil } } public func encode(with aCoder: NSCoder) { aCoder.encode(kodo, forKey: "kodo") aCoder.encode(nomo, forKey: "nomo") } public override var hash: Int { return kodo.hashValue } } // MARK: - Equatable extension Lingvo { public override func isEqual(_ object: Any?) -> Bool { if let lingvo = object as? Lingvo { return self == lingvo } else { return false } } public static func ==(lhs: Lingvo, rhs: Lingvo) -> Bool { return lhs.kodo == rhs.kodo && lhs.nomo == rhs.nomo } } // MARK: - Comparable extension Lingvo: Comparable { public static func < (lhs: Lingvo, rhs: Lingvo) -> Bool { return lhs.nomo.compare(rhs.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending } }
e5ad485f510a47897d66ee9541467391
23.583333
135
0.59887
false
false
false
false
ksuayan/JsonClient
refs/heads/master
JsonClient/APIController.swift
mit
1
// // APIController.swift // JsonClient // // Created by Suayan, William on 7/18/14. // Copyright (c) 2014 Kyo Suayan. All rights reserved. // import UIKit protocol APIControllerProtocol { func JSONAPIResults(results: NSArray) } class APIController: NSObject { var delegate:APIControllerProtocol? func GetAPIResultsAsync(urlString:String) { //The Url that will be called var url = NSURL.URLWithString(urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)) //Create a request var request: NSURLRequest = NSURLRequest(URL: url) println("url >>>> "+url.path) //Create a queue to hold the call var queue: NSOperationQueue = NSOperationQueue() // Sending Asynchronous request using NSURLConnection NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in var error: AutoreleasingUnsafePointer<NSError?> = nil // Serialize the JSON result into a dictionary let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary // If there is a result add the data into an array if jsonResult.count>0 && jsonResult["result"].count>0 { var results: NSArray = jsonResult["result"] as NSArray //Use the completion handler to pass the results self.delegate?.JSONAPIResults(results) } else { println(error) } }) } }
fe5ae47a004858259e9be5421200a6d8
31.482759
112
0.595011
false
false
false
false
moowahaha/Chuck
refs/heads/master
Chuck/GameScene.swift
mit
1
// // GameScene.swift // Chuck // // Created by Stephen Hardisty on 14/10/15. // Copyright (c) 2015 Mr. Stephen. All rights reserved. // import SpriteKit import AudioToolbox import CoreMotion class GameScene: SKScene, SKPhysicsContactDelegate { private var ball: Ball! private var wasLastMovingBall = false private var turn: Turn! private var isGameOver = false private var walls: Walls! private var isFirstThrow = true var score: Score! var missLabel: UILabel! var controller: GameViewController! var motionManager: CMMotionManager! required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(size: CGSize) { super.init(size: size) self.backgroundColor = UIColor.blackColor() ball = Ball.generate(CGPoint(x: size.width / 2, y: size.height / 2)) ball.physicsBody?.contactTestBitMask = 1 self.addChild(ball) self.walls = Walls(scene: self) self.physicsWorld.contactDelegate = self self.turn = Turn() } override func didMoveToView(view: SKView) { self.motionManager = CMMotionManager() self.motionManager.startAccelerometerUpdates() let panRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePanFrom:")) self.view!.addGestureRecognizer(panRecognizer) } // finger touches the ball override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if self.isGameOver { self.controller.startGame() return } let location = touches.first!.locationInNode(self) let touchedNode = self.nodeAtPoint(location) if self.isFirstThrow && touchedNode.isEqualToNode(ball) { self.isFirstThrow = false return } self.walls.hide() if touchedNode.isEqualToNode(ball) { self.initiateCatch(location) } else { self.gameOver("Missed catch") } } override func update(currentTime: CFTimeInterval) { // detect tilting to impact roll of ball #if !(arch(i386) || arch(x86_64)) if let accelerometerData = motionManager.accelerometerData { physicsWorld.gravity = CGVector( dx: accelerometerData.acceleration.x * 2, dy: accelerometerData.acceleration.y * 2 ) } #endif } // callback for contact (e.g. ball hitting side of screen) func didEndContact(contact: SKPhysicsContact) { if self.isGameOver { return } if !self.wasLastMovingBall { self.turn.registerBounce() if (self.walls.highlightWall(contact.bodyA.collisionBitMask)) { self.turn.registerSideHit() } } } // callback for finger sliding around the screen func handlePanFrom(recognizer : UIPanGestureRecognizer) { let viewLocation = recognizer.locationInView(self.view) let location = self.convertPointFromView(viewLocation) // check if the finger is moving on the ball if self.nodeAtPoint(location).isEqualToNode(ball) && ball.isStopped { if !self.isFirstThrow { self.score.display(viewLocation) } if recognizer.state == .Changed || recognizer.state == .Began { ball.moveTo(location) // hack: without this my finger can move faster than the ball and it self.wasLastMovingBall = true } else if recognizer.state == .Ended { self.initiateRoll(recognizer) } } if !self.nodeAtPoint(location).isEqualToNode(ball) { if recognizer.state == .Changed && self.wasLastMovingBall { self.initiateRoll(recognizer) } } } // make the ball move based on pan velocity private func initiateRoll(recognizer: UIPanGestureRecognizer) { self.wasLastMovingBall = false self.score.hide() ball.roll(recognizer.velocityInView(recognizer.view)) } // stop the ball private func initiateCatch(location: CGPoint) { if self.turn.hasHitAllSides() { ball.stop(location) self.score.add(self.turn.score()) self.score.display(self.convertPointFromView(location)) self.turn.reset() } else if !ball.isStopped { self.gameOver("Did not hit all sides") } } // game over. boo. private func gameOver(reason: String) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) ball.die() self.controller.promptForRestart(self.score, reason: reason) self.isGameOver = true } }
3215cec87f476324983c3f851dc52846
30.39375
100
0.595859
false
false
false
false
wilbert/sworm
refs/heads/master
Sworm/Sworm.swift
mit
1
// // Sworm.swift // Sworm // // Created by Wilbert Ribeiro on 30/10/15. // Copyright © 2015 Wilbert Ribeiro. All rights reserved. // import Foundation import Alamofire class Sworm: ResponseObjectSerializable { var id: Int! var errors: Dictionary<String, Array<String>>? static var site: String! class func className() -> String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } func className() -> String { return self.dynamicType.className() } class func resource() -> String? { return className().pluralize().snakeCase() } func resource() -> String { return self.dynamicType.resource()! } // MARK: Initializers @objc required init(response: NSHTTPURLResponse, representation: AnyObject) { self.id = representation.valueForKeyPath("id") as! Int } init() { } // MARK: Get objects class func get<T: ResponseObjectSerializable>(id: Int?, path: String?, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(id, path: path) Alamofire.request(.GET, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func get<T: ResponseObjectSerializable>(id: Int, completionHandler: (Response<T, NSError>) -> Void) { self.get(id, path: nil, parameters: Dictionary<String, AnyObject>(), completionHandler: completionHandler) } class func get<T: ResponseObjectSerializable>(id: Int, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { self.get(id, path: nil, parameters: parameters, completionHandler: completionHandler) } class func get<T: ResponseObjectSerializable>(parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { self.get(nil, path: nil, parameters: parameters, completionHandler: completionHandler) } // MARK: Get collections class func get<T: ResponseCollectionSerializable>(parameters: [String: AnyObject], completionHandler: (Response<[T], NSError>) -> Void ) { let url = self.mountResourceURL("") Alamofire.request(.GET, url, parameters: parameters).responseCollection { (response: Response<[T], NSError>) in completionHandler(response) } } class func get<T: ResponseCollectionSerializable>(path: String, parameters: [String: AnyObject], completionHandler: (Response<[T], NSError>) -> Void ) { let url = self.mountResourceURL(path) Alamofire.request(.GET, url, parameters: parameters).responseCollection { (response: Response<[T], NSError>) in completionHandler(response) } } class func get<T: ResponseCollectionSerializable>(id: Int, path: String, parameters: [String: AnyObject], completionHandler: (Response<[T], NSError>) -> Void ) { let url = self.mountResourceURL(id, path: path) print(url) Alamofire.request(.GET, url, parameters: parameters).responseCollection { (response: Response<[T], NSError>) in completionHandler(response) } } // MARK: Creations class func create<T: ResponseObjectSerializable>(parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL() Alamofire.request(.POST, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func create<T: ResponseObjectSerializable>(path: String, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(path) Alamofire.request(.POST, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func create<T: ResponseCollectionSerializable>(path: String, parameters: [String: AnyObject], completionHandler: (Response<[T], NSError>) -> Void) { let url = self.mountResourceURL(path) Alamofire.request(.POST, url, parameters: parameters).responseCollection { (response: Response<[T], NSError>) in completionHandler(response) } } class func create<T: ResponseObjectSerializable>(prefixes: [Sworm], parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let prefixesArray: [String] = prefixes.map({ self.prefix($0) }) let prefixesString = prefixesArray.joinWithSeparator("") let url = self.mountResourceURL(nil, path: nil, prefix: prefixesString) Alamofire.request(.POST, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func create<T: ResponseObjectSerializable>(prefixes: [Sworm], parameters: [String: AnyObject], progressHandler: (Int64, Int64, Int64) -> Void, completionHandler: (Response<T, NSError>) -> Void) { let prefixesArray: [String] = prefixes.map({ self.prefix($0) }) let prefixesString = prefixesArray.joinWithSeparator("") let url = self.mountResourceURL(nil, path: nil, prefix: prefixesString) Alamofire.request(.POST, url, parameters: parameters).progress{ (bytesRead, totalBytesRead, totalBytesExpectedToRead) in progressHandler(bytesRead, totalBytesRead, totalBytesExpectedToRead) }.responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func create<T: ResponseCollectionSerializable>(prefixes: [Sworm], parameters: [String: AnyObject], completionHandler: (Response<[T], NSError>) -> Void) { let prefixesArray: [String] = prefixes.map({ self.prefix($0) }) let prefixesString = prefixesArray.joinWithSeparator("") let url = self.mountResourceURL(nil, path: nil, prefix: prefixesString) Alamofire.request(.POST, url, parameters: parameters).responseCollection { (response: Response<[T], NSError>) in completionHandler(response) } } // MARK: Updates class func update<T: ResponseObjectSerializable>(id: Int, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(id) print(parameters) Alamofire.request(.PUT, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func update<T: ResponseObjectSerializable>(id: Int, path: String, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(id, path: path) Alamofire.request(.PUT, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } // MARK: Deletions class func delete<T: ResponseObjectSerializable>(path: String, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(nil, path: path) Alamofire.request(.DELETE, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func delete<T: ResponseObjectSerializable>(id: Int, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(id) Alamofire.request(.DELETE, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } class func delete<T: ResponseObjectSerializable>(id: Int, path: String, parameters: [String: AnyObject], completionHandler: (Response<T, NSError>) -> Void) { let url = self.mountResourceURL(id, path: path) Alamofire.request(.DELETE, url, parameters: parameters).responseObject { (response: Response<T, NSError>) in completionHandler(response) } } // MARK: Utilities class func prefix(object: Sworm) -> String { let prefix: String = object.resource() return "\(prefix)/\(object.id)" } class func mountResourceURL(id: Int?, path: String?, prefix: String?) -> String { var baseURL = self.site! if let _prefix = prefix { baseURL += "/\(_prefix)" } baseURL += "/\(self.resource()!)" if let _id = id { baseURL += "/\(_id)" } if let _path = path { baseURL += "/\(_path)" } return baseURL } class func mountResourceURL(id: Int?, path: String?) -> String { return self.mountResourceURL(id, path: path, prefix: nil) } class func mountResourceURL(id: Int) -> String { return self.mountResourceURL(id, path: nil, prefix: nil) } class func mountResourceURL(path: String) -> String { return self.mountResourceURL(nil, path: path, prefix: nil) } class func mountResourceURL() -> String { return self.mountResourceURL(nil, path: nil, prefix: nil) } func isNewObject() -> Bool { if self.id == nil { return true } else { return false } } }
64acd4a08622c85b4b6cce61b8dad6b5
37.412451
205
0.625975
false
false
false
false
yashigani/WebKitPlus
refs/heads/master
Sources/WebKitPlus/UIAlertController+Init.swift
mit
1
import UIKit extension UIAlertController { public convenience init?(for challenge: URLAuthenticationChallenge, completion: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let space = challenge.protectionSpace guard space.isUserCredential else { return nil } self.init(title: "\(space.`protocol`!)://\(space.host):\(space.port)", message: space.realm, preferredStyle: .alert) self.addTextField { $0.placeholder = localizedString(for: "user") } self.addTextField { $0.placeholder = localizedString(for: "password") $0.isSecureTextEntry = true } self.addAction(UIAlertAction(title: localizedString(for: "Cancel"), style: .cancel) { _ in completion(.cancelAuthenticationChallenge, nil) }) self.addAction(UIAlertAction(title: localizedString(for: "OK"), style: .default) { [weak self] _ in let textFields = self!.textFields! let credential = URLCredential(user: textFields[0].text!, password: textFields[1].text!, persistence: .forSession) completion(.useCredential, credential) }) } public convenience init?(error: NSError) { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return nil } // Ignore WebKitErrorFrameLoadInterruptedByPolicyChange if error.domain == "WebKitErrorDomain" && error.code == 102 { return nil } let title = error.userInfo[NSURLErrorFailingURLStringErrorKey] as? String let message = error.localizedDescription self.init(title: title, message: message, preferredStyle: .alert) self.addAction(UIAlertAction(title: localizedString(for: "OK"), style: .default) { _ in }) } }
33e9d51517cd97f2163492d4a3e379ad
44.146341
158
0.642355
false
false
false
false
angelvasa/AVXCAssets-Generator
refs/heads/master
AVXCAssetsGenerator/AVAssetCatalogCreator/AVIconScalar.swift
mit
1
// // IconGenerator.swift // AVXCAssetsGenerator // // Created by Angel Vasa on 27/04/16. // Copyright © 2016 Angel Vasa. All rights reserved. // import Foundation import Cocoa class AVIconScalar: AnyObject { var iconSizes = [29, 40, 50, 57, 58, 72, 76, 80 ,87, 100, 114, 120, 144, 152, 167, 180] func scaleImage(image: NSImage, withImageName: String, andSaveAtPath: String) { let contentCreator = ContentCreator() for size in iconSizes { let finalImage = image.resizeImage(CGFloat(size) / 2.0, CGFloat(size) / 2.0) let imageNameWithConvention = withImageName + "-" + "\(size)" + ".png" let pathToSaveImage = "\(andSaveAtPath + "/" + imageNameWithConvention)" contentCreator.writeImageToDirectory(image: finalImage, atPath: pathToSaveImage) contentCreator.writeDictionaryContent(contentCreator.defaultAppIconSetDictionary(), atPath: andSaveAtPath) } } }
efa6df52e4a916028e218900bc06a7d2
36.153846
118
0.663561
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Sources/AST/Type/TypeInheritanceClause.swift
apache-2.0
2
/* Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public struct TypeInheritanceClause { public let classRequirement: Bool public let typeInheritanceList: [TypeIdentifier] public init( classRequirement: Bool = false, typeInheritanceList: [TypeIdentifier] = [] ) { self.classRequirement = classRequirement self.typeInheritanceList = typeInheritanceList } } extension TypeInheritanceClause : ASTTextRepresentable { public var textDescription: String { var prefixText = ": " if classRequirement { prefixText += "class" } if classRequirement && !typeInheritanceList.isEmpty { prefixText += ", " } return "\(prefixText)\(typeInheritanceList.map({ $0.textDescription }).joined(separator: ", "))" } }
e78c42600d00b762811a522f58917219
32.9
100
0.728614
false
false
false
false
arkye-8th-semester-indiana-tech/dev_mob_apps
refs/heads/master
lessons/11_Subclassing_UITableViewCell/Homepwner/Homepwner/ItemsViewController.swift
gpl-3.0
1
// // ItemsViewController.swift // Homepwner // // Created by Maia de Moraes, Jonathan H - 01 on 3/28/16. // Copyright © 2016 Big Nerd Ranch. All rights reserved. // import UIKit class ItemsViewController: UITableViewController { var itemStore: ItemStore! @IBAction func addNewItem(sender: AnyObject) { // Create a new item and add it to the store let newItem = itemStore.createItem() // Figure out where that item is in the array if let index = itemStore.allItems.indexOf(newItem) { let indexPath = NSIndexPath(forRow: index, inSection: 0) // Insert this new row into the table tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } @IBAction func toggleEditingMode(sender: AnyObject) { // If you are currently in editing mode... if editing { // Change text of button to inform user of state sender.setTitle("Edit", forState: .Normal) // Turn off editing mode setEditing(false, animated: true) } else { // Change text of button to inform user of state sender.setTitle("Done", forState: .Normal) // Enter editing mode setEditing(true, animated: true) } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemStore.allItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Get a new or recycled cell let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! ItemCell // Update the labels for the new preferred text size cell.updateLabels() // Set the text on the cell with the dewscription of the item // that is at the nth index of items, where n = row this cell // will appear in on the tableview let item = itemStore.allItems[indexPath.row] // Configure the cell with the Item cell.nameLabel.text = item.name cell.serialNumberLabel.text = item.serialNumber cell.valueLabel.text = "$\(item.valueInDollars)" return cell } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // If the table view is asking to commit a delete command... if editingStyle == .Delete { let item = itemStore.allItems[indexPath.row] let title = "Delete \(item.name)?" let message = "Are you sure you want to delete this item?" let ac = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) ac.addAction(cancelAction) let deleteAction = UIAlertAction(title: "Delete", style: .Destructive, handler: { (action) -> Void in // Remove the item from the store self.itemStore.removeItem(item) // Also remove that row from the table view with an animation self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) }) ac.addAction(deleteAction) // Present the alert controller presentViewController(ac, animated: true, completion: nil) } } override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { // Update the model itemStore.moveItemAtIndex(sourceIndexPath.row, toIndex: destinationIndexPath.row) } override func viewDidLoad() { super.viewDidLoad() // Get the height of the status bar let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0) tableView.contentInset = insets tableView.scrollIndicatorInsets = insets tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 65 } }
2ae5554b35361c2e9d78c302f1563a01
37.598291
157
0.621262
false
false
false
false
Hperigo/Receipts
refs/heads/master
ReceiptsClient/ReceiptsClient/AppDelegate.swift
gpl-3.0
1
// // AppDelegate.swift // ReceiptsClient // // Created by Henrique on 5/12/17. // Copyright © 2017 Henrique. All rights reserved. // // // AppDelegate.swift // Recipts // // Created by Henrique on 5/10/17. // Copyright © 2017 Henrique. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var statusMenu: NSMenu! let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) let popover = NSPopover() var popoverViewController : MainViewController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application // statusItem.title = "Receipts" statusItem.button?.image = NSImage(named: "icon") statusItem.button?.image?.size = NSSize(width: 20, height: 20) let dragView = DragView(frame:(statusItem.button?.visibleRect)!) dragView.app = self statusItem.button?.addSubview(dragView) // statusItem.action = #selector(togglePopover( sender: )); statusItem.action = #selector(screenshot(sender: )) popoverViewController = MainViewController(nibName: "MainViewController", bundle: nil) popoverViewController?.app = self popover.contentViewController = popoverViewController } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } // -- HTTP Requests ---- func sendImageToServer( receipt: ReceiptInfo) { var r = URLRequest(url: URL(string: "http://0.0.0.0:4000/image")!) r.httpMethod = "POST" let boundary = "Boundary-\(UUID().uuidString)" r.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let image = receipt.image let bits = image?.representations.first as? NSBitmapImageRep let data = bits?.representation(using: .JPEG, properties: [:]) let str = String(data: receipt.toJson(), encoding: .utf8) r.httpBody = createBody(boundary: boundary, data: data!, mimeType: "image/jpg", filename: receipt.fileName!, parameters: ["data" : str!]) let task = URLSession.shared.dataTask(with: r) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error return } do { let str = String.init(data: data, encoding: .utf8) print( str! ) // return true } catch let error as NSError { print("error : \(error)") } } task.resume() } func createBody(boundary: String, data: Data, mimeType: String, filename: String, parameters:[String:String] ) -> Data { let body = NSMutableData() let boundaryPrefix = "--\(boundary)\r\n" for (key, value) in parameters { body.appendString("--\(boundary)\r\n") body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendString("\(value)\r\n") } body.appendString(boundaryPrefix) body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n") body.appendString("Content-Type: \(mimeType)\r\n\r\n") body.append(data) body.appendString("\r\n") body.appendString("--".appending(boundary.appending("--"))) return body as Data } // -- Popover --- func showPopover(sender: AnyObject?, path : NSURL?) { if let button = statusItem.button { popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) if(path != nil){ if(path?.isFileURL == true){ let img = NSImage(byReferencing: path!.filePathURL!) popoverViewController?.reciptImageView.image = img }else{ let url = path?.absoluteURL let data = try? Data(contentsOf: url!) let img = NSImage(data: data!) popoverViewController?.reciptImageView.image = img } } } } func closePopover(sender: AnyObject?) { popover.performClose(sender) cleanup() } func togglePopover(sender: AnyObject?) { if popover.isShown { closePopover(sender: sender) } else { showPopover(sender:nil, path: nil) } } func screenshot(sender: AnyObject?) { let task:Process = Process() task.launchPath = "/usr/sbin/screencapture" let temp_path = NSTemporaryDirectory() + "reciptsScreen.png" NSLog(temp_path) task.arguments = ["-i", temp_path] task.launch() task.waitUntilExit() // togglePopover(sender: nil) showPopover(sender: nil, path: NSURL(fileURLWithPath: temp_path)) } func cleanup(){ let fileManager = FileManager.default // Delete 'hello.swift' file let temp_path = NSTemporaryDirectory() + "reciptsScreen.png" do { try fileManager.removeItem(atPath: temp_path) } catch let error as NSError { print("Ooops! Something went wrong: \(error)") } } } // -- extension NSMutableData { func appendString(_ string: String) { let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false) append(data!) } }
e25ba66a01dd9e394429b91da4f23155
28.384977
110
0.537466
false
false
false
false
samphomsopha/mvvm
refs/heads/master
Carthage/Checkouts/Bond/Playground.playground/Pages/Key Value Observing.xcplaygroundpage/Contents.swift
gpl-3.0
1
//: [Previous](@previous) import UIKit import Bond import ReactiveKit import PlaygroundSupport class Test: NSObject { dynamic var test: String! = "0" } var test: Test! = Test() weak var weakTest: Test? = test test.keyPath("test", ofType: Optional<String>.self).observe { event in print(event) } test.test = "a" test.test = nil test.test = "g" Signal1.just("c").bind(to: test.keyPath("test", ofType: Optional<String>.self)) test = nil weakTest //: [Next](@next)
4d8009eae3a76904009b4b5925c0c6a6
15.892857
79
0.687104
false
true
false
false
DylanSecreast/uoregon-cis-portfolio
refs/heads/master
uoregon-cis-399/assignment6/Assignment6/Source/Controller/CatImagesViewController.swift
gpl-3.0
1
// // CatImagesViewController.swift // Assignment6 // import CoreData import UIKit class CatImagesViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, NSFetchedResultsControllerDelegate { // MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imagesFetchedResultsController.sections?.first?.numberOfObjects ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CatImageCell", for: indexPath) as! CatImageCell let image = imagesFetchedResultsController.object(at: indexPath) cell.update(for: image) return cell } // MARK: NSFetchedResultsControllerDelegate func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { imagesCollectionView.reloadData() } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() imagesFetchedResultsController = CatService.shared.images(for: category) imagesFetchedResultsController.delegate = self } // MARK: Properties var category: Category! = nil // MARK: Properties (Private) private var imagesFetchedResultsController: NSFetchedResultsController<Image>! // MARK: Properties (IBOutlet) @IBOutlet private weak var imagesCollectionView: UICollectionView! }
088d963071d82c11cbb3a0d377d3d5be
30.085106
140
0.80219
false
false
false
false
fancymax/12306ForMac
refs/heads/master
12306ForMac/Sheets/SubmitWindowController.swift
mit
1
// // PreOrderWindowController.swift // Train12306 // // Created by fancymax on 15/8/14. // Copyright (c) 2015年 fancy. All rights reserved. // import Cocoa class SubmitWindowController: BaseWindowController{ @IBOutlet weak var trainCodeLabel: NSTextField! @IBOutlet weak var trainDateLabel: NSTextField! @IBOutlet weak var trainTimeLabel: NSTextField! @IBOutlet weak var passengerTable: NSTableView! @IBOutlet weak var passengerImage: RandCodeImageView2! @IBOutlet weak var orderInfoView: NSView! @IBOutlet weak var preOrderView: GlassView! @IBOutlet weak var orderIdView: GlassView! @IBOutlet weak var submitOrderBtn: NSButton! private var spaceKeyboardMonitor:Any! @IBOutlet weak var orderInfoCloseButton: NSButton! @IBOutlet weak var orderInfoCheckOrderButton: NSButton! @IBOutlet weak var orderInfoExcludeButton: NSButton! @IBOutlet weak var preOrderCloseButton: NSButton! @IBOutlet weak var preOrderOkButton: NSButton! @IBOutlet weak var preOrderExcludeButton: NSButton! @IBOutlet weak var orderId: NSTextField! var isAutoSubmit = false var isSubmitting = false var ifShowCode = true var isCancel = false weak var timer:Timer? override var windowNibName: String{ return "SubmitWindowController" } override func windowDidLoad() { super.windowDidLoad() self.switchViewFrom(nil, to: orderInfoView) self.freshOrderInfoView() self.preOrderFlow() if isAutoSubmit { if !ifShowCode { let origin = orderInfoCheckOrderButton.frame.origin orderInfoCheckOrderButton.isHidden = true orderInfoCloseButton.title = "取消自动" orderInfoCloseButton.setFrameOrigin(origin) } } else { orderInfoExcludeButton.isHidden = true preOrderExcludeButton.isHidden = true } //增加对Space按键的支持 spaceKeyboardMonitor = NSEvent.addLocalMonitorForEvents(matching: NSKeyDownMask) { [weak self] (theEvent) -> NSEvent? in //Space Key if (theEvent.keyCode == 49){ if let weakSelf = self { weakSelf.clickNext(nil) } return nil } return theEvent } } // MARK: - custom function override func dismissWithModalResponse(_ response:NSModalResponse) { if window != nil { if window!.sheetParent != nil { window!.sheetParent!.endSheet(window!,returnCode: response) NSEvent.removeMonitor(spaceKeyboardMonitor!) } } } func freshOrderInfoView(){ let info = MainModel.selectedTicket! trainCodeLabel.stringValue = "\(info.TrainCode!) \(info.FromStationName!) - \(info.ToStationName!)" if let dateStr = MainModel.trainDate { trainDateLabel.stringValue = "\(G_Convert2StartTrainDateStr(dateStr))" } trainTimeLabel.stringValue = "\(info.start_time!)~\(info.arrive_time!) 历时\(info.lishi!)" passengerTable.reloadData() } func switchViewFrom(_ oldView:NSView?,to newView: NSView) { if oldView != nil { oldView!.removeFromSuperview() } self.window?.setFrame(newView.frame, display: true, animate: true) self.window?.contentView?.addSubview(newView) } func freshImage(){ self.passengerImage.clearRandCodes() let successHandler = {(image:NSImage) -> () in self.passengerImage.image = image } let failHandler = {(error:NSError) -> () in self.showTip(translate(error as NSError)) } Service.sharedInstance.getPassCodeNewForPassenger().then{ image in successHandler(image) }.catch{ error in failHandler(error as NSError) } } func dama(image:NSImage) { self.startLoadingTip("自动打码...") Dama.sharedInstance.dama(AdvancedPreferenceManager.sharedInstance.damaUser, password: AdvancedPreferenceManager.sharedInstance.damaPassword, ofImage: image, success: {imageCode in self.stopLoadingTip() self.passengerImage.drawDamaCodes(imageCode) self.clickOK(nil) }, failure: {error in self.stopLoadingTip() self.showTip(translate(error)) }) } func preOrderFlow(){ self.startLoadingTip("获取验证码...") if isSubmitting { return } isSubmitting = true let successHandler = {(image:NSImage) -> () in self.passengerImage.clearRandCodes() self.passengerImage.image = image if self.isAutoSubmit { self.checkOrderFlow() } else { self.isSubmitting = false } self.stopLoadingTip() } let failureHandler = { (error:NSError) -> () in self.showTip(translate(error)) self.isSubmitting = false self.stopLoadingTip() } Service.sharedInstance.preOrderFlow(isAuto: self.isAutoSubmit,success: successHandler, failure: failureHandler) } func checkOrderFlow() { self.startLoadingTip("验证订单...") let failureHandler = { (error:NSError) -> () in self.stopLoadingTip() self.isSubmitting = false self.showTip(translate(error)) } let successHandler = {(ifShowRandCode:Bool)->() in if self.isAutoSubmit { if ifShowRandCode { self.switchViewFrom(self.orderInfoView, to: self.preOrderView) if AdvancedPreferenceManager.sharedInstance.isUseDama { if let image = self.passengerImage.image { self.dama(image: image) } } self.isSubmitting = false } else { self.submitOrderFlow(isAuto: true,ifShowRandCode: false) } } else { if ifShowRandCode { self.stopLoadingTip() self.isSubmitting = false self.switchViewFrom(self.orderInfoView, to: self.preOrderView) } else { self.submitOrderFlow(isAuto: false,ifShowRandCode: false) } } } Service.sharedInstance.checkOrderFlow(success: successHandler, failure: failureHandler) } func closeAndReSubmit() { self.dismissWithModalResponse(NSModalResponseCancel) NotificationCenter.default.post(name: Notification.Name.App.DidStartQueryTicket, object:nil) } func submitOrderFlow(isAuto:Bool = false,ifShowRandCode:Bool = false,randCode:String = ""){ if isAuto { self.startLoadingTip("正在自动提交...") } else { self.startLoadingTip("正在提交...") } let failureHandler = { (error:NSError) -> () in self.stopLoadingTip() self.isSubmitting = false if ServiceError.isCheckRandCodeError(error) { self.showTip(translate(error)) self.freshImage() //if isAuto and use Dama, then should try to use Dama } else { //if isAuto and not CheckRandCodeError, then close window and retry if isAuto { self.showTip(translate(error) + " 请等3秒App重新提交") if !self.isCancel { self.isSubmitting = true self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(SubmitWindowController.closeAndReSubmit), userInfo: nil, repeats: false) } else { logger.info("取消自动重新提交车次 \(self.trainCodeLabel.stringValue)") } } else { self.showTip(translate(error) + " 可尝试重新查询车票并提交!") } } } let successHandler = { self.stopLoadingTip() self.orderId.stringValue = MainModel.orderId! if ifShowRandCode { self.switchViewFrom(self.preOrderView, to: self.orderIdView) } else { self.switchViewFrom(self.orderInfoView, to: self.orderIdView) } self.isSubmitting = false } let waitHandler = { (info:String)-> () in self.startLoadingTip(info) } if ifShowRandCode { Service.sharedInstance.orderFlowWithRandCode(randCode, success: successHandler, failure: failureHandler,wait: waitHandler) } else { Service.sharedInstance.orderFlowNoRandCode(success: successHandler, failure: failureHandler,wait: waitHandler) } } // MARK: - click Action @IBAction func clickNext(_ sender: AnyObject?) { if self.window!.contentView!.subviews.contains(orderInfoView) { self.clickCheckOrder(nil) } else if self.window!.contentView!.subviews.contains(preOrderView) { self.clickOK(nil) } else { self.clickRateInAppstore(nil) } } @IBAction func clickNextImage(_ sender: NSButton) { freshImage() } @IBAction func clickCheckOrder(_ sender: AnyObject?) { if isSubmitting { return } isSubmitting = true self.checkOrderFlow() } @IBAction func clickOK(_ sender:AnyObject?){ if let randCode = passengerImage.randCodeStr { if isSubmitting { return } isSubmitting = true self.submitOrderFlow(isAuto: isAutoSubmit,ifShowRandCode: true, randCode: randCode) } else { self.showTip("请先选择验证码") } } @IBAction func clickCancel(_ button:NSButton){ if timer != nil { timer!.invalidate() } isCancel = true dismissWithModalResponse(NSModalResponseCancel) } @IBAction func clickExcludeTrain(_ button:NSButton) { isCancel = true NotificationCenter.default.post(name: Notification.Name.App.DidExcludeTrainSubmit, object:MainModel.selectedTicket!.TrainCode) closeAndReSubmit() } @IBAction func clickRateInAppstore(_ button:AnyObject?){ NSWorkspace.shared().open(URL(string: "macappstore://itunes.apple.com/us/app/ding-piao-zhu-shou/id1163682213?l=zh&ls=1&mt=12")!) dismissWithModalResponse(NSModalResponseCancel) } deinit { print("SubmitWindowController deinit") } } // MARK: - NSTableViewDataSource extension SubmitWindowController:NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return MainModel.selectPassengers.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return MainModel.selectPassengers[row] } }
adb8d8a7bf13eefa37b13098675f3a2a
31.909859
181
0.567234
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Delay.xcplaygroundpage/Contents.swift
mit
1
//: ## Delay //: Exploring the powerful effect of repeating sounds after //: varying length delay times and feedback amounts import AudioKitPlaygrounds import AudioKit import AudioKitUI let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true var delay = AKDelay(player) delay.time = 0.01 // seconds delay.feedback = 0.9 // Normalized Value 0 - 1 delay.dryWetMix = 0.6 // Normalized Value 0 - 1 AudioKit.output = delay AudioKit.start() player.play() class LiveView: AKLiveViewController { var timeSlider: AKSlider? var feedbackSlider: AKSlider? var lowPassCutoffFrequencySlider: AKSlider? var dryWetMixSlider: AKSlider? override func viewDidLoad() { addTitle("Delay") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) timeSlider = AKSlider(property: "Time", value: delay.time) { sliderValue in delay.time = sliderValue } addView(timeSlider) feedbackSlider = AKSlider(property: "Feedback", value: delay.feedback) { sliderValue in delay.feedback = sliderValue } addView(feedbackSlider) lowPassCutoffFrequencySlider = AKSlider(property: "Low Pass Cutoff", value: delay.lowPassCutoff, range: 0 ... 22_050 ) { sliderValue in delay.lowPassCutoff = sliderValue } addView(lowPassCutoffFrequencySlider) dryWetMixSlider = AKSlider(property: "Mix", value: delay.dryWetMix) { sliderValue in delay.dryWetMix = sliderValue } addView(dryWetMixSlider) let presets = ["Short", "Dense Long", "Electric Circuits"] addView(AKPresetLoaderView(presets: presets) { preset in switch preset { case "Short": delay.presetShortDelay() case "Dense Long": delay.presetDenseLongDelay() case "Electric Circuits": delay.presetElectricCircuitsDelay() default: break } self.updateUI() }) } func updateUI() { timeSlider?.value = delay.time feedbackSlider?.value = delay.feedback lowPassCutoffFrequencySlider?.value = delay.lowPassCutoff dryWetMixSlider?.value = delay.dryWetMix } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
60e91d139e7a84848efbd103605b57b8
29.952381
96
0.635385
false
false
false
false
jaropawlak/Signal-iOS
refs/heads/master
Signal/src/Jobs/SessionResetJob.swift
gpl-3.0
1
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit @objc(OWSSessionResetJob) class SessionResetJob: NSObject { let TAG = "SessionResetJob" let recipientId: String let thread: TSThread let storageManager: TSStorageManager let messageSender: MessageSender required init(recipientId: String, thread: TSThread, messageSender: MessageSender, storageManager: TSStorageManager) { self.thread = thread self.recipientId = recipientId self.messageSender = messageSender self.storageManager = storageManager } func run() { Logger.info("\(TAG) Local user reset session.") OWSDispatch.sessionStoreQueue().async { Logger.info("\(self.TAG) deleting sessions for recipient: \(self.recipientId)") self.storageManager.deleteAllSessions(forContact: self.recipientId) DispatchQueue.main.async { let endSessionMessage = EndSessionMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.thread) self.messageSender.enqueue(endSessionMessage, success: { Logger.info("\(self.TAG) successfully sent EndSession<essage.") let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.thread, messageType: TSInfoMessageType.typeSessionDidEnd) message.save() }, failure: {error in Logger.error("\(self.TAG) failed to send EndSessionMessage with error: \(error.localizedDescription)") }) } } } class func run(contactThread: TSContactThread, messageSender: MessageSender, storageManager: TSStorageManager) { let job = self.init(recipientId: contactThread.contactIdentifier(), thread: contactThread, messageSender: messageSender, storageManager: storageManager) job.run() } }
1036dd512b93001e01b35bd535e47ee8
37.654545
122
0.61524
false
false
false
false
ggu/SimpleGridView
refs/heads/master
SimpleGridView/views/GridView.swift
mit
1
// // GridView.swift // SimpleGridView // // Created by Gabriel Uribe on 11/25/15. // import UIKit public class GridView : UIView { // MARK: - Fields private var grid: Grid = [] private var size: GridSize // MARK: - init(size: CGSize) { self.size = (Int(size.width), Int(size.height)) let frame = CGRectMake(0, 0, size.width, size.height) super.init(frame: frame) setup() } private func setup() { backgroundColor = Color.margin createGrid() } // MARK: - Grid Methods private func createGrid() { var xPos = 0 var yPos = 0 // TODO: Extra space // Currently adding 1 to guarantee that there is no blank space on edge of grid // instead, center grid with border over blank space and/or add support for larger grids and panning for x in 0..<(size.width/(TILE_WIDTH + TILE_MARGIN) + 1) { grid.append([]) for _ in 0..<(size.height/(TILE_HEIGHT + TILE_MARGIN) + 1) { let tileFrame = CGRectMake(CGFloat(xPos), CGFloat(yPos), CGFloat(TILE_WIDTH), CGFloat(TILE_HEIGHT)) let tile = TileView(frame: tileFrame) addSubview(tile) grid[x].append(tile) yPos += TILE_HEIGHT + TILE_MARGIN } yPos = 0 xPos += TILE_WIDTH + TILE_MARGIN } } private func traverseGrid(state: Tile.State, condition: Condition, value: Any?) { for x in grid { for tile in x { switch condition { case .setAll: toggleTileState(tile, state: state) case .location: if let point = value as! CGPoint? { setTileIfPoint(tile, point: point, state: state) } } } } } // MARK: - Tile state methods private func toggleTileState(tile: TileView, state: Tile.State) { switch state { case .new: tile.reset() case .active: tile.setActive() } } // MARK: - Touches methods override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if shouldResetGrid((event?.allTouches()?.count)!) { traverseGrid(Tile.State.new, condition: Condition.setAll, value: nil) } else { for touch in touches { setViewIfTile(touch.view!, state: Tile.State.active) } } } override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let location = touch.locationInView(self) traverseGrid(Tile.State.active, condition: Condition.location, value: location) } } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { } override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { } // MARK: Helper methods func setTileIfPoint(tile: TileView, point: CGPoint, state: Tile.State) { if tile.containsPoint(point) { toggleTileState(tile, state: state) } } func setViewIfTile(view: UIView, state: Tile.State) { if isTileView(view) { let tile = view as! TileView toggleTileState(tile, state: state) } } func shouldResetGrid(count: Int) -> Bool { return count > 1 } func isTileView(view: UIView) -> Bool { return view.isKindOfClass(TileView) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
5827afd0469e0cefe47ee5e443d28ad8
24.734848
107
0.617898
false
false
false
false
AlbertWu0212/MyDailyTodo
refs/heads/master
MyDailyTodo/MyDailyTodo/ChecklistItem.swift
mit
1
// // ChecklistItem.swift // Checklists // // Created by M.I. Hollemans on 27/07/15. // Copyright © 2015 Razeware. All rights reserved. // import UIKit import Foundation class ChecklistItem: NSObject, NSCoding { var text = "" var checked = false var dueDate = NSDate() var shouldRemind = false var itemID: Int // MARK: NSCoding protocol func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(text, forKey: "Text") aCoder.encodeBool(checked, forKey: "Checked") aCoder.encodeObject(dueDate, forKey: "DueDate") aCoder.encodeBool(shouldRemind, forKey: "ShouldRemind") aCoder.encodeInteger(itemID, forKey: "ItemID") } // MARK: initialize required init?(coder aDecoder: NSCoder) { text = aDecoder.decodeObjectForKey("Text") as! String checked = aDecoder.decodeBoolForKey("Checked") dueDate = aDecoder.decodeObjectForKey("DueDate") as! NSDate shouldRemind = aDecoder.decodeBoolForKey("ShouldRemind") itemID = aDecoder.decodeIntegerForKey("ItemID") super.init() } override init() { itemID = DataModel.nextChecklistItemID() super.init() } // Deinitialize deinit { if let notification = notificationForThisItem() { UIApplication.sharedApplication().cancelLocalNotification(notification) } } // API Methods func toggleChecked() { checked = !checked } func scheduleNotification() { let existingNotification = notificationForThisItem() if let notification = existingNotification { UIApplication.sharedApplication().cancelLocalNotification(notification) } if shouldRemind && dueDate.compare(NSDate()) != .OrderedAscending { let localNotification = UILocalNotification() localNotification.fireDate = dueDate localNotification.timeZone = NSTimeZone.defaultTimeZone() localNotification.alertBody = text localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.userInfo = ["ItemID": itemID] UIApplication.sharedApplication().scheduleLocalNotification(localNotification) print("Scheduled notification \(localNotification) for itemID \(itemID)") } } // Private methods private func notificationForThisItem() -> UILocalNotification? { let allNotifications = UIApplication.sharedApplication().scheduledLocalNotifications! for notification in allNotifications { if let number = notification.userInfo?["ItemID"] as? Int where number == itemID { return notification } } return nil } }
df6c0f13b2c3481cbd3776983e078299
29.511905
89
0.709325
false
false
false
false
andrea-prearo/ContactList
refs/heads/master
ContactList/ViewModels/ContactViewModel.swift
mit
1
// // ContactViewModel.swift // ContactList // // Created by Andrea Prearo on 3/10/16. // Copyright © 2016 Andrea Prearo // import Foundation class ContactViewModel { let avatarUrl: String? let username: String let company: String init(contact: Contact) { // Avatar if let url = contact.avatar { avatarUrl = url } else { avatarUrl = nil } // Username username = contact.fullName // Company company = contact.company ?? "" } }
4f9b15928726a5b3530cf2960371616c
17.766667
40
0.541741
false
false
false
false
tonyarnold/Differ
refs/heads/main
Examples/TableViewExample/Graph.playground/Sources/Arrows.swift
mit
1
import UIKit // https://gist.github.com/mayoff/4146780 rewritten in Swift public struct Arrow { let from: CGPoint let to: CGPoint let tailWidth: CGFloat let headWidth: CGFloat let headLength: CGFloat } public extension UIBezierPath { convenience init(arrow: Arrow) { let length = CGFloat(hypotf(Float(arrow.to.x - arrow.from.x), Float(arrow.to.y - arrow.from.y))) var points = [CGPoint]() let tailLength = length - arrow.headLength points.append(CGPoint(x: 0, y: arrow.tailWidth / 2)) points.append(CGPoint(x: tailLength, y: arrow.tailWidth / 2)) points.append(CGPoint(x: tailLength, y: arrow.headWidth / 2)) points.append(CGPoint(x: length, y: 0)) points.append(CGPoint(x: tailLength, y: -arrow.headWidth / 2)) points.append(CGPoint(x: tailLength, y: -arrow.tailWidth / 2)) points.append(CGPoint(x: 0, y: -arrow.tailWidth / 2)) let transform = UIBezierPath.transform(from: arrow.from, to: arrow.to, length: length) let path = CGMutablePath() path.addLines(between: points, transform: transform) path.closeSubpath() self.init(cgPath: path) } private static func transform(from start: CGPoint, to: CGPoint, length: CGFloat) -> CGAffineTransform { let cosine = (to.x - start.x) / length let sine = (to.y - start.y) / length return CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y) } func shapeLayer() -> CAShapeLayer { let l = CAShapeLayer() let bounds = self.bounds let origin = bounds.origin let path = copy() as! UIBezierPath path.apply(CGAffineTransform(translationX: -origin.x, y: -origin.y)) l.path = path.cgPath l.frame = bounds return l } }
53467cb3e8bcca60a38eac0f59d6038d
33.792453
107
0.630694
false
false
false
false
spritesun/MeditationHelper
refs/heads/master
MeditationHelper/MeditationHelper/MHMeditationListViewController.swift
mit
1
// // MHMeditationListViewController.swift // MeditationHelper // // Created by Long Sun on 23/01/2015. // Copyright (c) 2015 Sunlong. All rights reserved. // class MHMeditationListViewController: PFQueryTableViewController { var viewModel = MHMeditationListViewModel(meditations: [MHMeditation]()) var dateFormatter = NSDateFormatter() var needRefresh = false @IBOutlet var footer: UIView! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.parseClassName = MHMeditation.parseClassName() // dateFormatter.locale = NSLocale(localeIdentifier: "zh_Hant") dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle NSNotificationCenter.defaultCenter().addObserver(self, selector: "markAsNeedRefresh", name: MHNotification.MeditationDidUpdate, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if needRefresh { loadObjects() needRefresh = false } MHMeditationUploader.upload(slient: true) { (success : Bool) -> Void in if success { self.reloadTable() } } } func reloadTable () { tableView.reloadData() updateFooter() } func markAsNeedRefresh() { needRefresh = true } override func queryForTable() -> PFQuery! { var query = MHMeditation.currentUserQuery() query.orderByDescending("endTime") return query } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell! { var cell = tableView.dequeueReusableCellWithIdentifier("MHMeditationCell") as! MHMeditationCell! let meditation = object as! MHMeditation var metadata = "" if let location = meditation.location { metadata += (location + " | ") } if let weather = meditation.weather { metadata += (weather + " | ") } metadata += (String(meditation.rate) + NSLocalizedString("-star", comment: "star suffix")) cell.metadata.text = metadata cell.comment.text = meditation.comment cell.duration.text = meditation.shortDuration() if meditation.startTime != nil && meditation.endTime != nil { cell.timeRange.text = "\(dateFormatter.stringFromDate(meditation.startTime!)) - \(dateFormatter.stringFromDate(meditation.endTime!))" } return cell } override func objectsDidLoad(error: NSError!) { super.objectsDidLoad(error) if error == nil { viewModel = MHMeditationListViewModel(meditations: objects as! [MHMeditation]) reloadTable() } else { alert(title: NSLocalizedString("Fail to load", comment: "Fail to load records title"), message: NSLocalizedString("Please check you network", comment: "Fail to load records message")) } } override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject! { return viewModel.objectAtIndexPath(indexPath) as! PFObject! } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return viewModel.numberOfSections() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfObjectsInSection(section) } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForSection(section) } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { var meditation = objectAtIndexPath(indexPath) if nil == PFUser.currentUser() { //unpin aysnc task, callback not been called properly everytime. meditation.unpinInBackground() self.loadObjects() } else { //repeat delete same thing again and again seems be handle properly by Parse meditation.deleteInBackgroundWithBlock({ (success, error) -> Void in if success { self.loadObjects() } }) } } } override func scrollViewDidScroll(scrollView: UIScrollView) { if !footer.hidden && scrollView.contentOffset.y >= scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.bounds.height - footer.frame.height { if !loading { loadNextPage() updateFooter() } } } //Hack override func _shouldShowPaginationCell() -> Bool { return false; } func updateFooter() { footer.hidden = !super._shouldShowPaginationCell() } override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { var header = view as! UITableViewHeaderFooterView // header.contentView.backgroundColor = MHTheme.mainBgColor header.textLabel.textColor = MHTheme.mainBgColor } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "MHMeditationEdit" { let saveRecordVC = segue.destinationViewController as! MHMeditationDetailsViewController saveRecordVC.meditation = objectAtIndexPath(tableView.indexPathForSelectedRow()) as! MHMeditation saveRecordVC.mode = .Update } else if segue.identifier == "MHMeditationFreeformCreate" { let saveRecordVC = segue.destinationViewController.topViewController as! MHMeditationDetailsViewController saveRecordVC.meditation = MHMeditation() saveRecordVC.meditation.rate = 3 saveRecordVC.mode = .FreeformCreate } } }
9cfa7309a4f97cd41551959d7a32e633
33.304094
189
0.712922
false
false
false
false
13983441921/LTMorphingLabel
refs/heads/master
LTMorphingLabel/LTMorphingLabel+Pixelate.swift
mit
17
// // LTMorphingLabel+Pixelate.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2015 Lex Tang, http://LexTang.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 extension LTMorphingLabel { func PixelateLoad() { effectClosures["Pixelate\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: CGFloat(progress)) } effectClosures["Pixelate\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self.newRects[index], alpha: CGFloat(progress), size: self.font.pointSize, drawingProgress: CGFloat(1.0 - progress) ) } drawingClosures["Pixelate\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let charImage = self.pixelateImageForCharLimbo(charLimbo, withBlurRadius: charLimbo.drawingProgress * 6.0) let charRect = charLimbo.rect charImage.drawInRect(charLimbo.rect) return true } return false } } private func pixelateImageForCharLimbo(charLimbo: LTCharacterLimbo, withBlurRadius blurRadius: CGFloat) -> UIImage { let scale = min(UIScreen.mainScreen().scale, 1.0 / blurRadius) UIGraphicsBeginImageContextWithOptions(charLimbo.rect.size, false, scale) let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01)) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, charLimbo.rect.size.height) // let context = UIGraphicsGetCurrentContext() // CGContextSetShouldAntialias(context, false) String(charLimbo.char).drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor.colorWithAlphaComponent(fadeOutAlpha) ]) // CGContextSetShouldAntialias(context, true) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage } }
58e95744eec50b541df83d33ac978a6f
39.714286
122
0.636069
false
false
false
false
vladislav-k/VKCheckbox
refs/heads/master
VKCheckboxExample/VKCheckboxExample/TableViewController.swift
mit
1
// // TableViewController.swift // VKCheckboxExample // // Created by Vladislav Kovalyov on 8/16/17. // Copyright © 2016 WOOPSS.com http://woopss.com/ All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class TableViewController: UITableViewController { var selectedRows = [Int]() override func viewDidLoad() { super.viewDidLoad() } } // MARK: - UITableViewDataSource extension TableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell let title = "Item \(indexPath.row + 1)" cell.setTitle(title) cell.checkbox.setOn(self.selectedRows.contains(indexPath.row), animated: false) return cell } } // MARK: - UITableViewDelegate extension TableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if !self.selectedRows.contains(indexPath.row) { self.selectedRows.append(indexPath.row) } else { let index = self.selectedRows.firstIndex(of: indexPath.row)! self.selectedRows.remove(at: index) } let selected = self.selectedRows.contains(indexPath.row) let cell = tableView.cellForRow(at: indexPath) as! TableViewCell cell.checkbox.setOn(selected, animated: true) } }
adf5326920b95cacb344000a5e558aa6
32.729412
107
0.697942
false
false
false
false
JGiola/swift
refs/heads/main
test/SourceKit/Indexing/index_effective_access_level.swift
apache-2.0
5
// RUN: %empty-directory(%t) // RUN: %swift -emit-module -o %t/Exported.swiftmodule %S/Inputs/explicit-access/Exported.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import // RUN: %swift -emit-module -o %t/Module.swiftmodule %S/Inputs/explicit-access/Module.swift -I %t -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import // RUN: %sourcekitd-test -req=index %s -- -I %t %s -Xfrontend -disable-implicit-concurrency-module-import -Xfrontend -disable-implicit-string-processing-module-import | %sed_clean > %t.response // RUN: %diff -u %s.response %t.response public enum PublicEnum { case publicEnumCase } enum InternalEnum { case internalEnumCase } fileprivate enum FilePrivateEnum { case filePrivateEnumCase } private enum PrivateEnum { case privateEnumCase } extension PublicEnum { public func publicMethod() {} } public extension PublicEnum { func methodFromPublicExtension() {} } extension InternalEnum { func internalMethod() {} } extension FilePrivateEnum { fileprivate func filePrivateMethod() {} } fileprivate extension FilePrivateEnum { func methodFromFilePrivateExtension() {} } extension PrivateEnum { private func privateMethod() {} } private extension PrivateEnum { func methodFromPrivateExtension() {} } @propertyWrapper public struct PublicPropertyWrapper<T> { public var wrappedValue: T public init(wrappedValue: T) { self.wrappedValue = wrappedValue } } @propertyWrapper struct InternalPropertyWrapper<T> { let wrappedValue: T } @propertyWrapper fileprivate struct FilePrivatePropertyWrapper<T> { fileprivate let wrappedValue: T } @propertyWrapper private struct PrivatePropertyWrapper<T> { private let wrappedValue: T } private struct ScopeReducerStruct { public init(publicInitializer: Int) {} init(internalInitializer: Int) {} fileprivate init(filePrivateInitializer: Int) {} private init(privateInitializer: Int) {} public let publicProperty: Int = 0 let internalProperty: Int = 0 fileprivate let filePrivateProperty: Int = 0 private let privateProperty: Int = 0 public private(set) var publicPropertyWithPrivateSetter: Int = 0 @PublicPropertyWrapper public var publicPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper var internalPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper fileprivate var filePrivatePropertyWrappedProperty: Int = 0 @PublicPropertyWrapper private var privatePropertyWrappedProperty: Int = 0 public subscript(publicSubscript: Int) -> Int { return 0 } subscript(internalSubscript: Int) -> Int { return 0 } fileprivate subscript(filePrivateSubscript: Int) -> Int { return 0 } private subscript(privateSubscript: Int) -> Int { return 0 } public func publicMethod() {} func internalMethod() {} fileprivate func filePrivateMethod() {} private func privateMethod() {} } public struct ScopeKeeperStruct { public init(publicInitializer: Int) {} init(internalInitializer: Int) {} fileprivate init(filePrivateInitializer: Int) {} private init(privateInitializer: Int) {} public let publicProperty: Int = 0 let internalProperty: Int = 0 fileprivate let filePrivateProperty: Int = 0 private let privateProperty: Int = 0 public private(set) var publicPropertyWithPrivateSetter: Int = 0 @PublicPropertyWrapper public var publicPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper var internalPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper fileprivate var filePrivatePropertyWrappedProperty: Int = 0 @PublicPropertyWrapper private var privatePropertyWrappedProperty: Int = 0 public subscript(publicSubscript: Int) -> Int { return 0 } subscript(internalSubscript: Int) -> Int { return 0 } fileprivate subscript(filePrivateSubscript: Int) -> Int { return 0 } private subscript(privateSubscript: Int) -> Int { return 0 } public func publicMethod() {} func internalMethod() {} fileprivate func filePrivateMethod() {} private func privateMethod() {} } struct PartialScopeReducerStruct { public init(publicInitializer: Int) {} init(internalInitializer: Int) {} fileprivate init(filePrivateInitializer: Int) {} private init(privateInitializer: Int) {} public let publicProperty: Int = 0 let internalProperty: Int = 0 fileprivate let filePrivateProperty: Int = 0 private let privateProperty: Int = 0 public private(set) var publicPropertyWithPrivateSetter: Int = 0 @PublicPropertyWrapper public var publicPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper var internalPropertyWrappedProperty: Int = 0 @PublicPropertyWrapper fileprivate var filePrivatePropertyWrappedProperty: Int = 0 @PublicPropertyWrapper private var privatePropertyWrappedProperty: Int = 0 public subscript(publicSubscript: Int) -> Int { return 0 } subscript(internalSubscript: Int) -> Int { return 0 } fileprivate subscript(filePrivateSubscript: Int) -> Int { return 0 } private subscript(privateSubscript: Int) -> Int { return 0 } public func publicMethod() {} func internalMethod() {} fileprivate func filePrivateMethod() {} private func privateMethod() {} } private extension PrivateEnum { private func privateMethodFromPrivateExtension() {} } public protocol PublicProtocol { var member: Int { get set } func method() } protocol InternalProtocol { var member: Int { get set } func method() } fileprivate protocol FilePrivateProtocol { var member: Int { get set } func method() } private protocol PrivateProtocol { var member: Int { get set } func method() } fileprivate struct FilePrivateImplementationOfPublicProtocol: PublicProtocol { fileprivate var member: Int = 0 fileprivate func method() {} } open class OpenClass { open var openProperty: Int { return 0 } public var publicProperty: Int { return 0 } var internalProperty: Int { return 0 } open func openMethod() {} public func publicMethod() {} func internalMethod() {} } import Module struct InternalStruct { let propertyReferencingPublicClassFromModule: Module.ModuleClass let propertyReferencingPublicClassFromExportedModule: Exported.ExportedClass } public typealias Alias = Int public var globalVariable: Int = 0 protocol ProtocolWithAssociatedType { associatedtype T } struct ProtocolWithAssociatedTypeImpl: ProtocolWithAssociatedType { typealias T = Int func testLocalContent() { let localVariableShouldntBeIndexed = 0 } }
a7ed30e8bd2888c186cc7f25fe5b4864
29.605505
193
0.740108
false
false
false
false
coderwjq/swiftweibo
refs/heads/master
SwiftWeibo/SwiftWeibo/Classes/Others/Category/Date-Extension.swift
apache-2.0
1
// // Date-Extension.swift // SwiftWeibo // // Created by mzzdxt on 2016/11/3. // Copyright © 2016年 wjq. All rights reserved. // import Foundation extension Date { // 类方法,根据具体时间,返回对应的字符串 static func createDateString(_ createAtStr: String) -> String { // 创建时间格式化对象 let fmt = DateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" fmt.locale = Locale(identifier: "en") // 将字符串时间转换成NSDate类型 guard let createDate = fmt.date(from: createAtStr) else { return "" } // 创建当前时间 let nowDate = Date() //计算创建时间和当前时间的时间差 let interval = Int(nowDate.timeIntervalSince(createDate)) // 对时间间隔处理 // 显示刚刚 if interval < 60 { return "刚刚" } // 显示多少分钟前 if interval < 60 * 60 { return "\(interval / 60)分钟前" } // 显示多少小时前 if interval < 60 * 60 * 24 { return "\(interval / (60 * 60))小时前" } // 创建日历对象 let calendar = Calendar.current // 处理昨天数据 if calendar.isDateInYesterday(createDate) { fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 处理一年之内 let cmps = (calendar as NSCalendar).components(.year, from: createDate, to: nowDate, options: []) if cmps.year! < 1 { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } // 超过一年 fmt.dateFormat = "yyyy-MM-dd HH:mm" let timeStr = fmt.string(from: createDate) return timeStr } }
c6352fb73607f2c278fb54200f0f8bf0
24.5
105
0.505322
false
false
false
false
ivanbruel/Moya-ObjectMapper
refs/heads/master
Source/RxSwift/ObservableType+ObjectMapper.swift
mit
1
// // ObserverType+ObjectMapper.swift // // Created by Ivan Bruel on 09/12/15. // Copyright © 2015 Ivan Bruel. All rights reserved. // import Foundation import RxSwift import Moya import ObjectMapper /// Extension for processing Responses into Mappable objects through ObjectMapper public extension ObservableType where Element == Response { /// Maps data received from the signal into an object /// which implements the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: BaseMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(type, context: context)) } } /// Maps data received from the signal into an object /// which implements the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: BaseMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(T.self, atKeyPath: keyPath, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the Mappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: BaseMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(T.self, atKeyPath: keyPath, context: context)) } } } // MARK: - ImmutableMappable public extension ObservableType where Element == Response { /// Maps data received from the signal into an object /// which implements the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(type, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: ImmutableMappable>(_ type: T.Type, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(type, context: context)) } } /// Maps data received from the signal into an object /// which implements the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapObject<T: ImmutableMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.mapObject(T.self, atKeyPath: keyPath, context: context)) } } /// Maps data received from the signal into an array of objects /// which implement the ImmutableMappable protocol and returns the result back /// If the conversion fails, the signal errors. public func mapArray<T: ImmutableMappable>(_ type: T.Type, atKeyPath keyPath: String, context: MapContext? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.mapArray(T.self, atKeyPath: keyPath, context: context)) } } }
4c08232b4531aac05cf027eeb3028511
43.413043
136
0.721243
false
false
false
false
Ahrodite/LigaFix
refs/heads/master
LigaFix/SwiftForms/controllers/FormViewController.swift
mit
1
// // FormViewController.swift // SwiftForms // // Created by Miguel Angel Ortuño on 20/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit public class FormViewController : UITableViewController { /// MARK: Types private struct Static { static var onceDefaultCellClass: dispatch_once_t = 0 static var defaultCellClasses: [FormRowType : FormBaseCell.Type] = [:] } /// MARK: Properties public var form: FormDescriptor! /// MARK: Init public convenience init() { self.init(style: .Grouped) } public convenience init(form: FormDescriptor) { self.init() self.form = form } public override init(style: UITableViewStyle) { super.init(style: style) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) baseInit() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! baseInit() } private func baseInit() { } /// MARK: View life cycle public override func viewDidLoad() { super.viewDidLoad() assert(form != nil, "self.form property MUST be assigned!") navigationItem.title = form.title } /// MARK: Public interface public func valueForTag(tag: String) -> NSObject! { for section in form.sections { for row in section.rows { if row.tag == tag { return row.value } } } return nil } public func setValue(value: NSObject, forTag tag: String) { var sectionIndex = 0 var rowIndex = 0 for section in form.sections { for row in section.rows { if row.tag == tag { row.value = value if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: rowIndex, inSection: sectionIndex)) as? FormBaseCell { cell.update() } return } ++rowIndex } ++sectionIndex rowIndex = 0 } } /// MARK: UITableViewDataSource public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return form.sections.count } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return form.sections[section].rows.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) let reuseIdentifier = NSStringFromClass(formBaseCellClass) var cell: FormBaseCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? FormBaseCell if cell == nil { cell = formBaseCellClass.init(style: .Default, reuseIdentifier: reuseIdentifier) cell?.formViewController = self cell?.configure() } cell?.rowDescriptor = rowDescriptor // apply cell custom design if let cellConfiguration = rowDescriptor.configuration[FormRowDescriptor.Configuration.CellConfiguration] as? NSDictionary { for (keyPath, value) in cellConfiguration { cell?.setValue(value, forKeyPath: keyPath as! String) } } return cell! } public override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return form.sections[section].headerTitle } public override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return form.sections[section].footerTitle } /// MARK: UITableViewDelegate public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { return formBaseCellClass.formRowCellHeight() } return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let rowDescriptor = formRowDescriptorAtIndexPath(indexPath) if let selectedRow = tableView.cellForRowAtIndexPath(indexPath) as? FormBaseCell { if let formBaseCellClass = formBaseCellClassFromRowDescriptor(rowDescriptor) { formBaseCellClass.formViewController(self, didSelectRow: selectedRow) } } if let didSelectClosure = rowDescriptor.configuration[FormRowDescriptor.Configuration.DidSelectClosure] as? DidSelectClosure { didSelectClosure() } tableView.deselectRowAtIndexPath(indexPath, animated: true) } private class func defaultCellClassForRowType(rowType: FormRowType) -> FormBaseCell.Type { dispatch_once(&Static.onceDefaultCellClass) { Static.defaultCellClasses[FormRowType.Text] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Number] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.NumbersAndPunctuation] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Decimal] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Name] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Phone] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.URL] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Twitter] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.NamePhone] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Email] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.ASCIICapable] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Password] = FormTextFieldCell.self Static.defaultCellClasses[FormRowType.Indicator] = FormIndicatorCell.self Static.defaultCellClasses[FormRowType.Button] = FormButtonCell.self Static.defaultCellClasses[FormRowType.BooleanSwitch] = FormSwitchCell.self Static.defaultCellClasses[FormRowType.BooleanCheck] = FormCheckCell.self Static.defaultCellClasses[FormRowType.SegmentedControl] = FormSegmentedControlCell.self Static.defaultCellClasses[FormRowType.Picker] = FormPickerCell.self Static.defaultCellClasses[FormRowType.Date] = FormDateCell.self Static.defaultCellClasses[FormRowType.Time] = FormDateCell.self Static.defaultCellClasses[FormRowType.DateAndTime] = FormDateCell.self Static.defaultCellClasses[FormRowType.Stepper] = FormStepperCell.self Static.defaultCellClasses[FormRowType.Slider] = FormSliderCell.self Static.defaultCellClasses[FormRowType.MultipleSelector] = FormSelectorCell.self Static.defaultCellClasses[FormRowType.MultilineText] = FormTextViewCell.self } return Static.defaultCellClasses[rowType]! } private func formRowDescriptorAtIndexPath(indexPath: NSIndexPath!) -> FormRowDescriptor { let section = form.sections[indexPath.section] let rowDescriptor = section.rows[indexPath.row] return rowDescriptor } private func formBaseCellClassFromRowDescriptor(rowDescriptor: FormRowDescriptor) -> FormBaseCell.Type! { var formBaseCellClass: FormBaseCell.Type! if let cellClass: AnyClass = rowDescriptor.configuration[FormRowDescriptor.Configuration.CellClass] as? AnyClass { formBaseCellClass = cellClass as? FormBaseCell.Type } else { formBaseCellClass = FormViewController.defaultCellClassForRowType(rowDescriptor.rowType) } assert(formBaseCellClass != nil, "FormRowDescriptor.Configuration.CellClass must be a FormBaseCell derived class value.") return formBaseCellClass } }
372175a0393cfba80f8ec404d479a7cf
38.336364
145
0.662122
false
false
false
false
zakkhoyt/ColorPicKit
refs/heads/1.2.3
ColorPicKit/Classes/GradientSliderView.swift
mit
1
// // GradientSliderView.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/8/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class GradientSliderView: SliderView { private var _color1: UIColor = .clear var color1: UIColor { get { return _color1 } set { _color1 = newValue setNeedsDisplay() } } private var _color2: UIColor = .white var color2: UIColor { get { return _color2 } set { _color2 = newValue setNeedsDisplay() } } override func drawBackground(context: CGContext) { let rgba1 = color1.rgba() let rgba2 = color2.rgba() let colors: [CGFloat] = [ CGFloat(rgba1.red), CGFloat(rgba1.green), CGFloat(rgba1.blue), 1.0, CGFloat(rgba2.red), CGFloat(rgba2.green), CGFloat(rgba2.blue), 1.0, ] let colorSpace = CGColorSpaceCreateDeviceRGB() guard let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: nil, count: 2) else { print("No gradient") return } let rect = self.bounds // context.saveGState() context.addRect(rect) context.clip() let startPoint = CGPoint(x: rect.minX, y: rect.midY) let endPoint = CGPoint(x: rect.maxX, y: rect.midY) context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: []) // context.restoreGState() context.addRect(rect) context.drawPath(using: .stroke) } }
ce781db80655deec0d82144ce69689d2
25.384615
121
0.548105
false
false
false
false
leoru/Brainstorage
refs/heads/master
Brainstorage-iOS/Classes/Controllers/Base/BaseTableViewController.swift
mit
1
// // BaseTableViewController.swift // Brainstorage-iOS // // Created by Kirill Kunst on 04.02.15. // Copyright (c) 2015 Kirill Kunst. All rights reserved. // import UIKit class BaseTableViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var table : UITableView? var footerView : UIView? var footerActInd : UIImageView?//UIActivityIndicatorView? var isPageLoading : Bool? override func viewDidLoad() { super.viewDidLoad() self.isPageLoading = false self.registerTableNibsAndClasses() self.addFooter() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func loadMore() { // should be overriden } func refresh() { // should be overriden } func showLoading() { self.footerView?.hidden = false self.table?.tableFooterView = self.footerView self.footerActInd?.br_startAnimating() } func hideLoading() { self.footerView?.hidden = true self.table?.tableFooterView = nil; self.footerActInd?.br_stopAnimating() } func addPullToRefresh() { } func hidePullToRefresh() { } func registerTableNibsAndClasses() { } func setContentInset() { self.table?.contentInset = UIEdgeInsetsMake(64.0, 0.0, 64.0, 0.0); self.table?.scrollIndicatorInsets = UIEdgeInsetsMake(64.0, 0.0, 64.0, 0.0); } // UI func addFooter() { var footerFrame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44) self.footerView = UIView(frame: footerFrame) self.footerView?.backgroundColor = UIColor.clearColor() self.footerView?.hidden = false self.footerActInd = UIImageView(image: UIImage(named:"indicator")) self.footerActInd?.center = CGPointMake(footerFrame.width / 2, footerFrame.height / 2) self.footerView?.addSubview(self.footerActInd!) } // TableView func shouldWillLoadMore(cell : UITableViewCell, indexPath : NSIndexPath) -> Bool { return false } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if self.isPageLoading! { return } if (self.shouldWillLoadMore(cell, indexPath: indexPath)) { self.isPageLoading = true self.showLoading() var delayInSeconds : Double = 0.5 var popTime : dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, (Int64)(delayInSeconds * Double(NSEC_PER_SEC))) dispatch_after(popTime, dispatch_get_main_queue(), { [weak self] () -> Void in self!.loadMore() }) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } }
dd00bb98ec5e04ca04d2e2d1055df125
27.486957
125
0.618437
false
false
false
false
qkrqjadn/SoonChat
refs/heads/master
source/Controller/MainViewController.swift
mit
1
// // MainNavigationController.swift // soonchat // // Created by 박범우 on 2016. 12. 18.. // Copyright © 2016년 bumwoo. All rights reserved. // //TODO: 기존 사용자 로그아웃 처리후 로그인시 화면유지 이슈 해결. import UIKit import BATabBarController import Firebase import HidingNavigationBar class MainViewController : BATabBarController { private let option1 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "카드") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon1_unselected"), selectedImage: UIImage(named: "icon1_selected"), title: attributeString) return bt! }() private let option2 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "채팅") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon2_unselected"), selectedImage: UIImage(named: "icon2_selected"), title: attributeString) return bt! }() private let option3 : BATabBarItem = { let attributeString = NSMutableAttributedString(string: "매칭") attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.white], range: NSRange(location: 0, length: attributeString.string.characters.count)) let bt = BATabBarItem(image: UIImage(named: "icon3_unselected"), selectedImage: UIImage(named: "icon3_selected"), title: attributeString) return bt! }() fileprivate lazy var infoViewController : UINavigationController = { let iv = InfoViewController() iv.tabBarcontroller = self let nv = UINavigationController(rootViewController: iv) return nv }() fileprivate let chatViewController : UINavigationController = { let nv = UINavigationController(rootViewController: ChatViewController()) return nv }() fileprivate let userConfigureController : UINavigationController = { let nv = UINavigationController(rootViewController: UserConfigureController()) return nv }() override func viewDidLoad() { super.viewDidLoad() tabbarhandler() loginHandler() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) CurrentUser.sharedInstance.updateUserData() tabBar.selectedTabItem(0, animated: true) } func tabbarhandler() { self.tabBarItemStrokeColor = .white self.tabBarItemLineWidth = 3 tabBar.tintColor = .darkGray } func loginHandler() { if isLoggedIn() { self.tabBarItems = [option1,option2,option3] self.viewControllers = [infoViewController,chatViewController,userConfigureController] } else if isLoggedIn() == false { print("false!!!") perform(#selector(showLoginController), with: nil, afterDelay: 0.02) } } @objc fileprivate func logOut() { UserDefaults.standard.set(false, forKey: "isLoggedIn") UserDefaults.standard.synchronize() showLoginController() } fileprivate func isLoggedIn() -> Bool { return UserDefaults.standard.bool(forKey: "isLoggedIn") } @objc fileprivate func showLoginController() { let loginController = LoginController() present(loginController, animated: true, completion: { }) } }
5ee6c446d48467d35acece57e08d9c67
34.394231
163
0.671285
false
true
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Vdv/DepartureMonitor.swift
gpl-3.0
1
import Foundation import ObjectMapper class DepartureMonitor { private var busStops = [VdvBusStop]() private var lineFilter = [Int]() private var time = ApiTime.now() private var past = 300 private var maxElements = Int.max func atBusStop(busStop: Int) -> DepartureMonitor { busStops.append(VdvBusStop(id: busStop)) return self } func atBusStops(busStops: [Int]) -> DepartureMonitor { for busStop in busStops { self.busStops.append(VdvBusStop(id: busStop)) } return self } func atBusStopFamily(family: Int) -> DepartureMonitor { busStops.append(contentsOf: BusStopRealmHelper.getBusStopsFromFamily(family: family)) return self } func atBusStopFamilies(families: [Int]) -> DepartureMonitor { for busStopFamily in families { busStops.append(contentsOf: BusStopRealmHelper.getBusStopsFromFamily(family: busStopFamily)) } return self } func at(date: Date) -> DepartureMonitor { return at(millis: date.millis()) } private func at(millis: Int64) -> DepartureMonitor { time = ApiTime.addOffset(millis: millis) return self } func filterLine(line: Int) -> DepartureMonitor { lineFilter.append(line) return self } func filterLines(lines: [Int]) -> DepartureMonitor { lineFilter.append(contentsOf: lines) return self } func maxElements(maxElements: Int) -> DepartureMonitor { self.maxElements = maxElements return self } func includePastDepartures(seconds: Int) -> DepartureMonitor { past = seconds return self } func collect() -> [VdvDeparture] { let date = Date(timeIntervalSince1970: Double(time / 1000)) let isToday = Calendar.current.isDateInToday(date) if !isToday { do { try VdvTrips.loadTrips(day: VdvCalendar.date(date)) } catch { Log.error("Unable to load departures: \(error)") return [] } } var departures = [VdvDeparture]() var lines = [Int]() let busStopFamilies = busStops.map { BusStopRealmHelper.getBusStopGroup(id: $0.id) } for busStopFamily in busStopFamilies { lines.append(contentsOf: Api.getPassingLines(group: busStopFamily)) } if !lineFilter.isEmpty { lines = lines.filter { lineFilter.contains($0) } } time /= 1000 time %= 86400 let list = isToday ? VdvTrips.ofSelectedDay() : VdvTrips.ofOtherDay() for trip in list { if lines.contains(trip.lineId) { var path = trip.calcPath() if !Set(path).isDisjoint(with: busStops) { for busStop in busStops { if let index = path.index(of: busStop), index != path.count - 1 { path = trip.calcTimedPath() if path[index].departure > Int(time - past) { departures.append(VdvDeparture( lineId: trip.lineId, time: path[index].departure, destination: path.last!, tripId: trip.tripId )) } } } } } } departures.sort() if maxElements != 0 { let end: Int = (maxElements > departures.count) ? departures.count : maxElements departures = Array(departures[0..<end]) } return departures } static func calculateForWatch(_ group: Int, replyHandler: @escaping ([String : Any]) -> Void, addToFavorites: Bool = true) { if addToFavorites { UserRealmHelper.addRecentDeparture(group: group) } let monitor = DepartureMonitor() .atBusStopFamily(family: group) .maxElements(maxElements: 20) .at(date: Date()) DispatchQueue.global(qos: .background).async { let departures = monitor.collect() let mapped: [Departure] = departures.map { $0.asDeparture(busStopId: 0) } var message = [String: Any]() message["type"] = WatchMessage.calculateDeparturesResponse.rawValue message["data"] = Mapper().toJSONString(mapped, prettyPrint: false) message["is_favorite"] = UserRealmHelper.hasFavoriteBusStop(group: group) replyHandler(message) } } }
ea1103b63087164de701ea16746cbaaa
27.312139
128
0.534708
false
false
false
false
anotheren/TrafficPolice
refs/heads/master
Source/TrafficSpeed.swift
mit
1
// // TrafficSpeed.swift // TrafficPolice // // Created by 刘栋 on 2016/11/18. // Copyright © 2016年 anotheren.com. All rights reserved. // import Foundation public struct TrafficSpeed { public var received: Double // down btyes per second public var sent: Double // up btyes per second private init(received: Double, sent: Double) { self.received = received self.sent = sent } public init(old: TrafficData, new: TrafficData, interval: Double) { self.received = (new.received.double - old.received.double) / interval self.sent = (new.sent.double - old.sent.double) / interval } public static var zero: TrafficSpeed { return self.init(received: 0, sent: 0) } } extension TrafficSpeed: CustomStringConvertible { public var description: String { return "download: \(received.unitString)/s, upload: \(sent.unitString)/s" } } public func +(lhs: TrafficSpeed, rhs: TrafficSpeed) -> TrafficSpeed { var result = lhs result.received += rhs.received result.sent += rhs.sent return result }
487e19ebbbc89ae8635ccdf277748e18
24.953488
81
0.650538
false
false
false
false
awind/Pixel
refs/heads/master
Pixel/ReportPhotoActivity.swift
apache-2.0
1
// // ReportPhotoActivity.swift // Pixel // // Created by SongFei on 16/1/15. // Copyright © 2016年 SongFei. All rights reserved. // import UIKit import Alamofire import MBProgressHUD class ReportPhotoActivity: UIActivity { var photoId: Int? var viewcontroller: UIViewController? var view: UIView? let OFFENSIVE = 1 let SPAM = 2 let OFFTOPIC = 3 let COPYRIGHT = 4 let WRONGCONTENT = 5 let ADULTCONTENT = 6 let OTHER = 0 override func activityType() -> String? { return "Actions.Report" } override func activityTitle() -> String? { return NSLocalizedString("REPORT", comment: "report") } override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool { NSLog("%@", __FUNCTION__) return true } override func prepareWithActivityItems(activityItems: [AnyObject]) { NSLog("%@", __FUNCTION__) } override func activityViewController() -> UIViewController? { NSLog("%@", __FUNCTION__) return nil } override func performActivity() { // Todo: handle action: NSLog("%@", __FUNCTION__) let alertController = UIAlertController(title: "", message: NSLocalizedString("REPORT_ALERT_MESSAGE", comment: "reportMessage"), preferredStyle: .ActionSheet) let offensiveAction = UIAlertAction(title: NSLocalizedString("OFFENSIVE", comment: "offensive"), style: UIAlertActionStyle.Default) { action in let hud = MBProgressHUD.showHUDAddedTo(self.view!, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.labelText = "Loading..." hud.show(true) Alamofire.request(Router.Report(self.photoId!, self.OFFENSIVE, "")) .responseSwiftyJSON() { response in Logger.printLog(response) hud.mode = MBProgressHUDMode.CustomView hud.customView = UIImageView(image: UIImage(named: "ic_checkmark")) hud.labelText = "Success" hud.hide(true, afterDelay: 1) } } let spamAction = UIAlertAction(title: NSLocalizedString("SPAM", comment: "spam"), style: UIAlertActionStyle.Default) { action in let hud = MBProgressHUD.showHUDAddedTo(self.view!, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.labelText = "Loading..." hud.show(true) Alamofire.request(Router.Report(self.photoId!, self.SPAM, "")) .responseSwiftyJSON() { response in Logger.printLog(response) hud.mode = MBProgressHUDMode.CustomView hud.customView = UIImageView(image: UIImage(named: "ic_checkmark")) hud.labelText = "Success" hud.hide(true, afterDelay: 1) } } let offTopicAction = UIAlertAction(title: "Offtopic", style: UIAlertActionStyle.Default) { action in } let copyrightAction = UIAlertAction(title: NSLocalizedString("COPYRIGHT", comment: "COPYRIGHT"), style: UIAlertActionStyle.Default) { action in let hud = MBProgressHUD.showHUDAddedTo(self.view!, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.labelText = "Loading..." hud.show(true) Alamofire.request(Router.Report(self.photoId!, self.COPYRIGHT, "")) .responseSwiftyJSON() { response in Logger.printLog(response) hud.mode = MBProgressHUDMode.CustomView hud.customView = UIImageView(image: UIImage(named: "ic_checkmark")) hud.labelText = "Success" hud.hide(true, afterDelay: 1) } } let wrongContentAction = UIAlertAction(title: "Wrong content", style: UIAlertActionStyle.Default) { action in } let adultAction = UIAlertAction(title: NSLocalizedString("ADULTCONTENT", comment: "adult"), style: UIAlertActionStyle.Default) { action in let hud = MBProgressHUD.showHUDAddedTo(self.view!, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.labelText = "Loading..." hud.show(true) Alamofire.request(Router.Report(self.photoId!, self.ADULTCONTENT, "")) .responseSwiftyJSON() { response in hud.mode = MBProgressHUDMode.CustomView hud.customView = UIImageView(image: UIImage(named: "ic_checkmark")) hud.labelText = "Success" hud.hide(true, afterDelay: 1) Logger.printLog(response) } } let otherAction = UIAlertAction(title: "Other", style: UIAlertActionStyle.Default) { action in } let cancelAction = UIAlertAction(title: NSLocalizedString("CANCEL", comment: "cancel"), style: .Cancel) {action in } alertController.addAction(offensiveAction) alertController.addAction(spamAction) // alertController.addAction(offTopicAction) alertController.addAction(copyrightAction) // alertController.addAction(wronContentAction) alertController.addAction(adultAction) // alertController.addAction(otherAction) alertController.addAction(cancelAction) self.viewcontroller?.presentViewController(alertController, animated: true, completion: nil) self.activityDidFinish(true) } override func activityImage() -> UIImage? { return UIImage(named: "ic_report") } }
1ba44b50fa61d7dd6c1e0dad75c0b706
38.317568
166
0.598213
false
false
false
false
petrmanek/revolver
refs/heads/master
Sources/OnePointCrossover.swift
mit
1
/// One-point crossover simulates sexual reproduction of individuals within the population. /// It combines their chromosomes to create new offspring chromosomes, which are then inserted into the next generation. open class OnePointCrossover<Chromosome: OnePointCrossoverable>: GeneticOperator<Chromosome> { public override init(_ selection: Selection<Chromosome>) { super.init(selection) } open override func apply(_ generator: EntropyGenerator, pool: MatingPool<Chromosome>) { // Select 2 individuals. let selectedIndividuals = selection.select(generator, population: pool, numberOfIndividuals: 2) // Retrieve parent chromosomes. let firstChromosome = pool.individualAtIndex(selectedIndividuals.first!).chromosome let secondChromosome = pool.individualAtIndex(selectedIndividuals.last!).chromosome // Perform crossover on their underlying data structure. let result = firstChromosome.onePointCrossover(generator, other: secondChromosome) // Insert the offspring into new population. let firstOffspring = Individual<Chromosome>(chromosome: result.first) let secondOffspring = Individual<Chromosome>(chromosome: result.second) pool.addOffspring(firstOffspring) pool.addOffspring(secondOffspring) } }
5bcdaec54293cc318b4d48d48dda4be0
46.310345
120
0.721574
false
false
false
false
Takanu/Pelican
refs/heads/master
Sources/Pelican/Pelican/Pelican.swift
mit
1
import Dispatch // Linux thing. import Foundation import SwiftyJSON /** Your own personal pelican for building Telegram bots! To get started with Pelican, you'll need to place the code below as setup before running the app. You'll also need to add your API token as a `token` inside `config.json` (create it if you don't have the file), to assign it to your bot and start receiving updates. You can get your API token from @BotFather. ## Pelican JSON Contents ``` { "bot_token": "INSERT:YOUR-KEY-RIGHT-HERE" "payment_token": "INSERT:PAYMENTS-PLZ-DELICIOUS" } ``` ## Pelican Basic Setup ``` // Create a chat session class ShinyNewSession: ChatSession { override func postInit() { // ROUTING // Add a basic 'lil route. let start = RouteCommand(commands: "start") { update in self.requests.async.sendMessage("Ding!", markup: nil, chatID: self.tag.id) return true } // Add some more test routes. let taka = RouteCommand(commands: "taka") { update in let user = self.requests.sync.getMe() let responseMsg = """ HI! I AM A \(user?.firstName ?? "null") BOT. """ self.requests.async.sendMessage(responseMsg, markup: nil, chatID: self.tag.id) return true } // This is a blank route that allows any update given it to automatically pass. self.baseRoute = Route(name: "base", action: { update in return false }) self.baseRoute.addRoutes(start, taka) } } // Create a bot instance let pelican = try PelicanBot() // Add a builder pelican.addBuilder(SessionBuilder(spawner: Spawn.perChatID(types: nil), idType: .chat, session: ShinyNewSession.self, setup: nil) ) // Configure the bot polling bot.updateTimeout = 300 // Run it try pelican.boot() ``` */ public final class PelicanBot { // MARK: - Core Properties /// The cache system responsible for handling the re-using of already uploaded files and assets, to preserve system resources. var cache: CacheManager! /// A controller that records and manages client connections to Telegram. var client: Client /// The API key assigned to your bot. public private(set) var apiKey: String /// The Payment key assigned to your bot. To assign the key, add it to the JSON file inside config/pelican.json as "payment_token". public private(set) var paymentKey: String? /// The combination of the API request URL and your API token. public private(set) var apiURL: String // MARK: - Connection Settings /** Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten. - warning: Pelican automatically handles this variable, don't use it unless you want to perform something very specific. */ public var updateOffset: Int = 0 /// The number of messages that can be received in any given update, between 1 and 100. public var updateLimit: Int = 100 /// The length of time Pelican will hold onto an update connection with Telegram to wait for updates before disconnecting. public var updateTimeout: Int = 300 /// Defines what update types the bot will receive. Leave empty if all are allowed, or otherwise specify to optimise the bot. public var allowedUpdates: [UpdateType] = [.message, .editedMessage, .channelPost, .editedChannelPost, .callbackQuery, .inlineQuery, .chosenInlineResult, .shippingQuery, .preCheckoutQuery] /// If true, the bot will ignore any historic messages it has received while it has been offline. public var ignoreInitialUpdates: Bool = true /// Whether the bot has started and is running. private var started: Bool = false /// Whether the bot has started and is running. public var hasStarted: Bool { return started } // MARK: - Update Queues /// The DispatchQueue system that fetches updates and hands them off to any applicable Sessions to handle independently. private var updateQueue: LoopQueue? /// The DispatchQueue system that checks for any scheduled events and hands the ones it finds to the Session that requested them, on the Session queue. private var scheduleQueue: LoopQueue? /// A pre-built request type to be used for fetching updates. var getUpdatesRequest: TelegramRequest { let request = TelegramRequest() request.method = "getUpdates" request.query = [ "offset": updateOffset, "limit": updateLimit, "timeout": updateTimeout, //"allowed_updates": allowedUpdates.map { $0.rawValue }, ] return request } // MARK: - Read-only information /// The time the bot started operating. var timeStarted: Date? /// The time the last update the bot has received from Telegram. var timeLastUpdate: Date? // MARK: - Session Properties /// A manager that handles all sessionManager assigned to Pelican, and thats used by Sessions to find or create other Sessions. public var sessionManager = SessionManager() /// The schedule system for sessions to use to delay the execution of actions. public var schedule: Schedule! // MARK: - Moderation Properties /// The moderator system, used for blacklisting and whitelisting users and chats to either prevent or allow them to use the bot. public var mod: Moderator // DEBUG // ??? // MARK: - Initialisation /** Initialises Pelican. - warning: Pelican will attempt to find your API key at this point, and will fail if it's missing. */ public init() throws { let workingDir = PelicanBot.workingDirectory() if workingDir == "" { throw TGBotError.WorkingDirNotFound } let bundle = Bundle(path: workingDir) if bundle == nil { throw TGBotError.WorkingDirNotFound } let configURL = bundle?.url(forResource: "config", withExtension: "json", subdirectory: nil) if configURL == nil { throw TGBotError.ConfigMissing } let data = try Data(contentsOf: configURL!) let configJSON = JSON.init(data: data) guard let token = configJSON["bot_token"].string else { throw TGBotError.KeyMissing } // Set tokens self.apiKey = token self.apiURL = "https://api.telegram.org/bot" + token self.paymentKey = configJSON["payment_token"].string // Initialise controls and timers self.mod = Moderator() self.cache = try CacheManager(bundlePath: workingDir) self.client = Client(token: token, cache: cache) self.schedule = Schedule(workCallback: self.requestSessionWork) } /** Starts the bot! */ public func boot() throws { // The main thread needs to do 'something', keep this for later /** // Set the upload queue. updateQueue = LoopQueue(queueLabel: "com.pelican.fetchupdates", qos: .userInteractive, interval: TimeInterval(self.pollInterval)) { PLog.info("Update Starting...") let updates = self.requestUpdates() if updates != nil { self.handleUpdates(updates!) } self.timeLastUpdate = Date() PLog.info("Update Complete.") } */ // Set the schedule queue. scheduleQueue = LoopQueue(queueLabel: "com.pelican.eventschedule", qos: .default, interval: TimeInterval(1)) { self.schedule.run() } // Clear the first set of updates if we're asked to. if ignoreInitialUpdates == true { let request = TelegramRequest() request.method = "getUpdates" request.query = [ "offset": updateOffset, "limit": updateLimit, "timeout": 1, ] if let response = client.syncRequest(request: request) { let update_count = response.result!.array?.count ?? 0 let update_id = response.result![update_count - 1]["update_id"].int ?? -1 updateOffset = update_id + 1 } } // Boot! self.timeStarted = Date() self.timeLastUpdate = Date() started = true //updateQueue!.queueNext() scheduleQueue!.queueNext() print("<<<<< Pelican has started. >>>>>") // Run the update queue while 1 == 1 { updateCycle() } } // MARK: - Methods /** The main run loop for Pelican, responsible for fetching and dispatching updates to Sessions. */ private func updateCycle() { PLog.info("Update Starting...") let updates = self.requestUpdates() if updates != nil { self.handleUpdates(updates!) } self.timeLastUpdate = Date() PLog.info("Update Complete.") } /** Requests a set of updates from Telegram, based on the poll, offset, updateTimeout and update limit settings assigned to Pelican. - returns: A `TelegramUpdateSet` if succsessful, or nil if otherwise. */ public func requestUpdates() -> [Update]? { var response: TelegramResponse? = nil // Build a new request with the correct URI and fetch the other data from the Session Request PLog.info("Contacting Telegram for Updates...") response = client.syncRequest(request: getUpdatesRequest) // If we have a response, try and build an update list from it. if response != nil { if response!.status != .ok { return nil } let updateResult = self.generateUpdateTypes(response: response!) return updateResult } return nil } public func generateUpdateTypes(response: TelegramResponse) -> [Update]? { // Get the basic result data let results = response.result?.array ?? [] let messageCount = results.count if response.result == nil { return nil } // Make the collection types var updates: [Update] = [] PLog.verbose("Updates Found - \(messageCount)") // Iterate through the collected messages for i in 0..<messageCount { let update_id = response.result![i]["update_id"].int ?? -1 let responseSlice = response.result![i] // This is just a plain old message if allowedUpdates.contains(UpdateType.message) { if (responseSlice["message"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["message"], dataType: Message.self, updateType: .message) if update != nil { updates.append(update!) } } } // This is if a message was edited if allowedUpdates.contains(UpdateType.editedMessage) { if (responseSlice["edited_message"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["edited_message"], dataType: Message.self, updateType: .editedMessage) if update != nil { updates.append(update!) } } } // This is for a channel post if allowedUpdates.contains(UpdateType.channelPost) { if (responseSlice["channel_post"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["channel_post"], dataType: Message.self, updateType: .channelPost) if update != nil { updates.append(update!) } } } // This is for an edited channel post if allowedUpdates.contains(UpdateType.editedChannelPost) { if (responseSlice["edited_channel_post"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["edited_channel_post"], dataType: Message.self, updateType: .editedChannelPost) if update != nil { updates.append(update!) } } } // COME BACK TO THESE LATER // This type is for when someone tries to search something in the message box for this bot if allowedUpdates.contains(UpdateType.inlineQuery) { if (responseSlice["inline_query"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["inline_query"], dataType: InlineQuery.self, updateType: .inlineQuery) if update != nil { updates.append(update!) } } } // This type is for when someone has selected an search result from the inline query if allowedUpdates.contains(UpdateType.chosenInlineResult) { if (responseSlice["chosen_inline_result"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["chosen_inline_result"], dataType: ChosenInlineResult.self, updateType: .chosenInlineResult) if update != nil { updates.append(update!) } } } /// Callback Query handling (receiving button presses for inline buttons with callback data) if allowedUpdates.contains(UpdateType.callbackQuery) { if (responseSlice["callback_query"]) != JSON.null { let update = unwrapIncomingUpdate(json: responseSlice["callback_query"], dataType: CallbackQuery.self, updateType: .callbackQuery) if update != nil { updates.append(update!) } } } updateOffset = update_id + 1 } return updates } /** Attempts to unwrap a slice of the response to the desired type, returning it as an Update. */ internal func unwrapIncomingUpdate<T: UpdateModel>(json: JSON, dataType: T.Type, updateType: UpdateType) -> Update? { // Setup the decoder let decoder = JSONDecoder() // Attempt to decode do { let data = try json.rawData() let result = try decoder.decode(dataType, from: data) if let update = Update(withData: result, json: json, type: updateType) { // Check that the update isn't on any blacklists. if update.chat != nil { if mod.checkBlacklist(chatID: update.chat!.tgID) == true { return nil } } if update.from != nil { if mod.checkBlacklist(chatID: update.from!.tgID) == true { return nil } } // Now we can return return update } else { PLog.error("Pelican Error (Unable to create Update)\n") } } catch { PLog.error("Pelican Error (Decoding message from updates) - \n\n\(error)\n") return nil } return nil } /** Used by the in-built long polling solution to match updates to sessions. ### EDIT/REMOVE IN UPCOMING REFACTOR */ internal func handleUpdates(_ updates: [Update]) { PLog.info("Handling updates...") sessionManager.handleUpdates(updates, bot: self) // Update the last active time. timeLastUpdate = Date() PLog.info("Updates handled.") } /** Add new sessionManager to the bot, enabling the automated creation and filtering of updates to your defined Session types. */ public func addBuilder(_ incomingBuilders: SessionBuilder...) { sessionManager.addBuilders(incomingBuilders) } }
1f74e40043759a01b83a2e21ec1c840c
35.112
270
0.548682
false
false
false
false
lyft/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/TypeNameRuleExamples.swift
mit
1
import Foundation internal struct TypeNameRuleExamples { private static let types = ["class", "struct", "enum"] static let nonTriggeringExamples: [String] = { let typeExamples: [String] = types.flatMap { (type: String) -> [String] in [ "\(type) MyType {}", "private \(type) _MyType {}", "\(type) \(repeatElement("A", count: 40).joined()) {}" ] } let typeAliasAndAssociatedTypeExamples = [ "typealias Foo = Void", "private typealias Foo = Void", "protocol Foo {\n associatedtype Bar\n }", "protocol Foo {\n associatedtype Bar: Equatable\n }" ] return typeExamples + typeAliasAndAssociatedTypeExamples + ["enum MyType {\ncase value\n}"] }() static let triggeringExamples: [String] = { let typeExamples: [String] = types.flatMap { (type: String) -> [String] in [ "\(type) ↓myType {}", "\(type) ↓_MyType {}", "private \(type) ↓MyType_ {}", "\(type) ↓My {}", "\(type) ↓\(repeatElement("A", count: 41).joined()) {}" ] } let typeAliasAndAssociatedTypeExamples: [String] = [ "typealias ↓X = Void", "private typealias ↓Foo_Bar = Void", "private typealias ↓foo = Void", "typealias ↓\(repeatElement("A", count: 41).joined()) = Void", "protocol Foo {\n associatedtype ↓X\n }", "protocol Foo {\n associatedtype ↓Foo_Bar: Equatable\n }", "protocol Foo {\n associatedtype ↓\(repeatElement("A", count: 41).joined())\n }" ] return typeExamples + typeAliasAndAssociatedTypeExamples }() }
c69471bf08bd70f26dc84f6f650f0f2d
36.957447
99
0.52074
false
false
false
false
psmortal/Berry
refs/heads/master
Pod/Classes/KeyboardManager.swift
mit
1
// // KeyboardManager.swift // Zuzhong // // Created by mortal on 2016/12/22. // Copyright © 2016年 矩点医疗科技有 限公司. All rights reserved. // import Foundation import UIKit public class KeyboardManager { static var shared:KeyboardManager = KeyboardManager() var scrollView:UIScrollView? private init() { NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShowNotification(notification:)), name: Notification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHideNotification(notification:)), name: Notification.Name.UIKeyboardDidHide, object: nil) } @objc func keyboardDidShowNotification(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom:keyboardSize.height, right: 0) self.scrollView?.contentInset = contentInsets } } @objc func keyboardDidHideNotification(notification: NSNotification) { self.scrollView?.contentInset = UIEdgeInsets.zero } func regist(scrollView:UIScrollView){ self.scrollView = scrollView } }
247c1b08f584d270218e73fea227b503
29.795455
178
0.687085
false
false
false
false
Joachimdj/JobResume
refs/heads/master
Apps/Forum17/2017/Forum/LectureCell.swift
mit
1
// // ProgramCell.swift // Forum // // Created by Joachim Dittman on 04/08/2016. // Copyright © 2016 Joachim Dittman. All rights reserved. // // // NFCell.swift // Fritid // // Created by Joachim Dittman on 20/12/2015. // Copyright © 2015 Joachim Dittman. All rights reserved. // import UIKit class LectureCell: UITableViewCell { let cellView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 70)) let typeImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 70 , height: 70)) let favorite = UIButton(frame: CGRect(x: UIScreen.main.bounds.width - 60, y: 0, width: 70 , height: 70)) let titleLabel = UITextView(frame: CGRect(x: 80,y: 0,width: UIScreen.main.bounds.width-80 ,height: 50)) let placeLabel = UILabel(frame: CGRect(x: 80,y: 40,width: UIScreen.main.bounds.width-80,height: 25)) override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) cellView.backgroundColor = .white cellView.dropShadow() titleLabel.isUserInteractionEnabled = false titleLabel.textAlignment = .left titleLabel.font = UIFont (name: "HelveticaNeue-Bold", size: 14) placeLabel.textAlignment = .left placeLabel.font = UIFont (name: "Helvetica Neue", size: 13) typeImage.layer.cornerRadius = typeImage.frame.size.width / 2 typeImage.layer.borderWidth = 3.0 typeImage.layer.borderColor = UIColor.white.cgColor; typeImage.image = UIImage(named: "logo") typeImage.clipsToBounds = true favorite.setImage(UIImage(named: "heart"), for: UIControlState()) cellView.addSubview(titleLabel) cellView.addSubview(placeLabel) cellView.addSubview(typeImage) cellView.addSubview(favorite) self.contentView.addSubview(cellView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() } }
3b0998db6e17a049f404d757f0cd8113
31.461538
108
0.655924
false
false
false
false
coolmacmaniac/swift-ios
refs/heads/master
DesignPatterns/DesignPatterns/AbstractFactory/DPBinary.swift
gpl-3.0
1
// // DPBinary.swift // DesignPatterns // // Created by Sourabh on 28/06/17. // Copyright © 2017 Home. All rights reserved. // import Foundation /** Specifies the type for a number that has to be coverted to binary format */ struct DPBinary: DPBaseNumber { /// To hold the decimal input value private var value: Int public static func getNumber(value: Int) -> DPBaseNumber { return DPBinary(value: value) } public func convertBase() -> String { // find the binary equivalent let binVal = String(value, radix: DPNumberBase.binary.rawValue) // calculate the padded length if the length is not a multiple of 4 var padding = Int(ceil(Double(binVal.characters.count) / 4)) padding = padding * 4 - binVal.characters.count // pad the beginning with zeros var result = String(repeating: "0", count: padding) // append the actual converted value result = result.appending(binVal) return result } }
cfb22f42eb20c8a3f594fe24088eb126
22.097561
72
0.69905
false
false
false
false
iHunterX/SocketIODemo
refs/heads/master
DemoSocketIO/Utils/CustomTextField/iHBorderColorTextField.swift
gpl-3.0
1
// // iH2TextField.swift // DemoSocketIO // // Created by Đinh Xuân Lộc on 10/21/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import UIKit @IBDesignable open class iHBorderColorTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor = .black { didSet { updatePlaceholder() } } override open var backgroundColor: UIColor? { set { backgroundLayerColor = newValue } get { return backgroundLayerColor } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.65 { didSet { updatePlaceholder() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: CGFloat = 1 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CALayer() private var backgroundLayerColor: UIColor? // MARK: - TextFieldsEffects override open func drawViewsForRect(_ rect: CGRect) { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } override open func animateViewsForTextEntry() { borderLayer.borderColor = textColor?.cgColor borderLayer.shadowOffset = CGSize.zero borderLayer.borderWidth = borderThickness borderLayer.shadowColor = textColor?.cgColor borderLayer.shadowOpacity = 0.5 borderLayer.shadowRadius = 1 animationCompletionHandler?(.textEntry) } override open func animateViewsForTextDisplay() { borderLayer.borderColor = nil borderLayer.shadowOffset = CGSize.zero borderLayer.borderWidth = 0 borderLayer.shadowColor = nil borderLayer.shadowOpacity = 0 borderLayer.shadowRadius = 0 animationCompletionHandler?(.textDisplay) } // MARK: - Private open override func updateBorder() { borderLayer.frame = rectForBorder(frame) borderLayer.backgroundColor = backgroundColor?.cgColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder { animateViewsForTextEntry() } } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForBorder(_ bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return newRect } private func layoutPlaceholderInTextRect() { let textRect = self.textRect(forBounds: bounds) var originX = textRect.origin.x switch 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: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } override open func textRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } }
cb83b561996cd8dbfadbdfc383841e1e
30.025316
133
0.626275
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/JXPhotoBrowser/Source/Core/Enhance/JXNumberPageControlDelegate.swift
mit
1
// // JXNumberPageControlDelegate.swift // JXPhotoBrowser // // Created by JiongXing on 2018/10/15. // import Foundation /// 实现了以 数字型 为页码指示器的 Delegate. open class JXNumberPageControlDelegate: JXPhotoBrowserBaseDelegate { /// 字体 open var font = UIFont.systemFont(ofSize: 17) /// 字颜色 open var textColor = UIColor.white /// 指定Y轴从顶部往下偏移值 open lazy var offsetY: CGFloat = { if #available(iOS 11.0, *), let window = UIApplication.shared.keyWindow { return window.safeAreaInsets.top } return 20 }() /// 数字页码指示 open lazy var pageControl: UILabel = { let view = UILabel() view.font = font view.textColor = textColor return view }() open override func photoBrowser(_ browser: JXPhotoBrowser, pageIndexDidChanged pageIndex: Int) { super.photoBrowser(browser, pageIndexDidChanged: pageIndex) layout() } open override func photoBrowserViewWillLayoutSubviews(_ browser: JXPhotoBrowser) { super.photoBrowserViewWillLayoutSubviews(browser) layout() } open override func photoBrowser(_ browser: JXPhotoBrowser, viewDidAppear animated: Bool) { super.photoBrowser(browser, viewDidAppear: animated) // 页面出来后,再显示页码指示器 // 多于一张图才添加到视图 let totalPages = browser.itemsCount if totalPages > 1 { browser.view.addSubview(pageControl) } } open override func photoBrowserDidReloadData(_ browser: JXPhotoBrowser) { layout() } // // MARK: - Private // private func layout() { guard let browser = self.browser else { return } guard let superView = pageControl.superview else { return } let totalPages = browser.itemsCount pageControl.text = "\(browser.pageIndex + 1) / \(totalPages)" pageControl.sizeToFit() pageControl.center.x = superView.bounds.width / 2 pageControl.frame.origin.y = offsetY pageControl.isHidden = totalPages <= 1 } }
b118e74883cd5438e171dc93aadf316f
27.04
100
0.623871
false
false
false
false
GrandCentralBoard/GrandCentralBoard
refs/heads/develop
Pods/Operations/Sources/Core/Shared/RetryOperation.swift
gpl-3.0
2
// // RetryOperation.swift // Operations // // Created by Daniel Thorpe on 29/12/2015. // // import Foundation /** RetryFailureInfo is a value type which provides information related to a previously failed NSOperation which it is generic over. It is used in conjunction with RetryOperation. */ public struct RetryFailureInfo<T: NSOperation> { /// - returns: the failed operation public let operation: T /// - returns: the errors the operation finished with. public let errors: [ErrorType] /// - returns: all the aggregate errors of previous attempts public let aggregateErrors: [ErrorType] /// - returns: the number of attempts made so far public let count: Int /** This is a block which can be used to add operations to a queue. For example, perhaps it is necessary to retry the task, but only until another operation has completed. This can be done by creating the operation, setting the dependency and adding it using this block, before responding to the RetryOperation. - returns: a block which accects var arg NSOperation instances. */ public let addOperations: (NSOperation...) -> Void /// - returns: the `RetryOperation`'s log property. public let log: LoggerType /** - returns: the block which is used to configure operation instances before they are added to the queue */ public let configure: T -> Void } class RetryGenerator<T: NSOperation>: GeneratorType { typealias Payload = RetryOperation<T>.Payload typealias Handler = RetryOperation<T>.Handler internal let retry: Handler internal var info: RetryFailureInfo<T>? = .None private var generator: AnyGenerator<(Delay?, T)> init(generator: AnyGenerator<Payload>, retry: Handler) { self.generator = generator self.retry = retry } func next() -> Payload? { guard let payload = generator.next() else { return nil } guard let info = info else { return payload } return retry(info, payload) } } /** RetryOperation is a subclass of RepeatedOperation. Like RepeatedOperation it is generic over type T, an NSOperation subclass. It can be used to automatically retry another instance of operation T if the first operation finishes with errors. To support effective error recovery, in addition to a (Delay?, T) generator RetryOperation is initialized with a block. The block will receive failure info, in addition to the next result (if not nil) of the operation generator. The block must return (Delay?, T)?. Therefore consumers can inspect the failure info, and adjust the Delay, or operation before returning it. To finish, the block can return .None */ public class RetryOperation<T: NSOperation>: RepeatedOperation<T> { public typealias FailureInfo = RetryFailureInfo<T> public typealias Handler = (RetryFailureInfo<T>, Payload) -> Payload? let retry: RetryGenerator<T> /** A designated initializer Creates an operation which will retry executing operations in the face of errors. - parameter maxCount: an optional Int, which defaults to .None. If not nil, this is the maximum number of operations which will be executed. - parameter generator: the generator of (Delay?, T) values. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. */ public init(maxCount max: Int? = .None, generator: AnyGenerator<Payload>, retry block: Handler) { retry = RetryGenerator(generator: generator, retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } /** A designated initializer, which accepts two generators, one for the delay and another for the operation, in addition to a retry handler block - parameter maxCount: an optional Int, which defaults to .None. If not nil, this is the maximum number of operations which will be executed. - parameter delay: a generator with Delay element. - parameter generator: a generator with T element. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. */ public init<D, G where D: GeneratorType, D.Element == Delay, G: GeneratorType, G.Element == T>(maxCount max: Int? = .None, delay: D, generator: G, retry block: Handler) { let tuple = TupleGenerator(primary: generator, secondary: delay) retry = RetryGenerator(generator: AnyGenerator(tuple), retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } /** An initializer with wait strategy and generic operation generator. This is useful where another system can be responsible for vending instances of the custom operation. Typically there may be some state involved in such a Generator. e.g. The wait strategy is useful if say, you want to repeat the operations with random delays, or exponential backoff. These standard schemes and be easily expressed. ```swift class MyOperationGenerator: GeneratorType { func next() -> MyOperation? { // etc } } let operation = RetryOperation( maxCount: 3, strategy: .Random((0.1, 1.0)), generator: MyOperationGenerator() ) { info, delay, op in // inspect failure info return (delay, op) } ``` - parameter maxCount: an optional Int, which defaults to 5. - parameter strategy: a WaitStrategy which defaults to a 0.1 second fixed interval. - parameter [unnamed] generator: a generic generator which has an Element equal to T. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. This defaults to pass through the delay and operation regardless of error info. */ public init<G where G: GeneratorType, G.Element == T>(maxCount max: Int? = 5, strategy: WaitStrategy = .Fixed(0.1), _ generator: G, retry block: Handler = { $1 }) { let delay = MapGenerator(strategy.generator()) { Delay.By($0) } let tuple = TupleGenerator(primary: generator, secondary: delay) retry = RetryGenerator(generator: AnyGenerator(tuple), retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } public override func willFinishOperation(operation: NSOperation, withErrors errors: [ErrorType]) { if errors.isEmpty { retry.info = .None } else if let op = operation as? T { retry.info = createFailureInfo(op, errors: errors) addNextOperation() } } internal func createFailureInfo(operation: T, errors: [ErrorType]) -> RetryFailureInfo<T> { return RetryFailureInfo( operation: operation, errors: errors, aggregateErrors: aggregateErrors, count: count, addOperations: addOperations, log: log, configure: configure ) } }
84fed19080357062f06b39e15e397179
36.417526
174
0.678468
false
false
false
false
zjjzmw1/myGifSwift
refs/heads/master
myGifSwift/CodeFragment/Category/UIButton+IOSUtil.swift
mit
2
// // UIButton+IOSUtil.swift // niaoyutong // // Created by zhangmingwei on 2017/5/24. // Copyright © 2017年 niaoyutong. All rights reserved. // import Foundation import UIKit extension UIButton { /// - 设置按钮是否可以点击的状态 (不可点击为灰色,可点击为蓝色) public func setButtonEnabled(isEnable: Bool) { if isEnable { self.backgroundColor = UIColor.getMainColorSwift() self.setTitleColor(UIColor.white, for: .normal) self.isUserInteractionEnabled = true } else { self.backgroundColor = UIColor.colorRGB16(value: 0xececec) self.setTitleColor(UIColor.getContentSecondColorSwift(), for: .normal) self.isUserInteractionEnabled = false } } } /// MARK: - 避免按钮多次点击的方法 - (按钮的touchUpInside和Down能做到相互不影响) extension UIButton { /// 默认是0.5秒内不能重复点击按钮 private struct AssociatedKeys { static var xlx_defaultInterval:TimeInterval = 0.5 static var xlx_customInterval = "xlx_customInterval" // 需要自定义事件间隔的话例如 :TimeInterval = 1.0 static var xlx_ignoreInterval = "xlx_ignoreInterval" } // 自定义属性用来添加自定义的间隔时间。可以设置 1秒、2秒,等等 var customInterval: TimeInterval { get { let xlx_customInterval = objc_getAssociatedObject(self, &AssociatedKeys.xlx_customInterval) if let time = xlx_customInterval { return time as! TimeInterval }else{ return AssociatedKeys.xlx_defaultInterval } } set { objc_setAssociatedObject(self, &AssociatedKeys.xlx_customInterval, newValue as TimeInterval ,.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 自定义属性 - 是否忽略间隔 var ignoreInterval: Bool { get { return (objc_getAssociatedObject(self, &AssociatedKeys.xlx_ignoreInterval) != nil) } set { objc_setAssociatedObject(self, &AssociatedKeys.xlx_ignoreInterval, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } override open class func initialize() { if self == UIButton.self { DispatchQueue.once("com.wj.niaoyutong", block: { // DispatchQueue.once(NSUUID().uuidString, block: { // 先获取到系统和自己的 selector let systemSel = #selector(UIButton.sendAction(_:to:for:)) let swizzSel = #selector(UIButton.mySendAction(_:to:for:)) // 再根据seletor获取到Method let systemMethod = class_getInstanceMethod(self, systemSel) let swizzMethod = class_getInstanceMethod(self, swizzSel) /// 把系统的方法添加到类里面 - 如果存在就添加失败 let isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod)) if isAdd { class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod)); } else { method_exchangeImplementations(systemMethod, swizzMethod); } }) } } private dynamic func mySendAction(_ action: Selector, to target: Any?, for event: UIEvent?) { if !ignoreInterval { isUserInteractionEnabled = false DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+customInterval, execute: { [weak self] in self?.isUserInteractionEnabled = true }) } mySendAction(action, to: target, for: event) } }
6501747549c0a8e111a191f53b344058
36.446809
141
0.617614
false
false
false
false
weareyipyip/SwiftStylable
refs/heads/master
Sources/SwiftStylable/Classes/Style/Colors/ColorCollection.swift
mit
1
// // ColorCollection.swift // SwiftStylable // // Created by Marcel Bloemendaal on 21/09/2018. // import UIKit public class ColorCollection { private var _colorHolders = [String:ColorHolder]() // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Initializers // // ----------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------- // // MARK: - Internal methods // // ----------------------------------------------------------------------------------------------------------------------- internal func applyData(_ data:[String:String]) { var colorEntries = data var numParsedColors = 1 while colorEntries.count > 0 && numParsedColors > 0 { numParsedColors = 0 for (name, colorString) in colorEntries { if let color = UIColor(hexString: colorString) { if let colorHolder = self._colorHolders[name] { colorHolder.set(with: color) } else { self._colorHolders[name] = ColorHolder(color: color) } colorEntries.removeValue(forKey: name) numParsedColors += 1 } else if let colorHolder = self._colorHolders[colorString] { if let existingHolder = self._colorHolders[name] { existingHolder.set(with: colorHolder) } else { self._colorHolders[name] = ColorHolder(reference: colorHolder) } colorEntries.removeValue(forKey: name) numParsedColors += 1 } } } if colorEntries.count > 0 { // Not everything was parsed in the above code, this means there are unsatifyable colorStrings print("WARNING: not all colors could be parsed, this probably means a name is used, but no actual color is ever assigned to it") } } internal func colorHolderNamed(_ name:String)->ColorHolder? { return self._colorHolders[name] } }
83c6d62a2f6dee7c2a5491a57ef223c7
37.887097
140
0.425135
false
false
false
false
peferron/algo
refs/heads/master
EPI/Binary Trees/Reconstruct a binary tree from a preorder traversal with markers/swift/test.swift
mit
1
// swiftlint:disable variable_name assert(Node<Int>(preorder: []) == nil) let t = Node(preorder: [ 7, 1, 5, nil, nil, 4, 0, nil, nil, nil, 2, nil, 3, nil, 6, 8, nil, nil, nil ])! assert(t.value == 7) assert(t.left!.value == 1) assert(t.left!.left!.value == 5) assert(t.left!.right!.value == 4) assert(t.left!.right!.left!.value == 0) assert(t.right!.value == 2) assert(t.right!.right!.value == 3) assert(t.right!.right!.right!.value == 6) assert(t.right!.right!.right!.left!.value == 8)
22aed1fadb3feed753c7437167ef42a2
21.342857
47
0.392583
false
false
false
false
Pretz/SwiftGraphics
refs/heads/develop
Playgrounds/Broken or Limited Usefulness/RulerPoint.playground/contents.swift
bsd-2-clause
4
// Playground - noun: a place where people can play import Cocoa import CoreGraphics import SwiftUtilities import SwiftGraphics let size = CGSize(width: 100, height: 100) let context = CGContextRef.bitmapContext(size) context.setFillColor(CGColor.lightGrayColor()) CGContextFillRect(context, CGRect(size: size)) let p1 = CGPoint(x: 10, y: 10), p2 = CGPoint(x: 90, y: 20) context.strokeLine(p1, p2) let p3 = p2.rulerPoint(p1, dx: 0, dy: -40) context.strokeLine(p2, p3) let p4 = p3.rulerPoint(p1, dx: 40) context.strokeLine(p3, p4) let p5 = p4.rulerPoint(p3, dx: 0, dy: 40) context.strokeLine(p4, p5) let p6 = p4.rulerPoint(p5, dx: 20, dy: 20) context.strokeLine(p5, p6) context.nsimage
afa31a045e8df38dd6b7f0c861d07dbf
22.931034
58
0.730548
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/MySkillsViewController.swift
lgpl-2.1
2
// // MySkillsViewController.swift // Neocom // // Created by Artem Shimanski on 10/30/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import TreeController import Futures class MySkillsViewController: PageViewController, ContentProviderView { typealias Presenter = MySkillsPresenter lazy var presenter: Presenter! = Presenter(view: self) var unwinder: Unwinder? func present(_ content: Presenter.Presentation, animated: Bool) -> Future<Void> { let pages = viewControllers as? [MySkillsPageViewController] zip((0..<4), [content.all, content.canTrain, content.notKnown, content.all]).forEach { pages?[$0].input = $1 pages?[$0].presenter.reloadIfNeeded() } return .init(()) } func fail(_ error: Error) { let pages = viewControllers as? [MySkillsPageViewController] pages?.forEach { $0.fail(error) } } override func viewDidLoad() { super.viewDidLoad() presenter.configure() try! viewControllers = [NSLocalizedString("My", comment: ""), NSLocalizedString("Can Train", comment: ""), NSLocalizedString("Not Known", comment: ""), NSLocalizedString("All", comment: "")].map { title -> UIViewController in let view = try MySkillsPage.default.instantiate([]).get() view.title = title return view } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presenter.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) presenter.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.viewDidDisappear(animated) } }
126c7e7b8b3ef8ead45907a07c10e802
24.452055
88
0.707212
false
false
false
false
sstanic/VirtualTourist
refs/heads/master
VirtualTourist/VirtualTourist/PhotoDetailViewController.swift
mit
1
// // PhotoDetailViewController.swift // VirtualTourist // // Created by Sascha Stanic on 24.06.16. // Copyright © 2016 Sascha Stanic. All rights reserved. // import Foundation import UIKit class PhotoDetailViewController: UIViewController { //# MARK: Outlets @IBOutlet weak var imageView: UIImageView! //# MARK: Attributes var image: UIImage? //# MARK: Overrides override func viewDidLoad() { super.viewDidLoad() if let image = image { imageView.image = image } initializeGestureRecognizer() } //# MARK: - Gesture Recognizer fileprivate func initializeGestureRecognizer() { let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(pinchImage)) imageView.addGestureRecognizer(pinchGestureRecognizer) let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panImage)) imageView.addGestureRecognizer(panGestureRecognizer) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapImage)) tapGestureRecognizer.numberOfTapsRequired = 2 imageView.addGestureRecognizer(tapGestureRecognizer) } @objc func pinchImage(_ gestureRecognizer: UIPinchGestureRecognizer) { let scale: CGFloat = gestureRecognizer.scale; gestureRecognizer.view!.transform = gestureRecognizer.view!.transform.scaledBy(x: scale, y: scale); gestureRecognizer.scale = 1.0; } @objc func panImage(_ gestureRecognizer: UIPanGestureRecognizer) { let translate = gestureRecognizer.translation(in: self.view) gestureRecognizer.view!.center = CGPoint(x:gestureRecognizer.view!.center.x + translate.x, y:gestureRecognizer.view!.center.y + translate.y) gestureRecognizer.setTranslation(CGPoint.zero, in: self.view) } @objc func tapImage(_ gestureRecognizer: UITapGestureRecognizer) { imageView.frame = self.view.frame } }
7b2d448a2a74f934dbd6318c06873061
30.833333
148
0.674441
false
false
false
false
Amefuri/ZSwiftKit
refs/heads/master
ZSwiftKit/Classes/Helper+Data.swift
mit
1
// // Helper+Data.swift // fleet // // Created by peerapat atawatana on 7/29/2559 BE. // Copyright © 2559 DaydreamClover. All rights reserved. // import Foundation public extension Helper { struct Data { // To document folder as root, support only one level folder public static func saveData(_ data:Foundation.Data, folder:String , filename:String)-> String { // Always Attempt to Create Folder do { let photoFolder = Helper.getDocumentsDirectory().appendingPathComponent(folder) try FileManager.default.createDirectory(atPath: photoFolder, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { NSLog("\(error.localizedDescription)") } // Compose filepath and write to file let filePath = folder+"/"+filename let filePathFull = Helper.getDocumentsDirectory().appendingPathComponent(filePath) try? data.write(to: URL(fileURLWithPath: filePathFull), options: [.atomic]) return filePath } public static func loadData(_ path:String)-> Foundation.Data? { let loadPath = Helper.getDocumentsDirectory().appendingPathComponent(path) return (try? Foundation.Data(contentsOf: URL(fileURLWithPath: loadPath))) } public static func deleteData(_ path:String) { do { let fullPath = Helper.getDocumentsDirectory().appendingPathComponent(path) try FileManager.default.removeItem(atPath: fullPath) } catch let error as NSError { NSLog("\(error.localizedDescription)") } } } }
4382e4a8398f30c849404a97e37fa8fc
32.25
120
0.678571
false
false
false
false
CRAnimation/CRAnimation
refs/heads/master
Example/CRAnimation/Demo/WidgetDemo/S0016_NVActivityIndicatorView/NVActivityIndicatorViewDemoVC.swift
mit
1
// // ViewController.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 Foundation import NVActivityIndicatorView class NVActivityIndicatorViewDemoVC: CRProductionBaseVC, NVActivityIndicatorViewable { override func viewDidLoad() { super.viewDidLoad() addTopBar(withTitle: "NVActivityIndicatorView") self.view.backgroundColor = color_0a090e let cols = 4 let rows = 8 let cellWidth = Int(self.view.frame.width / CGFloat(cols)) let cellHeight = Int((self.view.frame.height - 64.0) / CGFloat(rows)) (NVActivityIndicatorType.ballPulse.rawValue ... NVActivityIndicatorType.audioEqualizer.rawValue).forEach { let x = ($0 - 1) % cols * cellWidth let y = ($0 - 1) / cols * cellHeight + 64 let frame = CGRect(x: x, y: y, width: cellWidth, height: cellHeight) let activityIndicatorView = NVActivityIndicatorView(frame: frame, type: NVActivityIndicatorType(rawValue: $0)!) let animationTypeLabel = UILabel(frame: frame) animationTypeLabel.text = String($0) animationTypeLabel.sizeToFit() animationTypeLabel.textColor = UIColor.white animationTypeLabel.frame.origin.x += 5 animationTypeLabel.frame.origin.y += CGFloat(cellHeight) - animationTypeLabel.frame.size.height activityIndicatorView.padding = 20 if $0 == NVActivityIndicatorType.orbit.rawValue { activityIndicatorView.padding = 0 } self.view.addSubview(activityIndicatorView) self.view.addSubview(animationTypeLabel) activityIndicatorView.startAnimating() let button: UIButton = UIButton(frame: frame) button.tag = $0 button.addTarget(self, action: #selector(buttonTapped(_:)), for: UIControlEvents.touchUpInside) self.view.addSubview(button) } } func buttonTapped(_ sender: UIButton) { let size = CGSize(width: 30, height: 30) startAnimating(size, message: "Loading...", type: NVActivityIndicatorType(rawValue: sender.tag)!) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) { NVActivityIndicatorPresenter.sharedInstance.setMessage("Authenticating...") } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { self.stopAnimating() } } }
70e4e586557534880a4e29fb2f44be46
40.617978
114
0.664417
false
false
false
false
CodaFi/swiftz
refs/heads/master
Sources/Swiftz/Stream.swift
apache-2.0
3
// // Stream.swift // Swiftz // // Created by Robert Widmann on 8/19/15. // Copyright © 2015-2016 TypeLift. All rights reserved. // #if SWIFT_PACKAGE import Operadics import Swiftx #endif /// A lazy infinite sequence of values. /// /// A `Stream` can be thought of as a function indexed by positions - stopping /// points at which the the function yields a value back. Rather than hold the /// entire domain and range of the function in memory, the `Stream` is aware of /// the current initial point and a way of garnering any subsequent points. /// /// A Stream is optimized for access to its head, which occurs in O(1). Element /// access is O(index) and is made even more expensive by implicit repeated /// evaluation of complex streams. /// /// Because `Stream`s and their assorted operations are lazy, building up a /// `Stream` from a large amount of combinators will necessarily increase the /// cost of forcing the stream down the line. In addition, due to the fact that /// a `Stream` is an infinite structure, attempting to traverse the `Stream` in /// a non-lazy manner will diverge e.g. invoking `.forEach(_:)` or using `zip` /// with an eager structure and a `Stream`. public struct Stream<Element> { fileprivate let step : () -> (Element, Stream<Element>) fileprivate init(_ step : @escaping () -> (Element, Stream<Element>)) { self.step = step } /// Uses function to construct a `Stream`. /// /// Unlike unfold for lists, unfolds to construct a `Stream` have no base /// case. public static func unfold<A>(_ initial : A, _ f : @escaping (A) -> (Element, A)) -> Stream<Element> { let (x, d) = f(initial) return Stream { (x, Stream.unfold(d, f)) } } /// Repeats a value into a constant stream of that same value. public static func `repeat`(_ x : Element) -> Stream<Element> { return Stream { (x, `repeat`(x)) } } /// Returns a `Stream` of an infinite number of iteratations of applications /// of a function to a value. public static func iterate(_ initial : Element, _ f : @escaping (Element) -> Element)-> Stream<Element> { return Stream { (initial, Stream.iterate(f(initial), f)) } } /// Cycles a non-empty list into an infinite `Stream` of repeating values. /// /// This function is partial with respect to the empty list. public static func cycle(_ xs : [Element]) -> Stream<Element> { switch xs.match { case .Nil: return error("Cannot cycle an empty list.") case .Cons(let x, let xs): return Stream { (x, cycle(xs + [x])) } } } public subscript(n : UInt) -> Element { return self.index(n) } /// Looks up the nth element of a `Stream`. public func index(_ n : UInt) -> Element { if n == 0 { return self.head } return self.tail.index(n.advanced(by: -1)) } /// Returns the first element of a `Stream`. public var head : Element { return self.step().0 } /// Returns the remaining elements of a `Stream`. public var tail : Stream<Element> { return self.step().1 } /// Returns a `Stream` of all initial segments of a `Stream`. public var inits : Stream<[Element]> { return Stream<[Element]> { ([], self.tail.inits.fmap({ $0.cons(self.head) })) } } /// Returns a `Stream` of all final segments of a `Stream`. public var tails : Stream<Stream<Element>> { return Stream<Stream<Element>> { (self, self.tail.tails) } } /// Returns a pair of the first n elements and the remaining eleemnts in a /// `Stream`. public func splitAt(_ n : UInt) -> ([Element], Stream<Element>) { if n == 0 { return ([], self) } let (p, r) = self.tail.splitAt(n - 1) return (p.cons(self.head), r) } /// Returns the longest prefix of values in a `Stream` for which a predicate /// holds. public func takeWhile(_ p : (Element) -> Bool) -> [Element] { if p(self.head) { return self.tail.takeWhile(p).cons(self.head) } return [] } /// Returns the longest suffix remaining after a predicate holds. public func dropWhile(_ p : (Element) -> Bool) -> Stream<Element> { if p(self.head) { return self.tail.dropWhile(p) } return self } /// Returns the first n elements of a `Stream`. public func take(_ n : UInt) -> [Element] { if n == 0 { return [] } return self.tail.take(n - 1).cons(self.head) } /// Returns a `Stream` with the first n elements removed. public func drop(_ n : UInt) -> Stream<Element> { if n == 0 { return self } return self.tail.drop(n - 1) } /// Removes elements from the `Stream` that do not satisfy a given predicate. /// /// If there are no elements that satisfy this predicate this function will diverge. public func filter(_ predicate : @escaping (Element) -> Bool) -> Stream<Element> { if predicate(self.head) { return Stream { (self.head, self.tail.filter(predicate)) } } return self.tail.filter(predicate) } /// Returns a `Stream` of alternating elements from each Stream. public func interleaveWith(_ s2 : Stream<Element>) -> Stream<Element> { return Stream { (self.head, s2.interleaveWith(self.tail)) } } /// Creates a `Stream` alternating an element in between the values of /// another Stream. public func intersperse(_ x : Element) -> Stream<Element> { return Stream { (self.head, Stream { (x, self.tail.intersperse(x)) } ) } } /// Returns a `Stream` of successive reduced values. public func scanl<A>(_ initial : A, combine : @escaping (A) -> (Element) -> A) -> Stream<A> { return Stream<A> { (initial, self.tail.scanl(combine(initial)(self.head), combine: combine)) } } /// Returns a `Stream` of successive reduced values. public func scanl1(_ f : @escaping (Element) -> (Element) -> Element) -> Stream<Element> { return self.tail.scanl(self.head, combine: f) } } /// Transposes the "Rows and Columns" of an infinite Stream. public func transpose<T>(_ ss : Stream<Stream<T>>) -> Stream<Stream<T>> { let xs = ss.head let yss = ss.tail return Stream({ (Stream({ (xs.head, yss.fmap{ $0.head }) }), transpose(Stream({ (xs.tail, yss.fmap{ $0.tail }) }) )) }) } /// Zips two `Stream`s into a third Stream using a combining function. public func zipWith<A, B, C>(_ s1 : Stream<A>, _ s2 : Stream<B>, _ f : @escaping (A) -> (B) -> C) -> Stream<C> { return Stream({ (f(s1.head)(s2.head), zipWith(s1.tail, s2.tail, f)) }) } /// Unzips a `Stream` of pairs into a pair of Streams. public func unzip<A, B>(sp : Stream<(A, B)>) -> (Stream<A>, Stream<B>) { return (sp.fmap(fst), sp.fmap(snd)) } extension Stream /*: Functor*/ { public typealias A = Element public typealias B = Any public typealias FB = Stream<B> public func fmap<B>(_ f : @escaping (A) -> B) -> Stream<B> { return Stream<B>({ (f(self.head), self.tail.fmap(f)) }) } } public func <^> <A, B>(_ f : @escaping (A) -> B, b : Stream<A>) -> Stream<B> { return b.fmap(f) } extension Stream /*: Pointed*/ { public static func pure(_ x : A) -> Stream<A> { return `repeat`(x) } } extension Stream /*: Applicative*/ { public typealias FAB = Stream<(A) -> B> public func ap<B>(_ fab : Stream<(A) -> B>) -> Stream<B> { let f = fab.head let fs = fab.tail let x = self.head let xss = self.tail return Stream<B>({ (f(x), (fs <*> xss)) }) } } public func <*> <A, B>(_ f : Stream<(A) -> B> , o : Stream<A>) -> Stream<B> { return o.ap(f) } extension Stream /*: Cartesian*/ { public typealias FTOP = Stream<()> public typealias FTAB = Stream<(A, B)> public typealias FTABC = Stream<(A, B, C)> public typealias FTABCD = Stream<(A, B, C, D)> public static var unit : Stream<()> { return Stream<()>.`repeat`(()) } public func product<B>(_ r : Stream<B>) -> Stream<(A, B)> { return zipWith(self, r, { x in { y in (x, y) } }) } public func product<B, C>(_ r : Stream<B>, _ s : Stream<C>) -> Stream<(A, B, C)> { return Stream.liftA3({ x in { y in { z in (x, y, z) } } })(self)(r)(s) } public func product<B, C, D>(_ r : Stream<B>, _ s : Stream<C>, _ t : Stream<D>) -> Stream<(A, B, C, D)> { return { x in { y in { z in { w in (x, y, z, w) } } } } <^> self <*> r <*> s <*> t } } extension Stream /*: ApplicativeOps*/ { public typealias C = Any public typealias FC = Stream<C> public typealias D = Any public typealias FD = Stream<D> public static func liftA<B>(_ f : @escaping (A) -> B) -> (Stream<A>) -> Stream<B> { return { (a : Stream<A>) -> Stream<B> in Stream<(A) -> B>.pure(f) <*> a } } public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Stream<A>) -> (Stream<B>) -> Stream<C> { return { (a : Stream<A>) -> (Stream<B>) -> Stream<C> in { (b : Stream<B>) -> Stream<C> in f <^> a <*> b } } } public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Stream<A>) -> (Stream<B>) -> (Stream<C>) -> Stream<D> { return { (a : Stream<A>) -> (Stream<B>) -> (Stream<C>) -> Stream<D> in { (b : Stream<B>) -> (Stream<C>) -> Stream<D> in { (c : Stream<C>) -> Stream<D> in f <^> a <*> b <*> c } } } } } extension Stream /*: Monad*/ { public func bind<B>(_ f : @escaping (A) -> Stream<B>) -> Stream<B> { return Stream<B>.unfold(self.fmap(f)) { ss in let bs = ss.head let bss = ss.tail return (bs.head, bss.fmap({ $0.tail })) } } } public func >>- <A, B>(x : Stream<A>, f : @escaping (A) -> Stream<B>) -> Stream<B> { return x.bind(f) } extension Stream /*: MonadOps*/ { public static func liftM<B>(_ f : @escaping (A) -> B) -> (Stream<A>) -> Stream<B> { return { (m1 : Stream<A>) -> Stream<B> in m1 >>- { (x1 : A) in Stream<B>.pure(f(x1)) } } } public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> (Stream<A>) -> (Stream<B>) -> Stream<C> { return { (m1 : Stream<A>) -> (Stream<B>) -> Stream<C> in { (m2 : Stream<B>) -> Stream<C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in Stream<C>.pure(f(x1)(x2)) } } } } } public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Stream<A>) -> (Stream<B>) -> (Stream<C>) -> Stream<D> { return { (m1 : Stream<A>) -> (Stream<B>) -> (Stream<C>) -> Stream<D> in { (m2 : Stream<B>) -> (Stream<C>) -> Stream<D> in { (m3 : Stream<C>) -> Stream<D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in Stream<D>.pure(f(x1)(x2)(x3)) } } } } } } } } public func >>->> <A, B, C>(_ f : @escaping (A) -> Stream<B>, g : @escaping (B) -> Stream<C>) -> ((A) -> Stream<C>) { return { x in f(x) >>- g } } public func <<-<< <A, B, C>(g : @escaping (B) -> Stream<C>, f : @escaping (A) -> Stream<B>) -> ((A) -> Stream<C>) { return f >>->> g } extension Stream : Copointed { public func extract() -> A { return self.head } } extension Stream /*: Comonad*/ { public typealias FFA = Stream<Stream<A>> public func duplicate() -> Stream<Stream<A>> { return self.tails } public func extend<B>(_ f : @escaping (Stream<A>) -> B) -> Stream<B> { return Stream<B>({ (f(self), self.tail.extend(f)) }) } } extension Stream : ExpressibleByArrayLiteral { public init(fromArray arr : [Element]) { self = Stream.cycle(arr) } public init(arrayLiteral s : Element...) { self.init(fromArray: s) } } public final class StreamIterator<Element> : IteratorProtocol { var l : Stream<Element> public func next() -> Optional<Element> { let (hd, tl) = l.step() l = tl return hd } public init(_ l : Stream<Element>) { self.l = l } } extension Stream : Sequence { public typealias Iterator = StreamIterator<Element> public func makeIterator() -> StreamIterator<Element> { return StreamIterator(self) } } extension Stream : Collection { /// 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 value immediately after `i`. public func index(after i : UInt) -> UInt { return i + 1 } public typealias Index = UInt public var startIndex : UInt { return 0 } public var endIndex : UInt { return error("An infinite list has no end index.") } } extension Stream : CustomStringConvertible { public var description : String { return "[\(self.head), ...]" } } public func sequence<A>(_ ms : [Stream<A>]) -> Stream<[A]> { return ms.reduce(Stream<[A]>.pure([]), { n, m in return n.bind { xs in return m.bind { x in return Stream<[A]>.pure(xs + [x]) } } }) }
3ad1c816efb52fd68108f0e4fc2ea1eb
30.453608
263
0.611439
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Sources/ComponentBase/Views/AspectRatioConstrainedImageView.swift
mit
1
import UIKit public class AspectRatioConstrainedImageView: UIImageView { private var aspectRatioConstraint: NSLayoutConstraint? override public init(frame: CGRect) { super.init(frame: frame) contentMode = .scaleAspectFit } required init?(coder: NSCoder) { super.init(coder: coder) contentMode = .scaleAspectFit } override public var image: UIImage? { didSet { aspectRatioConstraint.map(removeConstraint) aspectRatioConstraint = nil if let image = image { let size = image.size let constraint = NSLayoutConstraint( item: self, attribute: .height, relatedBy: .equal, toItem: self, attribute: .width, multiplier: size.height / size.width, constant: 0 ) constraint.identifier = "Image Aspect Ratio" constraint.priority = .defaultHigh aspectRatioConstraint = constraint constraint.isActive = true } } } override public var intrinsicContentSize: CGSize { CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric) } }
6170bebd2df3b19c4a3a78b90d93ff8f
28.638298
81
0.529792
false
false
false
false
snowpunch/AppLove
refs/heads/develop
App Love/Network/AppListEmail.swift
mit
1
// // AppListEmail.swift // App Love // // Created by Woodie Dovich on 2016-07-27. // Copyright © 2016 Snowpunch. All rights reserved. // import UIKit import MessageUI class AppListEmail: NSObject { class func generateAppList() -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.setSubject("App Links") let appModels = AppList.sharedInst.appModels var msgBody = "<small><b>Check out these Apps!</b><br></small>" for app in appModels { let appName = truncateAppName(app.appName) msgBody += "<small><a href='https://itunes.apple.com/app/id\(app.appId)'>\(appName)</a></small><br>" } let appLovePlug = "<small><br>List generated by <a href='https://itunes.apple.com/app/id\(Const.appId.AppLove)'>App Love.</a></small>" msgBody += appLovePlug mailComposerVC.setMessageBody(msgBody, isHTML: true) return mailComposerVC } // cut off app name at '-' dash, then limit to 30 characters for email. class func truncateAppName(originalAppName:String?) -> String { let fullAppName = originalAppName ?? "" let fullNameArray = fullAppName.characters.split("-").map{ String($0) } var appName = fullNameArray.first ?? "" if appName != fullAppName { appName = appName + "..." } let truncatedAppName = appName.truncate(30) return truncatedAppName } }
f1235b0b176d72e7f3dc17c829e5b224
33.181818
142
0.630073
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
refs/heads/develop
DuckDuckGo/Version.swift
apache-2.0
1
// // Version.swift // DuckDuckGo // // Created by Mia Alexiou on 30/01/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import Foundation import Core public struct Version { struct Keys { static let name = kCFBundleNameKey as String static let buildNumber = kCFBundleVersionKey as String static let versionNumber = "CFBundleShortVersionString" } private let bundle: InfoBundle init(bundle: InfoBundle) { self.bundle = bundle } init() { self.init(bundle: Bundle.main) } func name() -> String? { return bundle.object(forInfoDictionaryKey: Version.Keys.name) as? String } func versionNumber() -> String? { return bundle.object(forInfoDictionaryKey: Version.Keys.versionNumber) as? String } func buildNumber() -> String? { return bundle.object(forInfoDictionaryKey: Version.Keys.buildNumber) as? String } func localized() -> String? { guard let name = name() else { return nil } guard let versionNumber = versionNumber() else { return nil } guard let buildNumber = buildNumber() else { return nil } guard (versionNumber != buildNumber) else { return String.localizedStringWithFormat(UserText.appInfo, name, versionNumber) } return String.localizedStringWithFormat(UserText.appInfoWithBuild, name, versionNumber, buildNumber) } }
0454036a47e5b837613078ed49913b5d
26.555556
108
0.641129
false
false
false
false
manavgabhawala/swift
refs/heads/master
test/SILGen/accessors.swift
apache-2.0
1
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s // Hold a reference to do to magically become non-POD. class Reference {} // A struct with a non-mutating getter and a mutating setter. struct OrdinarySub { var ptr = Reference() subscript(value: Int) -> Int { get { return value } set {} } } class A { var array = OrdinarySub() } func index0() -> Int { return 0 } func index1() -> Int { return 1 } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // Verify that there is no unnecessary extra copy_value of ref.array. // rdar://19002913 func test0(_ ref: A) { ref.array[index0()] = ref.array[index1()] } // CHECK: sil hidden @_T09accessors5test0yAA1ACF : $@convention(thin) (@owned A) -> () { // CHECK: bb0([[ARG:%.*]] : $A): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: [[BORROWED_ARG_LHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: [[BORROWED_ARG_RHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = class_method [[BORROWED_ARG_RHS]] : $A, #A.array!getter.1 // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_ARG_RHS]]) // CHECK-NEXT: store [[T1]] to [init] [[TEMP]] // CHECK-NEXT: [[T0:%.*]] = load_borrow [[TEMP]] // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T1:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptS2icfg // CHECK-NEXT: [[VALUE:%.*]] = apply [[T1]]([[INDEX1]], [[T0]]) // CHECK-NEXT: end_borrow [[T0]] from [[TEMP]] // CHECK-NEXT: destroy_addr [[TEMP]] // Formal access to LHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $OrdinarySub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_LHS]] : $A, #A.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[BORROWED_ARG_LHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*OrdinarySub on [[BORROWED_ARG_LHS]] : $A // CHECK-NEXT: // function_ref accessors.OrdinarySub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11OrdinarySubV9subscriptS2icfs // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout A, @thick A.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $A // SEMANTIC SIL TODO: This is an issue caused by the callback for materializeForSet in the class case taking the value as @inout when it should really take it as @guaranteed. // CHECK-NEXT: store_borrow [[BORROWED_ARG_LHS]] to [[TEMP2]] : $*A // CHECK-NEXT: [[T0:%.*]] = metatype $@thick A.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*OrdinarySub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[BORROWED_ARG_RHS]] from [[ARG]] // CHECK-NEXT: end_borrow [[BORROWED_ARG_LHS]] from [[ARG]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // A struct with a mutating getter and a mutating setter. struct MutatingSub { var ptr = Reference() subscript(value: Int) -> Int { mutating get { return value } set {} } } class B { var array = MutatingSub() } func test1(_ ref: B) { ref.array[index0()] = ref.array[index1()] } // CHECK-LABEL: sil hidden @_T09accessors5test1yAA1BCF : $@convention(thin) (@owned B) -> () { // CHECK: bb0([[ARG:%.*]] : $B): // CHECK-NEXT: debug_value // Formal evaluation of LHS. // CHECK-NEXT: [[BORROWED_ARG_LHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index0 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index0SiyF // CHECK-NEXT: [[INDEX0:%.*]] = apply [[T0]]() // Formal evaluation of RHS. // CHECK-NEXT: [[BORROWED_ARG_RHS:%.*]] = begin_borrow [[ARG]] // CHECK-NEXT: // function_ref accessors.index1 () -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors6index1SiyF // CHECK-NEXT: [[INDEX1:%.*]] = apply [[T0]]() // Formal access to RHS. // CHECK-NEXT: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_RHS]] : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE]], [[BORROWED_ARG_RHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_RHS]] : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.getter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptS2icfg : $@convention(method) (Int, @inout MutatingSub) -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[T0]]([[INDEX1]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store_borrow [[BORROWED_ARG_RHS]] to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // // CHECK: [[CONT]]: // Formal access to LHS. // CHECK-NEXT: [[STORAGE2:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK-NEXT: [[BUFFER2:%.*]] = alloc_stack $MutatingSub // CHECK-NEXT: [[T0:%.*]] = address_to_pointer [[BUFFER2]] // CHECK-NEXT: [[T1:%.*]] = class_method [[BORROWED_ARG_LHS]] : $B, #B.array!materializeForSet.1 // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], [[STORAGE2]], [[BORROWED_ARG_LHS]]) // CHECK-NEXT: [[T3:%.*]] = tuple_extract [[T2]] {{.*}}, 0 // CHECK-NEXT: [[OPT_CALLBACK:%.*]] = tuple_extract [[T2]] {{.*}}, 1 // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[ADDR:%.*]] = mark_dependence [[T4]] : $*MutatingSub on [[BORROWED_ARG_LHS]] : $B // CHECK-NEXT: // function_ref accessors.MutatingSub.subscript.setter : (Swift.Int) -> Swift.Int // CHECK-NEXT: [[T0:%.*]] = function_ref @_T09accessors11MutatingSubV9subscriptS2icfs : $@convention(method) (Int, Int, @inout MutatingSub) -> () // CHECK-NEXT: apply [[T0]]([[VALUE]], [[INDEX0]], [[ADDR]]) // CHECK-NEXT: switch_enum [[OPT_CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: [[WRITEBACK:bb[0-9]+]], case #Optional.none!enumelt: [[CONT:bb[0-9]+]] // // CHECK: [[WRITEBACK]]([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer): // CHECK-NEXT: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout B, @thick B.Type) -> () // CHECK-NEXT: [[TEMP2:%.*]] = alloc_stack $B // CHECK-NEXT: store_borrow [[BORROWED_ARG_LHS]] to [[TEMP2]] : $*B // CHECK-NEXT: [[T0:%.*]] = metatype $@thick B.Type // CHECK-NEXT: [[T1:%.*]] = address_to_pointer [[ADDR]] : $*MutatingSub to $Builtin.RawPointer // CHECK-NEXT: apply [[CALLBACK]]([[T1]], [[STORAGE2]], [[TEMP2]], [[T0]]) // CHECK-NEXT: dealloc_stack [[TEMP2]] // CHECK-NEXT: br [[CONT]] // // CHECK: [[CONT]]: // CHECK-NEXT: dealloc_stack [[BUFFER2]] // CHECK-NEXT: dealloc_stack [[STORAGE2]] // CHECK-NEXT: dealloc_stack [[BUFFER]] // CHECK-NEXT: dealloc_stack [[STORAGE]] // CHECK: end_borrow [[BORROWED_ARG_RHS]] from [[ARG]] // CHECK: end_borrow [[BORROWED_ARG_LHS]] from [[ARG]] // Balance out the +1 from the function parameter. // CHECK-NEXT: destroy_value [[ARG]] // CHECK-NEXT: tuple () // CHECK-NEXT: return struct RecInner { subscript(i: Int) -> Int { get { return i } } } struct RecOuter { var inner : RecInner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec(_ outer: inout RecOuter) -> Int { return outer.inner[0] } // This uses the immutable addressor. // CHECK: sil hidden @_T09accessors8test_recSiAA8RecOuterVzF : $@convention(thin) (@inout RecOuter) -> Int { // CHECK: function_ref @_T09accessors8RecOuterV5innerAA0B5InnerVflu : $@convention(method) (RecOuter) -> UnsafePointer<RecInner> struct Rec2Inner { subscript(i: Int) -> Int { mutating get { return i } } } struct Rec2Outer { var inner : Rec2Inner { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } func test_rec2(_ outer: inout Rec2Outer) -> Int { return outer.inner[0] } // This uses the mutable addressor. // CHECK: sil hidden @_T09accessors9test_rec2SiAA9Rec2OuterVzF : $@convention(thin) (@inout Rec2Outer) -> Int { // CHECK: function_ref @_T09accessors9Rec2OuterV5innerAA0B5InnerVfau : $@convention(method) (@inout Rec2Outer) -> UnsafeMutablePointer<Rec2Inner>
98dc995e4934ea4211c5a7913c04a763
50.103774
208
0.635407
false
false
false
false
kamawshuang/iOS9--Study
refs/heads/master
iOS9-CoreSpotlight(一)/iOS9-CoreSpotlight/iOS9-CoreSpotlight/DataSource.swift
apache-2.0
1
// // DataSource.swift // iOS9-CoreSpotlight // // Created by 51Testing on 15/11/11. // Copyright © 2015年 HHW. All rights reserved. // import UIKit import CoreSpotlight class DataSource: NSObject { var peopleArray: [PersonModel] //为验证输出信息 //let identifier = "com.hhw.identifier|" let identifier = "" override init() { let becky = PersonModel() becky.name = "Becky" becky.id = "1" becky.image = UIImage(named: "becky")! let ben = PersonModel() ben.name = "Ben" ben.id = "2" ben.image = UIImage(named: "ben")! let jane = PersonModel() jane.name = "Jane" jane.id = "3" jane.image = UIImage(named: "jane")! let pete = PersonModel() pete.name = "Pete" pete.id = "4" pete.image = UIImage(named: "pete")! let ray = PersonModel() ray.name = "Ray" ray.id = "5" ray.image = UIImage(named: "ray")! let tom = PersonModel() tom.name = "Tom" tom.id = "6" tom.image = UIImage(named: "tom")! peopleArray = [becky, ben, jane, pete, ray, tom]; } func friendFromID(id: String) -> PersonModel? { for person in peopleArray { if person.id == id { return person } } return nil } func savePeopleToIndex() { /* * 注意:当第一次创建完Item后,如果需要更改,目前测试了好多,它不会随着你的插入而替换更新,需要删除再次添加 */ //定义一个CSSearchableItem类型的数组,为SearchSpotlight提供筛选的Item var searchableItems = [CSSearchableItem]() for person in peopleArray { //创建搜索时显示的Item,属性有很多,下面对常用的title、contentDescription、thumbnailData进行设置; let set = CSSearchableItemAttributeSet(itemContentType: "image" as String) set.title = person.name set.contentDescription = "This is \(person.name)" set.thumbnailData = UIImagePNGRepresentation(person.image) //以唯一的Identifier为索引,存储暴露在系统存储的控件 let item = CSSearchableItem(uniqueIdentifier: person.id, domainIdentifier: "hhw", attributeSet: set) searchableItems.append(item) } //设置搜索时显示的位置 CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { error -> Void in if error != nil { print(error?.localizedDescription) } } } //删除 func deleteItem(person: PersonModel){ let identifiers = ["\(identifier) \(person.id)"] CSSearchableIndex.defaultSearchableIndex().deleteSearchableItemsWithIdentifiers(identifiers) { (error) -> Void in print(error?.localizedDescription) } } }
43ff9d77ffc7e3e678e717ef8217ad62
24.928571
121
0.54511
false
false
false
false
zpz1237/NirWebImage
refs/heads/master
ImageCache.swift
mit
1
// // ImageCache.swift // NirWebImage // // Created by Nirvana on 11/15/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit public typealias RetrieveImageDiskTask = dispatch_block_t private let cacheReverseDNS = "com.NirWebImage.ImageCache." private let ioQueueName = "com.NirWebImage.ImageCache.ioQueue." private let processQueueName = "com.NirWebImage.ImageCache.processQueue." public let NirWebImageDidCleanDiskCacheNotification = "com.NirWebImage.DidCleanDiskCacheNotification" public let NirWebImageDiskCacheCleanedHashKey = "com.NirWebImage.cleanedHash" private let defaultCacheName = "default" private let defaultCacheInstance = ImageCache(name: defaultCacheName) private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 public enum CacheType { case None, Memory, Disk } public class ImageCache { //内存缓存 private let memoryCache = NSCache() public var maxMemoryCost: UInt = 0 { didSet { self.memoryCache.totalCostLimit = Int(maxMemoryCost) } } //硬盘缓存 private let ioQueue: dispatch_queue_t private let diskCachePath: String private var fileManager: NSFileManager! //最大缓存时长 public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond //最大缓存大小,零意味着无限制 public var MaxDiskCacheSize: UInt = 0 private let processQueue: dispatch_queue_t public class var defaultCache: ImageCache { return defaultCacheInstance } public init(name: String) { if name.isEmpty { fatalError() } let cacheName = cacheReverseDNS + name memoryCache.name = cacheName let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) diskCachePath = (paths.first! as NSString).stringByAppendingPathComponent(cacheName) ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL) processQueue = dispatch_queue_create(processQueueName, DISPATCH_QUEUE_CONCURRENT) dispatch_sync(ioQueue) { () -> Void in self.fileManager = NSFileManager() } NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } public extension ImageCache { public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) { storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil) } public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) { memoryCache.setObject(image, forKey: key, cost: image.nir_imageCost) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue(), { () -> Void in handler() }) } } if toDisk { dispatch_async(ioQueue, { () -> Void in let imageFormat: ImageFormat if let originalData = originalData { imageFormat = originalData.nir_imageFormat } else { imageFormat = .Unknown } let data: NSData? switch imageFormat { case .PNG: data = UIImagePNGRepresentation(image) case .JPEG: data = UIImageJPEGRepresentation(image, 1.0) case .GIF: data = UIImageGIFRepresentation(image) case .Unknown: data = originalData } if let data = data { if !self.fileManager.fileExistsAtPath(self.diskCachePath) { do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch { } } self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil) callHandlerInMainQueue() } else { callHandlerInMainQueue() } }) } else { callHandlerInMainQueue() } } public func removeImageForKey(key: String) { removeImageForKey(key, fromDisk: true, completionHandler: nil) } public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) { memoryCache.removeObjectForKey(key) func callHandlerInMainQueue() { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue(), { () -> Void in handler() }) } } if fromDisk { dispatch_async(ioQueue, { () -> Void in do { try self.fileManager.removeItemAtPath(self.cachePathForKey(key)) } catch { } }) } else { callHandlerInMainQueue() } } } extension ImageCache { public func retrieveImageForKey(key: String, options: NirWebImageManager.Options, completionHandler: ((UIImage?,CacheType!) -> ())?) -> RetrieveImageDiskTask? { guard let completionHandler = completionHandler else { return nil } var block: RetrieveImageDiskTask? if let image = self.retrieveImageInMemoryCacheForKey(key) { if options.shouldDecode { dispatch_async(self.processQueue, { () -> Void in let result = image.nir_decodeImage(scale: options.scale) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) }) }) } else { completionHandler(image, .Memory) } } else { var sSelf: ImageCache! = self block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, { () -> Void in dispatch_async(sSelf.ioQueue, { () -> Void in if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scale) { if options.shouldDecode { dispatch_async(sSelf.processQueue, { () -> Void in let result = image.nir_decodeImage(scale: options.scale) sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(result, .Memory) sSelf = nil }) }) } else { sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil) dispatch_async(options.queue, { () -> Void in completionHandler(image, .Disk) sSelf = nil }) } } else { dispatch_async(options.queue, { () -> Void in completionHandler(nil, nil) sSelf = nil }) } }) }) dispatch_async(dispatch_get_main_queue(), block!) } return block } public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? { return memoryCache.objectForKey(key) as? UIImage } public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = NirWebImageManager.DefaultOptions.scale) -> UIImage? { return diskImageForKey(key, scale: scale) } } extension ImageCache { public func clearMemoryCache() { memoryCache.removeAllObjects() } public func clearDiskCache() { clearDiskCacheWithCompletionHandler(nil) } public func clearDiskCacheWithCompletionHandler(completionHandler: (()->())?) { dispatch_async(ioQueue) { () -> Void in do { try self.fileManager.removeItemAtPath(self.diskCachePath) } catch { } do { try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch { } if let completionHandler = completionHandler { dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler() }) } } } public func clearExpiredDiskCache() { clearExpiredDiskCacheWithCompletionHandler(nil) } public func clearExpiredDiskCacheWithCompletionHandler(completionHandler: (()->())?) { dispatch_async(ioQueue) { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey] let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond) var cachedFiles: [NSURL: [NSObject: AnyObject]] = [:] var URLsToDelete: [NSURL] = [] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil) { for fileURL in fileEnumerator.allObjects as! [NSURL] { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber { if isDirectory.boolValue { continue } } if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate { if modificationDate.laterDate(expiredDate) == expiredDate { URLsToDelete.append(fileURL) continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue cachedFiles[fileURL] = resourceValues } } catch { } } } for fileURL in URLsToDelete { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } } if self.MaxDiskCacheSize > 0 && diskCacheSize > self.MaxDiskCacheSize { let targetSize = self.MaxDiskCacheSize / 2 let sortedFiles = cachedFiles.keysSortedByValue({ (resourceValue1, resourceValue2) -> Bool in if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate { if let date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate { return date1.compare(date2) == .OrderedAscending } } return true }) for fileURL in sortedFiles { do { try self.fileManager.removeItemAtURL(fileURL) } catch { } URLsToDelete.append(fileURL) if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize -= fileSize.unsignedLongValue } if diskCacheSize < targetSize { break } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if URLsToDelete.count != 0 { let cleanedHashes = URLsToDelete.map({ (url) -> String in return url.lastPathComponent! }) NSNotificationCenter.defaultCenter().postNotificationName(NirWebImageDidCleanDiskCacheNotification, object: self, userInfo: [NirWebImageDiskCacheCleanedHashKey: cleanedHashes]) } if let completionHandler = completionHandler { completionHandler() } }) } } public func backgroudCleanExpiredDiskCache() { func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(task) task = UIBackgroundTaskInvalid } var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in endBackgroundTask(&backgroundTask!) }) clearExpiredDiskCacheWithCompletionHandler { () -> () in endBackgroundTask(&backgroundTask!) } } } public extension ImageCache { public struct CacheCheckResult { public let cached: Bool public let cacheType: CacheType? } public func isImageCachedForKey(key: String) -> CacheCheckResult { if memoryCache.objectForKey(key) != nil { return CacheCheckResult(cached: true, cacheType: .Memory) } let filePath = cachePathForKey(key) if fileManager.fileExistsAtPath(filePath) { return CacheCheckResult(cached: true, cacheType: .Disk) } return CacheCheckResult(cached: false, cacheType: nil) } public func hashForKey(key: String) -> String { return cacheFileNameForKey(key) } public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) { dispatch_async(ioQueue) { () -> Void in let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath) let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil) { for fileURL in fileEnumerator.allObjects as! [NSURL] { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue { if isDirectory { continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue } } catch { } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if let completionHandler = completionHandler { completionHandler(size: diskCacheSize) } }) } } } extension ImageCache { func diskImageForKey(key: String, scale: CGFloat) -> UIImage? { if let data = diskImageDataForKey(key) { return UIImage.nir_imageWithData(data, scale: scale) } else { return nil } } func diskImageDataForKey(key: String) -> NSData? { let filePath = cachePathForKey(key) return NSData(contentsOfFile: filePath) } func cachePathForKey(key: String) -> String { let fileName = cacheFileNameForKey(key) return (diskCachePath as NSString).stringByAppendingPathComponent(fileName) } func cacheFileNameForKey(key: String) -> String { return key.nir_MD5() } } extension UIImage { var nir_imageCost: Int { return Int(size.height * size.width * scale * scale) } } extension Dictionary { func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] { var array = Array(self) array.sortInPlace { let (_, lv) = $0 let (_, rv) = $1 return isOrderedBefore(lv, rv) } return array.map { let (k, _) = $0 return k } } }
8bb8cf207b61bacf4bcd0cf706903bf8
37.778017
202
0.544712
false
false
false
false
zhuhaow/SpechtLite
refs/heads/master
SpechtLite/Manager/PreferenceManager.swift
gpl-3.0
1
import Foundation import ReactiveSwift class PreferenceManager { static let defaultProfileKey = "defaultConfiguration" static let allowFromLanKey = "allowFromLan" static let setAsSystemProxyKey = "setUpSystemProxy" static let useDevChannelKey = "useDevChannel" static let autostartKey = "autostart" static func setUp() { let defaults = UserDefaults.standard ProfileManager.currentProfile.swap(defaults.string(forKey: defaultProfileKey)) ProfileManager.allowFromLan.swap(defaults.bool(forKey: allowFromLanKey)) ProxySettingManager.setAsSystemProxy.swap(defaults.bool(forKey: setAsSystemProxyKey)) UpdateManager.useDevChannel.swap(defaults.bool(forKey: useDevChannelKey)) AutostartManager.autostartAtLogin.swap(defaults.bool(forKey: autostartKey)) ProfileManager.currentProfile.signal.skipRepeats(==).observeValues { defaults.set($0, forKey: defaultProfileKey) } ProfileManager.allowFromLan.signal.skipRepeats(==).observeValues { defaults.set($0, forKey: allowFromLanKey) } ProxySettingManager.setAsSystemProxy.signal.skipRepeats(==).observeValues { defaults.set($0, forKey: setAsSystemProxyKey) } UpdateManager.useDevChannel.signal.skipRepeats(==).observeValues { defaults.set($0, forKey: useDevChannelKey) } AutostartManager.autostartAtLogin.signal.skipRepeats(==).observeValues { defaults.set($0, forKey: autostartKey) } } }
7e5896f0fade902d66699d434876b95a
39.846154
93
0.691149
false
false
false
false
tripleCC/GanHuoCode
refs/heads/master
GanHuo/Extension/UIScrollView+Extension.swift
mit
1
// // UIScrollView+Extension.swift // // Created by tripleCC on 16/1/29. // Copyright © 2016年 tripleCC. All rights reserved. // import UIKit extension UIScrollView { /** 滚动至顶部 - parameter animated: 是否执行动画 */ public func scrollToTopAnimated(animated: Bool = true) { var offset = contentOffset offset.y = -contentInset.top setContentOffset(offset, animated: animated) } /** 滚动至底部 - parameter animated: 是否执行动画 */ public func scrollToBottomAnimated(animated: Bool = true) { var offset = contentOffset offset.y = contentSize.height - bounds.height + contentInset.bottom setContentOffset(offset, animated: animated) } /** 滚动至左边 - parameter animated: 是否执行动画 */ public func scrollToLeftAnimated(animated: Bool = true) { var offset = contentOffset offset.x = -contentInset.left setContentOffset(offset, animated: animated) } /** 滚动至右边 - parameter animated: 是否执行动画 */ public func scrollToRightAnimated(animated: Bool = true) { var offset = contentOffset offset.x = contentSize.width - bounds.width + contentInset.right setContentOffset(offset, animated: animated) } }
bb972545a175d305c437d8f9507ca331
23.185185
75
0.619923
false
false
false
false
zapdroid/RXWeather
refs/heads/master
Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift
mit
1
// // SingleAssignmentDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /** Represents a disposable resource which only allows a single assignment of its underlying disposable resource. If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. */ public final class SingleAssignmentDisposable: DisposeBase, Disposable, Cancelable { fileprivate enum DisposeState: UInt32 { case disposed = 1 case disposableSet = 2 } // Jeej, swift API consistency rules fileprivate enum DisposeStateInt32: Int32 { case disposed = 1 case disposableSet = 2 } // state private var _state: AtomicInt = 0 private var _disposable = nil as Disposable? /// - returns: A value that indicates whether the object is disposed. public var isDisposed: Bool { return AtomicFlagSet(DisposeState.disposed.rawValue, &_state) } /// Initializes a new instance of the `SingleAssignmentDisposable`. public override init() { super.init() } /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. /// /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** public func setDisposable(_ disposable: Disposable) { _disposable = disposable let previousState = AtomicOr(DisposeState.disposableSet.rawValue, &_state) if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { rxFatalError("oldState.disposable != nil") } if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { disposable.dispose() _disposable = nil } } /// Disposes the underlying disposable. public func dispose() { let previousState = AtomicOr(DisposeState.disposed.rawValue, &_state) if (previousState & DisposeStateInt32.disposed.rawValue) != 0 { return } if (previousState & DisposeStateInt32.disposableSet.rawValue) != 0 { guard let disposable = _disposable else { rxFatalError("Disposable not set") } disposable.dispose() _disposable = nil } } }
eb7d89cd08160b5c1ab1b7acf17466c6
31.053333
142
0.658486
false
false
false
false
bcylin/QuickTableViewController
refs/heads/develop
Source/Rows/OptionRow.swift
mit
1
// // OptionRow.swift // QuickTableViewController // // Created by Ben on 30/07/2017. // Copyright © 2017 bcylin. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// A class that represents a row of selectable option. open class OptionRow<T: UITableViewCell>: OptionRowCompatible, Equatable { // MARK: - Initializer /// Initializes an `OptionRow` with a text, a selection state and an action closure. /// The detail text, icon, and the customization closure are optional. public init( text: String, detailText: DetailText? = nil, isSelected: Bool, icon: Icon? = nil, customization: ((UITableViewCell, Row & RowStyle) -> Void)? = nil, action: ((Row) -> Void)? ) { self.text = text self.detailText = detailText self.isSelected = isSelected self.icon = icon self.customize = customization self.action = action } // MARK: - OptionRowCompatible /// The state of selection. public var isSelected: Bool = false { didSet { guard isSelected != oldValue else { return } DispatchQueue.main.async { self.action?(self) } } } // MARK: - Row /// The text of the row. public let text: String /// The detail text of the row. public let detailText: DetailText? /// A closure that will be invoked when the `isSelected` is changed. public let action: ((Row) -> Void)? // MARK: - RowStyle /// The type of the table view cell to display the row. public let cellType: UITableViewCell.Type = T.self /// Returns the reuse identifier of the table view cell to display the row. public var cellReuseIdentifier: String { return T.reuseIdentifier + (detailText?.style.stringValue ?? "") } /// Returns the table view cell style for the specified detail text. public var cellStyle: UITableViewCell.CellStyle { return detailText?.style ?? .default } /// The icon of the row. public let icon: Icon? /// Returns `.checkmark` when the row is selected, otherwise returns `.none`. public var accessoryType: UITableViewCell.AccessoryType { return isSelected ? .checkmark : .none } /// `OptionRow` is always selectable. public let isSelectable: Bool = true /// Additional customization during cell configuration. public let customize: ((UITableViewCell, Row & RowStyle) -> Void)? // MARK: - Equatable /// Returns true iff `lhs` and `rhs` have equal titles, detail texts, selection states, and icons. public static func == (lhs: OptionRow, rhs: OptionRow) -> Bool { return lhs.text == rhs.text && lhs.detailText == rhs.detailText && lhs.isSelected == rhs.isSelected && lhs.icon == rhs.icon } }
3ff65306d6efbb416eeade59de0bf8f7
31.051282
100
0.690933
false
false
false
false
inacioferrarini/glasgow
refs/heads/master
Glasgow/Classes/UIKit/DataSource/Arrays/TableViewArrayDataSource.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // 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 /** Array-based UITableView data source having elements of type `Type` and using `ConfigurableTableViewCell`. */ open class TableViewArrayDataSource<CellType: UITableViewCell, Type: Equatable>: ArrayDataSource<Type>, UITableViewDataSource where CellType: Configurable { // MARK: - Properties /** TableView that owns this DataSource. */ open let tableView: UITableView /** Returns the Reuse Identifier for a Cell at the given `IndexPath`. */ let reuseIdentifier: ((IndexPath) -> (String)) // MARK: - Initialization /** Inits the DataSource providing a UITableView and its objects. Assumes the ReuseIdentifier will have the same name as `CellType` type. - parameter for: The target UITableView. - parameter dataProvider: The array-based Data provider. */ public convenience init(for tableView: UITableView, with dataProvider: ArrayDataProvider<Type>) { let reuseIdentifier = { (indexPath: IndexPath) -> String in return CellType.simpleClassName() } self.init(for: tableView, reuseIdentifier: reuseIdentifier, with: dataProvider) } /** Inits the DataSource providing a UITableView and its objects. - parameter for: The target UITableView. - parameter reuseIdentifier: Block used to define the Ruse Identifier based on the given IndexPath. - parameter dataProvider: The array-based Data provider. */ public required init(for tableView: UITableView, reuseIdentifier: @escaping ((IndexPath) -> (String)), with dataProvider: ArrayDataProvider<Type>) { self.tableView = tableView self.reuseIdentifier = reuseIdentifier super.init(with: dataProvider) } // MARK: - Public Methods /** Propagates through `onRefresh` a refresh for interested objects and also calls `reloadData` on `tableView`. */ open override func refresh() { super.refresh() self.tableView.reloadData() } // MARK: - Table View Data Source /** Returns the number of rows in its only section. The number of rows always matches the number of contained objects. - parameter tableView: The target UITableView. - parameter section: The desired sections. Values different than `0` will result in `0` being returned. - returns: number of objects. */ open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataProvider.numberOfItems(in: section) } /** Returns the number of rows in its only section. The number of rows always matches the number of contained objects. - parameter tableView: The target UITableView. - parameter cellForRowAt: The indexPath for the given object, or `nil` if not found. - returns: number of objects. */ open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = self.reuseIdentifier(indexPath) guard var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as? CellType else { return UITableViewCell() } if let value = self.dataProvider[indexPath] as? CellType.ValueType { cell.setup(with: value) } return cell } }
ee224df3996422c9915a1f438c528acb
35.069231
150
0.67669
false
false
false
false
Red-Analyzer/red-analyzer
refs/heads/master
Pods/Charts/Charts/Classes/Charts/CombinedChartView.swift
mit
1
// // CombinedChartView.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 /// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area. public class CombinedChartView: BarLineChartViewBase, LineChartDataProvider, BarChartDataProvider, ScatterChartDataProvider, CandleChartDataProvider, BubbleChartDataProvider { /// the fill-formatter used for determining the position of the fill-line internal var _fillFormatter: ChartFillFormatter! /// enum that allows to specify the order in which the different data objects for the combined-chart are drawn @objc public enum CombinedChartDrawOrder: Int { case Bar case Bubble case Line case Candle case Scatter } public override func initialize() { super.initialize() _highlighter = CombinedHighlighter(chart: self) /// WORKAROUND: Swift 2.0 compiler malfunctions when optimizations are enabled, and assigning directly to _fillFormatter causes a crash with a EXC_BAD_ACCESS. See https://github.com/danielgindi/ios-charts/issues/406 let workaroundFormatter = BarLineChartFillFormatter() _fillFormatter = workaroundFormatter renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } override func calcMinMax() { super.calcMinMax() if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil) { _chartXMin = -0.5 _chartXMax = Double(_data.xVals.count) - 0.5 if (self.bubbleData !== nil) { for set in self.bubbleData?.dataSets as! [BubbleChartDataSet] { let xmin = set.xMin let xmax = set.xMax if (xmin < chartXMin) { _chartXMin = xmin } if (xmax > chartXMax) { _chartXMax = xmax } } } _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) } } public override var data: ChartData? { get { return super.data } set { super.data = newValue (renderer as! CombinedChartRenderer?)!.createRenderers() } } public var fillFormatter: ChartFillFormatter { get { return _fillFormatter } set { _fillFormatter = newValue if (_fillFormatter == nil) { _fillFormatter = BarLineChartFillFormatter() } } } // MARK: - LineChartDataProvider public var lineData: LineChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).lineData } } // MARK: - BarChartDataProvider public var barData: BarChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).barData } } // MARK: - ScatterChartDataProvider public var scatterData: ScatterChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).scatterData } } // MARK: - CandleChartDataProvider public var candleData: CandleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).candleData } } // MARK: - BubbleChartDataProvider public var bubbleData: BubbleChartData? { get { if (_data === nil) { return nil } return (_data as! CombinedChartData!).bubbleData } } // MARK: - Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled } set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled } set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue } } /// if set to true, a grey area is darawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled } set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue } } /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [Int] { get { return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue } } set { (renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! } } } }
0294dd7395943a7aa6b8f89a8b869813
29.102679
223
0.570157
false
false
false
false
sora0077/Memcached
refs/heads/master
Sources/ConnectionPool.swift
mit
1
// // ConnectionPool.swift // Memcached // // Created by 林達也 on 2016/01/11. // Copyright © 2016年 jp.sora0077. All rights reserved. // import Foundation import CMemcached import CMemcachedUtil final public class ConnectionPool { public let options: ConnectionOption private var _pool: COpaquePointer? private var _connections: [Connection] = [] public init(options: ConnectionOption) { self.options = options _pool = memcached_pool(options.configuration, options.configuration.utf8.count) } public convenience init(options: [String]) { self.init(options: ConnectionOptions(options: options.map { StringLiteralConnectionOption(stringLiteral: $0) })) } public convenience init(options: String...) { self.init(options: options) } deinit { detach() } func detach() { if let pool = _pool { memcached_pool_destroy(pool) } } public func connection() throws -> Connection { var rc: memcached_return = CMemcached.MEMCACHED_MAXIMUM_RETURN let mc = memcached_pool_pop(_pool!, false, &rc) try throwIfError(mc, rc) let conn = Connection(memcached: mc, pool: self) return conn } func pop(mc: UnsafeMutablePointer<memcached_st>) { if let pool = _pool { memcached_pool_push(pool, mc) } } }
4505a6637f361067e6599c8f5f77fc66
23.474576
120
0.61192
false
false
false
false
xuech/OMS-WH
refs/heads/master
OMS-WH/Classes/TakeOrder/器械信息/Model/TempleBrandModel.swift
mit
1
// // TempleBrandModel.swift // OMS-WH // // Created by xuech on 2017/9/14. // Copyright © 2017年 medlog. All rights reserved. // import UIKit class TempleBrandModel:Reflect { var medBrandCode = "" var medBrandName = "" var prolns : [TempleProlns]! } class TempleProlns:Reflect { var medProdLnCodeWithTool = "" var medProdLnCode = "" var diseaseInfo = "" var medProdLnName = "" var medProdLnCodeWithToolName = "" var remark = "" var medMaterialList: [MedMaterialList]? }
3b4828d2a170121eeee23eb2cdbdf1d5
16.129032
50
0.640301
false
false
false
false
Bulochkin/tensorflow_pack
refs/heads/main
3party/protobuf/protobuf/objectivec/Tests/GPBSwiftTests.swift
apache-2.0
41
// Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation import XCTest // Test some usage of the ObjC library from Swift. class GPBBridgeTests: XCTestCase { func testProto2Basics() { let msg = Message2() let msg2 = Message2() let msg3 = Message2_OptionalGroup() msg.optionalInt32 = 100 msg.optionalString = "abc" msg.optionalEnum = .bar msg2.optionalString = "other" msg.optional = msg2 msg3.a = 200 msg.optionalGroup = msg3 msg.repeatedInt32Array.addValue(300) msg.repeatedInt32Array.addValue(301) msg.repeatedStringArray.add("mno") msg.repeatedStringArray.add("pqr") msg.repeatedEnumArray.addValue(Message2_Enum.bar.rawValue) msg.repeatedEnumArray.addValue(Message2_Enum.baz.rawValue) msg.mapInt32Int32.setInt32(400, forKey:500) msg.mapInt32Int32.setInt32(401, forKey:501) msg.mapStringString.setObject("foo", forKey:"bar" as NSString) msg.mapStringString.setObject("abc", forKey:"xyz" as NSString) msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600) msg.mapInt32Enum.setEnum(Message2_Enum.baz.rawValue, forKey:601) // Check has*. XCTAssertTrue(msg.hasOptionalInt32) XCTAssertTrue(msg.hasOptionalString) XCTAssertTrue(msg.hasOptionalEnum) XCTAssertTrue(msg2.hasOptionalString) XCTAssertTrue(msg.hasOptionalMessage) XCTAssertTrue(msg3.hasA) XCTAssertTrue(msg.hasOptionalGroup) XCTAssertFalse(msg.hasOptionalInt64) XCTAssertFalse(msg.hasOptionalFloat) // Check values. XCTAssertEqual(msg.optionalInt32, Int32(100)) XCTAssertEqual(msg.optionalString, "abc") XCTAssertEqual(msg2.optionalString, "other") XCTAssertTrue(msg.optional === msg2) XCTAssertEqual(msg.optionalEnum, Message2_Enum.bar) XCTAssertEqual(msg3.a, Int32(200)) XCTAssertTrue(msg.optionalGroup === msg3) XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2)) XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300)) XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301)) XCTAssertEqual(msg.repeatedStringArray.count, Int(2)) XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno") XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr") XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2)) XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message2_Enum.bar.rawValue) XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message2_Enum.baz.rawValue) XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0)) XCTAssertEqual(msg.mapInt32Int32.count, UInt(2)) var intValue: Int32 = 0 XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey: 500)) XCTAssertEqual(intValue, Int32(400)) XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey: 501)) XCTAssertEqual(intValue, Int32(401)) XCTAssertEqual(msg.mapStringString.count, Int(2)) XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo") XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc") XCTAssertEqual(msg.mapInt32Enum.count, UInt(2)) XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600)) XCTAssertEqual(intValue, Message2_Enum.bar.rawValue) XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601)) XCTAssertEqual(intValue, Message2_Enum.baz.rawValue) // Clearing a string with nil. msg2.optionalString = nil XCTAssertFalse(msg2.hasOptionalString) XCTAssertEqual(msg2.optionalString, "") // Clearing a message with nil. msg.optionalGroup = nil XCTAssertFalse(msg.hasOptionalGroup) XCTAssertTrue(msg.optionalGroup !== msg3) // New instance // Clear. msg.clear() XCTAssertFalse(msg.hasOptionalInt32) XCTAssertFalse(msg.hasOptionalString) XCTAssertFalse(msg.hasOptionalEnum) XCTAssertFalse(msg.hasOptionalMessage) XCTAssertFalse(msg.hasOptionalInt64) XCTAssertFalse(msg.hasOptionalFloat) XCTAssertEqual(msg.optionalInt32, Int32(0)) XCTAssertEqual(msg.optionalString, "") XCTAssertTrue(msg.optional !== msg2) // New instance XCTAssertEqual(msg.optionalEnum, Message2_Enum.foo) // Default XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0)) XCTAssertEqual(msg.repeatedStringArray.count, Int(0)) XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0)) XCTAssertEqual(msg.mapInt32Int32.count, UInt(0)) XCTAssertEqual(msg.mapStringString.count, Int(0)) XCTAssertEqual(msg.mapInt32Enum.count, UInt(0)) } func testProto3Basics() { let msg = Message3() let msg2 = Message3() msg.optionalInt32 = 100 msg.optionalString = "abc" msg.optionalEnum = .bar msg2.optionalString = "other" msg.optional = msg2 msg.repeatedInt32Array.addValue(300) msg.repeatedInt32Array.addValue(301) msg.repeatedStringArray.add("mno") msg.repeatedStringArray.add("pqr") // "proto3" syntax lets enum get unknown values. msg.repeatedEnumArray.addValue(Message3_Enum.bar.rawValue) msg.repeatedEnumArray.addRawValue(666) SetMessage3_OptionalEnum_RawValue(msg2, 666) msg.mapInt32Int32.setInt32(400, forKey:500) msg.mapInt32Int32.setInt32(401, forKey:501) msg.mapStringString.setObject("foo", forKey:"bar" as NSString) msg.mapStringString.setObject("abc", forKey:"xyz" as NSString) msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600) // "proto3" syntax lets enum get unknown values. msg.mapInt32Enum.setRawValue(666, forKey:601) // Has only exists on for message fields. XCTAssertTrue(msg.hasOptionalMessage) XCTAssertFalse(msg2.hasOptionalMessage) // Check values. XCTAssertEqual(msg.optionalInt32, Int32(100)) XCTAssertEqual(msg.optionalString, "abc") XCTAssertEqual(msg2.optionalString, "other") XCTAssertTrue(msg.optional === msg2) XCTAssertEqual(msg.optionalEnum, Message3_Enum.bar) XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2)) XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300)) XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301)) XCTAssertEqual(msg.repeatedStringArray.count, Int(2)) XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno") XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr") XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0)) XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2)) XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message3_Enum.bar.rawValue) XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue) XCTAssertEqual(msg.repeatedEnumArray.rawValue(at: 1), 666) XCTAssertEqual(msg2.optionalEnum, Message3_Enum.gpbUnrecognizedEnumeratorValue) XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Int32(666)) XCTAssertEqual(msg.mapInt32Int32.count, UInt(2)) var intValue: Int32 = 0 XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey:500)) XCTAssertEqual(intValue, Int32(400)) XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey:501)) XCTAssertEqual(intValue, Int32(401)) XCTAssertEqual(msg.mapStringString.count, Int(2)) XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo") XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc") XCTAssertEqual(msg.mapInt32Enum.count, UInt(2)) XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600)) XCTAssertEqual(intValue, Message2_Enum.bar.rawValue) XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601)) XCTAssertEqual(intValue, Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue) XCTAssertTrue(msg.mapInt32Enum.getRawValue(&intValue, forKey:601)) XCTAssertEqual(intValue, 666) // Clearing a string with nil. msg2.optionalString = nil XCTAssertEqual(msg2.optionalString, "") // Clearing a message with nil. msg.optional = nil XCTAssertFalse(msg.hasOptionalMessage) XCTAssertTrue(msg.optional !== msg2) // New instance // Clear. msg.clear() XCTAssertFalse(msg.hasOptionalMessage) XCTAssertEqual(msg.optionalInt32, Int32(0)) XCTAssertEqual(msg.optionalString, "") XCTAssertTrue(msg.optional !== msg2) // New instance XCTAssertEqual(msg.optionalEnum, Message3_Enum.foo) // Default XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0)) XCTAssertEqual(msg.repeatedStringArray.count, Int(0)) XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0)) msg2.clear() XCTAssertEqual(msg2.optionalEnum, Message3_Enum.foo) // Default XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Message3_Enum.foo.rawValue) XCTAssertEqual(msg.mapInt32Int32.count, UInt(0)) XCTAssertEqual(msg.mapStringString.count, Int(0)) XCTAssertEqual(msg.mapInt32Enum.count, UInt(0)) } func testAutoCreation() { let msg = Message2() XCTAssertFalse(msg.hasOptionalGroup) XCTAssertFalse(msg.hasOptionalMessage) // Access shouldn't result in has* but should return objects. let msg2 = msg.optionalGroup let msg3 = msg.optional.optional let msg4 = msg.optional XCTAssertNotNil(msg2) XCTAssertNotNil(msg3) XCTAssertFalse(msg.hasOptionalGroup) XCTAssertFalse(msg.optional.hasOptionalMessage) XCTAssertFalse(msg.hasOptionalMessage) // Setting things should trigger has* getting set. msg.optionalGroup.a = 10 msg.optional.optional.optionalInt32 = 100 XCTAssertTrue(msg.hasOptionalGroup) XCTAssertTrue(msg.optional.hasOptionalMessage) XCTAssertTrue(msg.hasOptionalMessage) // And they should be the same pointer as before. XCTAssertTrue(msg2 === msg.optionalGroup) XCTAssertTrue(msg3 === msg.optional.optional) XCTAssertTrue(msg4 === msg.optional) // Clear gets us new objects next time around. msg.clear() XCTAssertFalse(msg.hasOptionalGroup) XCTAssertFalse(msg.optional.hasOptionalMessage) XCTAssertFalse(msg.hasOptionalMessage) msg.optionalGroup.a = 20 msg.optional.optional.optionalInt32 = 200 XCTAssertTrue(msg.hasOptionalGroup) XCTAssertTrue(msg.optional.hasOptionalMessage) XCTAssertTrue(msg.hasOptionalMessage) XCTAssertTrue(msg2 !== msg.optionalGroup) XCTAssertTrue(msg3 !== msg.optional.optional) XCTAssertTrue(msg4 !== msg.optional) // Explicit set of a message, means autocreated object doesn't bind. msg.clear() let autoCreated = msg.optional XCTAssertFalse(msg.hasOptionalMessage) let msg5 = Message2() msg5.optionalInt32 = 123 msg.optional = msg5 XCTAssertTrue(msg.hasOptionalMessage) // Modifing the autocreated doesn't replaced the explicit set one. autoCreated?.optionalInt32 = 456 XCTAssertTrue(msg.hasOptionalMessage) XCTAssertTrue(msg.optional === msg5) XCTAssertEqual(msg.optional.optionalInt32, Int32(123)) } func testProto2OneOfSupport() { let msg = Message2() XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase) XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default let autoCreated = msg.oneof // Default create one. XCTAssertNotNil(autoCreated) XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase) msg.oneofInt32 = 10 XCTAssertEqual(msg.oneofInt32, Int32(10)) XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32) msg.oneofFloat = 20.0 XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oneofFloat, Float(20.0)) XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofFloat) msg.oneofEnum = .bar XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default XCTAssertEqual(msg.oneofEnum, Message2_Enum.bar) XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofEnum) // Sets via the autocreated instance. msg.oneof.optionalInt32 = 200 XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oneof.optionalInt32, Int32(200)) XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage) // Clear the oneof. Message2_ClearOOneOfCase(msg) XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default let autoCreated2 = msg.oneof // Default create one XCTAssertNotNil(autoCreated2) XCTAssertTrue(autoCreated2 !== autoCreated) // New instance XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase) msg.oneofInt32 = 10 XCTAssertEqual(msg.oneofInt32, Int32(10)) XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32) // Confirm Message.clear() handles the oneof correctly. msg.clear() XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase) // Sets via the autocreated instance. msg.oneof.optionalInt32 = 300 XCTAssertTrue(msg.oneof !== autoCreated) // New instance XCTAssertTrue(msg.oneof !== autoCreated2) // New instance XCTAssertEqual(msg.oneof.optionalInt32, Int32(300)) XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage) // Set message to nil clears the oneof. msg.oneof = nil XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase) } func testProto3OneOfSupport() { let msg = Message3() XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase) XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default let autoCreated = msg.oneof // Default create one. XCTAssertNotNil(autoCreated) XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase) msg.oneofInt32 = 10 XCTAssertEqual(msg.oneofInt32, Int32(10)) XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32) msg.oneofFloat = 20.0 XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oneofFloat, Float(20.0)) XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofFloat) msg.oneofEnum = .bar XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default XCTAssertEqual(msg.oneofEnum, Message3_Enum.bar) XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofEnum) // Sets via the autocreated instance. msg.oneof.optionalInt32 = 200 XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default XCTAssertTrue(msg.oneof === autoCreated) // Still the same XCTAssertEqual(msg.oneof.optionalInt32, Int32(200)) XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage) // Clear the oneof. Message3_ClearOOneOfCase(msg) XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default let autoCreated2 = msg.oneof // Default create one XCTAssertNotNil(autoCreated2) XCTAssertTrue(autoCreated2 !== autoCreated) // New instance XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase) msg.oneofInt32 = 10 XCTAssertEqual(msg.oneofInt32, Int32(10)) XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32) // Confirm Message.clear() handles the oneof correctly. msg.clear() XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase) // Sets via the autocreated instance. msg.oneof.optionalInt32 = 300 XCTAssertTrue(msg.oneof !== autoCreated) // New instance XCTAssertTrue(msg.oneof !== autoCreated2) // New instance XCTAssertEqual(msg.oneof.optionalInt32, Int32(300)) XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage) // Set message to nil clears the oneof. msg.oneof = nil XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase) } func testSerialization() { let msg = Message2() msg.optionalInt32 = 100 msg.optionalInt64 = 101 msg.optionalGroup.a = 102 msg.repeatedStringArray.add("abc") msg.repeatedStringArray.add("def") msg.mapInt32Int32.setInt32(200, forKey:300) msg.mapInt32Int32.setInt32(201, forKey:201) msg.mapStringString.setObject("foo", forKey:"bar" as NSString) msg.mapStringString.setObject("abc", forKey:"xyz" as NSString) let data = msg.data() let msg2 = try! Message2(data: data!) XCTAssertTrue(msg2 !== msg) // New instance XCTAssertEqual(msg.optionalInt32, Int32(100)) XCTAssertEqual(msg.optionalInt64, Int64(101)) XCTAssertEqual(msg.optionalGroup.a, Int32(102)) XCTAssertEqual(msg.repeatedStringArray.count, Int(2)) XCTAssertEqual(msg.mapInt32Int32.count, UInt(2)) XCTAssertEqual(msg.mapStringString.count, Int(2)) XCTAssertEqual(msg2, msg) } }
c07e48a4b6d2c233e00fc12be96e5025
42.721739
109
0.740105
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
Tests/PackageCollectionsSigningTests/PackageCollectionSigningTest.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import Dispatch import Foundation import PackageCollectionsModel @testable import PackageCollectionsSigning import SPMTestSupport import TSCBasic import XCTest class PackageCollectionSigningTests: XCTestCase { func test_RSA_signAndValidate_happyCase() throws { try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) let certPath = fixturePath.appending(components: "Signing", "Test_rsa.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "TestIntermediateCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "TestRootCA.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "Test_rsa_key.pem") let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(rootCAPath)) // Trust the self-signed root cert let certPolicy = TestCertificatePolicy(anchorCerts: [rootCA]) let signing = PackageCollectionSigning(certPolicy: certPolicy, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: .custom, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: .custom, callback: callback) }) } } func test_RSA_signAndValidate_collectionMismatch() throws { try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let collection1 = PackageCollectionModel.V1.Collection( name: "Test Package Collection 1", overview: nil, keywords: nil, packages: [], formatVersion: .v1_0, revision: nil, generatedAt: Date(), generatedBy: nil ) let collection2 = PackageCollectionModel.V1.Collection( name: "Test Package Collection 2", overview: nil, keywords: nil, packages: [], formatVersion: .v1_0, revision: nil, generatedAt: Date(), generatedBy: nil ) let certPath = fixturePath.appending(components: "Signing", "Test_rsa.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "TestIntermediateCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "TestRootCA.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "Test_rsa_key.pem") let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(rootCAPath)) // Trust the self-signed root cert let certPolicy = TestCertificatePolicy(anchorCerts: [rootCA]) let signing = PackageCollectionSigning(certPolicy: certPolicy, callbackQueue: callbackQueue) // Sign collection1 let signedCollection = try tsc_await { callback in signing.sign(collection: collection1, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: .custom, callback: callback) } // Use collection1's signature for collection2 let badSignedCollection = PackageCollectionModel.V1.SignedCollection(collection: collection2, signature: signedCollection.signature) // The signature should be invalid XCTAssertThrowsError( try tsc_await { callback in signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom, callback: callback) }) { error in guard PackageCollectionSigningError.invalidSignature == error as? PackageCollectionSigningError else { return XCTFail("Expected PackageCollectionSigningError.invalidSignature") } } } } func test_EC_signAndValidate_happyCase() throws { try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) let certPath = fixturePath.appending(components: "Signing", "Test_ec.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "TestIntermediateCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "TestRootCA.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "Test_ec_key.pem") let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(rootCAPath)) // Trust the self-signed root cert let certPolicy = TestCertificatePolicy(anchorCerts: [rootCA]) let signing = PackageCollectionSigning(certPolicy: certPolicy, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: .custom, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: .custom, callback: callback) }) } } func test_EC_signAndValidate_collectionMismatch() throws { try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let collection1 = PackageCollectionModel.V1.Collection( name: "Test Package Collection 1", overview: nil, keywords: nil, packages: [], formatVersion: .v1_0, revision: nil, generatedAt: Date(), generatedBy: nil ) let collection2 = PackageCollectionModel.V1.Collection( name: "Test Package Collection 2", overview: nil, keywords: nil, packages: [], formatVersion: .v1_0, revision: nil, generatedAt: Date(), generatedBy: nil ) let certPath = fixturePath.appending(components: "Signing", "Test_ec.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "TestIntermediateCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "TestRootCA.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "Test_ec_key.pem") let rootCA = try Certificate(derEncoded: try localFileSystem.readFileContents(rootCAPath)) // Trust the self-signed root cert let certPolicy = TestCertificatePolicy(anchorCerts: [rootCA]) let signing = PackageCollectionSigning(certPolicy: certPolicy, callbackQueue: callbackQueue) // Sign collection1 let signedCollection = try tsc_await { callback in signing.sign(collection: collection1, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: .custom, callback: callback) } // Use collection1's signature for collection2 let badSignedCollection = PackageCollectionModel.V1.SignedCollection(collection: collection2, signature: signedCollection.signature) // The signature should be invalid XCTAssertThrowsError( try tsc_await { callback in signing.validate(signedCollection: badSignedCollection, certPolicyKey: .custom, callback: callback) }) { error in guard PackageCollectionSigningError.invalidSignature == error as? PackageCollectionSigningError else { return XCTFail("Expected PackageCollectionSigningError.invalidSignature") } } } } func test_signAndValidate_defaultPolicy() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) let certPath = fixturePath.appending(components: "Signing", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCAG3.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let rootCAData: Data = try localFileSystem.readFileContents(rootCAPath) let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .default #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted do { let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback ) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback ) }) } // Try passing in the cert with `additionalTrustedRootCerts` even though it's already in the default trust store do { let signing = PackageCollectionSigning( additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue ) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback ) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) // Specify `trustedRootCertsDir` do { let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } // Another way is to pass in `additionalTrustedRootCerts` do { let signing = PackageCollectionSigning(additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } } #endif } } func test_signAndValidate_appleDistributionPolicy() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) // This must be an Apple Distribution cert let certPath = fixturePath.appending(components: "Signing", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCAG3.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let rootCAData: Data = try localFileSystem.readFileContents(rootCAPath) let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .appleDistribution #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted do { let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } // Try passing in the cert with `additionalTrustedRootCerts` even though it's already in the default trust store do { let signing = PackageCollectionSigning( additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue ) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) // Specify `trustedRootCertsDir` do { let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } // Another way is to pass in `additionalTrustedRootCerts` do { let signing = PackageCollectionSigning(additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } } #endif } } func test_signAndValidate_appleSwiftPackageCollectionPolicy() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) // This must be an Apple Swift Package Collection cert let certPath = fixturePath.appending(components: "Signing", "swift_package_collection.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let rootCAData: Data = try localFileSystem.readFileContents(rootCAPath) let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .appleSwiftPackageCollection #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted do { let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } // Try passing in the cert with `additionalTrustedRootCerts` even though it's already in the default trust store do { let signing = PackageCollectionSigning( additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue ) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) // Specify `trustedRootCertsDir` do { let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } // Another way is to pass in `additionalTrustedRootCerts` do { let signing = PackageCollectionSigning(additionalTrustedRootCerts: [rootCAData.base64EncodedString()], callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } } #endif } } func test_signAndValidate_defaultPolicy_user() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) let certPath = fixturePath.appending(components: "Signing", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCAG3.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .default(subjectUserID: expectedSubjectUserID) #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #endif } } func test_signAndValidate_appleDistributionPolicy_user() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) // This must be an Apple Distribution cert let certPath = fixturePath.appending(components: "Signing", "development.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCAG3.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .appleDistribution(subjectUserID: expectedSubjectUserID) #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign( collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback ) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate( signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback ) }) #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #endif } } func test_signAndValidate_appleSwiftPackageCollectionPolicy_user() throws { #if ENABLE_REAL_CERT_TEST #else try XCTSkipIf(true) #endif try PackageCollectionsSigningTests_skipIfUnsupportedPlatform() try fixture(name: "Collections", createGitRepo: false) { fixturePath in let jsonDecoder = JSONDecoder.makeWithDefaults() let collectionPath = fixturePath.appending(components: "JSON", "good.json") let collectionData: Data = try localFileSystem.readFileContents(collectionPath) let collection = try jsonDecoder.decode(PackageCollectionModel.V1.Collection.self, from: collectionData) // This must be an Apple Distribution cert let certPath = fixturePath.appending(components: "Signing", "swift_package_collection.cer") let intermediateCAPath = fixturePath.appending(components: "Signing", "AppleWWDRCA.cer") let rootCAPath = fixturePath.appending(components: "Signing", "AppleIncRoot.cer") let certChainPaths = [certPath, intermediateCAPath, rootCAPath].map { $0.asURL } let privateKeyPath = fixturePath.appending(components: "Signing", "development-key.pem") let certPolicyKey: CertificatePolicyKey = .appleSwiftPackageCollection(subjectUserID: expectedSubjectUserID) #if os(macOS) // The Apple root certs come preinstalled on Apple platforms and they are automatically trusted let signing = PackageCollectionSigning(callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) #elseif os(Linux) || os(Windows) || os(Android) // On other platforms we have to specify `trustedRootCertsDir` so the Apple root cert is trusted try withTemporaryDirectory { tmp in try localFileSystem.copy(from: rootCAPath, to: tmp.appending(components: "AppleIncRoot.cer")) let signing = PackageCollectionSigning(trustedRootCertsDir: tmp.asURL, callbackQueue: callbackQueue) // Sign the collection let signedCollection = try tsc_await { callback in signing.sign(collection: collection, certChainPaths: certChainPaths, certPrivateKeyPath: privateKeyPath.asURL, certPolicyKey: certPolicyKey, callback: callback) } // Then validate that signature is valid XCTAssertNoThrow(try tsc_await { callback in signing.validate(signedCollection: signedCollection, certPolicyKey: certPolicyKey, callback: callback) }) } #endif } } } fileprivate extension PackageCollectionSigning { init(trustedRootCertsDir: URL? = nil, additionalTrustedRootCerts: [String]? = nil, callbackQueue: DispatchQueue) { self.init(trustedRootCertsDir: trustedRootCertsDir, additionalTrustedRootCerts: additionalTrustedRootCerts, observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue) } init(certPolicy: CertificatePolicy, callbackQueue: DispatchQueue) { self.init(certPolicy: certPolicy, observabilityScope: ObservabilitySystem.NOOP, callbackQueue: callbackQueue) } }
d1cbc058cb3eda9aaf1ca267ca0c8060
52.379056
191
0.630378
false
true
false
false
ole/SortedArray
refs/heads/master
Sources/SortedArray.swift
mit
1
import Foundation // Needed for ComparisonResult (used privately) /// An array that keeps its elements sorted at all times. public struct SortedArray<Element> { /// The backing store fileprivate var _elements: [Element] public typealias Comparator<A> = (A, A) -> Bool /// The predicate that determines the array's sort order. fileprivate let areInIncreasingOrder: Comparator<Element> /// Initializes an empty array. /// /// - Parameter areInIncreasingOrder: The comparison predicate the array should use to sort its elements. public init(areInIncreasingOrder: @escaping Comparator<Element>) { self._elements = [] self.areInIncreasingOrder = areInIncreasingOrder } /// Initializes the array with a sequence of unsorted elements and a comparison predicate. public init<S: Sequence>(unsorted: S, areInIncreasingOrder: @escaping Comparator<Element>) where S.Element == Element { let sorted = unsorted.sorted(by: areInIncreasingOrder) self._elements = sorted self.areInIncreasingOrder = areInIncreasingOrder } /// Initializes the array with a sequence that is already sorted according to the given comparison predicate. /// /// This is faster than `init(unsorted:areInIncreasingOrder:)` because the elements don't have to sorted again. /// /// - Precondition: `sorted` is sorted according to the given comparison predicate. If you violate this condition, the behavior is undefined. public init<S: Sequence>(sorted: S, areInIncreasingOrder: @escaping Comparator<Element>) where S.Element == Element { self._elements = Array(sorted) self.areInIncreasingOrder = areInIncreasingOrder } /// Inserts a new element into the array, preserving the sort order. /// /// - Returns: the index where the new element was inserted. /// - Complexity: O(_n_) where _n_ is the size of the array. O(_log n_) if the new /// element can be appended, i.e. if it is ordered last in the resulting array. @discardableResult public mutating func insert(_ newElement: Element) -> Index { let index = insertionIndex(for: newElement) // This should be O(1) if the element is to be inserted at the end, // O(_n) in the worst case (inserted at the front). _elements.insert(newElement, at: index) return index } /// Inserts all elements from `elements` into `self`, preserving the sort order. /// /// This can be faster than inserting the individual elements one after another because /// we only need to re-sort once. /// /// - Complexity: O(_n * log(n)_) where _n_ is the size of the resulting array. public mutating func insert<S: Sequence>(contentsOf newElements: S) where S.Element == Element { _elements.append(contentsOf: newElements) _elements.sort(by: areInIncreasingOrder) } } extension SortedArray where Element: Comparable { /// Initializes an empty sorted array. Uses `<` as the comparison predicate. public init() { self.init(areInIncreasingOrder: <) } /// Initializes the array with a sequence of unsorted elements. Uses `<` as the comparison predicate. public init<S: Sequence>(unsorted: S) where S.Element == Element { self.init(unsorted: unsorted, areInIncreasingOrder: <) } /// Initializes the array with a sequence that is already sorted according to the `<` comparison predicate. Uses `<` as the comparison predicate. /// /// This is faster than `init(unsorted:)` because the elements don't have to sorted again. /// /// - Precondition: `sorted` is sorted according to the `<` predicate. If you violate this condition, the behavior is undefined. public init<S: Sequence>(sorted: S) where S.Element == Element { self.init(sorted: sorted, areInIncreasingOrder: <) } } extension SortedArray: RandomAccessCollection { public typealias Index = Int public var startIndex: Index { return _elements.startIndex } public var endIndex: Index { return _elements.endIndex } public func index(after i: Index) -> Index { return _elements.index(after: i) } public func index(before i: Index) -> Index { return _elements.index(before: i) } public subscript(position: Index) -> Element { return _elements[position] } } extension SortedArray { /// Like `Sequence.filter(_:)`, but returns a `SortedArray` instead of an `Array`. /// We can do this efficiently because filtering doesn't change the sort order. public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> SortedArray<Element> { let newElements = try _elements.filter(isIncluded) return SortedArray(sorted: newElements, areInIncreasingOrder: areInIncreasingOrder) } } extension SortedArray: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "\(String(describing: _elements)) (sorted)" } public var debugDescription: String { return "<SortedArray> \(String(reflecting: _elements))" } } // MARK: - Removing elements. This is mostly a reimplementation of part `RangeReplaceableCollection`'s interface. `SortedArray` can't conform to `RangeReplaceableCollection` because some of that protocol's semantics (e.g. `append(_:)` don't fit `SortedArray`'s semantics. extension SortedArray { /// Removes and returns the element at the specified position. /// /// - 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. @discardableResult public mutating func remove(at index: Int) -> Element { return _elements.remove(at: index) } /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: Range<Int>) { _elements.removeSubrange(bounds) } /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: ClosedRange<Int>) { _elements.removeSubrange(bounds) } // Starting with Swift 4.2, CountableRange and CountableClosedRange are typealiases for // Range and ClosedRange, so these methods trigger "Invalid redeclaration" errors. // Compile them only for older compiler versions. // swift(3.1): Latest version of Swift 3 under the Swift 3 compiler. // swift(3.2): Swift 4 compiler under Swift 3 mode. // swift(3.3): Swift 4.1 compiler under Swift 3 mode. // swift(3.4): Swift 4.2 compiler under Swift 3 mode. // swift(4.0): Swift 4 compiler // swift(4.1): Swift 4.1 compiler // swift(4.1.50): Swift 4.2 compiler in Swift 4 mode // swift(4.2): Swift 4.2 compiler #if !swift(>=4.1.50) /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: CountableRange<Int>) { _elements.removeSubrange(bounds) } /// Removes the elements in the specified subrange from the array. /// /// - Parameter bounds: The range of the array to be removed. The /// bounds of the range must be valid indices of the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeSubrange(_ bounds: CountableClosedRange<Int>) { _elements.removeSubrange(bounds) } #endif /// Removes the specified number of elements from the beginning of the /// array. /// /// - Parameter n: The number of elements to remove from the array. /// `n` must be greater than or equal to zero and must not exceed the /// number of elements in the array. /// /// - Complexity: O(_n_), where _n_ is the length of the array. public mutating func removeFirst(_ n: Int) { _elements.removeFirst(n) } /// Removes and returns the first element of the array. /// /// - Precondition: The array must not be empty. /// - Returns: The removed element. /// - Complexity: O(_n_), where _n_ is the length of the collection. @discardableResult public mutating func removeFirst() -> Element { return _elements.removeFirst() } /// Removes and returns the last element of the array. /// /// - Precondition: The collection must not be empty. /// - Returns: The last element of the collection. /// - Complexity: O(1) @discardableResult public mutating func removeLast() -> Element { return _elements.removeLast() } /// Removes the given number of elements from the end of the array. /// /// - Parameter n: The number of elements to remove. `n` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the array. /// - Complexity: O(1). public mutating func removeLast(_ n: Int) { _elements.removeLast(n) } /// 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. public mutating func removeAll(keepingCapacity keepCapacity: Bool = true) { _elements.removeAll(keepingCapacity: keepCapacity) } /// Removes an element from the array. If the array contains multiple /// instances of `element`, this method only removes the first one. /// /// - Complexity: O(_n_), where _n_ is the size of the array. public mutating func remove(_ element: Element) { guard let index = index(of: element) else { return } _elements.remove(at: index) } } // MARK: - More efficient variants of default implementations or implementations that need fewer constraints than the default implementations. extension SortedArray { /// Returns the first index where the specified value appears in the collection. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func firstIndex(of element: Element) -> Index? { var range: Range<Index> = startIndex ..< endIndex var match: Index? = nil while case let .found(m) = search(for: element, in: range) { // We found a matching element // Check if its predecessor also matches if let predecessor = index(m, offsetBy: -1, limitedBy: range.lowerBound), compare(self[predecessor], element) == .orderedSame { // Predecessor matches => continue searching using binary search match = predecessor range = range.lowerBound ..< predecessor } else { // We're done match = m break } } return match } /// Returns the first index in which an element of the collection satisfies the given predicate. /// /// - Requires: The `predicate` must return `false` for elements of the array up to a given point, and `true` for /// all elements after that point _(the opposite of `lastIndex(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 > … }` or `{ $0 >= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? { var match: Index? = nil if case let .found(m) = try searchFirst(where: predicate) { match = m } return match } /// Returns the first element of the sequence that satisfies the given predicate. /// /// - Requires: The `predicate` must return `false` for elements of the array up to a given point, and `true` for /// all elements after that point _(the opposite of `last(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 > … }` or `{ $0 >= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func first(where predicate: (Element) throws -> Bool) rethrows -> Element? { guard let index = try firstIndex(where: predicate) else { return nil } return self[index] } /// Returns the first index where the specified value appears in the collection. /// Old name for `firstIndex(of:)`. /// - Seealso: `firstIndex(of:)` public func index(of element: Element) -> Index? { return firstIndex(of: element) } /// Returns a Boolean value indicating whether the sequence contains the given element. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func contains(_ element: Element) -> Bool { return anyIndex(of: element) != nil } /// Returns the minimum element in the sequence. /// /// - Complexity: O(1). @warn_unqualified_access public func min() -> Element? { return first } /// Returns the maximum element in the sequence. /// /// - Complexity: O(1). @warn_unqualified_access public func max() -> Element? { return last } } // MARK: - APIs that go beyond what's in the stdlib extension SortedArray { /// Returns an arbitrary index where the specified value appears in the collection. /// Like `index(of:)`, but without the guarantee to return the *first* index /// if the array contains duplicates of the searched element. /// /// Can be slightly faster than `index(of:)`. public func anyIndex(of element: Element) -> Index? { switch search(for: element) { case let .found(at: index): return index case .notFound(insertAt: _): return nil } } /// Returns the last index where the specified value appears in the collection. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func lastIndex(of element: Element) -> Index? { var range: Range<Index> = startIndex ..< endIndex var match: Index? = nil while case let .found(m) = search(for: element, in: range) { // We found a matching element // Check if its successor also matches let lastValidIndex = index(before: range.upperBound) if let successor = index(m, offsetBy: 1, limitedBy: lastValidIndex), compare(self[successor], element) == .orderedSame { // Successor matches => continue searching using binary search match = successor guard let afterSuccessor = index(successor, offsetBy: 1, limitedBy: lastValidIndex) else { break } range = afterSuccessor ..< range.upperBound } else { // We're done match = m break } } return match } /// Returns the index of the last element in the collection that matches the given predicate. /// /// - Requires: The `predicate` must return `true` for elements of the array up to a given point, and `false` for /// all elements after that point _(the opposite of `firstIndex(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 < … }` or `{ $0 <= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func lastIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? { var match: Index? = nil if case let .found(m) = try searchLast(where: predicate) { match = m } return match } /// Returns the last element of the sequence that satisfies the given predicate. /// /// - Requires: The `predicate` must return `true` for elements of the array up to a given point, and `false` for /// all elements after that point _(the opposite of `first(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 < … }` or `{ $0 <= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. public func last(where predicate: (Element) throws -> Bool) rethrows -> Element? { guard let index = try lastIndex(where: predicate) else { return nil } return self[index] } } // MARK: - Converting between a stdlib comparator function and Foundation.ComparisonResult extension SortedArray { fileprivate func compare(_ lhs: Element, _ rhs: Element) -> Foundation.ComparisonResult { if areInIncreasingOrder(lhs, rhs) { return .orderedAscending } else if areInIncreasingOrder(rhs, lhs) { return .orderedDescending } else { // If neither element comes before the other, they _must_ be // equal, per the strict ordering requirement of `areInIncreasingOrder`. return .orderedSame } } } // MARK: - Binary search extension SortedArray { /// The index where `newElement` should be inserted to preserve the array's sort order. fileprivate func insertionIndex(for newElement: Element) -> Index { switch search(for: newElement) { case let .found(at: index): return index case let .notFound(insertAt: index): return index } } } fileprivate enum Match<Index: Comparable> { case found(at: Index) case notFound(insertAt: Index) } extension Range where Bound == Int { var middle: Int? { guard !isEmpty else { return nil } return lowerBound + count / 2 } } extension SortedArray { /// Searches the array for `element` using binary search. /// /// - Returns: If `element` is in the array, returns `.found(at: index)` /// where `index` is the index of the element in the array. /// If `element` is not in the array, returns `.notFound(insertAt: index)` /// where `index` is the index where the element should be inserted to /// preserve the sort order. /// If the array contains multiple elements that are equal to `element`, /// there is no guarantee which of these is found. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. fileprivate func search(for element: Element) -> Match<Index> { return search(for: element, in: startIndex ..< endIndex) } fileprivate func search(for element: Element, in range: Range<Index>) -> Match<Index> { guard let middle = range.middle else { return .notFound(insertAt: range.upperBound) } switch compare(element, self[middle]) { case .orderedDescending: return search(for: element, in: index(after: middle)..<range.upperBound) case .orderedAscending: return search(for: element, in: range.lowerBound..<middle) case .orderedSame: return .found(at: middle) } } /// Searches the array for the first element matching the `predicate` using binary search. /// /// - Requires: The `predicate` must return `false` for elements of the array up to a given point, and `true` for /// all elements after that point _(the opposite of `searchLast(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 > … }` or `{ $0 >= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Parameter predicate: A closure that returns `false` for elements up to a point; and `true` for all after. /// - Returns: If `element` is in the array, returns `.found(at: index)` /// where `index` is the index of the element in the array. /// If `element` is not in the array, returns `.notFound(insertAt: index)` /// where `index` is the index where the element should be inserted to /// preserve the sort order. /// If the array contains multiple elements that are equal to `element`, /// there is no guarantee which of these is found. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. /// - SeeAlso: http://ruby-doc.org/core-2.6.3/Array.html#method-i-bsearch_index fileprivate func searchFirst(where predicate: (Element) throws -> Bool) rethrows -> Match<Index> { return try searchFirst(where: predicate, in: startIndex ..< endIndex) } fileprivate func searchFirst(where predicate: (Element) throws -> Bool, in range: Range<Index>) rethrows -> Match<Index> { guard let middle = range.middle else { return .notFound(insertAt: range.upperBound) } if try predicate(self[middle]) { if middle == 0 { return .found(at: middle) } else if !(try predicate(self[index(before: middle)])) { return .found(at: middle) } else { return try searchFirst(where: predicate, in: range.lowerBound ..< middle) } } else { return try searchFirst(where: predicate, in: index(after: middle) ..< range.upperBound) } } /// Searches the array for the last element matching the `predicate` using binary search. /// /// - Requires: The `predicate` must return `true` for elements of the array up to a given point, and `false` for /// all elements after that point _(the opposite of `searchFirst(where:)`)_. /// The given point may be before the first element or after the last element; i.e. it is valid to return `true` /// for all elements or `false` for all elements. /// For most use-cases, the `predicate` closure will use the form `{ $0 < … }` or `{ $0 <= … }` _(or equivalent, /// if the SortedArray was initialized with a custom Comparator)_. /// /// - Parameter predicate: A closure that returns `false` for elements up to a point; and `true` for all after. /// - Returns: If `element` is in the array, returns `.found(at: index)` /// where `index` is the index of the element in the array. /// If `element` is not in the array, returns `.notFound(insertAt: index)` /// where `index` is the index where the element should be inserted to /// preserve the sort order. /// If the array contains multiple elements that are equal to `element`, /// there is no guarantee which of these is found. /// /// - Complexity: O(_log(n)_), where _n_ is the size of the array. /// - SeeAlso: http://ruby-doc.org/core-2.6.3/Array.html#method-i-bsearch_index fileprivate func searchLast(where predicate: (Element) throws -> Bool) rethrows -> Match<Index> { return try searchLast(where: predicate, in: startIndex ..< endIndex) } fileprivate func searchLast(where predicate: (Element) throws -> Bool, in range: Range<Index>) rethrows -> Match<Index> { guard let middle = range.middle else { return .notFound(insertAt: range.upperBound) } if try predicate(self[middle]) { if middle == range.upperBound - 1 { return .found(at: middle) } else if !(try predicate(self[index(after: middle)])) { return .found(at: middle) } else { return try searchLast(where: predicate, in: index(after: middle) ..< range.upperBound) } } else { return try searchLast(where: predicate, in: range.lowerBound ..< middle) } } } #if swift(>=4.1) extension SortedArray: Equatable where Element: Equatable { public static func == (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> Bool { // Ignore the comparator function for Equatable return lhs._elements == rhs._elements } } #else public func ==<Element: Equatable> (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> Bool { return lhs._elements == rhs._elements } public func !=<Element: Equatable> (lhs: SortedArray<Element>, rhs: SortedArray<Element>) -> Bool { return lhs._elements != rhs._elements } #endif #if swift(>=4.1.50) extension SortedArray: Hashable where Element: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(_elements) } } #endif
ed2ac1efb9f34f967515beb4deb4707f
44.020478
271
0.633879
false
false
false
false
wibosco/SwiftPaginationCoreData-Example
refs/heads/master
SwiftPaginationCoreDataExample/ViewControllers/Question/Cells/QuestionTableViewCell.swift
mit
1
// // QuestionTableViewCell.swift // SwiftPaginationCoreDataExample // // Created by Home on 27/02/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit import PureLayout class QuestionTableViewCell: UITableViewCell { //MARK: - Accessors lazy var titleLabel : UILabel = { let label = UILabel.newAutoLayoutView() label.numberOfLines = 2 label.font = UIFont.boldSystemFontOfSize(15) return label }() lazy var authorLabel : UILabel = { let label = UILabel.newAutoLayoutView() label.font = UIFont.systemFontOfSize(14) return label }() //MARK: - Init override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.authorLabel) self.contentView.backgroundColor = UIColor.whiteColor() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARK: - Constraints override func updateConstraints() { self.titleLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.contentView, withOffset: 10.0) self.titleLabel.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: self.contentView, withOffset: 8.0) self.titleLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.contentView, withOffset: -10.0) /*---------------------*/ self.authorLabel.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Left, ofView: self.contentView, withOffset: 10.0) self.authorLabel.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: self.contentView, withOffset: -10.0) self.authorLabel.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: self.contentView, withOffset: -5.0) /*---------------------*/ super.updateConstraints() } func layoutByApplyingConstraints() { self.setNeedsUpdateConstraints() self.updateConstraintsIfNeeded() self.setNeedsLayout() self.layoutIfNeeded() } //MARK: - ReuseIdentifier class func reuseIdentifier() -> String { return NSStringFromClass(QuestionTableViewCell.self) } }
803cd68e29483bf246fa99ecc2747b74
29.0375
118
0.632127
false
false
false
false
amdaza/HackerBooks
refs/heads/master
HackerBooks/HackerBooks/AsyncImage.swift
gpl-3.0
1
// // AsyncImage.swift // HackerBooks // // Created by Alicia Daza on 16/07/16. // Copyright © 2016 Alicia Daza. All rights reserved. // import UIKit let ImageDidChangeNotification = "Book image did change" let ImageKey = "imageKey" class AsyncImage { var image: UIImage let url: URL var loaded: Bool init(remoteUrl url: URL, defaultImage image: UIImage){ self.url = url self.image = image self.loaded = false } func downloadImage() { let queue = DispatchQueue(label: "downloadImages", attributes: []) queue.async { if let data = try? Data(contentsOf: self.url), let img = UIImage(data: data){ DispatchQueue.main.async { self.image = img self.loaded = true // Notify let nc = NotificationCenter.default let notif = Notification(name: Notification.Name(rawValue: ImageDidChangeNotification), object: self, userInfo: [ImageKey: self.url.path]) nc.post(notif) } } else { //throw HackerBooksError.resourcePointedByUrLNotReachable } } } func getImage() { if (!loaded) { // Get cache url if let cacheUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first{ // First because it returns an array // Get image filename let imageFileName = url.lastPathComponent //{ let destination = cacheUrl.appendingPathComponent(imageFileName) // Check if image exists before downloading it if FileManager().fileExists(atPath: destination.path) { // File exists at path if let data = try? Data(contentsOf: destination), let img = UIImage(data: data){ self.image = img } } else { // File doesn't exists. Download downloadImage() } } } } }
fa6df578553f8091e5c2995c50b001f1
26.407407
121
0.517117
false
false
false
false
DanielCech/Vapor-Catalogue
refs/heads/master
Sources/App/Models/Artist.swift
mit
1
// // Artist.swift // Catalog // // Created by Dan on 18.01.17. // // import Foundation import Vapor import HTTP final class Artist: Model { var id: Node? var exists: Bool = false var name: String init(name: String) { self.id = nil self.name = name } init(node: Node, in context: Context) throws { id = try node.extract("id") name = try node.extract("name") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "name": name ]) } static func prepare(_ database: Database) throws { try database.create("artists") { artists in artists.id() artists.string("name") } } static func revert(_ database: Database) throws { try database.delete("artists") } } extension Artist { func albums() throws -> [Album] { return try children(nil, Album.self).all() } }
3a1dbbfe75e37b54cc7a6fe6a1f877ff
16.913793
54
0.517806
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/LinearEquations/Solution/Items/MLinearEquationsSolutionEquationItemEquals.swift
mit
1
import UIKit class MLinearEquationsSolutionEquationItemEquals:MLinearEquationsSolutionEquationItem { let image:UIImage private let kCellWidth:CGFloat = 20 private let kEquals:String = "=" init() { image = #imageLiteral(resourceName: "assetGenericColEqualsSmall") let reusableIdentifier:String = VLinearEquationsSolutionCellEquals.reusableIdentifier super.init( reusableIdentifier:reusableIdentifier, cellWidth:kCellWidth) } override func shareText() -> String? { return kEquals } override func drawInRect(rect:CGRect) { let imageWidth:CGFloat = image.size.width let imageHeight:CGFloat = image.size.height let remainTop:CGFloat = rect.size.height - imageHeight let remainLeft:CGFloat = rect.size.width - imageWidth let marginTop:CGFloat = remainTop / 2.0 let marginLeft:CGFloat = remainLeft / 2.0 let posX:CGFloat = marginLeft + rect.origin.x let posY:CGFloat = marginTop + rect.origin.y let rect:CGRect = CGRect( x:posX, y:posY, width:imageWidth, height:imageHeight) image.draw(in:rect) } }
83c7b2a069d74560dc50e583d2ca8db2
28.488372
94
0.630126
false
false
false
false
cozkurt/coframework
refs/heads/main
COFramework/COFramework/Swift/Extentions/UITableView+Additions.swift
gpl-3.0
1
// // UITableView+Additions.swift // FuzFuz // // Created by Cenker Ozkurt on 10/07/19. // Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved. // import UIKit import Foundation extension UITableView { public func addColorToBottom(color: UIColor) { let tag = 9000009 if self.tableFooterView?.viewWithTag(tag) != nil { return } if let _ = self.tableFooterView {} else { self.addFooter() } let size = UIScreen.main.bounds let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let bgView = UIView(frame: rect) bgView.tag = tag bgView.backgroundColor = color self.tableFooterView?.clipsToBounds = false self.tableFooterView?.addSubview(bgView) } public func addFooter(height: CGFloat = 0) { self.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: height)) } public func addEmptyFooter() { self.tableFooterView = UIView(frame: CGRect.zero) } public func removeFooter() { let tag = 9000009 if self.tableFooterView?.viewWithTag(tag) != nil { self.tableFooterView?.viewWithTag(tag)?.removeFromSuperview() } } public func scrollToBottom(animated: Bool = true) { if self.visibleCells.count == 0 { return } DispatchQueue.main.async { let section = max(self.numberOfSections - 1, 0) let row = max(self.numberOfRows(inSection: section) - 1, 0) if row == 0 && section == 0 { return } let indexPath = IndexPath(row: row, section: section) self.scrollToRow(at: indexPath, at: .bottom, animated: animated) } } public func scrollToTop(animated: Bool = false) { if self.visibleCells.count == 0 { return } DispatchQueue.main.async { let indexPath = IndexPath(row: 0, section: 0) self.scrollToRow(at: indexPath, at: .top, animated: animated) } } } extension UITableView { public func setUpRefreshing(_ object: Any, _ refreshText:String = "", handleRefresh: Selector?) { if refreshControl == nil { addRefreshUI(object, refreshText, handleRefresh) } } public func endRefreshing() { self.refreshControl?.endRefreshing() } public func sendValueChangeAction() { self.refreshControl?.sendActions(for: .valueChanged) } public func addRefreshUI(_ object: Any, _ refreshText:String, _ handleRefresh: Selector?) { let refreshControl = UIRefreshControl() if let handleRefresh = handleRefresh { refreshControl.addTarget(object, action: handleRefresh, for: .valueChanged) } let attributes = [NSAttributedString.Key.foregroundColor: UIColor.systemGray] refreshControl.attributedTitle = NSAttributedString(string: refreshText, attributes: attributes) self.refreshControl = refreshControl } }
4a95b27e5caf7f9033736397365cb8da
28.903846
110
0.611576
false
false
false
false
Scior/Spica
refs/heads/master
Spica/ImageViewController.swift
mit
1
// // ImageViewController.swift // Spica // // Created by Scior on 2016/10/17. // Copyright © 2017年 Scior All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { // MARK: プロパティ var photo : Photo? { didSet { image = nil if view.window != nil { fetchImage() } titleLabel.text = photo?.title == "" ? " " : photo?.title userNameLabel.text = photo?.ownerName } } var photos : [Photo]? /// ダウンロードした画像を格納する private var imageHolder : [URL : UIImage] = [:] private var imageView = UIImageView() private var image: UIImage? { get { return imageView.image } set { scrollView?.zoomScale = 1.0 imageView.image = newValue imageView.sizeToFit() if let image = newValue { scrollView?.contentSize = imageView.frame.size scrollView.minimumZoomScale = min(scrollView.frame.size.height / image.size.height, scrollView.frame.size.width / image.size.width) scrollView.zoomScale = scrollView.minimumZoomScale updateScrollInset() } } } private var fetchingURL : URL? @IBOutlet weak var scrollView: UIScrollView! { didSet { scrollView.contentSize = imageView.frame.size scrollView.delegate = self scrollView.minimumZoomScale = 1.0 scrollView.maximumZoomScale = 2.0 } } @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var titleLabel: UILabel! { didSet { titleLabel.accessibilityIdentifier = "Title Label" } } @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var exifButton: UIButton! { didSet { exifButton.accessibilityIdentifier = "Exif Button" } } // MARK: - メソッド override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(imageView) } override func viewDidAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanging(notification:)), name: .UIDeviceOrientationDidChange, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if image == nil { fetchImage() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// スワイプ時の処理 // @IBAction func recognizeSwipe(_ sender: UISwipeGestureRecognizer) { // guard let photo = photo, // let photos = photos, // let index = photos.index(of: photo) else { return } // // let count = photos.count // // if sender.direction == .right { // if index + 1 < count { // self.photo = photos[index + 1] // } // } else if sender.direction == .left { // if index - 1 >= 0 { // self.photo = photos[index - 1] // } // } // } /// ダブルタップの処理 @IBAction func recognizeTap(_ sender: UITapGestureRecognizer) { let scale = scrollView.zoomScale == scrollView.minimumZoomScale ? 1.0 : scrollView.minimumZoomScale UIView.animate(withDuration: 0.5) { self.scrollView.zoomScale = scale } } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { updateScrollInset() } func onOrientationChanging(notification: Notification) { if let image = image { scrollView.minimumZoomScale = min(scrollView.frame.size.height / image.size.height, scrollView.frame.size.width / image.size.width) } } /// 画像を非同期で取得 private func fetchImage() { guard let url = photo?.urls.largeImageURL ?? photo?.urls.originalImageURL else { return } // 既に取得していたらそれを使う if let image = imageHolder[url] { self.image = image return } fetchingURL = url spinner?.startAnimating() DispatchQueue.global(qos: .userInitiated).async { var contentsOfURL : Data? = nil do { contentsOfURL = try Data(contentsOf: url) } catch let error { log?.error(error) self.spinner?.stopAnimating() return } DispatchQueue.main.async { if url == self.fetchingURL, let contents = contentsOfURL { self.image = UIImage(data: contents) self.imageHolder[url] = self.image self.spinner?.stopAnimating() } } } } /// 画像を中央に持ってくるように調整 private func updateScrollInset() { scrollView.contentInset = UIEdgeInsetsMake( max((scrollView.frame.height - imageView.frame.height) / 2, 0), max((scrollView.frame.width - imageView.frame.width) / 2, 0), 0, 0 ) } }
75646da9726ea8bebed8b56ef5ed4d2e
28.423913
161
0.551533
false
false
false
false
LubosPlavucha/CocoaGlue
refs/heads/master
CocoaGlue/classes/BDatePickerTextField.swift
mit
1
// Created by lubos plavucha on 06/12/14. // Copyright (c) 2014 Acepricot. All rights reserved. // import Foundation import UIKit open class BDatePickerTextField: BTextField { open weak var listener : BDatePickerTextFieldProtocol? fileprivate var datePicker: UIDatePicker! public required init?(coder: NSCoder) { super.init(coder: coder) datePicker = UIDatePicker() datePicker.datePickerMode = .date; datePicker.addTarget(self, action: #selector(BDatePickerTextField.dateChanged), for: .valueChanged) self.inputView = datePicker } func dateChanged() { assert(formatter != nil && formatter is DateFormatter) // sets value from date picker both to entity and text field modelBeingUpdated = true; self.object.setValue(datePicker.date, forKeyPath: self.keyPath) self.text = (formatter as! DateFormatter).string(from: datePicker.date) modelBeingUpdated = false; listener?.dateChanged() } override func setValueFromComponent(_ value: String?) { // should not be implemented - text field change event should do nothing, because date picker takes control } override func setValueFromModel(_ value: AnyObject?, placeholder: Bool? = false) { assert(formatter != nil && formatter is DateFormatter) if modelBeingUpdated { return } let placeholder = placeholder != nil && placeholder == true // TODO crashing sometime -> even if it shows here it is not nil - in fact, there is hidden null pointer -> reproduce this when trying to set date to nil if value is NSDate { self.text = (formatter as! DateFormatter).string(from: value as! Date) datePicker.date = value as! Date } else { // show placeholder if it is wished, because there is no value self.placeholder = placeholder ? (formatter as! DateFormatter).dateFormat : "" } } }
012de6f59b124d9a1b41498a42eb08a2
34
161
0.639709
false
false
false
false
VadimPavlov/Swifty
refs/heads/master
Sources/Swifty/ios/CoreData/Primitives.swift
mit
1
// // Primitives.swift // Swifty // // Created by Vadim Pavlov on 10/20/17. // Copyright © 2017 Vadym Pavlov. All rights reserved. // import CoreData public protocol Primitives: AnyObject { associatedtype PrimitiveKey: RawRepresentable } public extension Primitives where Self: NSManagedObject, PrimitiveKey.RawValue == String { subscript<O>(key: PrimitiveKey) -> O? { set { let primitiveKey = key.rawValue let primitiveValue = newValue self.willChangeValue(forKey: primitiveKey) if let value = primitiveValue { self.setPrimitiveValue(value, forKey: primitiveKey) } else { self.setPrimitiveValue(nil, forKey: primitiveKey) } self.didChangeValue(forKey: primitiveKey) } get { let primitiveKey = key.rawValue self.willAccessValue(forKey: primitiveKey) let primitiveValue = self.primitiveValue(forKey: primitiveKey) as? O self.didAccessValue(forKey: primitiveKey) return primitiveValue } } subscript<P: RawRepresentable>(key: PrimitiveKey) -> P? { set { let primitiveKey = key.rawValue let primitiveValue = newValue?.rawValue self.willChangeValue(forKey: primitiveKey) self.setPrimitiveValue(primitiveValue, forKey: primitiveKey) self.didChangeValue(forKey: primitiveKey) } get { let primitiveKey = key.rawValue self.willAccessValue(forKey: primitiveKey) let primitiveValue = self.primitiveValue(forKey: primitiveKey) as? P.RawValue self.didAccessValue(forKey: primitiveKey) return primitiveValue.flatMap(P.init) } } }
368ab6dde965d947db0da2be201e2a50
32.425926
90
0.624377
false
false
false
false
velvetroom/columbus
refs/heads/master
Source/View/Plans/VPlansList+Actions.swift
mit
1
import UIKit extension VPlansList { //MARK: internal func modelAtIndex(index:IndexPath) -> DPlan { let item:DPlan = controller.model.plans![index.item] return item } func modelIsActive(model:DPlan) -> Bool { guard let active:DPlan = controller.model.settings?.activePlan, active === model else { return false } return true } }
4725dc813dfa056beb593ef2dc2fc2c4
16.642857
69
0.5
false
false
false
false
lemberg/obd2-swift-lib
refs/heads/master
OBD2-Swift/Classes/Operations/OpenOBDConnectionOperation.swift
mit
1
// // OpenOBDConnectionOperation.swift // OBD2Swift // // Created by Sergiy Loza on 30.05.17. // Copyright © 2017 Lemberg. All rights reserved. // import Foundation class OpenOBDConnectionOperation: StreamHandleOperation { class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["inputOpen" as NSObject, "outOpen" as NSObject, "error" as NSObject] } class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["inputOpen" as NSObject, "outOpen" as NSObject, "error" as NSObject] } private var inputOpen = false { didSet { if inputOpen { print("Input stream opened") input.remove(from: .current, forMode: .defaultRunLoopMode) } } } private var outOpen = false { didSet { if outOpen { print("Output stream opened") output.remove(from: .current, forMode: .defaultRunLoopMode) } } } override var isExecuting: Bool { let value = !(inputOpen && outOpen) && error == nil print("isExecuting \(value)") return value } override var isFinished: Bool { let value = (inputOpen && outOpen) || error != nil print("isFinished \(value)") return value } override func execute() { input.open() output.open() } override func inputStremEvent(event: Stream.Event) { if event == .openCompleted { inputOpen = true } else if event == .errorOccurred { print("Stream open error") self.error = input.streamError } } override func outputStremEvent(event: Stream.Event) { if event == .openCompleted { outOpen = true } else if event == .errorOccurred { print("Stream open error") self.error = output.streamError } } }
46166a858d18f47e48684ab0d3997f0a
26.246575
84
0.564605
false
false
false
false
attackFromCat/LivingTVDemo
refs/heads/master
LivingTVDemo/LivingTVDemo/Classes/Main/View/PageTitleView.swift
mit
1
// // PageTitleView.swift // LivingTVDemo // // Created by 李翔 on 2017/1/9. // Copyright © 2017年 Lee Xiang. All rights reserved. // import UIKit // MARK: - 代理协议 protocol PageTitleViewDelegate : class { func titleLabelClick(_ titleView : PageTitleView, selectedIndex : Int) } // MARK: - 定义常量 fileprivate let kTitleUnderlineH : CGFloat = 2 fileprivate let kNormalColor : (CGFloat ,CGFloat ,CGFloat) = (85, 85, 85) fileprivate let kSelectedColor : (CGFloat ,CGFloat ,CGFloat) = (255, 128, 0) class PageTitleView: UIView { // MARK: - 属性 fileprivate var titles : [String] fileprivate var currentIndex : Int = 0 weak var delegate : PageTitleViewDelegate? // MARK: - 懒加载 fileprivate lazy var titleLabels : [UILabel] = [UILabel]() fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var titleUnderLine :UIView = { let titleUnderLine = UIView() titleUnderLine.backgroundColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0) return titleUnderLine }() init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) setUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func setUI() { // 添加滚动视图 addSubview(scrollView) scrollView.frame = bounds // 添加滚动视图上面的label createTitleLabers() //设置底部分界线和滚动线条 createTitleUnderLine() } fileprivate func createTitleLabers() { let titleLabelW : CGFloat = frame.width / CGFloat(titles.count) let titleLabelH : CGFloat = frame.height - kTitleUnderlineH let titleLabelY : CGFloat = 0 for (index, title) in titles.enumerated() { let label = UILabel() label.font = UIFont.systemFont(ofSize: 16) label.textAlignment = .center label.text = title label.tag = index label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2, alpha: 1.0) let titleLabelX : CGFloat = CGFloat(index) * titleLabelW label.frame = CGRect(x: titleLabelX, y: titleLabelY, width: titleLabelW, height: titleLabelH) // 创建手势监听点击事件 label.isUserInteractionEnabled = true let tapGestrue = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelDidClick(_:))) label.addGestureRecognizer(tapGestrue) scrollView.addSubview(label) // 保存创建的label titleLabels.append(label) } } fileprivate func createTitleUnderLine() { // 标题模块与滑动内容的分界线 let DividingLine = UIView() let lineH : CGFloat = 0.5 DividingLine.backgroundColor = UIColor.lightGray DividingLine.frame = CGRect(x: 0, y: frame.height - lineH, width: scrollView.frame.width, height: lineH) scrollView.addSubview(DividingLine) // 滚动滑块 guard let fristBtn = titleLabels.first else {return} fristBtn.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0) titleUnderLine.frame = CGRect(x: 0, y: frame.height - kTitleUnderlineH, width: fristBtn.frame.width, height: kTitleUnderlineH) scrollView.addSubview(titleUnderLine) } } // MARK: - label的点击事件 extension PageTitleView { @objc func titleLabelDidClick(_ tapGest : UITapGestureRecognizer) { // 拿到选中的label guard let selectedLabel = tapGest.view as? UILabel else { return } let prelabel = titleLabels[currentIndex] // 变化颜色 prelabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2, alpha: 1.0) selectedLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2, alpha: 1.0) // 重新记录当前下标 currentIndex = selectedLabel.tag // 滑动下划线 let offSetX = CGFloat(currentIndex) * titleUnderLine.frame.width UIView.animate(withDuration: 0.15) { self.titleUnderLine.frame.origin.x = offSetX } // 代理传值 delegate?.titleLabelClick(self, selectedIndex: currentIndex) } } // MARK: - 暴露的方法 extension PageTitleView { func setTitleStatus(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 取出要进行变化的两个label let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] // 移动下划线 let offSetX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let lineOffsetX = offSetX * progress titleUnderLine.frame.origin.x = sourceLabel.frame.origin.x + lineOffsetX // 改变标题的颜色 // 取出颜色改变的范围 let colorRange = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2) sourceLabel.textColor = UIColor(r: kSelectedColor.0 - colorRange.0 * progress, g: kSelectedColor.1 - colorRange.1 * progress, b: kSelectedColor.2 - colorRange.2 * progress, alpha: 1.0) targetLabel.textColor = UIColor(r: kNormalColor.0 + colorRange.0 * progress, g: kNormalColor.1 + colorRange.1 * progress, b: kNormalColor.2 + colorRange.2 * progress, alpha: 1.0) // 记录最新的下标值 currentIndex = targetIndex } }
3b665341c08c8760ec5b86af9ffcfd25
33.394118
192
0.624594
false
false
false
false
apple/swift-tools-support-core
refs/heads/main
Sources/TSCBasic/Thread.swift
apache-2.0
1
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation #if os(Windows) import WinSDK #endif /// This class bridges the gap between Darwin and Linux Foundation Threading API. /// It provides closure based execution and a join method to block the calling thread /// until the thread is finished executing. final public class Thread { /// The thread implementation which is Foundation.Thread on Linux and /// a Thread subclass which provides closure support on Darwin. private var thread: ThreadImpl! /// Condition variable to support blocking other threads using join when this thread has not finished executing. private var finishedCondition: Condition /// A boolean variable to track if this thread has finished executing its task. private var isFinished: Bool /// Creates an instance of thread class with closure to be executed when start() is called. public init(task: @escaping () -> Void) { isFinished = false finishedCondition = Condition() // Wrap the task with condition notifying any other threads blocked due to this thread. // Capture self weakly to avoid reference cycle. In case Thread is deinited before the task // runs, skip the use of finishedCondition. let theTask = { [weak self] in if let strongSelf = self { precondition(!strongSelf.isFinished) strongSelf.finishedCondition.whileLocked { task() strongSelf.isFinished = true strongSelf.finishedCondition.broadcast() } } else { // If the containing thread has been destroyed, we can ignore the finished condition and just run the // task. task() } } self.thread = ThreadImpl(block: theTask) } /// Starts the thread execution. public func start() { thread.start() } /// Blocks the calling thread until this thread is finished execution. public func join() { finishedCondition.whileLocked { while !isFinished { finishedCondition.wait() } } } /// Causes the calling thread to yield execution to another thread. public static func yield() { #if os(Windows) SwitchToThread() #else sched_yield() #endif } } #if canImport(Darwin) /// A helper subclass of Foundation's Thread with closure support. final private class ThreadImpl: Foundation.Thread { /// The task to be executed. private let task: () -> Void override func main() { task() } init(block task: @escaping () -> Void) { self.task = task } } #else // Thread on Linux supports closure so just use it directly. typealias ThreadImpl = Foundation.Thread #endif
a9c9ade53ad260abbc314bf65a3bb82f
30.959596
117
0.645702
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/SILOptimizer/unreachable_code.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify func ifFalse() -> Int { if false { // expected-note {{always evaluates to false}} return 0 // expected-warning {{will never be executed}} } else { return 1 } } func ifTrue() -> Int { _ = 0 if true { // expected-note {{always evaluates to true}} return 1 } return 0 // expected-warning {{will never be executed}} } // Work-around <rdar://problem/17687851> by ensuring there is // something that appears to be user code in unreachable blocks. func userCode() {} func whileTrue() { var x = 0 while true { // expected-note {{always evaluates to true}} x += 1 } userCode() // expected-warning {{will never be executed}} } func whileTrueSilent() { while true { } } // no warning! func whileTrueReachable(_ v: Int) -> () { var x = 0 while true { if v == 0 { break } x += 1 } x -= 1 } func whileTrueTwoPredecessorsEliminated() -> () { var x = 0 while (true) { // expected-note {{always evaluates to true}} if false { break } x += 1 } userCode() // expected-warning {{will never be executed}} } func unreachableBranch() -> Int { if false { // expected-note {{always evaluates to false}} // FIXME: It'd be nice if the warning were on 'if true' instead of the // body. if true { return 0 // expected-warning {{will never be executed}} } } else { return 1 } } // We should not report unreachable user code inside inlined transparent function. @_transparent func ifTrueTransparent(_ b: Bool) -> Int { _ = 0 if b { return 1 } return 0 } func testIfTrueTransparent() { _ = ifTrueTransparent(true) // no-warning _ = ifTrueTransparent(false) // no-warning } // We should not report unreachable user code inside generic instantiations. // TODO: This test should start failing after we add support for generic // specialization in SIL. To fix it, add generic instantiation detection // within the DeadCodeElimination pass to address the corresponding FIXME note. protocol HavingGetCond { func getCond() -> Bool } struct ReturnsTrue : HavingGetCond { func getCond() -> Bool { return true } } struct ReturnsOpaque : HavingGetCond { var b: Bool func getCond() -> Bool { return b } } func ifTrueGeneric<T : HavingGetCond>(_ x: T) -> Int { if x.getCond() { return 1 } return 0 } func testIfTrueGeneric(_ b1: ReturnsOpaque, b2: ReturnsTrue) { _ = ifTrueGeneric(b1) // no-warning _ = ifTrueGeneric(b2) // no-warning } // Test switch_enum folding/diagnostic. enum X { case One case Two case Three } func testSwitchEnum(_ xi: Int) -> Int { var x = xi let cond: X = .Two switch cond { // expected-warning {{switch condition evaluates to a constant}} case .One: userCode() // expected-note {{will never be executed}} case .Two: x -= 1 case .Three: x -= 1 } switch cond { // no warning default: x += 1 } switch cond { // expected-warning{{switch condition evaluates to a constant}} case .Two: x += 1 default: userCode() // expected-note{{will never be executed}} } switch cond { // expected-warning{{switch condition evaluates to a constant}} case .One: userCode() // expected-note{{will never be executed}} default: x -= 1 } return x } @_silgen_name("exit") func exit() -> Never func reachableThroughNonFoldedPredecessor(fn: @autoclosure () -> Bool = false) { if !_fastPath(fn()) { exit() } var _: Int = 0 // no warning } func intConstantTest() -> Int{ let y: Int = 1 if y == 1 { // expected-note {{condition always evaluates to true}} return y } return 1 // expected-warning {{will never be executed}} } func intConstantTest2() -> Int{ let y:Int = 1 let x:Int = y if x != 1 { // expected-note {{condition always evaluates to false}} return y // expected-warning {{will never be executed}} } return 3 } func test_single_statement_closure(_ fn:() -> ()) {} test_single_statement_closure() { exit() // no-warning } class C { } class Super { var s = C() deinit { // no-warning } } class D : Super { var c = C() deinit { // no-warning exit() } } // <rdar://problem/20097963> incorrect DI diagnostic in unreachable code enum r20097963Test { case A case B } class r20097963MyClass { func testStr(_ t: r20097963Test) -> String { let str: String switch t { case .A: str = "A" case .B: str = "B" default: // expected-warning {{default will never be executed}} str = "unknown" // Should not be rejected. } return str } } func die() -> Never { die() } func testGuard(_ a : Int) { guard case 4 = a else { } // expected-error {{'guard' body must not fall through, consider using a 'return' or 'throw'}} guard case 4 = a else { return } // ok guard case 4 = a else { die() } // ok guard case 4 = a else { fatalError("baaad") } // ok for _ in 0...100 { guard case 4 = a else { continue } // ok } } func testFailingCast(_ s:String) -> Int { // There should be no notes or warnings about a call to a noreturn function, because we do not expose // how casts are lowered. return s as! Int // expected-warning {{cast from 'String' to unrelated type 'Int' always fails}} } enum MyError : Error { case A } func raise() throws -> Never { throw MyError.A } func test_raise_1() throws -> Int { try raise() } func test_raise_2() throws -> Int { try raise() // expected-note {{a call to a never-returning function}} try raise() // expected-warning {{will never be executed}} } // If a guaranteed self call requires cleanup, don't warn about // release instructions struct Algol { var x: [UInt8] func fail() throws -> Never { throw MyError.A } mutating func blah() throws -> Int { try fail() // no-warning } } class Lisp { func fail() throws -> Never { throw MyError.A } } func transform<Scheme : Lisp>(_ s: Scheme) throws { try s.fail() // no-warning } func deferNoReturn() throws { defer { _ = Lisp() // no-warning } die() } func deferTryNoReturn() throws { defer { _ = Lisp() // no-warning } try raise() } func noReturnInDefer() { defer { _ = Lisp() die() // expected-note {{a call to a never-returning function}} die() // expected-warning {{will never be executed}} } } while true { } // no warning! // SR-1010 - rdar://25278336 - Spurious "will never be executed" warnings when building standard library struct SR1010<T> { var a : T } extension SR1010 { @available(*, unavailable, message: "use the 'enumerated()' method on the sequence") init(_ base: Int) { fatalError("unavailable function can't be called") } } // More spurious 'will never be executed' warnings struct FailingStruct { init?(x: ()) { fatalError("gotcha") } } class FailingClass { init?(x: ()) { fatalError("gotcha") } convenience init?(y: ()) { fatalError("gotcha") } }
a65cbc5ccad3b2ef7919199952450d23
20.46789
124
0.626353
false
false
false
false
Eonil/Editor
refs/heads/develop
Editor4/Version.swift
mit
1
// // Version.swift // Editor4 // // Created by Hoon H. on 2016/05/09. // Copyright © 2016 Eonil. All rights reserved. // /// Instantiation produces different version value. /// Copy produces equal version value. public struct Version: Hashable, VersionType, RevisableVersionType { public init() { } public var hashValue: Int { get { return ObjectIdentifier(addressID).hashValue } } private var addressID = NonObjectiveCBase() /// Exists only for debugging convenience. /// Can be wrong in multi-threaded code... Don't care for now. private var revisionCountForDebuggingOnly = Int(0) } public extension Version { public mutating func revise() { self = revised() } public func revised() -> Version { var copy = self guard copy.revisionCountForDebuggingOnly < Int.max else { return Version() } copy.addressID = NonObjectiveCBase() copy.revisionCountForDebuggingOnly += 1 return copy } } extension Version: CustomDebugStringConvertible { public var debugDescription: String { get { let id = String(format: "%x", ObjectIdentifier(addressID).uintValue) let rev = String(format: "%i", revisionCountForDebuggingOnly) return "(" + id + "/" + rev + ")" } } } public func == (a: Version, b: Version) -> Bool { return a.addressID === b.addressID }
33ae3c173e8c3ce45c117c5b758ea6f5
22.75
84
0.637193
false
false
false
false
Wzxhaha/Viscosity
refs/heads/dev
Example/Example_iOS/Example_iOS/VisExampleAnimatedView.swift
mit
1
// // VisExampleAnimatedView.swift // Example // // Created by WzxJiang on 17/2/6. // Copyright © 2017年 wzxjiang. All rights reserved. // import UIKit import Viscosity class VisExampleAnimatedView: UIView { var redView: UIView! var greenView: UIView! var blueView: UIView! var padding: CGFloat = 10.0 var animating = false init() { super.init(frame: .null) createUI() } func createUI() -> Void { let padding: CGFloat = 10.0 let paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding) redView = UIView.exampleView(color: .red) addSubview(redView) greenView = UIView.exampleView(color: .green) addSubview(greenView) blueView = UIView.exampleView(color: .blue) addSubview(blueView) redView.vis.makeConstraints { make in make.edges == self +~ paddingInsets ~~ .low make.bottom == blueView.vis.top +~ -padding make.size == greenView make.height == blueView } greenView.vis.makeConstraints { make in make.edges == self +~ paddingInsets ~~ .low make.left == redView.vis.right +~ padding make.bottom == blueView.vis.top +~ -padding make.height == blueView } blueView.vis.makeConstraints { make in make.edges == self +~ paddingInsets ~~ .low } } override func willMove(toWindow newWindow: UIWindow?) { animating = newWindow != nil; } override func didMoveToWindow() { layoutIfNeeded() if ((window) != nil) { animating = true animate(withInvertedInsets: false) } } func animate(withInvertedInsets invertedInsets: Bool) -> Void { if (!animating) { return } let padding = invertedInsets ? 100 : self.padding; let paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding) redView.vis.updateConstraints { make in make.edges == self +~ paddingInsets ~~ .low make.bottom == blueView.vis.top +~ -padding } greenView.vis.updateConstraints { make in make.left == redView.vis.right +~ padding make.bottom == blueView.vis.top +~ -padding make.edges == self +~ paddingInsets ~~ .low } blueView.vis.updateConstraints { make in make.edges == self +~ paddingInsets ~~ .low } UIView.animate(withDuration: 1, animations: { self.layoutIfNeeded() }) { _ in self.animate(withInvertedInsets: !invertedInsets) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
994b5a1534d5fb09bf525434757a8ac0
27.009615
80
0.560247
false
false
false
false