repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
cp3hnu/Bricking
refs/heads/master
Bricking/Source/Center.swift
mit
1
// // Center.swift // Bricking // // Created by CP3 on 2017/7/1. // Copyright © 2017年 CP3. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif extension View { @discardableResult public func centerInContainer() -> Self { centerHorizontally() centerVertically() return self } @discardableResult public func centerHorizontally(_ offset: CGFloat = 0) -> Self { self.laCenterX == offset return self } @discardableResult public func centerVertically(_ offset: CGFloat = 0) -> Self { self.laCenterY == offset return self } } @discardableResult public func centerHorizontally(_ views: View...) -> [View] { return centerHorizontally(views) } @discardableResult public func centerHorizontally(_ views: [View]) -> [View] { views.first?.centerHorizontally() alignVertically(views) return views } @discardableResult public func centerVertically(_ views: View...) -> [View] { return centerVertically(views) } @discardableResult public func centerVertically(_ views: [View]) -> [View] { views.first?.centerVertically() alignHorizontally(views) return views } extension Array where Element: View { @discardableResult public func centerHorizontally() -> Array<View> { return Bricking.centerHorizontally(self) } @discardableResult public func centerVertically() -> Array<View> { return Bricking.centerVertically(self) } }
5dd86abdd0166be9b16a84cf32487244
20.943662
67
0.661104
false
false
false
false
SaeidBsn/SwiftyGuideOverlay
refs/heads/master
Sample/SwiftyGuideOverlay/ViewController.swift
mit
1
// // ViewController.swift // SwiftyGuideOverlay // // Created by Saeid Basirnia on 8/19/16. // Copyright © 2016 Saeid Basirnia. All rights reserved. // import UIKit class ViewController: UIViewController, SkipOverlayDelegate{ @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! @IBOutlet weak var tableView: UITableView! var navItem: UIBarButtonItem! var navItem2: UIBarButtonItem! var list: [String] = [ "This is number 1", "This is number 2", "This is number 3", "This is number 4", "This is number 5", ] var o: GDOverlay! override func viewDidAppear(_ animated: Bool){ navItem = navigationItem.leftBarButtonItem navItem2 = navigationItem.rightBarButtonItem navItem2.title = "Share" navItem.title = "cool" //Create an instance of GDOverlay to setup help view o = GDOverlay() /////appereance customizations o.arrowColor = UIColor.red o.showBorder = false o.boxBackColor = UIColor.clear o.highlightView = true //o.arrowWidth = 2.0 //o.backColor = UIColor.blue //o.showBorder = true o.boxBackColor = UIColor.gray.withAlphaComponent(0.2) //o.boxBorderColor = UIColor.black //o.headColor = UIColor.white //o.headRadius = 6 //o.labelFont = UIFont.systemFont(ofSize: 12) //o.labelColor = UIColor.green /// types are .line_arrow | .line_bubble | .dash_bubble o.lineType = LineType.line_arrow //Always set the delegate for SkipOverlayDelegate //for onSkipSignal() function call o.delegate = self self.onSkipSignal() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } var a = 0 func onSkipSignal(){ a += 1 if a == 1{ o.drawOverlay(to: navItem2, desc: "This is really cool this is really cool this is really cool this is really cool this is really cool this is really cool this is really cool!") }else if a == 2{ o.drawOverlay(to: navItem, desc: "this is really coolt!") }else if a == 3{ o.drawOverlay(to: tableView, section: 0, row: 0, desc: "This is nice!") }else if a == 4{ o.drawOverlay(to: button1, desc: "This button is doing some stuff!") }else if a == 5{ o.drawOverlay(to: button2, desc: "This button is awsome!!") }else if a == 6{ guard let tabbar = tabBarController?.tabBar else { return } o.drawOverlay(to: tabbar, item: 1, desc: "This is second tabbar item!") }else{ // close it! } } } extension ViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let curr = list[indexPath.row] cell.textLabel?.text = curr return cell } }
16fe216bf1b20d9cc96a2007c8bf5945
28.770492
190
0.579295
false
false
false
false
cpuu/OTT
refs/heads/master
OTT/Group1ViewController.swift
mit
1
// // Group1ViewController.swift // BlueCap // // Created by 박재유 on 2016. 6. 1.. // Copyright © 2016년 Troy Stribling. All rights reserved. // import UIKit class Group1ViewController: UIViewController , UITableViewDataSource,UITableViewDelegate { var valueToPass:Int = 0 var valueToTitle: String = String() var marrGroupData : NSMutableArray! var averageValue:Float = 0 @IBOutlet weak var tbGroupData: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //navigation bar style let font = UIFont(name:"Thonburi", size:20.0) var titleAttributes : [String:AnyObject] if let defaultTitleAttributes = UINavigationBar.appearance().titleTextAttributes { titleAttributes = defaultTitleAttributes } else { titleAttributes = [String:AnyObject]() } titleAttributes[NSFontAttributeName] = font self.navigationController?.navigationBar.titleTextAttributes = titleAttributes } override func viewWillAppear(animated: Bool) { self.getGroupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Other methods func getGroupData() { marrGroupData = NSMutableArray() marrGroupData = ModelManager.getInstance().getAllGroupData() tbGroupData.reloadData() //All member의 평균 계산하기 averageValue = ModelManager.getInstance().getAllMemberAverage() //print("\(averageValue)") } //MARK: UITableView delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return marrGroupData.count + 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Name with value" } func imageResize (cellimage:UIImage, sizeChange:CGSize)-> UIImage{ let hasAlpha = true let scale: CGFloat = 0.0 // Use scale factor of main screen UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale) cellimage.drawInRect(CGRect(origin: CGPointZero, size: sizeChange)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() return scaledImage } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FriendCell = tableView.dequeueReusableCellWithIdentifier("cell") as! FriendCell if(indexPath.row == 0) { cell.lblContent.text = "All Members" cell.valContent.text = "\(averageValue)" } else{ let group:Group = marrGroupData.objectAtIndex((indexPath.row)-1) as! Group cell.lblContent.text = "\(group.GROUP_NM)" cell.valContent.text = "\(group.GROUP_VALUE)" cell.GroupImage.image! = imageResize(UIImage(named: group.GROUP_ICON_FILE_NM)!, sizeChange: CGSizeMake(30,30)) //cell.btnDelete.tag = (indexPath.row)-1 //cell.btnEdit.tag = (indexPath.row)-1 } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //print(group.GROUP_NM) if(indexPath.row == 0) { valueToPass = Int("9999")! valueToTitle = "All Members" } else { let group:Group = marrGroupData.objectAtIndex((indexPath.row)-1) as! Group valueToPass = Int(group.GROUP_SEQ)! valueToTitle = group.GROUP_NM } //print("true answer : ?", valueToPass) self.performSegueWithIdentifier("detailSegue", sender: self) } //MARK: UIButton Action methods @IBAction func btnDeleteClicked(sender: AnyObject) { let btnDelete : UIButton = sender as! UIButton let selectedIndex : Int = btnDelete.tag let friend: Group = marrGroupData.objectAtIndex(selectedIndex) as! Group let isDeleted = ModelManager.getInstance().deleteGroupData(friend) if isDeleted { Util.invokeAlertMethod("", strBody: "Record deleted successfully.", delegate: nil) } else { Util.invokeAlertMethod("", strBody: "Error in deleting record.", delegate: nil) } self.getGroupData() } @IBAction func btnEditClicked(sender: AnyObject) { self.performSegueWithIdentifier("editSegue", sender: sender) } //MARK: Navigation methods override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "editSegue") { let btnEdit : UIButton = sender as! UIButton let selectedIndex : Int = btnEdit.tag let viewController : Group2ViewController = segue.destinationViewController as! Group2ViewController viewController.isEdit = true viewController.groupData = marrGroupData.objectAtIndex(selectedIndex) as! Group } else if(segue.identifier == "detailSegue") { //get a reference to the destination view controller let destinationVC:Group3ViewController = segue.destinationViewController as! Group3ViewController //set properties on the destination view controller destinationVC.groupMemberSeq = valueToPass destinationVC.title = valueToTitle //print("destinationVC.value : ?", destinationVC.groupMemberSeq) //print("valuetopass : ?", valueToPass) //etc... } } }
40aeb21d5ab0763e9021ab037e739341
34.925926
122
0.632818
false
false
false
false
exyte/Macaw
refs/heads/master
Source/animation/types/animation_generators/MorphingGenerator.swift
mit
1
// // MorphingGenerator.swift // Pods // // Created by Victor Sukochev on 24/01/2017. // // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif func addMorphingAnimation(_ animation: BasicAnimation, _ context: AnimationContext, sceneLayer: CALayer?, completion: @escaping (() -> Void)) { guard let morphingAnimation = animation as? MorphingAnimation else { return } guard let shape = animation.node as? Shape, let renderer = animation.nodeRenderer else { return } let transactionsDisabled = CATransaction.disableActions() CATransaction.setDisableActions(true) let fromLocus = morphingAnimation.getVFunc()(0.0) let toLocus = morphingAnimation.getVFunc()(animation.autoreverses ? 0.5 : 1.0) let duration = animation.autoreverses ? animation.getDuration() / 2.0 : animation.getDuration() let layer = AnimationUtils.layerForNodeRenderer(renderer, animation: animation, shouldRenderContent: false) // Creating proper animation let generatedAnimation = pathAnimation( from: fromLocus, to: toLocus, duration: duration) generatedAnimation.repeatCount = Float(animation.repeatCount) generatedAnimation.timingFunction = caTimingFunction(animation.easing) generatedAnimation.autoreverses = animation.autoreverses generatedAnimation.progress = { progress in let t = Double(progress) animation.progress = t animation.onProgressUpdate?(t) } generatedAnimation.completion = { finished in if animation.manualStop { animation.progress = 0.0 shape.form = morphingAnimation.getVFunc()(0.0) } else if finished { animation.progress = 1.0 shape.form = morphingAnimation.getVFunc()(1.0) } renderer.freeLayer() if !animation.cycled && !animation.manualStop { animation.completion?() } completion() } layer.path = fromLocus.toCGPath() layer.setupStrokeAndFill(shape) let animationId = animation.ID layer.add(generatedAnimation, forKey: animationId) animation.removeFunc = { [weak layer] in shape.animations.removeAll { $0 === animation } layer?.removeAnimation(forKey: animationId) } if !transactionsDisabled { CATransaction.commit() } } fileprivate func pathAnimation(from: Locus, to: Locus, duration: Double) -> CAAnimation { let fromPath = from.toCGPath() let toPath = to.toCGPath() let animation = CABasicAnimation(keyPath: "path") animation.fromValue = fromPath animation.toValue = toPath animation.duration = duration animation.fillMode = MCAMediaTimingFillMode.forwards animation.isRemovedOnCompletion = false return animation }
15310d2e3e7640e667910402ed348db3
27.575758
143
0.681159
false
false
false
false
epv44/TwitchAPIWrapper
refs/heads/master
Example/Tests/Request Tests/GetBannedUsersRequestTests.swift
mit
1
// // GetBannedUsersRequestTests.swift // TwitchAPIWrapper_Tests // // Created by Eric Vennaro on 6/14/21. // Copyright © 2021 CocoaPods. All rights reserved. // import XCTest @testable import TwitchAPIWrapper class GetBannedUsersRequestTests: XCTestCase { override func setUpWithError() throws { TwitchAuthorizationManager.sharedInstance.clientID = "1" TwitchAuthorizationManager.sharedInstance.credentials = Credentials(accessToken: "XXX", scopes: ["user", "read"]) super.setUp() } func testBuildRequest_withRequiredParams_shouldSucceed() { let request = GetBannedUsersRequest(broadcasterID: "1") XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/moderation/banned?broadcaster_id=1") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } func testBuildRequest_withOptionalParams_shouldSucceed() { let request = GetBannedUsersRequest(broadcasterID: "1", userIDs: ["2"], after: "3", first: "4", before: "5") XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/moderation/banned?broadcaster_id=1&user_id=2&after=3&first=4&before=5") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } }
a7ffe52abf604a8cd7975158b79a1bf2
38.702703
125
0.682777
false
true
false
false
segmentio/analytics-swift
refs/heads/main
Sources/Segment/Utilities/QueueTimer.swift
mit
1
// // QueueTimer.swift // Segment // // Created by Brandon Sneed on 6/16/21. // import Foundation internal class QueueTimer { enum State { case suspended case resumed } let interval: TimeInterval let timer: DispatchSourceTimer let queue: DispatchQueue let handler: () -> Void @Atomic var state: State = .suspended static var timers = [QueueTimer]() static func schedule(interval: TimeInterval, queue: DispatchQueue = .main, handler: @escaping () -> Void) { let timer = QueueTimer(interval: interval, queue: queue, handler: handler) Self.timers.append(timer) } init(interval: TimeInterval, queue: DispatchQueue = .main, handler: @escaping () -> Void) { self.interval = interval self.queue = queue self.handler = handler timer = DispatchSource.makeTimerSource(flags: [], queue: queue) timer.schedule(deadline: .now() + self.interval, repeating: self.interval) timer.setEventHandler { [weak self] in self?.handler() } resume() } deinit { timer.setEventHandler { // do nothing ... } // if timer is suspended, we must resume if we're going to cancel. timer.cancel() resume() } func suspend() { if state == .suspended { return } state = .suspended timer.suspend() } func resume() { if state == .resumed { return } state = .resumed timer.resume() } } extension TimeInterval { static func milliseconds(_ value: Int) -> TimeInterval { return TimeInterval(value / 1000) } static func seconds(_ value: Int) -> TimeInterval { return TimeInterval(value) } static func hours(_ value: Int) -> TimeInterval { return TimeInterval(60 * value) } static func days(_ value: Int) -> TimeInterval { return TimeInterval((60 * value) * 24) } }
d2aae5e66ad303df6f4c94f759cd95f2
23.069767
111
0.566184
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/DynamicsCatalog/Controllers/InstantaneousPushVC.swift
mit
1
// // InstantaneousPushVC.swift // Lumia // // Created by 黄伯驹 on 2019/12/31. // Copyright © 2019 黄伯驹. All rights reserved. // import UIKit class InstantaneousPushVC: UIViewController { private lazy var square: UIImageView = { let square = UIImageView(image: UIImage(named: "Box1")) return square }() private lazy var centerPoint: UIImageView = { let centerPoint = UIImageView(image: UIImage(named: "Origin")) centerPoint.translatesAutoresizingMaskIntoConstraints = false return centerPoint }() private lazy var pushBehavior: UIPushBehavior = { let pushBehavior = UIPushBehavior(items: [square], mode: .instantaneous) pushBehavior.angle = 0.0 pushBehavior.magnitude = 0.0 return pushBehavior }() private lazy var animator: UIDynamicAnimator = { let animator = UIDynamicAnimator(referenceView: self.view) return animator }() private lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.text = "Tap anywhere to create a force." textLabel.font = UIFont(name: "Chalkduster", size: 15) textLabel.translatesAutoresizingMaskIntoConstraints = false return textLabel }() override func loadView() { view = DecorationView() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(textLabel) textLabel.bottomAnchor.constraint(equalTo: view.safeBottomAnchor).isActive = true textLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true view.addSubview(centerPoint) centerPoint.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true centerPoint.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true square.frame.origin = CGPoint(x: 200, y: 200) view.addSubview(square) let collisionBehavior = UICollisionBehavior(items: [square]) collisionBehavior.setTranslatesReferenceBoundsIntoBoundary(with: UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right: 0)) // Account for any top and bottom bars when setting up the reference bounds. animator.addBehavior(collisionBehavior) animator.addBehavior(pushBehavior) let tap = UITapGestureRecognizer(target: self, action: #selector(handleSnapGesture)) view.addGestureRecognizer(tap) } @objc func handleSnapGesture(_ gesture: UITapGestureRecognizer) { // Tapping will change the angle and magnitude of the impulse. To visually // show the impulse vector on screen, a red arrow representing the angle // and magnitude of this vector is briefly drawn. let p = gesture.location(in: view) let o = CGPoint(x: view.bounds.midX, y: view.bounds.midY) var distance = sqrt(pow(p.x - o.x, 2.0)+pow(p.y-o.y, 2.0)) let angle = atan2(p.y-o.y, p.x-o.x) distance = min(distance, 100.0) // Display an arrow showing the direction and magnitude of the applied // impulse. (view as? DecorationView)?.drawMagnitudeVector(with: distance, angle: angle, color: .red, forLimitedTime: true) // These two lines change the actual force vector. pushBehavior.magnitude = distance / 100 pushBehavior.angle = angle // A push behavior in instantaneous (impulse) mode automatically // deactivate itself after applying the impulse. We thus need to reactivate // it when changing the impulse vector. pushBehavior.active = true } }
acb9af59086c772e3307f8f1fdff4228
37.103093
173
0.665314
false
false
false
false
Decybel07/L10n-swift
refs/heads/master
Example/Example iOS/Scenes/SimpleTranslator/SimpleTranslatorViewController.swift
mit
1
// // SimpleTranslatorViewController.swift // Example // // Created by Adrian Bobrowski on 16.08.2017. // // import UIKit import L10n_swift final class SimpleTranslatorViewController: UIViewController { // MARK: - @IBOutlet @IBOutlet fileprivate weak var pickerView: UIPickerView! @IBOutlet fileprivate weak var tableView: UITableView! // MARK: - variable fileprivate var languages: [String] = L10n.supportedLanguages fileprivate var items: [String] = [ "apple", "bee", "cat", "dolphin", "elephant", "fish", "giraffe", "house", "iceCream", "jelly", "kite", "ladybird", "mouse", "newt", "octopus", "pig", "queen", "rocket", "snake", "teddybear", "umbrella", "vase", "whale", "xylophone", "yoYo", "zebra", ] fileprivate var from = L10n.shared fileprivate var to: L10n = { L10n(language: L10n.supportedLanguages.first(where: { $0 != L10n.shared.language })) }() // MARK: - Life cycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.pickerView.selectRow(self.languages.firstIndex(of: self.from.language) ?? 0, inComponent: 0, animated: false) self.pickerView.selectRow(self.languages.firstIndex(of: self.to.language) ?? 0, inComponent: 1, animated: false) } } // MARK: - UITableViewDataSource extension SimpleTranslatorViewController: UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return self.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "translator", for: indexPath) let key = "simpleTranslator.list.\(self.items[indexPath.row])" cell.textLabel?.text = key.l10n(self.from) cell.detailTextLabel?.text = key.l10n(self.to) return cell } } // MARK: - UIPickerViewDataSource extension SimpleTranslatorViewController: UIPickerViewDataSource { func numberOfComponents(in _: UIPickerView) -> Int { return 2 } func pickerView(_: UIPickerView, numberOfRowsInComponent _: Int) -> Int { return self.languages.count } } // MARK: - UIPickerViewDelegate extension SimpleTranslatorViewController: UIPickerViewDelegate { func pickerView(_: UIPickerView, titleForRow row: Int, forComponent _: Int) -> String? { return L10n.shared.locale?.localizedString(forLanguageCode: self.languages[row]) } func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0 { self.from = L10n(language: self.languages[row]) } else if component == 1 { self.to = L10n(language: self.languages[row]) } self.tableView.reloadData() } }
7741449cc7f7a502b566709e980bc394
28.752577
122
0.661816
false
false
false
false
zhxnlai/ZLBalancedFlowLayout
refs/heads/master
ZLBalancedFlowLayoutDemo/ZLBalancedFlowLayoutDemo/ViewController.swift
mit
1
// // ViewController.swift // ZLBalancedFlowLayoutDemo // // Created by Zhixuan Lai on 12/23/14. // Copyright (c) 2014 Zhixuan Lai. All rights reserved. // import UIKit class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var numRepetitions: Int = 1 { didSet { collectionView?.reloadData() } } var numSections: Int = 10 { didSet { collectionView?.reloadData() } } var direction: UICollectionViewScrollDirection = .Vertical { didSet { needsResetLayout = true } } var rowHeight: CGFloat = 100 { didSet { needsResetLayout = true } } var enforcesRowHeight: Bool = false { didSet { needsResetLayout = true } } private var images = [UIImage](), needsResetLayout = false private let cellIdentifier = "cell", headerIdentifier = "header", footerIdentifier = "footer" override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) var paths = NSBundle.mainBundle().pathsForResourcesOfType("jpg", inDirectory: "") as! Array<String> for path in paths { if let image = UIImage(contentsOfFile: path) { images.append(image) } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "ZLBalancedFlowLayout" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self , action: Selector("refreshButtonAction:")) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: Selector("settingsButtonAction:")) collectionView?.backgroundColor = UIColor.whiteColor() collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellIdentifier) collectionView?.registerClass(LabelCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier) collectionView?.registerClass(LabelCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) resetLayoutIfNeeded(animated) } private func resetLayoutIfNeeded(animated: Bool) { if needsResetLayout { needsResetLayout = false var layout = ZLBalancedFlowLayout() layout.headerReferenceSize = CGSize(width: 100, height: 100) layout.footerReferenceSize = CGSize(width: 100, height: 100) layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) layout.scrollDirection = direction layout.rowHeight = rowHeight layout.enforcesRowHeight = enforcesRowHeight collectionView?.setCollectionViewLayout(layout, animated: true) } } // MARK: - Action func refreshButtonAction(sender:UIBarButtonItem) { self.collectionView?.reloadData() } func settingsButtonAction(sender:UIBarButtonItem) { SettingsViewController.presentInViewController(self) } // MARK: - UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numSections } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count*numRepetitions } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell var imageView = UIImageView(image: imageForIndexPath(indexPath)) imageView.contentMode = .ScaleAspectFill cell.backgroundView = imageView cell.clipsToBounds = true return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var view = LabelCollectionReusableView(frame: CGRectZero) switch (kind) { case UICollectionElementKindSectionHeader: view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! LabelCollectionReusableView view.textLabel.text = "Header" case UICollectionElementKindSectionFooter: view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier, forIndexPath: indexPath) as! LabelCollectionReusableView view.textLabel.text = "Footer" default: view.textLabel.text = "N/A" } return view } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var size = imageForIndexPath(indexPath).size var percentWidth = CGFloat(140 - arc4random_uniform(80))/100 return CGSize(width: size.width*percentWidth/4, height: size.height/4) } // MARK: - () func imageForIndexPath(indexPath:NSIndexPath) -> UIImage { return images[indexPath.item%images.count] } }
b6cbbcdd47d90f474f33530360ace3d3
39.026846
206
0.690141
false
false
false
false
zehrer/SOGraphDB
refs/heads/master
Sources/SOGraphDB_old/Model/Values/Node.swift
mit
1
// // Node.swift // SOGraphDB // // Created by Stephan Zehrer on 02.07.15. // Copyright © 2015 Stephan Zehrer. All rights reserved. // import Foundation extension Node : Identiy, PropertyAccess , RelationshipAccess {} // Equatable interface for Node public func ==(lhs: Node, rhs: Node) -> Bool { if (lhs.uid != nil && rhs.uid != nil) { if lhs.uid! == rhs.uid! { return true } } return false } public struct Node : ValueStoreElement , Context , Hashable { public weak var context : GraphContext! = nil public var uid: UID? = nil public var dirty = true public var nextPropertyID: UID = 0 public var nextOutRelationshipID: UID = 0 public var nextInRelationshipID: UID = 0 public static func generateSizeTestInstance() -> Node { var result = Node() result.nextPropertyID = Int.max result.nextOutRelationshipID = Int.max result.nextInRelationshipID = Int.max return result } public init() {} public init (uid aID : UID) { uid = aID } public init(coder decoder: Decode) { nextPropertyID = decoder.decode() nextOutRelationshipID = decoder.decode() nextInRelationshipID = decoder.decode() dirty = false } public func encodeWithCoder(_ encoder : Encode) { encoder.encode(nextPropertyID) encoder.encode(nextOutRelationshipID) encoder.encode(nextInRelationshipID) } // MARK: CRUD public mutating func delete() { context.delete(&self) } public mutating func update() { context.update(&self) } // MARK: Hashable public var hashValue: Int { get { if uid != nil { return uid!.hashValue } return 0 } } }
9dd251c4cbfb6bb44b3286d8fb4234c4
19.62766
64
0.566271
false
false
false
false
inamiy/ReactiveCocoaCatalog
refs/heads/master
ReactiveCocoaCatalog/Samples/MenuSettingsViewController.swift
mit
1
// // MenuSettingsViewController.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import UIKit import Result import ReactiveSwift import ReactiveObjC import ReactiveObjCBridge private let _cellIdentifier = "MenuSettingsCell" final class MenuSettingsViewController: UITableViewController, StoryboardSceneProvider { static let storyboardScene = StoryboardScene<MenuSettingsViewController>(name: "MenuBadge") weak var menu: SettingsMenu? override func viewDidLoad() { super.viewDidLoad() guard let menu = self.menu else { fatalError("Required properties are not set.") } let menusChanged = menu.menusProperty.signal.map { _ in () } let badgeChanged = BadgeManager.badges.mergedSignal.map { _ in () } // `reloadData()` when menus or badges changed. menusChanged .merge(with: badgeChanged) .observeValues { [weak self] _ in self?.tableView?.reloadData() } // Modal presentation & dismissal for serial execution. let modalAction = Action<MenuType, (), NoError> { [weak self] menu in return SignalProducer { observer, disposable in let modalVC = menu.viewController self?.present(modalVC, animated: true) { _ = QueueScheduler.main.schedule(after: 1) { self?.dismiss(animated: true) { observer.send(value: ()) observer.sendCompleted() } } } } } // `tableView.didSelectRow()` handling bridgedSignalProducer(from: self.rac_signal(for: Selector._didSelectRow.0, from: Selector._didSelectRow.1)) .on(event: logSink("didSelectRow")) .withLatest(from: self.menu!.menusProperty.producer) .map { racTuple, menus -> MenuType in let racTuple = racTuple as! RACTuple let indexPath = racTuple.second as! NSIndexPath let menu = menus[indexPath.row] return menu } .flatMap(.merge) { menu in return modalAction.apply(menu) .ignoreCastError(NoError.self) } .start() self.tableView.delegate = nil // set nil to clear selector cache self.tableView.delegate = self } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.menu!.menusProperty.value.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: _cellIdentifier, for: indexPath) let menu = self.menu!.menusProperty.value[indexPath.row] cell.textLabel?.text = "\(menu.menuId)" cell.detailTextLabel?.text = menu.badge.value.rawValue cell.imageView?.image = menu.tabImage.value return cell } } // MARK: Selectors extension Selector { // NOTE: needed to upcast to `Protocol` for some reason... fileprivate static let _didSelectRow: (Selector, Protocol) = ( #selector(UITableViewDelegate.tableView(_:didSelectRowAt:)), UITableViewDelegate.self ) }
ffd0b5e2e8b4d70eac4fc3c148c49421
32.307692
115
0.609411
false
false
false
false
amraboelela/SwiftLevelDB
refs/heads/master
Tests/SwiftLevelDBTests/DateTests.swift
mit
1
// // DateTests.swift // SwiftLevelDBAppTests // // Created by Amr Aboelela on 6/29/22. // import XCTest import Foundation import Dispatch @testable import SwiftLevelDB @available(iOS 13.0.0, *) class DateTests: TestsBase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testSecondsSince1970() { let now = Date.secondsSince1970 let now2 = Date.secondsSinceReferenceDate XCTAssertTrue(now - now2 > (1970 - 2001) * 360 * 24 * 60 * 60) } func testSecondsSinceReferenceDate() { let now = Date.secondsSince1970 let now2 = Date.secondsSinceReferenceDate XCTAssertTrue(now - now2 > (1970 - 2001) * 360 * 24 * 60 * 60) } func testDayOfWeek() { var date = Date(timeIntervalSince1970: 1658086329) // Sunday 7/17/22 var dayOfWeek = date.dayOfWeek XCTAssertEqual(dayOfWeek, 0) date = Date(timeIntervalSince1970: 1658345529) // Wednesday 7/20/22 dayOfWeek = date.dayOfWeek XCTAssertEqual(dayOfWeek, 3) } }
ac287c3be5e2c5bc3b4ae1ebfc4ee412
23.543478
76
0.620903
false
true
false
false
trillione/JNaturalKorean
refs/heads/master
Sampler/Sampler/ContentView.swift
mit
2
// // ContentView.swift // Sampler // // Created by won on 2020/11/13. // import SwiftUI import JNaturalKorean struct ContentView: View { var body: some View { ScrollView { Text(sampleText) .padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } let sampleText = """ 주격조사\n\n \("그 사람".이_가) 주인입니다. \("저 여자".이_가) 여친 입니다. \n목적격조사\n \("3개의 문장".을_를) 외워야 합니다. \("12개의 단어".을_를) 외워야 합니다. \n보조사\n \("그 사람".은_는) 프로그래머입니다. \("그 여자".은_는) 개발자. \n호격조사\n \("이 세상".아_야)! \("이 여자".아_야)!\n \("그날".으로_로)부터 \("100일".이_가) 지났습니다. \n==== String+JNaturalKorean ====\n 주격조사\n \("그 사람".이_가) 주인입니다. \("010-0000-7330".이_가) 전 여친 전화번호 입니다.. \("그 여자".이_가) 전 여친 입니다. \n목적격조사\n \("3개의 문장".을_를) 외워야 합니다. \("010-0000-7332".을_를) 해킹. \("12개의 단어".을_를) 외워야 합니다. \n보조사 \("그 사람".은_는) 프로그래머입니 \("그 여자".은_는) 이뻐 \("010-0000-7335".은_는) 내 전화번호 입니다.. \n호격조사\n \("이 세상".아_야)! \("이 세상".아_야)! \("010-0000-7336".아_야)!\n\n \("그 여자".와_과) 함께 \("그 사람".와_과) 함께 \("010-0000-7338".와_과) 내 번호는 비슷함. \("010-0000-7333".으로_로) 인증번호가 발송됩니다. \("오늘".으로_로) 부터 \("100일".이_가) 지났습니다. """
7d46716e90b309c5e4511c4a00fc9711
18.969231
46
0.48228
false
false
false
false
wuyezhiguhun/DDSwift
refs/heads/master
DDSwift/Main/RootViewController.swift
mit
1
// // RootViewController.swift // DDSwift // // Created by 王允顶 on 17/4/23. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let leftImage = UIImage(named: "back")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: leftImage, style: UIBarButtonItemStyle.done, target: self, action:#selector(backTouch)) // Do any additional setup after loading the view. } func backTouch() -> Void { self.navigationController!.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var _titleString:String? var titleString:String { get{ if _titleString == nil { _titleString = String() } return _titleString! } set{ _titleString = newValue self.navigationItem.title = _titleString } } }
9f0fa866d0b483ee8e297a15c652e8d4
26.714286
158
0.633162
false
false
false
false
orta/PonyDebuggerApp
refs/heads/master
PonyDebugger/PonyDServer.swift
mit
1
import Cocoa class PonyDServer: NSObject { let task = NSTask() func startServer() { let outputPipe = NSPipe() task.launchPath = "/usr/local/bin/ponyd" let arguments = ["serve", "--listen-interface=127.0.0.1"] task.arguments = arguments task.launch() let notifications = NSNotificationCenter.defaultCenter() task.standardOutput = outputPipe; notifications.addObserver(self, selector: #selector(outputAvailable), name: NSFileHandleDataAvailableNotification, object: outputPipe.fileHandleForReading) outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotifyForModes([NSDefaultRunLoopMode, NSEventTrackingRunLoopMode]) let errorPipe = NSPipe() task.standardError = errorPipe; notifications.addObserver(self, selector: #selector(outputAvailable), name: NSFileHandleDataAvailableNotification, object: outputPipe.fileHandleForReading) errorPipe.fileHandleForReading.waitForDataInBackgroundAndNotifyForModes([NSDefaultRunLoopMode, NSEventTrackingRunLoopMode]) } func stop() { task.terminate() task.waitUntilExit() let killAll = NSTask() killAll.launchPath = "/usr/bin/killall" killAll.arguments = ["ponyd"] killAll.launch() killAll.waitUntilExit() } func outputAvailable(notification: NSNotification) { guard let fileHandle = notification.object as? NSFileHandle else { return } let data = fileHandle.availableData if data.length > 0 { let output = NSString(data: data, encoding: NSUTF8StringEncoding) print(output) } } }
a8d1b3b6e396cd5166644df6eb03735d
33.244898
163
0.688915
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
refs/heads/master
solutions/26_Remove_Duplicates_from_Sorted_Array.playground/Contents.swift
mit
1
// #26 Remove Duplicates from Sorted Array https://leetcode.com/problems/remove-duplicates-from-sorted-array/ // 很简单的数组处理。一个指针往后读,一个指针指向写入的位置,读到不重复的(跟前一位不一样的)就在写指针的位置写入,不然继续往后读即可。 // 从这道题我们也可以学到如何在 swift 的函数里传进一个可变的参数~ // 时间复杂度:O(n) 空间复杂度:O(1) class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { guard nums.count > 0 else { return 0 } var writeIndex = 1 for readIndex in 1 ..< nums.count { if nums[readIndex] != nums[readIndex - 1] { nums[writeIndex] = nums[readIndex] writeIndex += 1 } } return writeIndex } } var array = [1,2,2,2] Solution().removeDuplicates(&array)
86f693c582236b3bbd41732a6f4d6700
28.2
109
0.588477
false
false
false
false
n8armstrong/CalendarView
refs/heads/master
CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/SwiftMoment/Duration.swift
mit
1
// // Duration.swift // SwiftMoment // // Created by Adrian on 19/01/15. // Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved. // import Foundation public struct Duration: Equatable { let interval: TimeInterval public init(value: TimeInterval) { self.interval = value } public init(value: Int) { self.interval = TimeInterval(value) } public var years: Double { return interval / 31536000 // 365 days } public var quarters: Double { return interval / 7776000 // 3 months } public var months: Double { return interval / 2592000 // 30 days } public var days: Double { return interval / 86400 // 24 hours } public var hours: Double { return interval / 3600 // 60 minutes } public var minutes: Double { return interval / 60 } public var seconds: Double { return interval } public func ago() -> Moment { return moment().subtract(self) } public func add(_ duration: Duration) -> Duration { return Duration(value: self.interval + duration.interval) } public func subtract(_ duration: Duration) -> Duration { return Duration(value: self.interval - duration.interval) } public func isEqualTo(_ duration: Duration) -> Bool { return self.interval == duration.interval } } extension Duration: CustomStringConvertible { public var description: String { let formatter = DateComponentsFormatter() formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian) formatter.calendar?.timeZone = TimeZone(abbreviation: "UTC")! formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second] let referenceDate = Date(timeIntervalSinceReferenceDate: 0) let intervalDate = Date(timeInterval: self.interval, since: referenceDate) return formatter.string(from: referenceDate, to: intervalDate)! } }
767fdf69bd577dab9432cc10d4efc600
24.794872
93
0.642644
false
false
false
false
abecker3/SeniorDesignGroup7
refs/heads/master
ProvidenceWayfinding/ProvidenceWayfinding/LocationTableViewController.swift
apache-2.0
1
// // LocationTableViewController.swift // Test2 // // Created by Bilsborough, Michael J on 11/19/15. // Copyright © 2015 Gonzaga University. All rights reserved. // import UIKit class LocationTableViewController: UITableViewController, UISearchResultsUpdating{ //Passed in variables var passInTextFieldTag: Int! var passInCategory: String! var allLocationsClicked: Bool = false //Referencing Outlets @IBOutlet var locationTableView: UITableView! @IBOutlet var controllerTitle: UINavigationItem! //Variables var resultSearchController = UISearchController() var filteredTableData = [String]() var locationOptions:[Directory] = [] var locationStringOptions = [String]() var allLocationsTag: Bool = false override func viewDidLoad() { super.viewDidLoad() //resultSearchController.active = false //Choose options based on passed in building initControllerTitle() initOptions() //definesPresentationContext = true self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() //Reload table self.tableView.reloadData() //extendedLayoutIncludesOpaqueBars = true; //keeps the search bar from disappearing on tap } override func viewDidAppear(animated: Bool) { if(resetToRootView == 1){ self.navigationController?.popToRootViewControllerAnimated(true) } } func updateSearchResultsForSearchController(searchController: UISearchController) { filteredTableData.removeAll(keepCapacity: false) let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!) var newArray = [String]() for x in locationOptions { newArray.append(x.name) } //var oldArray = uniqueCategoryArray let array = (newArray as NSArray).filteredArrayUsingPredicate(searchPredicate) filteredTableData = array as! [String] filteredTableData.sortInPlace() self.tableView.reloadData() } /* func uniqueCategoryArray(inputArray: [Location]!) -> [String]! { var newArray = [String]() for x in inputArray { if(newArray.contains(x.category)) { continue } else { newArray.append(x.category) } } return newArray }*/ //Populate Table override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return locationOptions.count //Takes the filtered data and assigns them to the number of rows needed if(self.resultSearchController.active) { return self.filteredTableData.count } // No searching is going on so the table stays regular using the same number of rows as before else { return self.locationOptions.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("location cell", forIndexPath: indexPath) /*// Configure the cell... let option = locationOptions[indexPath.row] cell.textLabel!.text = option.name return cell*/ if(self.resultSearchController.active) { cell.textLabel?.text = filteredTableData[indexPath.row] //cell.detailTextLabel!.text = "11 AM to 8 PM" return cell } else { let option = locationStringOptions[indexPath.row] cell.textLabel?.text = option //cell.detailTextLabel!.text = "11 AM to 8 PM" return cell } } //This function checks whether the search bar cell that was clicked is part of Locations func checkArrayForMember(tableView: UITableView, indexPath: NSIndexPath) -> Bool { for x in directory { if(filteredTableData.count > indexPath.row) { if(x.name == filteredTableData[indexPath.row]) { return true } } } return false } func getLocationFromName(name: String) -> Directory { for x in directory{ if(x.name == name) { return x } } return Directory(name: "Admitting", category: "Main Tower", floor: "Main", hours: "NA", ext: "", notes: "") } //Pop back 2 once a row is selected override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let navController = self.navigationController! let indexOfLastViewController = navController.viewControllers.count - 1 let indexOfSurvey = indexOfLastViewController - 2 let surveyViewController = navController.viewControllers[indexOfSurvey] as! SurveyViewController if(passInTextFieldTag == surveyViewController.currentTextField.tag && resultSearchController.active && allLocationsTag) { surveyViewController.currentTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.startLocation = location print(location) print("Current: search is active") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag && resultSearchController.active && allLocationsTag) { surveyViewController.destinationTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.destinationTextField.placeholder!) surveyViewController.endLocation = location print(location) print("Destination: search is active") } /*else if(passInTextFieldTag == surveyViewController.currentTextField.tag ) { surveyViewController.currentTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.startLocation = location print("Current: regular cell selection") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag) { surveyViewController.destinationTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.endLocation = location print("Destination: regular cell selection") }*/ else if(passInTextFieldTag == surveyViewController.currentTextField.tag /*&& !allLocationsTag*/) { surveyViewController.currentTextField.placeholder = locationStringOptions[indexPath.row] surveyViewController.startLocation = getLocationFromName(locationStringOptions[indexPath.row]) print(locationOptions[indexPath.row]) print("Current: regular cell selection") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag /*&& !allLocationsTag*/) { surveyViewController.destinationTextField.placeholder = locationStringOptions[indexPath.row] surveyViewController.endLocation = getLocationFromName(locationStringOptions[indexPath.row]) print(locationOptions[indexPath.row]) print("Destination: regular cell selection") } resultSearchController.active = false navController.popToViewController(surveyViewController, animated: true) } func initOptions() { for location in directory { if(location.category == passInCategory && !allLocationsClicked) { locationOptions.append(location) locationStringOptions.append(location.name) } else if(passInCategory == "All Locations") { allLocationsTag = true if(location.category != "All Locations") { locationOptions.append(location) locationStringOptions.append(location.name) } } } locationStringOptions.sortInPlace() } func initControllerTitle() { controllerTitle.title = passInCategory } }
bea037ab8e393de47135ee1ff0da10aa
35.242188
136
0.628584
false
false
false
false
SheffieldKevin/SwiftGraphics
refs/heads/develop
SwiftGraphics/Geometry/Arc.swift
bsd-2-clause
1
// // Arc.swift // SwiftGraphics // // Created by Jonathan Wight on 12/26/15. // Copyright © 2015 schwa.io. All rights reserved. // private let pi = CGFloat(M_PI) public struct Arc { public let center: CGPoint public let radius: CGFloat public let theta: CGFloat public let phi: CGFloat public init(center: CGPoint, radius: CGFloat, theta: CGFloat, phi: CGFloat) { self.center = center self.radius = radius self.theta = theta self.phi = phi } } // TODO: all geometry should be equatable/fuzzy equatable extension Arc: Equatable { } public func == (lhs: Arc, rhs: Arc) -> Bool { return lhs.center == rhs.center && lhs.radius == rhs.radius && lhs.theta == rhs.theta && lhs.phi == rhs.phi } extension Arc: FuzzyEquatable { } public func ==% (lhs: Arc, rhs: Arc) -> Bool { return lhs.center ==% rhs.center && lhs.radius ==% rhs.radius && lhs.theta ==% rhs.theta && lhs.phi ==% rhs.phi } public extension Arc { static func arcToBezierCurves(center: CGPoint, radius: CGFloat, alpha: CGFloat, beta: CGFloat, maximumArcs: Int = 4) -> [BezierCurve] { assert(maximumArcs >= 3) let limit = pi * 2 / CGFloat(maximumArcs) //If[Abs[\[Beta] - \[Alpha]] > limit, // Return[{ // BezierArcConstruction[{xc, yc}, // r, {\[Alpha], \[Alpha] + limit}], // BezierArcConstruction[{xc, yc}, // r, {\[Alpha] + limit, \[Beta]}] // }] // ]; if abs(beta - alpha) > (limit + CGFloat(FLT_EPSILON)) { return arcToBezierCurves(center, radius: radius, alpha: alpha, beta: alpha + limit, maximumArcs: maximumArcs) + arcToBezierCurves(center, radius: radius, alpha: alpha + limit, beta: beta, maximumArcs: maximumArcs) } //{x1, y1} = {xc, yc} + r*{Cos[\[Alpha]], Sin[\[Alpha]]}; let pt1 = center + radius * CGPoint(x: cos(alpha), y: sin(alpha)) //{x4, y4} = {xc, yc} + r*{Cos[\[Beta]], Sin[\[Beta]]}; let pt4 = center + radius * CGPoint(x: cos(beta), y: sin(beta)) // {ax, ay} = {x1, y1} - {xc, yc}; let (ax, ay) = (pt1 - center).toTuple() // {bx, by} = {x4, y4} - {xc, yc}; let (bx, by) = (pt4 - center).toTuple() // q1 = ax*ax + ay*ay; let q1 = ax * ax + ay * ay // q2 = q1 + ax*bx + ay*by; let q2 = q1 + ax * bx + ay * by // k2 = 4/3 (Sqrt[2*q1*q2] - q2)/(ax*by - ay*bx); var k2 = (sqrt(2 * q1 * q2) - q2) / (ax * by - ay * bx) k2 *= 4 / 3 //x2 = xc + ax - k2*ay; //y2 = yc + ay + k2*ax; let pt2 = center + CGPoint(x: ax - k2 * ay, y: ay + k2 * ax) //x3 = xc + bx + k2*by; //y3 = yc + by - k2*bx; let pt3 = center + CGPoint(x: bx + k2 * by, y: by - k2 * bx) let curve = BezierCurve(points: [pt1, pt2, pt3, pt4]) return [ curve ] } func toBezierCurves(maximumArcs: Int = 4) -> [BezierCurve] { return Arc.arcToBezierCurves(center, radius: radius, alpha: phi, beta: phi + theta, maximumArcs: maximumArcs) } }
94f75ef0598c1295b1b163ae4819c4bf
30.39604
139
0.526963
false
false
false
false
jestspoko/Reveal
refs/heads/master
Reveal/Classes/RevealLabel.swift
mit
1
// // RevealLabel.swift // MaskedLabel // // Created by Lukasz Czechowicz on 26.10.2016. // Copyright © 2016 Lukasz Czechowicz. All rights reserved. // import UIKit /// holds UILabel and creates animations public class RevealLabel:Equatable { /// label's reference private var label:UILabel /// animation speed private var speed:Double /// animation's delay private var delay:Double /// function describing a timing curve private var timingFunction:CAMediaTimingFunction /// animation's direction private var direction:Reveal.RevealDirection /// destination mask frame private var destinationRect:CGRect /// layer with B&W gradient used as mask var gradientLayer:CAGradientLayer /** Initializes new label holder - Parameters: - label: UILabel reference - speed: animation speed - delay: animation delay - timingFunction: function describing timing curve - direction: animation direction */ init(_ label:UILabel, speed:Double, delay:Double, timingFunction:CAMediaTimingFunction, direction:Reveal.RevealDirection) { self.label = label self.speed = speed self.delay = delay self.timingFunction = timingFunction self.direction = direction destinationRect = label.bounds gradientLayer = CAGradientLayer() // creates and tweaks destination frame and mask layer depends of animation direction switch direction { case .fromLeft: destinationRect.origin.x = destinationRect.origin.x - destinationRect.size.width - 20 gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) case .fromRight: destinationRect.origin.x = destinationRect.origin.x + destinationRect.size.width + 20 gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x-20, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) } gradientLayer.colors = [UIColor.black.cgColor,UIColor.clear.cgColor] gradientLayer.locations = [0.9, 1.0] label.layer.mask = gradientLayer } /// holds UILabel content public var text:String? { set { self.label.text = newValue } get { return self.label.text } } public static func ==(l: RevealLabel, r: RevealLabel) -> Bool { return l.label == r.label } /** Creates and perfomrs reveal animation on mask - Parameters: - complete: handler fires when animation in complete */ func reaval(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.fromValue = NSValue(cgRect: label.bounds) animation.toValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"reveal") CATransaction.commit() } /** Creates and perfomrs hide animation on mask - Parameters: - complete: handler fires when animation in complete */ func hide(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.toValue = NSValue(cgRect: label.bounds) animation.fromValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"hide") CATransaction.commit() } }
d15100d7e94587d18453a0f253ac9c37
31.383562
178
0.624577
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/WCDB.swift/swift/source/core/codable/ColumnTypeDecoder.swift
mit
1
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation final class ColumnTypeDecoder: Decoder { private var results: [String: ColumnType] = [:] static func types(of type: TableDecodableBase.Type) -> [String: ColumnType] { let decoder = ColumnTypeDecoder() _ = try? type.init(from: decoder) return decoder.results } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey { return KeyedDecodingContainer(ColumnTypeDecodingContainer<Key>(with: self)) } private final class ColumnTypeDecodingContainer<CodingKeys: CodingKey>: KeyedDecodingContainerProtocol { typealias Key = CodingKeys private let decoder: ColumnTypeDecoder private struct SizedPointer { private let pointer: UnsafeMutableRawPointer private let size: Int init<T>(of type: T.Type = T.self) { size = MemoryLayout<T>.size pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 1) memset(pointer, 0, size) } func deallocate() { pointer.deallocate() } func getPointee<T>(of type: T.Type = T.self) -> T { return pointer.assumingMemoryBound(to: type).pointee } } private var sizedPointers: ContiguousArray<SizedPointer> init(with decoder: ColumnTypeDecoder) { self.decoder = decoder self.sizedPointers = ContiguousArray<SizedPointer>() } deinit { for sizedPointer in sizedPointers { sizedPointer.deallocate() } } func contains(_ key: Key) -> Bool { return true } func decodeNil(forKey key: Key) throws -> Bool { decoder.results[key.stringValue] = Bool.columnType return false } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.results[key.stringValue] = type.columnType return false } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.results[key.stringValue] = type.columnType return "" } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { // `type` must conform to ColumnDecodableBase protocol let columnDecodableType = type as! ColumnDecodable.Type decoder.results[key.stringValue] = columnDecodableType.columnType let sizedPointer = SizedPointer(of: T.self) sizedPointers.append(sizedPointer) return sizedPointer.getPointee() } var codingPath: [CodingKey] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } var allKeys: [Key] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func superDecoder() throws -> Decoder { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func superDecoder(forKey key: Key) throws -> Decoder { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } } var codingPath: [CodingKey] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } var userInfo: [CodingUserInfoKey: Any] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func singleValueContainer() throws -> SingleValueDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } }
a54ac7afdc0d933bccf81ec2940ba51e
35.182266
108
0.606943
false
false
false
false
bilogub/Chirrup
refs/heads/master
ChirrupTests/ChirrupSpec.swift
mit
1
// // ChirrupSpec.swift // Chirrup // // Created by Yuriy Bilogub on 2016-01-25. // Copyright © 2016 Yuriy Bilogub. All rights reserved. // import Quick import Nimble import Chirrup class ChirrupSpec: QuickSpec { override func spec() { let chirrup = Chirrup() var fieldName = "" describe("Single validation rule") { describe(".isTrue") { beforeEach { fieldName = "Activate" } context("When `Activate` is switched Off") { it("should return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue)) expect(error!.errorMessageFor(fieldName)) .to(equal("Activate should be true")) } context("When rule evaluation is skipped") { it("should not return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue, on: { false })) expect(error).to(beNil()) } } } context("When `Activate` is switched On") { it("should not return an error") { let error = chirrup.validate(fieldName, value: true, with: ValidationRule(.IsTrue)) expect(error).to(beNil()) } } } describe(".NonEmpty") { beforeEach { fieldName = "Greeting" } context("When `Greeting` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.NonEmpty)) expect(error!.errorMessageFor(fieldName)) .to(equal("Greeting should not be empty")) } } context("When `Greeting` is set to value") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "hey there!", with: ValidationRule(.NonEmpty)) expect(error).to(beNil()) } } } describe(".Greater") { beforeEach { fieldName = "Min. Price" } context("When `Min. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error because validation is skipped") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: "5499.98"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } } context("When `Min. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "two hundred", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } context("When `Min. Price` is set to a equal value") { it("should return an error") { let val = "5499.98" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be greater than \(val)")) } } context("When `Min. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "5499.99", with: ValidationRule(.Greater(than: "5499.98"))) expect(error).to(beNil()) } } } } describe(".Lower") { beforeEach { fieldName = "Max. Price" } context("When `Max. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: "10000.00"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } } context("When `Max. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "ten thousand", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } context("When `Max. Price` is set to a equal value") { it("should return an error") { let val = "10000.00" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be lower than \(val)")) } } context("When `Max. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "9999.99", with: ValidationRule(.Lower(than: "10000.00"))) expect(error).to(beNil()) } } } describe(".Between") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a lower value than possible") { it("should return an error") { let error = chirrup.validate(fieldName, value: "0", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be between 4 and 6")) } it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error).to(beNil()) } } } describe(".IsNumeric") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "five", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be a number")) } } context("When `Gear Number` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName, should: "be a positive number")) .to(equal("Gear Number should be a positive number")) } } context("When `Gear Number` is a number") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.IsNumeric)) expect(error).to(beNil()) } } } describe("Multiple validation rules") { describe(".Contains .NonBlank") { beforeEach { fieldName = "Greeting" } it("should return .Contains and .NonEmpty errors") { let errors = chirrup.validate(fieldName, value: "", with: [ValidationRule(.NonEmpty, message: "Couple greeting words here?"), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Couple greeting words here?\nGreeting should contain `hey there!`")) } context("When we have a greeting but not the one we expect") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } context("When rule evaluation is skipped") { it("should return empty error array") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 < 0 })]) expect(errors).to(beEmpty()) } } context("When rule evaluation is not skipped") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 > 0 })]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } } } } } } }
3c16ffcdca38e40f4db4ae04ad4d64bd
31.928339
91
0.510586
false
false
false
false
ObjSer/objser-swift
refs/heads/master
ObjSer/util/IntegralType.swift
mit
1
// // IntegralType.swift // ObjSer // // The MIT License (MIT) // // Copyright (c) 2015 Greg Omelaenko // // 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. // public protocol IntegralType : NumericType, IntegerType { init<T : IntegralType>(_ v: T) init(_ v: Int8) init(_ v: UInt8) init(_ v: Int16) init(_ v: UInt16) init(_ v: Int32) init(_ v: UInt32) init(_ v: Int64) init(_ v: UInt64) init(_ v: Int) init(_ v: UInt) static var min: Self { get } static var max: Self { get } } extension IntegralType { public init<T : IntegralType>(_ v: T) { switch v { case let v as Int8: self = Self(v) case let v as UInt8: self = Self(v) case let v as Int16: self = Self(v) case let v as UInt16: self = Self(v) case let v as Int32: self = Self(v) case let v as UInt32: self = Self(v) case let v as Int64: self = Self(v) case let v as UInt64: self = Self(v) case let v as Int: self = Self(v) case let v as UInt: self = Self(v) default: preconditionFailure("Unrecognised IntegralType type \(T.self).") } } } extension Int8 : IntegralType { } extension UInt8 : IntegralType { } extension Int16 : IntegralType { } extension UInt16 : IntegralType { } extension Int32 : IntegralType { } extension UInt32 : IntegralType { } extension Int64 : IntegralType { } extension UInt64 : IntegralType { } extension Int : IntegralType { } extension UInt : IntegralType { } /// A type-erased integer. public struct AnyInteger { private let negative: Bool private let value: UInt64 public init<T : IntegralType>(_ v: T) { if v < 0 { negative = true value = UInt64(-Int64(v)) } else { negative = false value = UInt64(v) } } } extension IntegralType { /// Initialise from `v`, trapping on overflow. public init(_ v: AnyInteger) { self = v.negative ? Self(-Int64(v.value)) : Self(v.value) } } extension IntegralType { /// Attempt to convert initialise from `v`, performing bounds checking and failing if this is not possible. public init?(convert v: AnyInteger) { if v.negative { if Int64(Self.min) <= -Int64(v.value) { self.init(-Int64(v.value)) } else { return nil } } else { if UInt64(Self.max) >= v.value { self.init(v.value) } else { return nil } } } } extension AnyInteger : IntegerLiteralConvertible { public init(integerLiteral value: Int64) { self.init(value) } } extension AnyInteger : Hashable { public var hashValue: Int { return value.hashValue } } public func ==(a: AnyInteger, b: AnyInteger) -> Bool { return (a.negative == b.negative && a.value == b.value) || (a.value == 0 && b.value == 0) } public func <(a: AnyInteger, b: AnyInteger) -> Bool { return (a.negative == b.negative && (a.value < b.value) != a.negative) || (a.negative && !b.negative) } extension AnyInteger : Equatable, Comparable { }
838e97c1bb8160edfaeee1eedec3b04a
27.541096
111
0.62971
false
false
false
false
Joywii/ImageView
refs/heads/master
Swift/ImageView/ImageViewer/KZImageViewer.swift
mit
2
// // KZImageViewer.swift // ImageViewDemo // // Created by joywii on 15/4/30. // Copyright (c) 2015年 joywii. All rights reserved. // import UIKit let kPadding = 10 class KZImageViewer: UIView , UIScrollViewDelegate ,KZImageScrollViewDelegate{ private var scrollView : UIScrollView? private var selectIndex : NSInteger? private var scrollImageViewArray : NSMutableArray? private var selectImageView : UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { self.backgroundColor = UIColor.blackColor() self.scrollImageViewArray = NSMutableArray() self.scrollView = UIScrollView(frame: self.frameForPagingScrollView()) self.scrollView?.pagingEnabled = true self.scrollView?.showsHorizontalScrollIndicator = false self.scrollView?.showsVerticalScrollIndicator = false self.scrollView?.backgroundColor = UIColor.clearColor() self.scrollView?.delegate = self self.addSubview(self.scrollView!) } func showImages(imageArray:NSArray,index:NSInteger) { self.alpha = 0.0 var window : UIWindow = UIApplication.sharedApplication().keyWindow! window.addSubview(self) let currentPage = index self.selectIndex = index var kzSelectImage : KZImage = imageArray.objectAtIndex(Int(index)) as! KZImage var selectImage : UIImage? = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(kzSelectImage.imageUrl?.absoluteString) if(selectImage == nil) { selectImage = kzSelectImage.thumbnailImage } var selectImageView : UIImageView = kzSelectImage.srcImageView! self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height) self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0) //动画 var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview) var imageView = UIImageView(frame: selectImageViewFrame) imageView.contentMode = selectImageView.contentMode imageView.clipsToBounds = true imageView.image = selectImage imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 1.0 imageView.transform = CGAffineTransformIdentity var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size var ratio = min(fullWidth / size!.width,fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio * size!.width var h = ratio > 1 ? size!.height : ratio * size!.height imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) }) { (finished) -> Void in for(var i = 0 ; i < imageArray.count ; i++) { var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i))) zoomImageView.kzImage = kzImage zoomImageView.imageDelegate = self zoomImageView.userInteractionEnabled = true if(i == Int(currentPage)){ if(kzImage.image == nil) { zoomImageView.startLoadImage() } } self.scrollView?.addSubview(zoomImageView) self.scrollImageViewArray?.addObject(zoomImageView) } self.preLoadImage(currentPage) imageView.removeFromSuperview() } } func showImages(imageArray:NSArray,selectImageView:UIImageView,index:NSInteger) { self.alpha = 0.0 var window : UIWindow = UIApplication.sharedApplication().keyWindow! window.addSubview(self) let currentPage = index self.selectIndex = index self.selectImageView = selectImageView self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height) self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0) //动画 var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview) var imageView = UIImageView(frame: selectImageViewFrame) imageView.contentMode = selectImageView.contentMode imageView.clipsToBounds = true imageView.image = selectImageView.image imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 1.0 imageView.transform = CGAffineTransformIdentity var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size var ratio = min(fullWidth / size!.width,fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio * size!.width var h = ratio > 1 ? size!.height : ratio * size!.height imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) }) { (finished) -> Void in for(var i = 0 ; i < imageArray.count ; i++) { var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i))) zoomImageView.kzImage = kzImage zoomImageView.imageDelegate = self zoomImageView.userInteractionEnabled = true if(i == Int(currentPage)){ if(kzImage.image == nil) { zoomImageView.startLoadImage() } } self.scrollView?.addSubview(zoomImageView) self.scrollImageViewArray?.addObject(zoomImageView) } self.preLoadImage(currentPage) imageView.removeFromSuperview() } } private func tappedScrollView(tap:UITapGestureRecognizer) { self.hide() } private func hide() { for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] { imageView.cancelLoadImage() imageView.removeFromSuperview() } var window : UIWindow = UIApplication.sharedApplication().keyWindow! let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height var index = self.pageIndex() var zoomImageView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView var size = zoomImageView.kzImage?.image != nil ? zoomImageView.kzImage?.image?.size : zoomImageView.frame.size var ratio = min(fullWidth / size!.width, fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio*size!.width var h = ratio > 1 ? size!.height : ratio*size!.height var frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) var imageView = UIImageView(frame: frame) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.image = zoomImageView.kzImage!.image imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) var selectImageViewFrame = window.convertRect(zoomImageView.kzImage!.srcImageView!.frame, fromView: zoomImageView.kzImage!.srcImageView!.superview) UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 0.0 imageView.frame = selectImageViewFrame }) { (finished) -> Void in for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] { SDImageCache.sharedImageCache().removeImageForKey(imageView.kzImage?.imageUrl?.absoluteString, fromDisk: false) } imageView.removeFromSuperview() self.removeFromSuperview() } } private func pageIndex() -> NSInteger{ return NSInteger(self.scrollView!.contentOffset.x / self.scrollView!.frame.size.width) } private func frameForPagingScrollView() -> CGRect { var frame = self.bounds frame.origin.x -= CGFloat(kPadding) frame.size.width += 2 * CGFloat(kPadding) return CGRectIntegral(frame) } private func frameForPageAtIndex(index:UInt) -> CGRect { var bounds = self.scrollView?.bounds var pageFrame = bounds pageFrame?.size.width -= (2*CGFloat(kPadding)) pageFrame?.origin.x = (bounds!.size.width * CGFloat(index)) + CGFloat(kPadding) return CGRectIntegral(pageFrame!) } func imageScrollViewSingleTap(imageScrollView: KZImageScrollView) { self.hide() } func preLoadImage(currentIndex:NSInteger) { var preIndex = currentIndex - 1 if(preIndex > 1) { var preZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(preIndex)) as! KZImageScrollView preZoomImageView.startLoadImage() } var nextIndex = currentIndex + 1 if(nextIndex < self.scrollImageViewArray?.count) { var nextZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(nextIndex)) as! KZImageScrollView nextZoomImageView.startLoadImage() } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { var index = self.pageIndex() var zoomImageView : KZImageScrollView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView zoomImageView.startLoadImage() self.preLoadImage(index) } }
9eb2944527c9cde28aaa75a7b6952379
43.639004
155
0.630508
false
false
false
false
AgentFeeble/pgoapi
refs/heads/master
pgoapi/Classes/Utility/CellIDUtility.swift
apache-2.0
1
// // CellIDUtility.swift // pgoapi // // Created by Rayman Rosevear on 2016/07/30. // Copyright © 2016 MC. All rights reserved. // import Foundation func getCellIDs(_ location: Location, radius: Int = 1000) -> [UInt64] { // Max values allowed by server according to this comment: // https://github.com/AeonLucid/POGOProtos/issues/83#issuecomment-235612285 let r = min(radius, 1500) let level = Int32(15) let maxCells = Int32(100) //100 is max allowed by the server let cells = MCS2CellID.cellIDsForRegion(atLat: location.latitude, long: location.longitude, radius: Double(r), level: level, maxCellCount: maxCells) return cells.map({ $0.cellID }).sorted() }
aa04d3ade6640e6fdf2f80a4f6654f81
33.538462
79
0.540089
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/Cells/ChatRightLocation/ChatRightLocationCell.swift
mit
1
// // ChatRightLocationCell.swift // Yep // // Created by NIX on 15/5/5. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import MapKit import YepKit final class ChatRightLocationCell: ChatRightBaseCell { static private let mapSize = CGSize(width: 192, height: 108) lazy var mapImageView: UIImageView = { let imageView = UIImageView() imageView.tintColor = UIColor.rightBubbleTintColor() return imageView }() lazy var locationNameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.whiteColor() label.font = UIFont.systemFontOfSize(12) label.textAlignment = .Center return label }() lazy var borderImageView: UIImageView = { let imageView = UIImageView(image: UIImage.yep_rightTailImageBubbleBorder) return imageView }() typealias MediaTapAction = () -> Void var mediaTapAction: MediaTapAction? func makeUI() { let fullWidth = UIScreen.mainScreen().bounds.width let halfAvatarSize = YepConfig.chatCellAvatarSize() / 2 avatarImageView.center = CGPoint(x: fullWidth - halfAvatarSize - YepConfig.chatCellGapBetweenWallAndAvatar(), y: halfAvatarSize) mapImageView.frame = CGRect(x: CGRectGetMinX(avatarImageView.frame) - YepConfig.ChatCell.gapBetweenAvatarImageViewAndBubble - 192, y: 0, width: 192, height: 108) borderImageView.frame = mapImageView.frame dotImageView.center = CGPoint(x: CGRectGetMinX(mapImageView.frame) - YepConfig.ChatCell.gapBetweenDotImageViewAndBubble, y: CGRectGetMidY(mapImageView.frame)) let locationNameLabelHeight = YepConfig.ChatCell.locationNameLabelHeight locationNameLabel.frame = CGRect(x: CGRectGetMinX(mapImageView.frame) + 20, y: CGRectGetMaxY(mapImageView.frame) - locationNameLabelHeight, width: 192 - 20 * 2 - 7, height: locationNameLabelHeight) } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(mapImageView) contentView.addSubview(locationNameLabel) contentView.addSubview(borderImageView) UIView.performWithoutAnimation { [weak self] in self?.makeUI() } mapImageView.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(ChatRightLocationCell.tapMediaView)) mapImageView.addGestureRecognizer(tap) prepareForMenuAction = { otherGesturesEnabled in tap.enabled = otherGesturesEnabled } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tapMediaView() { mediaTapAction?() } func configureWithMessage(message: Message, mediaTapAction: MediaTapAction?) { self.message = message self.user = message.fromFriend self.mediaTapAction = mediaTapAction UIView.performWithoutAnimation { [weak self] in self?.makeUI() } if let sender = message.fromFriend { let userAvatar = UserAvatar(userID: sender.userID, avatarURLString: sender.avatarURLString, avatarStyle: nanoAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) } let locationName = message.textContent locationNameLabel.text = locationName mapImageView.yep_setMapImageOfMessage(message, withSize: ChatRightLocationCell.mapSize, tailDirection: .Right) } }
effb112e3a7f2b6f935f9e15153ecd88
32.027778
205
0.694141
false
true
false
false
egouletlang/ios-BaseUtilityClasses
refs/heads/master
BaseUtilityClasses/DateHelper.swift
mit
1
// // DateHelper.swift // BaseUtilityClasses // // Created by Etienne Goulet-Lang on 8/19/16. // Copyright © 2016 Etienne Goulet-Lang. All rights reserved. // import Foundation private var dateObjs: [String: DateFormatter] = [:] public class DateHelper { // Data formatter Methods public enum DateComparison { case sameDay case dayBefore case sameWeek case sameYear case differentYear case na } public class func isLater(later: Date?, earlier: Date?) -> Bool { if let l = later, let e = earlier { return l.compare(e) == .orderedDescending } else if later == nil { return false } else if earlier == nil { return true } return false } public class func compareDates(day1: Date!, day2: Date!) -> DateComparison { if day1 == nil || day2 == nil { return .na } let calendar = Calendar.current let components: NSCalendar.Unit = [NSCalendar.Unit.year, NSCalendar.Unit.weekOfYear, NSCalendar.Unit.day, NSCalendar.Unit.hour, NSCalendar.Unit.minute] let comp1 = (calendar as NSCalendar).components(components, from: day1) let comp2 = (calendar as NSCalendar).components(components, from: day2) if (comp1.year != comp2.year) { return .differentYear } else if (comp1.weekOfYear != comp2.weekOfYear) { return .sameYear } else if (comp1.day != comp2.day) { if abs(comp1.day! - comp2.day!) == 1 { return .dayBefore } return .sameWeek } else { return .sameDay } } public class func isWithin(curr: Date, prev: Date!, within: Int) -> Bool { if prev == nil { return false } let diff = Int(abs(curr.timeIntervalSince(prev))) return (diff < within) } public class func formatDate(_ format: String, date: Date) -> String { var formatter = dateObjs[format] if formatter == nil { formatter = DateFormatter() formatter!.dateFormat = format dateObjs[format] = formatter } return formatter!.string(from: date) } }
af35e445bf3e30c51aef417f50da9be0
29.223684
159
0.566826
false
false
false
false
edx/edx-app-ios
refs/heads/master
Test/UserPreferenceManagerTests.swift
apache-2.0
2
// // UserPreferenceManagerTests.swift // edX // // Created by Kevin Kim on 8/8/16. // Copyright © 2016 edX. All rights reserved. // import Foundation @testable import edX class UserPreferenceManagerTests : XCTestCase { func testUserPreferencesLoginLogout() { let userPrefernces = UserPreference(json: ["time_zone": "Asia/Tokyo"]) XCTAssertNotNil(userPrefernces) let preferences = userPrefernces! let environment = TestRouterEnvironment() environment.mockNetworkManager.interceptWhenMatching({_ in true }) { return (nil, preferences) } let manager = UserPreferenceManager(networkManager: environment.networkManager) let feed = manager.feed // starts empty XCTAssertNil(feed.output.value ?? nil) // Log in. Preferences should load environment.logInTestUser() feed.refresh() stepRunLoop() waitForStream(feed.output) XCTAssertEqual(feed.output.value??.timeZone, preferences.timeZone) // Log out. Now preferences should be cleared environment.session.closeAndClear() XCTAssertNil(feed.output.value!) } }
418d3a08a17e8d42501c581cd2a5c518
27
87
0.627778
false
true
false
false
niunaruto/DeDaoAppSwift
refs/heads/master
DeDaoSwift/DeDaoSwift/Home/UIKitExtension/UIButton+Extension.swift
mit
1
// // UIButton+Extension.swift // DeDaoSwift // // Created by niuting on 2017/3/13. // Copyright © 2017年 niuNaruto. All rights reserved. // import Foundation public enum UIButtonImagePosition : Int { case left case right case bottom case top } extension UIButton { func setImagePosition(_ position : UIButtonImagePosition ,spacing : CGFloat? = 0) { setImage(currentImage, for: .normal) setTitle(currentTitle, for: .normal) let imageWidth = imageView?.image?.size.width let imageHeight = imageView?.image?.size.height guard imageWidth != nil && imageHeight != nil else { return } var tempSpc : CGFloat = 0 if let temp = spacing{ tempSpc = temp } var attrs = Dictionary<String, Any>() attrs[NSFontAttributeName] = titleLabel?.font; let labelSize = titleLabel?.text?.boundingRect(with: UIScreen.main .bounds.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil).size if let size = labelSize { let imageOffsetX = imageWidth! + size.width / 2.0 - imageWidth! / 2.0 let imageOffsetY = imageHeight! / 2.0 + tempSpc / 2.0 let labelOffsetX = (imageWidth! + size.width / 2.0) - (imageWidth! + size.width) / 2.0 let labelOffsetY = size.height / 2 + tempSpc / 2 let tempWidth = getMax(size.width,imageWidth!) let changedWidth = size.width + imageWidth! - tempWidth let tempHeight = getMax(size.height, imageHeight!) let changedHeight = size.height + imageHeight! + tempSpc - tempHeight; switch position { case .bottom: self.imageEdgeInsets = UIEdgeInsetsMake(imageOffsetY, imageOffsetX - imageWidth!, -imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(-labelOffsetY, -labelOffsetX, labelOffsetY, labelOffsetX); self.contentEdgeInsets = UIEdgeInsetsMake(changedHeight-imageOffsetY, -changedWidth/2, imageOffsetY, -changedWidth/2); case .top: self.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX - imageWidth!, imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX); self.contentEdgeInsets = UIEdgeInsetsMake(imageOffsetY, -changedWidth/2, changedHeight-imageOffsetY, -changedWidth/2); case .right: self.imageEdgeInsets = UIEdgeInsetsMake(0, size.width + tempSpc/2, 0, -(size.width + tempSpc/2)); self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageWidth! + tempSpc/2), 0, imageWidth! + tempSpc/2); self.contentEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, tempSpc/2); case .left: self.imageEdgeInsets = UIEdgeInsetsMake(0, -tempSpc/2, 0, tempSpc/2); self.titleEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, -tempSpc/2); self.contentEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, tempSpc/2); } } } func getMax(_ num1 : CGFloat ,_ num2 : CGFloat) -> CGFloat { guard num1 >= num2 else { return num1 } return num2 } }
915200e1477c4f888dd37e6ff268193a
33.174312
134
0.562148
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Floral/Classes/Expand/Extensions/RxSwift/Cocoa/UITextField+Rx.swift
mit
1
// // UITextField+Rx.swift // RxSwiftX // // Created by Pircate on 2018/6/1. // Copyright © 2018年 Pircate. All rights reserved. // import RxSwift import RxCocoa public extension Reactive where Base: UITextField { var delegate: RxTextFieldDelegateProxy { return RxTextFieldDelegateProxy.proxy(for: base) } var shouldClear: ControlEvent<UITextField> { let source = delegate.shouldClearPublishSubject return ControlEvent(events: source) } var shouldReturn: ControlEvent<UITextField> { let source = delegate.shouldReturnPublishSubject return ControlEvent(events: source) } var valueChanged: Binder<Void> { return Binder(base) { textField, _ in textField.sendActions(for: .valueChanged) } } } public extension UITextField { var maxLength: Int { get { return 0 } set { RxTextFieldDelegateProxy.proxy(for: self).shouldChangeCharacters = { (textField, range, string) -> Bool in if string.isEmpty { return true } guard let text = textField.text else { return true } let length = text.count + string.count - range.length return length <= newValue } } } }
ce3deda9a748a0f499e65720c8b663d3
26.020833
118
0.619121
false
false
false
false
pragmapilot/PPCollectionViewDragNDrop
refs/heads/master
PPCollectionViewDragNDrop/ViewController.swift
unlicense
1
// // ViewController.swift // PPCollectionViewDragNDrop // // Created by PragmaPilot on 13/10/2015. // Copyright © 2015 PragmaPilot. All rights reserved. // import UIKit class ViewController: UIViewController { private var downloadsCounter = 0 var items = NSMutableArray() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() initializeItems(100) let longPress = UILongPressGestureRecognizer(target: self, action: "didLongPress:"); self.collectionView.addGestureRecognizer(longPress) } func didLongPress(gesture: UILongPressGestureRecognizer){ switch(gesture.state) { case UIGestureRecognizerState.Began: guard let indexPath = self.collectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else { break } self.collectionView.beginInteractiveMovementForItemAtIndexPath(indexPath) case UIGestureRecognizerState.Changed: self.collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!)) case UIGestureRecognizerState.Ended: self.collectionView.endInteractiveMovement() default: self.collectionView.cancelInteractiveMovement() } } func initializeItems(size:Int){ self.downloadsCounter = size let photoManager = PhotoManager() UIApplication.sharedApplication().networkActivityIndicatorVisible = true for i in 0 ..< size { let photo = photoManager.buildPhoto(i) photoManager.loadImage(photo, completion: { (model) -> () in self.downloadsCounter-- if self.downloadsCounter == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { () -> Void in self.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forRow: model.id, inSection: 0)]) }) }) items.addObject(photo) } } }
37be725fe0e3d16fd9c7a73258eede4f
31.260274
122
0.609342
false
false
false
false
loudnate/xDripG5
refs/heads/master
CGMBLEKit/PeripheralManager+G5.swift
mit
1
// // PeripheralManager+G5.swift // xDripG5 // // Copyright © 2017 LoopKit Authors. All rights reserved. // import CoreBluetooth import os.log private let log = OSLog(category: "PeripheralManager+G5") extension PeripheralManager { private func getCharacteristicWithUUID(_ uuid: CGMServiceCharacteristicUUID) -> CBCharacteristic? { return peripheral.getCharacteristicWithUUID(uuid) } func setNotifyValue(_ enabled: Bool, for characteristicUUID: CGMServiceCharacteristicUUID, timeout: TimeInterval = 2) throws { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } try setNotifyValue(enabled, for: characteristic, timeout: timeout) } func readMessage<R: TransmitterRxMessage>( for characteristicUUID: CGMServiceCharacteristicUUID, timeout: TimeInterval = 2 ) throws -> R { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } var capturedResponse: R? try runCommand(timeout: timeout) { addCondition(.valueUpdate(characteristic: characteristic, matching: { (data) -> Bool in guard let value = data else { return false } guard let response = R(data: value) else { // We don't recognize the contents. Keep listening. return false } capturedResponse = response return true })) peripheral.readValue(for: characteristic) } guard let response = capturedResponse else { // TODO: This is an "unknown value" issue, not a timeout if let value = characteristic.value { log.error("Unknown response data: %{public}@", value.hexadecimalString) } throw PeripheralManagerError.timeout } return response } /// - Throws: PeripheralManagerError func writeMessage<T: RespondableMessage>(_ message: T, for characteristicUUID: CGMServiceCharacteristicUUID, type: CBCharacteristicWriteType = .withResponse, timeout: TimeInterval = 2 ) throws -> T.Response { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } var capturedResponse: T.Response? try runCommand(timeout: timeout) { if case .withResponse = type { addCondition(.write(characteristic: characteristic)) } if characteristic.isNotifying { addCondition(.valueUpdate(characteristic: characteristic, matching: { (data) -> Bool in guard let value = data else { return false } guard let response = T.Response(data: value) else { // We don't recognize the contents. Keep listening. return false } capturedResponse = response return true })) } peripheral.writeValue(message.data, for: characteristic, type: type) } guard let response = capturedResponse else { // TODO: This is an "unknown value" issue, not a timeout if let value = characteristic.value { log.error("Unknown response data: %{public}@", value.hexadecimalString) } throw PeripheralManagerError.timeout } return response } /// - Throws: PeripheralManagerError func writeMessage(_ message: TransmitterTxMessage, for characteristicUUID: CGMServiceCharacteristicUUID, type: CBCharacteristicWriteType = .withResponse, timeout: TimeInterval = 2) throws { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } try writeValue(message.data, for: characteristic, type: type, timeout: timeout) } } fileprivate extension CBPeripheral { func getServiceWithUUID(_ uuid: TransmitterServiceUUID) -> CBService? { return services?.itemWithUUIDString(uuid.rawValue) } func getCharacteristicForServiceUUID(_ serviceUUID: TransmitterServiceUUID, withUUIDString UUIDString: String) -> CBCharacteristic? { guard let characteristics = getServiceWithUUID(serviceUUID)?.characteristics else { return nil } return characteristics.itemWithUUIDString(UUIDString) } func getCharacteristicWithUUID(_ uuid: CGMServiceCharacteristicUUID) -> CBCharacteristic? { return getCharacteristicForServiceUUID(.cgmService, withUUIDString: uuid.rawValue) } }
ace80c2849ec4e313d7e141495877123
32.586667
137
0.626836
false
false
false
false
Stitch7/Instapod
refs/heads/master
Instapod/ColorCube.swift
mit
1
// // ColorCube.swift // Instapod // // Created by Christopher Reitz on 23.03.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit extension UIImage { var colorCube: UIColor { var color = UIColor.black let cube = ColorCube() let imageColors = cube.extractColorsFromImage(self, flags: [.AvoidWhite, .AvoidBlack]) if let mainColor = imageColors.first { color = mainColor } return color } } extension Data { var colorCube: UIColor { guard let image = UIImage(data: self) else { return UIColor.black } return image.colorCube } } struct ColorCubeFlags: OptionSet { let rawValue: Int static let None = ColorCubeFlags(rawValue: 0) static let OnlyBrightColors = ColorCubeFlags(rawValue: 1 << 0) static let OnlyDarkColors = ColorCubeFlags(rawValue: 1 << 1) static let OnlyDistinctColors = ColorCubeFlags(rawValue: 1 << 2) static let OrderByBrightness = ColorCubeFlags(rawValue: 1 << 3) static let OrderByDarkness = ColorCubeFlags(rawValue: 1 << 4) static let AvoidWhite = ColorCubeFlags(rawValue: 1 << 5) static let AvoidBlack = ColorCubeFlags(rawValue: 1 << 6) } final class ColorCubeLocalMaximum { let hitCount: Int // Linear index of the cell let cellIndex: Int // Average color of cell let red: Double let green: Double let blue: Double // Maximum color component value of average color let brightness: Double init( hitCount: Int, cellIndex: Int, red: Double, green: Double, blue: Double, brightness: Double ) { self.hitCount = hitCount self.cellIndex = cellIndex self.red = red self.green = green self.blue = blue self.brightness = brightness } } struct ColorCubeCell { // Count of hits (dividing the accumulators by this value gives the average) var hitCount: Int = 0 // Accumulators for color components var redAcc: Double = 0.0 var greenAcc: Double = 0.0 var blueAcc: Double = 0.0 } final class ColorCube { // The cell resolution in each color dimension let resolution = 30 // Threshold used to filter bright colors let brightColorThreshold = 0.6 // Threshold used to filter dark colors let darkColorThreshold = 0.4 // Threshold (distance in color space) for distinct colors let distinctColorThreshold: CGFloat = 0.2 // Helper macro to compute linear index for cells // let CELL_INDEX(r,g,b) (r+g*COLOR_CUBE_RESOLUTION+b*COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION) // Helper macro to get total count of cells // let CELL_COUNT COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION // Indices for neighbour cells in three dimensional grid let neighbourIndices: [[Int]] = [ [0, 0, 0], [0, 0, 1], [0, 0,-1], [0, 1, 0], [0, 1, 1], [0, 1,-1], [0,-1, 0], [0,-1, 1], [0,-1,-1], [1, 0, 0], [1, 0, 1], [1, 0,-1], [1, 1, 0], [1, 1, 1], [1, 1,-1], [1,-1, 0], [1,-1, 1], [1,-1,-1], [-1, 0, 0], [-1, 0, 1], [-1, 0,-1], [-1, 1, 0], [-1, 1, 1], [-1, 1,-1], [-1,-1, 0], [-1,-1, 1], [-1,-1,-1] ] var cells = [ColorCubeCell](repeating: ColorCubeCell(), count: 27000) func cellIndexCreate(_ r: Int, _ g: Int, _ b: Int) -> Int { return r + g * resolution + b * resolution * resolution } func findLocalMaximaInImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // We collect local maxima in here var localMaxima = [ColorCubeLocalMaximum]() // Reset all cells clearCells() // guard let context = rawPixelDataFromImage(image, pixelCount: &pixelCount) else { return localMaxima } // let rawData = UnsafeMutablePointer<UInt8>(context.data) // let rawData: UnsafeMutablePointer<CGImage> = context.data! let cgImage = image.cgImage! let width = cgImage.width let height = cgImage.height // Allocate storage for the pixel data let rawDataSize = height * width * 4 let rawData: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.allocate(capacity: rawDataSize) // Create the color space let colorSpace = CGColorSpaceCreateDeviceRGB(); // Set some metrics let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue).rawValue // Create context using the storage _ = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // rawData.deallocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) // rawData.deallocate(capacity: rawDataSize) let pixelCount = width * height // Helper vars var red, green, blue: Double var redIndex, greenIndex, blueIndex, cellIndex, localHitCount: Int var isLocalMaximum: Bool // Project each pixel into one of the cells in the three dimensional grid for k in 0 ..< pixelCount { // Get color components as floating point value in [0,1] red = Double(rawData[k * 4 + 0]) / 255.0 green = Double(rawData[k * 4 + 1]) / 255.0 blue = Double(rawData[k * 4 + 2]) / 255.0 // If we only want bright colors and this pixel is dark, ignore it if flags.contains(.OnlyBrightColors) { if red < brightColorThreshold && green < brightColorThreshold && blue < brightColorThreshold { continue } } else if flags.contains(.OnlyDarkColors) { if red >= darkColorThreshold || green >= darkColorThreshold || blue >= darkColorThreshold { continue } } // Map color components to cell indices in each color dimension let redIndex = Int(red * (Double(resolution) - 1.0)) let greenIndex = Int(green * (Double(resolution) - 1.0)) let blueIndex = Int(blue * (Double(resolution) - 1.0)) // Compute linear cell index cellIndex = cellIndexCreate(redIndex, greenIndex, blueIndex) // Increase hit count of cell cells[cellIndex].hitCount += 1 // Add pixel colors to cell color accumulators cells[cellIndex].redAcc += red cells[cellIndex].greenAcc += green cells[cellIndex].blueAcc += blue } // Deallocate raw pixel data memory rawData.deinitialize() rawData.deallocate(capacity: rawDataSize) // Find local maxima in the grid for r in 0 ..< resolution { for g in 0 ..< resolution { for b in 0 ..< resolution { // Get hit count of this cell localHitCount = cells[cellIndexCreate(r, g, b)].hitCount // If this cell has no hits, ignore it (we are not interested in zero hits) if localHitCount == 0 { continue } // It is local maximum until we find a neighbour with a higher hit count isLocalMaximum = true // Check if any neighbour has a higher hit count, if so, no local maxima for n in 0..<27 { redIndex = r + neighbourIndices[n][0]; greenIndex = g + neighbourIndices[n][1]; blueIndex = b + neighbourIndices[n][2]; // Only check valid cell indices (skip out of bounds indices) if redIndex >= 0 && greenIndex >= 0 && blueIndex >= 0 { if redIndex < resolution && greenIndex < resolution && blueIndex < resolution { if cells[cellIndexCreate(redIndex, greenIndex, blueIndex)].hitCount > localHitCount { // Neighbour hit count is higher, so this is NOT a local maximum. isLocalMaximum = false // Break inner loop break } } } } // If this is not a local maximum, continue with loop. if !isLocalMaximum { continue } // Otherwise add this cell as local maximum let cellIndex = cellIndexCreate(r, g, b) let hitCount = cells[cellIndex].hitCount let red = cells[cellIndex].redAcc / Double(cells[cellIndex].hitCount) let green = cells[cellIndex].greenAcc / Double(cells[cellIndex].hitCount) let blue = cells[cellIndex].blueAcc / Double(cells[cellIndex].hitCount) let brightness = fmax(fmax(red, green), blue) let maximum = ColorCubeLocalMaximum( hitCount: hitCount, cellIndex: cellIndex, red: red, green: green, blue: blue, brightness: brightness ) localMaxima.append(maximum) } } } let sorttedMaxima = localMaxima.sorted { $0.hitCount > $1.hitCount } return sorttedMaxima } func findAndSortMaximaInImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // First get local maxima of image var sortedMaxima = findLocalMaximaInImage(image, flags: flags) // Filter the maxima if we want only distinct colors if flags.contains(.OnlyDistinctColors) { sortedMaxima = filterDistinctMaxima(sortedMaxima, threshold: distinctColorThreshold) } // If we should order the result array by brightness, do it if flags.contains(.OrderByBrightness) { sortedMaxima = orderByBrightness(sortedMaxima) } else if flags.contains(.OrderByDarkness) { sortedMaxima = orderByDarkness(sortedMaxima) } return sortedMaxima } // MARK: - Filtering and sorting func filterDistinctMaxima(_ maxima: [ColorCubeLocalMaximum], threshold: CGFloat) -> [ColorCubeLocalMaximum] { var filteredMaxima = [ColorCubeLocalMaximum]() // Check for each maximum for k in 0 ..< maxima.count { // Get the maximum we are checking out let max1 = maxima[k] // This color is distinct until a color from before is too close var isDistinct = true // Go through previous colors and look if any of them is too close for n in 0 ..< k { // Get the maximum we compare to let max2 = maxima[n] // Compute delta components let redDelta = max1.red - max2.red let greenDelta = max1.green - max2.green let blueDelta = max1.blue - max2.blue // Compute delta in color space distance let delta = CGFloat(sqrt(redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta)) // If too close mark as non-distinct and break inner loop if delta < threshold { isDistinct = false break } } // Add to filtered array if is distinct if isDistinct { filteredMaxima.append(max1) } } return filteredMaxima } func filterMaxima(_ maxima: [ColorCubeLocalMaximum], tooCloseToColor color: UIColor) -> [ColorCubeLocalMaximum] { // Get color components let components = color.cgColor.components var filteredMaxima = [ColorCubeLocalMaximum]() // Check for each maximum for k in 0..<maxima.count { // Get the maximum we are checking out let max1 = maxima[k] // Compute delta components let redDelta = max1.red - Double((components?[0])!) let greenDelta = max1.green - Double((components?[1])!) let blueDelta = max1.blue - Double((components?[2])!) // Compute delta in color space distance let delta = sqrt(redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta) // If not too close add it if delta >= 0.5 { filteredMaxima.append(max1) } } return filteredMaxima } func orderByBrightness(_ maxima: [ColorCubeLocalMaximum]) -> [ColorCubeLocalMaximum] { return maxima.sorted { $0.brightness > $1.brightness } } func orderByDarkness(_ maxima: [ColorCubeLocalMaximum]) -> [ColorCubeLocalMaximum] { return maxima.sorted { $0.brightness < $1.brightness } } func performAdaptiveDistinctFilteringForMaxima(_ maxima: [ColorCubeLocalMaximum], count: Int) -> [ColorCubeLocalMaximum] { var tempMaxima = maxima // If the count of maxima is higher than the requested count, perform distinct thresholding if (maxima.count > count) { var tempDistinctMaxima = maxima var distinctThreshold: CGFloat = 0.1 // Decrease the threshold ten times. If this does not result in the wanted count for _ in 0 ..< 10 { // Get array with current distinct threshold tempDistinctMaxima = filterDistinctMaxima(maxima, threshold: distinctThreshold) // If this array has less than count, break and take the current sortedMaxima if tempDistinctMaxima.count <= count { break } // Keep this result (length is > count) tempMaxima = tempDistinctMaxima // Increase threshold by 0.05 distinctThreshold += 0.05 } // Only take first count maxima tempMaxima = Array(maxima[0..<count]) } return tempMaxima } // MARK: - Maximum to color conversion func colorsFromMaxima(_ maxima: [ColorCubeLocalMaximum]) -> [UIColor] { // Build the resulting color array var colorArray = [UIColor]() // For each local maximum generate UIColor and add it to the result array for maximum in maxima { let color = UIColor( red: CGFloat(maximum.red), green: CGFloat(maximum.green), blue: CGFloat(maximum.blue), alpha: 1.0 ) colorArray.append(color) } return colorArray } // MARK: - Default maxima extraction and filtering func extractAndFilterMaximaFromImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // Get maxima var sortedMaxima = findAndSortMaximaInImage(image, flags: flags) // Filter out colors too close to black if flags.contains(.AvoidBlack) { let black = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1) sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: black) } // Filter out colors too close to white if flags.contains(.AvoidWhite) { let white = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1) sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: white) } // Return maxima array return sortedMaxima } // MARK: - Public methods func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags) -> [UIColor] { // Get maxima let sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Return color array return colorsFromMaxima(sortedMaxima) } func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags, avoidColor: UIColor) -> [UIColor] { // Get maxima var sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Return color array return colorsFromMaxima(sortedMaxima) } func extractBrightColorsFromImage(_ image: UIImage, avoidColor: UIColor, count: Int) -> [UIColor] { // Get maxima (bright only) var sortedMaxima = findAndSortMaximaInImage(image, flags: .OnlyBrightColors) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } func extractDarkColorsFromImage(_ image: UIImage, avoidColor: UIColor, count: Int) -> [UIColor] { // Get maxima (bright only) var sortedMaxima = findAndSortMaximaInImage(image, flags: .OnlyDarkColors) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags, count: Int) -> [UIColor] { // Get maxima var sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } // MARK: - Resetting cells func clearCells() { let cellCount = resolution * resolution * resolution for k in 0 ..< cellCount { cells[k].hitCount = 0 cells[k].redAcc = 0.0 cells[k].greenAcc = 0.0 cells[k].blueAcc = 0.0 } } // MARK: - Pixel data extraction func rawPixelDataFromImage(_ image: UIImage, pixelCount: inout Int) -> CGContext? { // Get cg image and its size guard let cgImage = image.cgImage else { return nil } let width = cgImage.width let height = cgImage.height // Allocate storage for the pixel data let rawDataSize = height * width * 4 // let rawData = UnsafeMutableRawPointer.allocate(capacity: rawDataSize) // let rawData = UnsafeMutableRawPointer.allocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) let rawData: UnsafeMutablePointer<CGImage> = UnsafeMutablePointer.allocate(capacity: rawDataSize) // Create the color space let colorSpace = CGColorSpaceCreateDeviceRGB(); // Set some metrics let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue).rawValue // Create context using the storage let context = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // rawData.deallocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) rawData.deallocate(capacity: rawDataSize) // Draw the image into the storage context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) // Write pixel count to passed pointer pixelCount = width * height // Return pixel data (needs to be freed) return context } }
76532858b699970a8d0578bbc8508acf
35.139085
181
0.593511
false
false
false
false
ceecer1/open-muvr
refs/heads/master
ios/Lift/Device/This/ThisDeviceSession+HealthKit.swift
apache-2.0
5
import Foundation import HealthKit /// /// Provides HK connector /// extension ThisDeviceSession { class HealthKit { let store: HKHealthStore! var heartRateQuery: HKObserverQuery? init() { let readTypes: NSSet = NSSet(object: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)) let shareTypes: NSSet = NSSet() store = HKHealthStore() let hr = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) store.requestAuthorizationToShareTypes(shareTypes, readTypes: readTypes) { (x, err) in self.store.enableBackgroundDeliveryForType(hr, frequency: HKUpdateFrequency.Immediate, withCompletion: { (x, err) in self.heartRateQuery = HKObserverQuery(sampleType: hr, predicate: nil, updateHandler: self.heartRateUpdateHandler) self.store.executeQuery(self.heartRateQuery!) }) } } func stop() { store.stopQuery(heartRateQuery?) } func heartRateUpdateHandler(query: HKObserverQuery!, completion: HKObserverQueryCompletionHandler!, error: NSError!) { NSLog("Got HR") } } }
8bea3e3cf86961f47c9bd6c07c16621c
34.833333
133
0.629946
false
false
false
false
Centroida/SwiftImageCarousel
refs/heads/master
SwiftImageCarousel/SwiftImageCarouselVC.swift
mit
1
import UIKit // // SwiftImageCarouselVC.swift // SwiftImageCarousel // // Created by Deyan Aleksandrov on 1/3/17. // /// The delegate of a SwiftImageCarouselVC object must adopt this protocol. Optional methods of the protocol allow the delegate to configure the appearance of the view controllers, the timer and get notified when a new image is shown @objc public protocol SwiftImageCarouselVCDelegate: class { /// Fires when the timer starts helps to track of all the properties the timer has when it was started. /// /// - Parameter timer: The timer that manages the automatic swiping of images @objc optional func didStartTimer(_ timer: Timer) /// Fires when the timer is on and a new SwiftImageCarouselItemVC gets instantiated every few seconds. /// /// - Parameter SwiftImageCarouselItemController: The next pageItemController that has been initialized due to the timer ticking @objc optional func didGetNextITemController(next SwiftImageCarouselItemController: SwiftImageCarouselItemVC) /// Fires when an unwinding action coming from GalleryItemVC is performed and a new SwiftImageCarouselItemVC gets instantiated. /// /// - Parameter SwiftImageCarouselItemController: The page controller received when unwinding the GalleryVC @objc optional func didunwindToSwiftImageCarouselVC(unwindedTo SwiftImageCarouselItemController: SwiftImageCarouselItemVC) /// Fires when SwiftImageCarouselVC is initialized. Use it to setup the appearance of the paging controls (dots) of both the SwiftImageCarouselVC and the GalleryVC. /// /// - Parameters: /// - firstPageControl: The page control in SwiftImageCarouselVC /// - secondPageControl: The page control in GalleryVC @objc optional func setupAppearance(forFirst firstPageControl: UIPageControl, forSecond secondPageControl: UIPageControl) /// Fires when a pageItemController is tapped. /// /// - Parameter SwiftImageCarouselItemController: The SwiftImageCarouselItemVC taht is tapped @objc optional func didTapSwiftImageCarouselItemVC(swiftImageCarouselItemController: SwiftImageCarouselItemVC) } /// SwiftImageCarouselVC is the controller base class and initilizes the first view the user sees when a developer implements this carousel. It implements methods used for instantiating the proper page view, setting up the page controller appearance and setting up the timer used for automatic swiping of the page views. public class SwiftImageCarouselVC: UIPageViewController { /// The model array of image urls used in the carousel. public var contentImageURLs: [String] = [] { didSet { getNextItemController() } } // MARK: - Delegate weak public var swiftImageCarouselVCDelegate: SwiftImageCarouselVCDelegate? /// When set to TRUE, sets the image container frame to extend over the UIPageControl frame but not cover it (it goes underneath). To see it the proper effect of this variable in most cases, the contentMode should be .scaleToFill. Note also that background of the page control defaults to .clear when this variable is set to TRUE Default value is FALSE. public var escapeFirstPageControlDefaultFrame = false /// Keeps track of the page control frame height and provides it when needed var pageControlFrameHeight: CGFloat = 0 /// Enables/disables the showing of the modal gallery. public var showModalGalleryOnTap = true /// The image shown when an image to be downloaded does not do that successfully public var noImage: UIImage? = nil /// Enables resetting the UIViewContentMode of SwiftImageCarouselItemVC UIViewContentMode. The default is .scaleAspectFit. public var contentMode: UIViewContentMode = .scaleAspectFit // MARK: - Timer properties /// The timer that is used to move the next page item. var timer = Timer() /// Enables/disables the automatic swiping of the timer. Default value is true. public var isTimerOn = true /// The interval on which the view changes when the timer is on. Default value is 3 seconds. public var swipeTimeIntervalSeconds = 3.0 /// Shows/hides the close button in the modal gallery. Default value is false. public var showCloseButtonInModalGallery = false /// This variable keeps track of the index used in the page control in terms of the array of URLs. fileprivate var pageIndicatorIndex = 0 /// This variable keeps track of the index of the SwiftImageCarouselVC in terms of the array of URLs. fileprivate var currentPageViewControllerItemIndex = 0 // MARK: - Unwind segue /// In this unwind method, it is made sure that the view that will be instantiated has the proper image (meaning that same that we unwinded from). /// It is also made sure that that pageIndicatorIndex is setup to the proper dot shows up on the page control. @IBAction func unwindToSwiftImageCarouselVC(withSegue segue: UIStoryboardSegue) { // Making sure that the proper page control appearance comes on here when unwinding. setupPageControl() if let galleryItemVC = segue.source as? GalleryItemVC { loadPageViewControllerWhenUnwinding(atIndex: galleryItemVC.itemIndex) } } /// Loads a view controller with the index from the unwind segue. /// /// - Parameter itemIndex: The index for the VC from the model that will be loaded func loadPageViewControllerWhenUnwinding(atIndex itemIndex: Int) { if let currentController = getItemController(itemIndex) { swiftImageCarouselVCDelegate?.didunwindToSwiftImageCarouselVC?(unwindedTo: currentController) pageIndicatorIndex = currentController.itemIndex let startingViewControllers = [currentController] setViewControllers(startingViewControllers, direction: .forward, animated: false, completion: nil) } } // MARK: - Functions /// Loads a starting view controller from the model array with an index. /// /// - Parameter index: The index for the VC from the model that will be loaded func loadPageViewController(atIndex index: Int = 0) { if let firstController = getItemController(index) { let startingViewControllers = [firstController] setViewControllers(startingViewControllers, direction: .forward, animated: true, completion: nil) } } /// A method for getting the next SwiftImageCarouselItemVC. Called only by the timer selector. @objc func getNextItemController() { guard let currentViewController = viewControllers?.first else { return } // Use delegate method to retrieve the next view controller. guard let nextViewController = pageViewController(self, viewControllerAfter: currentViewController) as? SwiftImageCarouselItemVC else { return } swiftImageCarouselVCDelegate?.didGetNextITemController?(next: nextViewController) // Need to keep track of page indicator index in order to update it properly. pageIndicatorIndex = nextViewController.itemIndex setViewControllers([nextViewController], direction: .forward, animated: true, completion: nil) } /// A method for getting SwiftImageCarouselItemVC with a given index. func getItemController(_ itemIndex: Int) -> SwiftImageCarouselItemVC? { if !contentImageURLs.isEmpty && itemIndex <= contentImageURLs.count { let pageItemController = storyboard!.instantiateViewController(withIdentifier: "SwiftImageCarouselItemVC") as! SwiftImageCarouselItemVC pageItemController.itemIndex = itemIndex < contentImageURLs.count ? itemIndex : 0 pageItemController.contentImageURLs = contentImageURLs pageItemController.swiftImageCarouselVCDelegate = swiftImageCarouselVCDelegate pageItemController.showModalGalleryOnTap = showModalGalleryOnTap pageItemController.contentMode = contentMode pageItemController.noImage = noImage pageItemController.showCloseButtonInModalGallery = showCloseButtonInModalGallery return pageItemController } return nil } // MARK: - Timer Function func startTimer() { if timer.isValid { timer.invalidate() } timer = Timer.scheduledTimer(timeInterval: swipeTimeIntervalSeconds, target: self, selector: #selector(getNextItemController), userInfo: nil, repeats: true) swiftImageCarouselVCDelegate?.didStartTimer?(timer) } // MARK: - Page Indicator public func presentationCount(for pageViewController: UIPageViewController) -> Int { return contentImageURLs.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { return pageIndicatorIndex } // MARK: - Setup page control func setupPageControl() { view.backgroundColor = .white // Default appearance let appearance = UIPageControl.appearance() appearance.pageIndicatorTintColor = .orange appearance.currentPageIndicatorTintColor = .gray appearance.backgroundColor = .clear // Custom appearance setup with delegation from outside this framework. let firstAppearance = UIPageControl.appearance(whenContainedInInstancesOf: [SwiftImageCarouselVC.self]) let secondAppearance = UIPageControl.appearance(whenContainedInInstancesOf: [GalleryVC.self]) swiftImageCarouselVCDelegate?.setupAppearance?(forFirst: firstAppearance, forSecond: secondAppearance) } // MARK: - View Lifecycle override public func viewDidLoad() { super.viewDidLoad() dataSource = self loadPageViewController() setupPageControl() } /// A method fixing the bounds of the image so that page control with the dots does not cover that particular image. override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if escapeFirstPageControlDefaultFrame { for view in self.view.subviews { if view is UIScrollView { // Sets the image container frame to extend over the UIPageControl frame but not cover it (it goes underneath). // To see it properly working contentMode should be .scaleToFill // 37 is generally the default height of a UIPageControl if pageControlFrameHeight != 0 { view.frame = CGRect(x: view.frame.minX , y: view.frame.minY, width: view.frame.width, height: view.frame.height + pageControlFrameHeight) } } else if view is UIPageControl { pageControlFrameHeight = view.frame.height view.backgroundColor = .clear } } } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isTimerOn { startTimer() } } public override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) timer.invalidate() } override public var prefersStatusBarHidden : Bool { return true } } // MARK: - UIPageViewControllerDataSource extension SwiftImageCarouselVC: UIPageViewControllerDataSource { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard contentImageURLs.count > 1 else { return nil } let itemController = viewController as! SwiftImageCarouselItemVC let nextIndex = itemController.itemIndex > 0 ? (itemController.itemIndex - 1) : (contentImageURLs.count - 1) return getItemController(nextIndex) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard contentImageURLs.count > 1 else { return nil } let itemController = viewController as! SwiftImageCarouselItemVC let previousIndex = itemController.itemIndex + 1 < contentImageURLs.count ? (itemController.itemIndex + 1) : (0) return getItemController(previousIndex) } }
ae0565a866ab4e1266d36a09657338b4
48.01992
357
0.72131
false
false
false
false
montionugera/swift-101
refs/heads/master
4-swiftTour-Class.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" /*Objects and Classes Use class followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it is in the context of a class. Likewise, method and function declarations are written the same way. */ class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } /*EXPERIMENT Add a constant property with let, and add another method that takes an argument. */ class RectShape { let numberOfSides = 4 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } /* Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance. */ var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() //This version of the Shape class is missing something important: an initializer to set up the class when an instance is created. Use init to create one. class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } //Notice how self is used to distinguish the name property from the name argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as with numberOfSides) or in the initializer (as with name). // //Use deinit to create a deinitializer if you need to perform some cleanup before the object is deallocated. // //Subclasses include their superclass name after their class name, separated by a colon. There is no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed. // //Methods on a subclass that override the superclass’s implementation are marked with override—overriding a method by accident, without override, is detected by the compiler as an error. The compiler also detects methods with override that don’t actually override any method in the superclass. // class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription() //EXPERIMENT // //Make another subclass of NamedShape called Circle that takes a radius and a name as arguments to its initializer. Implement an area() and a simpleDescription() method on the Circle class. //In addition to simple properties that are stored, properties can have a getter and a setter. class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") println(triangle.perimeter) triangle.perimeter = 9.9 println(triangle.sideLength) //In the setter for perimeter, the new value has the implicit name newValue. You can provide an explicit name in parentheses after set. //Notice that the initializer for the EquilateralTriangle class has three different steps: // //Setting the value of properties that the subclass declares. //Calling the superclass’s initializer. //Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point. //If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use willSet and didSet. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square. class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") println(triangleAndSquare.square.sideLength) println(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "larger square") println(triangleAndSquare.triangle.sideLength) //Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method. class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) { count += amount * times } } var counter = Counter() counter.incrementBy(2, numberOfTimes: 7) //When working with optional values, you can write ? before operations like methods, properties, and subscripting. If the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, the optional value is unwrapped, and everything after the ? acts on the unwrapped value. In both cases, the value of the whole expression is an optional value. let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
a94558311ab7d69219aa542ca595d28f
39.209877
404
0.724593
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
refs/heads/master
PlagiarismChecker/Classes/CopyleaksRequest.swift
mit
1
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.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 Foundation public class CopyleaksRequest { /* The delegate for the underlying task. */ public let delegate: TaskDelegate /* The underlying task. */ public var task: NSURLSessionTask { return delegate.task } /* The session belonging to the underlying task. */ public let session: NSURLSession /* The request sent or to be sent to the server. */ public var request: NSURLRequest? { return task.originalRequest } /* The response received from the server, if any. */ public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } /* The progress of the request lifecycle. */ public var progress: NSProgress { return delegate.progress } // MARK: - Lifecycle init(session: NSURLSession, task: NSURLSessionTask) { self.session = session switch task { case is NSURLSessionUploadTask: delegate = UploadTaskDelegate(task: task) case is NSURLSessionDataTask: delegate = DataTaskDelegate(task: task) default: delegate = TaskDelegate(task: task) } } // MARK: - State /** Resumes the request. */ public func resume() { task.resume() } /** Suspends the request. */ public func suspend() { task.suspend() } /** Cancels the request. */ public func cancel() { task.cancel() } // MARK: - TaskDelegate /** The task delegate is responsible for handling all delegate callbacks for the underlying task as well as executing all operations attached to the serial operation queue upon task completion. */ public class TaskDelegate: NSObject { public let queue: NSOperationQueue let task: NSURLSessionTask let progress: NSProgress var data: NSData? { return nil } var error: NSError? init(task: NSURLSessionTask) { self.task = task self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true return operationQueue }() } deinit { queue.cancelAllOperations() queue.suspended = false } // MARK: - NSURLSessionTaskDelegate var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { self.error = error } queue.suspended = false } } } // MARK: - DataTaskDelegate class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } private var totalBytesReceived: Int64 = 0 private var mutableData: NSMutableData override var data: NSData? { return mutableData } private var expectedContentLength: Int64? private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? override init(task: NSURLSessionTask) { mutableData = NSMutableData() super.init(task: task) } // MARK: - NSURLSessionDataDelegate var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { mutableData.appendData(data) totalBytesReceived += data.length let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived dataProgress?( bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpected ) } } } class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
6f9d4f4c5e68630e1583112e71e53ced
34.376106
162
0.61626
false
false
false
false
bradvandyk/OpenSim
refs/heads/master
OpenSim/DirectoryWatcher.swift
mit
1
// // DirectoryWatcher.swift // Markdown // // Created by Luo Sheng on 15/10/31. // Copyright © 2015年 Pop Tap. All rights reserved. // import Foundation public class DirectoryWatcher { enum Error: ErrorType { case CannotOpenPath case CannotCreateSource } enum Mask { case Attribute case Delete case Extend case Link case Rename case Revoke case Write var flag: dispatch_source_vnode_flags_t { get { switch self { case .Attribute: return DISPATCH_VNODE_ATTRIB case .Delete: return DISPATCH_VNODE_DELETE case .Extend: return DISPATCH_VNODE_EXTEND case .Link: return DISPATCH_VNODE_LINK case .Rename: return DISPATCH_VNODE_RENAME case .Revoke: return DISPATCH_VNODE_REVOKE case .Write: return DISPATCH_VNODE_WRITE } } } } public typealias CompletionCallback = () -> () var watchedURL: NSURL let mask: Mask public var completionCallback: CompletionCallback? private let queue = dispatch_queue_create("com.pop-tap.directory-watcher", DISPATCH_QUEUE_SERIAL) private var source: dispatch_source_t? private var directoryChanging = false private var oldDirectoryInfo = [FileInfo?]() init(URL: NSURL, mask: Mask = .Write) { watchedURL = URL self.mask = mask } deinit { self.stop() } public func start() throws { guard source == nil else { return } guard let path = watchedURL.path else { return } let fd = open((path as NSString).fileSystemRepresentation, O_EVTONLY) guard fd >= 0 else { throw Error.CannotOpenPath } let cleanUp: () -> () = { close(fd) } guard let src = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(fd), mask.flag, queue) else { cleanUp() throw Error.CannotCreateSource } source = src dispatch_source_set_event_handler(src) { self.waitForDirectoryToFinishChanging() } dispatch_source_set_cancel_handler(src, cleanUp) dispatch_resume(src) } public func stop() { guard let src = source else { return } dispatch_source_cancel(src) } private func waitForDirectoryToFinishChanging() { if (!directoryChanging) { directoryChanging = true oldDirectoryInfo = self.directoryInfo() // print(oldDirectoryInfo) let timer = NSTimer(timeInterval: 0.5, target: self, selector: #selector(checkDirectoryInfo(_:)), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } } private func directoryInfo() -> [FileInfo?] { do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(watchedURL, includingPropertiesForKeys: FileInfo.prefetchedProperties, options: .SkipsSubdirectoryDescendants) return contents.map { FileInfo(URL: $0) } } catch { return [] } } @objc private func checkDirectoryInfo(timer: NSTimer) { let directoryInfo = self.directoryInfo() directoryChanging = directoryInfo != oldDirectoryInfo if directoryChanging { oldDirectoryInfo = directoryInfo } else { timer.invalidate() if let completion = completionCallback { completion() } } } }
f59e29bc6923ac87ae8896f98c073c66
27.126761
197
0.542449
false
false
false
false
tempestrock/CarPlayer
refs/heads/master
CarPlayer/TransitionManager.swift
gpl-3.0
1
// // TransitionManager.swift // Transitions between views // import UIKit class TransitionManager_Rotating: TransitionManager_Base { // // Animates a rotation from one view controller to another. // override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // DEBUG print("TransitionManager_Rotating.animateTransition()") // Get reference to our fromView, toView and the container view that we should perform the transition in: let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // set up from 2D transforms that we'll use in the animation: let π : CGFloat = 3.14159265359 let offScreenDown = CGAffineTransformMakeRotation(π/2) let offScreenUp = CGAffineTransformMakeRotation(-π/2) // Prepare the toView for the animation, depending on whether we are presenting or dismissing: toView.transform = self.presenting ? offScreenDown : offScreenUp // set the anchor point so that rotations happen from the top-left corner toView.layer.anchorPoint = CGPoint(x: 0, y: 0) fromView.layer.anchorPoint = CGPoint(x: 0, y: 0) // updating the anchor point also moves the position to we have to move the center position to the top-left to compensate toView.layer.position = CGPoint(x :0, y: 0) fromView.layer.position = CGPoint(x: 0, y: 0) // add the both views to our view controller container!.addSubview(toView) container!.addSubview(fromView) // Get the duration of the animation: let duration = self.transitionDuration(transitionContext) // Perform the animation: UIView.animateWithDuration( duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [], animations: { // slide fromView off either the left or right edge of the screen // depending if we're presenting or dismissing this view fromView.transform = self.presenting ? offScreenUp : offScreenDown toView.transform = CGAffineTransformIdentity }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) } ) } } // // A manager for vertical sliding transitions. Use the "DirectionToStartWith" to define whether the initial animation goes up or down. // class TransitionManager_Sliding: TransitionManager_Base { // An enum to define the initial animation direction enum DirectionToStartWith { case Up case Down } // The direction to us when animating the presentation. The dismissal is in the respective opposite direction private var _directionToStartWith: DirectionToStartWith = .Down override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // set up from 2D transforms that we'll use in the animation let offScreenDown = CGAffineTransformMakeTranslation(0, container!.frame.height) let offScreenUp = CGAffineTransformMakeTranslation(0, -container!.frame.height) // start the toView to the right of the screen if _directionToStartWith == DirectionToStartWith.Up { toView.transform = self.presenting ? offScreenDown : offScreenUp } else { toView.transform = self.presenting ? offScreenUp : offScreenDown } // add the both views to our view controller container!.addSubview(toView) container!.addSubview(fromView) // Get the duration of the animation: let duration = self.transitionDuration(transitionContext) // Perform the animation: UIView.animateWithDuration( duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [], animations: { // Depending on the two aspects "direction to start with" and "presentation or dismissal" we set the fromview's transformation: if self._directionToStartWith == DirectionToStartWith.Up { fromView.transform = self.presenting ? offScreenUp : offScreenDown } else { fromView.transform = self.presenting ? offScreenDown : offScreenUp } toView.transform = CGAffineTransformIdentity }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) } ) } // // Sets the direction of swiping for the presentation. The direction back (dismissal) is always the respective opposite direction. // func setDirectionToStartWith(direction: DirectionToStartWith) { _directionToStartWith = direction } } // // The base class of all transition managers // class TransitionManager_Base: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { // --------- attributes --------- // A flag to define whether we are in the presenting or in the dismissing part of the animation: private var presenting = true // --------- methods --------- // // Empty animation. Needs to be implemented by derived class. // func animateTransition(transitionContext: UIViewControllerContextTransitioning) { assert(false, "TransitionManager_Base.animateTransition(): Missing implementation in derived class") } // // Returns how many seconds the transiton animation will take. // func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.75 } // // Returns the animator when presenting a viewcontroller. // Remmeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol // func animationControllerForPresentedController( presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { // DEBUG print("TransitionManager_Base.animationControllerForPresentedController()") // These methods are the perfect place to set our `presenting` flag to either true or false - voila! self.presenting = true return self } // // Returns the animator used when dismissing from a view controller. // func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // DEBUG print("TransitionManager_Base.animationControllerForDismissedController()") self.presenting = false return self } }
84663eda4a863b50605c10fc5d75f4dc
35.665072
143
0.666319
false
false
false
false
Tinkertanker/intro-coding-swift
refs/heads/master
0-2 Number Variables.playground/Contents.swift
mit
1
/*: # Intro to Programming in Swift Worksheet 2 In this set of exercises, you'll use Swift to learn about variables. Remember to turn on the *Assistant Editor* before you start. */ /*: ## Part 1B: Numbers This is a demonstration of number variables */ println("Part 1B: Numbers") println("--------------------------------") println("") //: Read through this code. var a : Int = 5 var b : Int = 6 var c : Int = a * b // * is times println("a is \(a), b is \(b), and a times b is \(c)") println("") var d : Double = 5.0 var e : Double = 2.4 var f : Double = d / e // / is divide println("d is \(d), e is \(e), and d divided by e is \(f)") println("") //: Your turn! Can you edit the variables **result1** and **result2** so that the sentence is correct? //: **Hint for result1**: squaring is the same as multiplying something by itself. var var1 : Int = 5 var result1 : Int = var1 + var1 // THIS IS WRONG! Please fix it. println("I know that the square of \(var1) is \(result1)!") println("") //: **Hint for result2**: * is multiply, / is divide. var var2 : Double = 4.0 var var3 : Double = 5.0 var result2 = var2 * var3 // THIS IS WRONG! Please fix it. println("My maths skills say that \(var2) divided by \(var3) is equal to \(result2)!")
10cdd7dfd0127150dcc011fe71666908
27.409091
103
0.6296
false
false
false
false
googlemaps/last-mile-fleet-solution-samples
refs/heads/main
ios_driverapp_samples/LMFSDriverSampleApp/Services/NetworkServiceManager.swift
apache-2.0
1
/* * Copyright 2022 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import Combine import Foundation /// This protocol defines an interface for obtaining publishers for network data operations. protocol NetworkManagerSession { /// The type of the objects that the publisher(for:) method returns. This is aligned with /// URLSession.DataTaskPublisher since that's a common production implementation. typealias Publisher = AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure> /// Returns an publisher for the given URLRequest. func publisher(for: URLRequest) -> Publisher } /// The production implementation of NetworkManagerSession is created by extending URLSession to /// implement the protocol. extension URLSession: NetworkManagerSession { func publisher(for request: URLRequest) -> NetworkManagerSession.Publisher { return self.dataTaskPublisher(for: request).eraseToAnyPublisher() } } /// The class that manages communication with the backend. class NetworkServiceManager: ObservableObject { /// Pending manifest get requests. private var pendingManifestFetches = InMemoryRequestTracker<String>() /// The identifier for a task update request is the final state of the task after the update. private struct TaskUpdateIdentifier: Hashable { let taskId: String let outcome: ModelData.Task.Outcome } /// Pending task update requests. private var pendingTaskUpdates = InMemoryRequestTracker<TaskUpdateIdentifier>() /// The identifier for a stop update request is the final state of the stop after the update. private struct StopUpdateIdentifier: Hashable { let newState: ModelData.StopState? let stopIds: [String] } /// Pending stop update requests. /// /// We limit the number of outstanding stop requests to one, because subsequent stop requests /// should always incorporate the result of preceding requests: Stop states can only go in a /// certain order, and the remaining stop IDs list should only ever get shorter. By only keeping /// a single outstanding stop update, we don't have to worry about stop updates being applied /// out-of-order on the backend. private var pendingStopUpdates = InMemoryRequestTracker<StopUpdateIdentifier>(requestLimit: 1) /// The properties below are published for the sake of diagnostic/debugging views. /// The error, if any, from the most recent attempt to update tasks. @Published var taskUpdateLatestError: Error? @Published var taskUpdatesCompleted = 0 @Published var taskUpdatesFailed = 0 /// A status string for the most recent attempt to fetch a manifest. @Published var manifestFetchStatus = "Uninitialized" /// A status string for the most recent attempt to update tasks. @Published var taskUpdateStatus = "Uninitialized" /// A status string for the most recent attempt to update stops. @Published var stopUpdateStatus = "None" /// Sends a request to update the outcome of the given task. /// - Parameter task: The task whose outcome should be updated. /// - Parameter updateCompletion: A block which will be invoked when the update completes or fails. public func updateTask(task: ModelData.Task, updateCompletion: os_block_t? = nil) { let taskId = task.taskInfo.taskId let outcomeValue: String switch task.outcome { case .pending: return case .completed: outcomeValue = "SUCCEEDED" case .couldNotComplete: outcomeValue = "FAILED" } do { var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/task/\(taskId)" var request = URLRequest(url: components.url!) request.httpMethod = "POST" let requestBody = ["task_outcome": outcomeValue] request.httpBody = try JSONEncoder().encode(requestBody) let taskUpdateIdentifier = TaskUpdateIdentifier(taskId: taskId, outcome: task.outcome) let taskUpdateCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .finished: self.taskUpdateLatestError = nil case .failure(let error): self.taskUpdateLatestError = error self.taskUpdatesFailed += 1 } self.taskUpdatesCompleted += 1 self.pendingTaskUpdates.completed(identifier: taskUpdateIdentifier) updateCompletion?(); }, receiveValue: { _ in }) self.pendingTaskUpdates.started( identifier: taskUpdateIdentifier, cancellable: taskUpdateCancellable) } catch { taskUpdateLatestError = error let errorDesc = "Error encoding json: \(error)" self.taskUpdateStatus = errorDesc updateCompletion?(); } } /// Attempts to fetch a new manifest from the backend. /// /// - Parameters: /// - clientId: This client's persistent ID string. /// - vehicleId: Specifies the ID of the vehicle to fetch. If nil, the next available vehicle /// will be fetched. /// - completion: This will be called exactly once with the new manifest or nil. public func fetchManifest( clientId: String, vehicleId: String?, fetchCompletion: @escaping (Manifest?) -> Void ) { manifestFetchStatus = "waiting for response" var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/manifest/\(vehicleId ?? "")" var request = URLRequest(url: components.url!) request.httpMethod = "POST" let requestBody = ["client_id": clientId] do { request.httpBody = try JSONEncoder().encode(requestBody) } catch { self.manifestFetchStatus = "Error encoding json: \(error)" fetchCompletion(nil) } let manifestFetchCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .failure(let error): self.manifestFetchStatus = "Error: \(String(describing: error))" fetchCompletion(nil) case .finished: self.manifestFetchStatus = "Success" } self.pendingManifestFetches.completed(identifier: clientId) }, receiveValue: { urlResponse in do { if let httpResponse = urlResponse.response as? HTTPURLResponse { if httpResponse.statusCode != 200 { let responseCodeString = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode) let dataString = String(decoding: urlResponse.data, as: UTF8.self) self.manifestFetchStatus = "Status \(responseCodeString) Response: \(dataString)" fetchCompletion(nil) return } } let newManifest = try Manifest.loadFrom(data: urlResponse.data) self.manifestFetchStatus = "Success" fetchCompletion(newManifest) } catch { let dataString = String(decoding: urlResponse.data, as: UTF8.self) let errorDesc = "Error parsing output: \(error) data: \(dataString)" self.manifestFetchStatus = errorDesc fetchCompletion(nil) } } ) self.pendingManifestFetches.started( identifier: clientId, cancellable: manifestFetchCancellable) } /// Sends a request to update the current stop's state and/or the list of remaining stops. /// - Parameters: /// - vehicleId: The vehicle ID for the currently loaded manifest. /// - newStopState: The new state of the current stop. /// - stops: The new list of remaining stops in this manifest. public func updateStops( vehicleId: String, newStopState: ModelData.StopState? = nil, stops: [ModelData.Stop], updateCompletion: os_block_t? = nil ) { let newStopIds = stops.filter { $0.taskStatus == .pending }.map { $0.stopInfo.id } let stopUpdateIdentifier = StopUpdateIdentifier(newState: newStopState, stopIds: newStopIds) var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/manifest/\(vehicleId)" var request = URLRequest(url: components.url!) request.httpMethod = "POST" var requestBody: [String: Any] = [:] if let newStopStateValue = newStopState { requestBody["current_stop_state"] = newStopStateValue.rawValue } requestBody["remaining_stop_id_list"] = newStopIds do { request.httpBody = try JSONSerialization.data( withJSONObject: requestBody, options: JSONSerialization.WritingOptions() ) as Data } catch { self.stopUpdateStatus = "Error encoding json: \(error)" } self.stopUpdateStatus = "Pending" let stopUpdateCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .failure(let error): self.stopUpdateStatus = "Error: \(String(describing: error))" case .finished: self.stopUpdateStatus = "Success" } self.pendingStopUpdates.completed(identifier: stopUpdateIdentifier) updateCompletion?() }, receiveValue: { _ in }) self.pendingStopUpdates.started( identifier: stopUpdateIdentifier, cancellable: stopUpdateCancellable) } private var session: NetworkManagerSession /// Creates a new NetworkServiceManager. /// - Parameter session: The NetworkManagerSession to use for HTTP requests. init(session: NetworkManagerSession = URLSession.shared) { self.session = session // This can't be done in the property initialization because self must be available. pendingManifestFetches.errorHandler = self.manifestTrackingError pendingTaskUpdates.errorHandler = self.taskUpdateTrackingError pendingStopUpdates.errorHandler = self.stopUpdateTrackingError } /// The base URL for the backend from defaults. static func backendBaseURL() -> URL { // The backend URL may be updated while the app is running, so always re-read from defaults. return URL(string: ApplicationDefaults.backendBaseURLString.value)! } private func manifestTrackingError(error: RequestTrackingError) { // The tracker calls back on an arbitrary queue, so dispatch to main queue before updating UI. DispatchQueue.main.async { self.manifestFetchStatus = String(describing: error) } } private func taskUpdateTrackingError(error: RequestTrackingError) { DispatchQueue.main.async { self.taskUpdateStatus = String(describing: error) } } private func stopUpdateTrackingError(error: RequestTrackingError) { DispatchQueue.main.async { self.stopUpdateStatus = String(describing: error) } } }
b602966ddf000fc3519aa8f77b373bcf
38.898305
101
0.682753
false
false
false
false
ZB0106/MCSXY
refs/heads/master
MCSXY/MCSXY/Root/MCAPPRoot.swift
mit
1
// // MCAPPRoot.swift // MCSXY // // Created by 瞄财网 on 2017/6/16. // Copyright © 2017年 瞄财网. All rights reserved. // import UIKit import Foundation class MCAPPRoot: NSObject { public class func setRootViewController(window:UIWindow) -> Void{ UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) let locaVersion :String? = RHUserDefaults.objectForKey(key: LocalVersion) as? String let appVersion :String = RHUserDefaults .currentAppVersion()! UITableView .appearance() let isInstall:Bool = appVersion == locaVersion sleep(UInt32(1.5)) let tab : MCTabBarController = MCTabBarController() let nav : MCNavigationController = MCNavigationController.init(rootViewController:tab) if !isInstall { window.rootViewController = MCGuideController.init(images: ["guidePage1", "guidePage2", "guidePage3"], enter: { RHUserDefaults .setObject(value: appVersion, key: LocalVersion) window.rootViewController = nav }) UIApplication.shared.isStatusBarHidden = true } else { window.rootViewController = nav } window.makeKeyAndVisible() } }
87d900099f9c002ea93dcfc0964a25c2
30.682927
124
0.639723
false
false
false
false
robertzhang/Enterprise-Phone
refs/heads/master
EP/LoginViewController.swift
mit
1
// // LoginViewController.swift // EP // // Created by robertzhang on 27/9/15. // Copyright (c) 2015年 [email protected]. All rights reserved. // import UIKit import SwiftyJSON class LoginViewController: UIViewController , UITextFieldDelegate{ @IBOutlet weak var userTextField: ElasticTextField! @IBOutlet weak var passwordTextField: ElasticTextField! @IBOutlet weak var goto: UIButton! override func viewDidLoad() { super.viewDidLoad() // 给viewcontroller的view添加一个点击事件,用于关闭键盘 self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("backgroundTap"))) // 确定按钮的颜色 goto.backgroundColor = UIColor(red: 30.0/255.0, green: 144.0/255.0, blue: 205.0/255.0, alpha: 0.7) // userTextField.keyboardType = UIKeyboardType.Default userTextField.returnKeyType = UIReturnKeyType.Next userTextField.borderStyle = UITextBorderStyle.RoundedRect userTextField.delegate = self // passwordTextField.keyboardType = UIKeyboardType.Default passwordTextField.returnKeyType = UIReturnKeyType.Done passwordTextField.borderStyle = UITextBorderStyle.RoundedRect passwordTextField.delegate = self goto.addTarget(self, action: "pressed", forControlEvents: UIControlEvents.TouchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #mark textField delegate begin ----- func textFieldShouldReturn(textField: UITextField) -> Bool{ UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) let rect = CGRectMake(0.0,20.0,self.view.frame.size.width,self.view.frame.size.height) self.view.frame = rect UIView.commitAnimations() textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { var frame = textField.frame let offset = CGFloat(-35.0) UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) let width = self.view.frame.size.width let height = self.view.frame.size.height let rect = CGRectMake(0.0, offset, width, height) self.view.frame = rect NSLog("---\(self.view.frame.origin.y)---\(self.view.frame.size.height)--\(offset)") UIView.commitAnimations() } func textFieldDidEndEditing(textField: UITextField) { self.view.frame = CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height) } // #mark textField delegate end ----- func backgroundTap() { if self.view.frame.origin.y < 0 { UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) var rect = CGRectMake(0.0,20.0,self.view.frame.size.width,self.view.frame.size.height) self.view.frame = rect UIView.commitAnimations() } userTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } var alert:UIAlertView? func pressed() { alert = UIAlertView(title: "正在登陆", message: "正在登陆请稍候...", delegate: nil, cancelButtonTitle: nil) let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activity.center = CGPointMake(alert!.bounds.size.width / 2.0, alert!.bounds.size.height-40.0) activity.startAnimating() alert!.addSubview(activity) alert!.show() self.view.addSubview(activity) guard let jsonData = NSData.dataFromJSONFile("enterprise") else { return } let jsonObject = JSON(data: jsonData) if ContactsCompany.sharedInstance.parseJSON(jsonObject.object as! Dictionary) {//解析json数据 FMDBHelper.shareInstance().deleteAllDBData() FMDBHelper.shareInstance().insert(ContactsCompany.sharedInstance._organization!, groups: ContactsCompany.sharedInstance._groups, users: ContactsCompany.sharedInstance._users) } else { FMDBHelper.shareInstance().query() } //计时器模仿登陆效果 NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "closeAlert", userInfo: nil, repeats: false) } func closeAlert() { alert!.dismissWithClickedButtonIndex(0, animated: false) //关闭alert view self.performSegueWithIdentifier("second", sender: self) } }
d75941d615c0f452c18685554bc750f7
36.48
186
0.661686
false
false
false
false
nearfri/Strix
refs/heads/main
Sources/StrixParsers/CSVParser.swift
mit
1
import Foundation import Strix public typealias CSV = [[String]] public struct CSVParser { private let parser: Parser<CSV> public init() { let ws = Parser.many(.whitespace) parser = ws *> Parser.csv <* ws <* .endOfStream } public func parse(_ csvString: String) throws -> CSV { return try parser.run(csvString) } public func callAsFunction(_ csvString: String) throws -> CSV { return try parse(csvString) } } extension Parser where T == CSV { public static var csv: Parser<CSV> { CSVParserGenerator().csv } } private struct CSVParserGenerator { var csv: Parser<CSV> { Parser.many(record, separatedBy: .newline).map({ fixCSV($0) }) } private var record: Parser<[String]> { .many(field, separatedBy: .character(",")) } private var field: Parser<String> { escapedField <|> nonEscapedField } private var escapedField: Parser<String> { doubleQuote *> escapedText <* doubleQuote } private var escapedText: Parser<String> { return Parser.many((.none(of: "\"") <|> twoDoubleQuote)).map({ String($0) }) } private let doubleQuote: Parser<Character> = .character("\"") private let twoDoubleQuote: Parser<Character> = Parser.string("\"\"") *> .just("\"") private var nonEscapedField: Parser<String> { .skipped(by: .many(nonSeparator)) } private let nonSeparator: Parser<Character> = .satisfy({ $0 != "," && !$0.isNewline }, label: "non-separator") } private func fixCSV(_ csv: CSV) -> CSV { var csv = csv if let lastValidRecordIndex = csv.lastIndex(where: { $0 != [""] }) { let invalidRecordIndex = lastValidRecordIndex + 1 csv.removeSubrange(invalidRecordIndex...) } else { csv.removeAll() } return csv }
c78d71fc1935fb841c104ea8b26f0b79
31.614035
91
0.60893
false
false
false
false
cornerstonecollege/401
refs/heads/master
olderFiles/boyoung_chae/Swift/Introduction of Swift.playground/Contents.swift
gpl-3.0
1
//: Playground - noun: a place where people can play import Foundation var str = "Hello, playground" str = "Hi 2" // It is ok to change the value! str = str.appending("a") print(str) let j:Int j = 1 // J = 2 // It si not going to work because j is a constant. print(j); var studentName:String? studentName = nil studentName = "Chris" studentName = "Bo Young" print(studentName) // Wrapped value print(studentName!) // Unwrapped value. I know that the value is not nil. print(studentName?.appending("a")) // Unwrapped value if studentName is not nil. print(studentName!.appending("a")) // Unwrapped value (we know that it is not nil.) // Functions work just like Objective-C. //[Object print:@"aaa" second:@"bbb" third:@ccc"]; print("Hey", "Hi", "Hello", separator: " ", terminator: ".\n") /* Wrong - It's not Bollean. It's Ingeger. if 1 { } */ // Right - The if needs a boolean value unlike C and Objective-C. if 1 == 1 { } if str == "Luiz" { print("str equals to Luiz.") } else { print("str is not equals to Luiz.") } let alwaysTrue = true while alwaysTrue { // Infinite loop print("hi") break // It will excute the loop only once. } let checkCondition = 1 > 2 // boolean value repeat { // run at least once even though the condition is false. print("It will run only once") } while (checkCondition) // for (int i = 1 ; i <=10 ; i++) for i in 1...10 { // 1,2,3,4,5,6,7,8,9,10 print(i) } // for (int i = 1 ; i < 10 ; i++) for i in 1..<10 { // 1,2,3,4,5,6,7,8,9 print(i) } var string = String() // new regular string var arr = [String]() // new array of strings //var arr:[String] = [String]() arr.append("a") // addObject arr.append("b") print(arr[1]) // print letter "b" for string in arr { print("The string is \(string) \(1 + 2)") } let arrStrings = ["a", "b", "123", "567"] print(arrStrings) for (index, value) in arrStrings.enumerated() { print("The index: \(index) contains the value: \(value)"); } var x = 1 true.description // true is object. 1.description // 1 is object. // ==> Everything is an object. 1.description == "2" // REPL - Rean, Evaluate, Print and Loop var dictionary = [ "object1" : "table", "object2" : "fridge" ] print(dictionary["object1"]) print(dictionary["object1"]!) var dictionaryElements = [String:Int]() dictionaryElements.updateValue(1, forKey: "DS") var dictionaryElements2:[String:Int] = ["DS1":1, "DS2":2, "DS3":3] //dictionaryElements2.removeValue(forKey: "DS3") for (key, value) in dictionaryElements2 { print("The key is \(key) and the value is \(value)") } dictionaryElements2["DS4"] = 4 dictionaryElements2 print("\n") print("=== Exercise1: Array ===") let array1 = ["String1", "String2", "String3"] var array2 = array1 //array2.append("String1") //array2.append("String2") //array2.append("String3") array2.append("String4") array2.append("String5") print("The first value is \(array2[0])."); print("The fifth value is \(array2[4])."); print("\n") print("=== Exercise2: Dictionary ===") var storeDictionary = [String:String]() storeDictionary.updateValue("table", forKey: "object1") storeDictionary.updateValue("fridge", forKey: "object2") storeDictionary.updateValue("WallMart", forKey: "storeName") storeDictionary.updateValue("123 Fake St", forKey: "address") print("The store \(storeDictionary["storeName"]!) in \(storeDictionary["address"]!) is selling \(storeDictionary["object1"]!) and \(storeDictionary["object2"]!).") print("\n") var str1 = "1234" let intFromStr = Int(str1) print(intFromStr) print(intFromStr!)
10130486ca741064dcc760b7932db7cf
22.134615
163
0.650596
false
false
false
false
MrAlek/Swiftalytics
refs/heads/master
Source/Swiftalytics.swift
mit
1
// // Swiftalytics.swift // // Created by Alek Åström on 2015-02-14. // Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek) // // 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 public enum TrackingNameType { case navigationTitle } private let storage = SWAClassBlockStorage() public func setTrackingName<T: UIViewController>(for viewController: T.Type, name: @autoclosure () -> String) { let n = name() setTrackingName(for: viewController) {_ in n} } public func setTrackingName<T: UIViewController>(for viewController: T.Type, trackingType: TrackingNameType) { switch trackingType { case .navigationTitle: setTrackingName(for: viewController) { vc in if let title = vc.navigationItem.title { return title } let className = String(describing: type(of: vc)) print("Swiftalytics: View Controller \(className) missing navigation item title") return className } } } public func setTrackingName<T: UIViewController>(for viewController: T.Type, nameFunction: @escaping ((T) -> String)) { let block: MapBlock = { vc in nameFunction(vc as! T) } storage.setBlock(block, forClass: T.value(forKey: "self")!) } public func setTrackingName<T: UIViewController>(for curriedNameFunction: @escaping (T) -> () -> String) { let block: MapBlock = { vc in curriedNameFunction(vc as! T)() } storage.setBlock(block, forClass:T.value(forKey: "self")!) } public func trackingName<T: UIViewController>(for viewController: T) -> String? { return storage.block(forClass: viewController.value(forKey: "class")!)?(viewController) as! String? } public func clearTrackingNames() { storage.removeAllBlocks() } public func removeTrackingForViewController<T: UIViewController>(_: T.Type) { storage.removeBlock(forClass: T.value(forKey: "self")!) }
d401be0ecb99f0e4919af14895b1b75c
39.054795
119
0.716826
false
false
false
false
akane/Gaikan
refs/heads/master
Gaikan/Style/StyleRule.swift
mit
1
// // This file is part of Gaikan // // Created by JC on 30/08/15. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation /** * Defines design properties with their values. */ public struct StyleRule : ExpressibleByDictionaryLiteral { public typealias Key = Property public typealias Value = Any? var attributes : Dictionary<Key, Value> public init(attributes: [Key:Value]) { self.attributes = attributes } public init(dictionaryLiteral elements: (Key, Value)...) { var attributes = Dictionary<Key, Value>() for (attributeName, attributeValue) in elements { attributes[attributeName] = attributeValue } self.attributes = attributes } public init(_ styleBlock: (_ style: inout StyleRule) -> ()) { self.init(attributes: [:]) styleBlock(&self) } public func extends(_ styles: StyleRule?...) -> StyleRule { var composedAttributes: [Key:Value] = [:] for style in styles { if let styleAttributes = style?.attributes { composedAttributes.gaikan_merge(styleAttributes) } } return StyleRule(attributes: composedAttributes.gaikan_merge(self.attributes)) } subscript(keyname: Property) -> Value { get { return self.attributes[keyname] != nil ? self.attributes[keyname]! : nil } } } extension StyleRule { public var textAttributes: [String:AnyObject] { let attributes: [String:AnyObject?] = [ NSForegroundColorAttributeName: self.color, NSFontAttributeName: self.font, NSShadowAttributeName: self.textShadow ] return attributes.trimmed() } }
8305852f5fa3bac359c7c439a5cde9b4
26
88
0.636263
false
false
false
false
ppamorim/CrazyAutomaticDimension
refs/heads/master
UITableView-AutomaticDimension/ViewController.swift
apache-2.0
1
/* * Copyright (C) 2016 Pedro Paulo de Amorim * * 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 import PureLayout class ViewController: UIViewController { var didUpdateViews = false var secondState = false var alternativeType = false var comments : NSMutableArray? = NSMutableArray() var videoPinEdgeLeftConstraint : NSLayoutConstraint? var videoPinEdgeRightConstraint : NSLayoutConstraint? var videoPinEdgeTopConstraint : NSLayoutConstraint? var videoPinEdgeBottomConstraint : NSLayoutConstraint? var videoPaddingConstraint : NSLayoutConstraint? let container : UIView = { let container = UIView.newAutoLayoutView() return container }() let commentsTableView : UITableView = { let commentsTableView = UITableView.newAutoLayoutView() commentsTableView.registerClass(ChatViewCell.self, forCellReuseIdentifier: "ChatViewCell") commentsTableView.separatorStyle = .None commentsTableView.backgroundColor = UIColor.grayColor() return commentsTableView }() deinit { self.commentsTableView.dataSource = nil self.commentsTableView.delegate = nil } override func loadView() { super.loadView() configTableview() container.addSubview(commentsTableView) self.view.addSubview(container) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if !didUpdateViews { commentsTableView.autoPinEdgesToSuperviewEdges() didUpdateViews = true } videoPinEdgeLeftConstraint?.autoRemove() videoPinEdgeRightConstraint?.autoRemove() videoPinEdgeTopConstraint?.autoRemove() videoPinEdgeBottomConstraint?.autoRemove() if(!secondState) { videoPinEdgeLeftConstraint = container.autoPinEdgeToSuperviewEdge(.Left) videoPinEdgeRightConstraint = container.autoPinEdgeToSuperviewEdge(.Right) videoPinEdgeTopConstraint = container.autoMatchDimension( .Height, toDimension: .Width, ofView: self.view, withMultiplier: 0.57) videoPinEdgeBottomConstraint = container.autoPinEdgeToSuperviewEdge(.Top, withInset: 0.0) } else { videoPinEdgeLeftConstraint = container.autoMatchDimension( .Width, toDimension: .Width, ofView: self.view, withMultiplier: 0.45) videoPinEdgeRightConstraint = container.autoPinEdgeToSuperviewEdge(.Right, withInset: 4.0) videoPinEdgeTopConstraint = container.autoMatchDimension( .Height, toDimension: .Width, ofView: container, withMultiplier: 0.57) videoPinEdgeBottomConstraint = container.autoPinEdge(.Bottom, toEdge: .Bottom, ofView: self.view, withOffset: -4.0) } super.updateViewConstraints() } override func viewDidLoad() { super.viewDidLoad() infiniteChat() toggleContainer() } func configTableview() { commentsTableView.dataSource = self commentsTableView.delegate = self } func infiniteChat() { let seconds = 4.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.addItem(self.alternativeType ? Comment(userName: "Paulo", comment: "Teste legal") : Comment(userName: "Paulo nervoso", comment: "Texto longo pq eu quero testar essa bagaça que não funciona com AutomaticDimension direito")) self.alternativeType = !self.alternativeType self.infiniteChat() }) } func addItem(comment: Comment) { self.commentsTableView.beginUpdates() if self.comments!.count == 5 { self.commentsTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow : 4, inSection: 0)], withRowAnimation: .Right) comments?.removeObjectAtIndex(4) } self.comments?.insertObject(comment, atIndex: 0) self.commentsTableView.insertRowsAtIndexPaths([NSIndexPath(forRow : 0, inSection: 0)], withRowAnimation: .Right) self.commentsTableView.endUpdates() } func toggleContainer() { if secondState { collapse() } else { expand() } } func expand() { self.secondState = true view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(2, delay: 5.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (completion) in self.toggleContainer() }) } func collapse() { self.secondState = false view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(2, delay: 5.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (completion) in self.toggleContainer() }) } } extension ViewController : UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if self.comments != nil { (cell as! ChatViewCell).load((self.comments?.objectAtIndex(indexPath.row))! as? Comment) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } } extension ViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.comments?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("ChatViewCell", forIndexPath: indexPath) as! ChatViewCell } }
7c7efa8819bece980eb6a4d6e950501a
31.581281
233
0.721911
false
false
false
false
mmick66/GradientViewiOS
refs/heads/master
KDGradientView/GradientView.swift
mit
1
// // GradientView.swift // GradientView // // Created by Michael Michailidis on 23/07/2015. // Copyright © 2015 karmadust. All rights reserved. // import UIKit class GradientView: UIView { var lastElementIndex: Int = 0 var colors: Array<UIColor> = [] { didSet { lastElementIndex = colors.count - 1 } } var index: Int = 0 lazy var displayLink : CADisplayLink = { let displayLink : CADisplayLink = CADisplayLink(target: self, selector: "screenUpdated:") displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true return displayLink }() func animateToNextGradient() { index = (index + 1) % colors.count factor = 0.0 self.displayLink.paused = false } var factor: CGFloat = 1.0 func screenUpdated(displayLink : CADisplayLink) { self.factor += CGFloat(displayLink.duration) if(self.factor > 1.0) { self.displayLink.paused = true } self.setNeedsDisplay() } override func drawRect(rect: CGRect) { if colors.count < 2 { return; } let context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); let c1 = colors[index == 0 ? lastElementIndex : index - 1] // => previous color from index let c2 = colors[index] // => current color let c3 = colors[index == lastElementIndex ? 0 : index + 1] // => next color var c1Comp = CGColorGetComponents(c1.CGColor) var c2Comp = CGColorGetComponents(c2.CGColor) var c3Comp = CGColorGetComponents(c3.CGColor) var colorComponents = [ c1Comp[0] * (1 - factor) + c2Comp[0] * factor, c1Comp[1] * (1 - factor) + c2Comp[1] * factor, c1Comp[2] * (1 - factor) + c2Comp[2] * factor, c1Comp[3] * (1 - factor) + c2Comp[3] * factor, c2Comp[0] * (1 - factor) + c3Comp[0] * factor, c2Comp[1] * (1 - factor) + c3Comp[1] * factor, c2Comp[2] * (1 - factor) + c3Comp[2] * factor, c2Comp[3] * (1 - factor) + c3Comp[3] * factor ] let gradient = CGGradientCreateWithColorComponents( CGColorSpaceCreateDeviceRGB(), &colorComponents, [0.0, 1.0], 2 ) CGContextDrawLinearGradient( context, gradient, CGPoint(x: 0.0, y: 0.0), CGPoint(x: rect.size.width, y: rect.size.height), 0 ) CGContextRestoreGState(context); } }
580ca38aa92fc6064053baaf80d04584
24.405172
101
0.503902
false
false
false
false
doncl/shortness-of-pants
refs/heads/master
ModalPopup/BaseModalPopup.swift
mit
1
// // BaseModalPopup.swift // BaseModalPopup // // Created by Don Clore on 5/21/18. // Copyright © 2018 Beer Barrel Poker Studios. All rights reserved. // import UIKit enum PointerDirection { case up case down } enum AvatarMode { case leftTopLargeProtruding case leftTopMediumInterior } fileprivate struct AvatarLayoutInfo { var width : CGFloat var offset : CGFloat var constraintsMaker : (UIImageView, UIView, CGFloat, CGFloat) -> () func layout(avatar : UIImageView, popup : UIView) { constraintsMaker(avatar, popup, width, offset) } } class BaseModalPopup: UIViewController { var loaded : Bool = false var presenting : Bool = true static let pointerHeight : CGFloat = 16.0 static let pointerBaseWidth : CGFloat = 24.0 static let horzFudge : CGFloat = 15.0 var origin : CGPoint weak var referenceView : UIView? private var width : CGFloat private var height : CGFloat let popupView : UIView = UIView() let avatar : UIImageView = UIImageView() let pointer : CAShapeLayer = CAShapeLayer() var avatarMode : AvatarMode? var avatarUserId : String? var avatarImage : UIImage? var avatarOffset : CGFloat { var offset : CGFloat = 0 if let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { offset = layoutInfo.offset } return offset } private let avatarModeSizeMap : [AvatarMode : AvatarLayoutInfo] = [ .leftTopLargeProtruding : AvatarLayoutInfo(width: 48.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(-offset) } }), .leftTopMediumInterior : AvatarLayoutInfo(width: 32.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(offset) } }) ] required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(origin : CGPoint, referenceView : UIView, size: CGSize, avatarUserId: String? = nil, avatarImage : UIImage?, avatarMode : AvatarMode?) { self.origin = origin self.width = size.width self.height = size.height self.referenceView = referenceView super.init(nibName: nil, bundle: nil) self.avatarMode = avatarMode self.avatarUserId = avatarUserId if let image = avatarImage { self.avatarImage = image.deepCopy() } } override func viewDidLoad() { if loaded { return } loaded = true super.viewDidLoad() if let ref = referenceView { origin = view.convert(origin, from: ref) } view.addSubview(popupView) view.backgroundColor = .clear popupView.backgroundColor = .white popupView.layer.shadowOffset = CGSize(width: 2.0, height: 3.0) popupView.layer.shadowRadius = 5.0 popupView.layer.shadowOpacity = 0.5 popupView.addSubview(avatar) popupView.clipsToBounds = false popupView.layer.masksToBounds = false if let userId = avatarUserId, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { if let image = avatarImage { avatar.image = image.deepCopy() avatar.createRoundedImageView(diameter: layoutInfo.width, borderColor: UIColor.clear) } else { avatar.setAvatarImage(fromId: userId, avatarVersion: nil, diameter: layoutInfo.width, bustCache: false, placeHolderImageURL: nil, useImageProxy: true, completion: nil) } popupView.bringSubview(toFront: avatar) } view.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(BaseModalPopup.tap)) view.addGestureRecognizer(tap) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let tuple = getPopupFrameAndPointerDirection(size: view.frame.size) let popupFrame = tuple.0 let direction = tuple.1 let pointerPath = makePointerPath(direction: direction, popupFrame: popupFrame) pointer.path = pointerPath.cgPath pointer.fillColor = UIColor.white.cgColor pointer.lineWidth = 0.5 pointer.masksToBounds = false popupView.layer.addSublayer(pointer) remakeConstraints(popupFrame) let bounds = UIScreen.main.bounds let width = view.frame.width + avatarOffset if bounds.width < width && width > 0 { let ratio = (bounds.width / width) * 0.9 let xform = CGAffineTransform(scaleX: ratio, y: ratio) popupView.transform = xform } else { popupView.transform = .identity } } private func getPopupFrameAndPointerDirection(size: CGSize) -> (CGRect, PointerDirection) { let y : CGFloat let direction : PointerDirection if origin.y > size.height / 2 { y = origin.y - (height + BaseModalPopup.pointerHeight) direction = .down } else { y = origin.y + BaseModalPopup.pointerHeight direction = .up } var rc : CGRect = CGRect(x: 30.0, y: y, width: width, height: height) let rightmost = rc.origin.x + rc.width let center = rc.center if origin.x > rightmost { let offset = origin.x - center.x rc = rc.offsetBy(dx: offset, dy: 0) } else if origin.x < rc.origin.x { let offset = center.x - origin.x rc = rc.offsetBy(dx: -offset, dy: 0) } let bounds = UIScreen.main.bounds let popupWidth = rc.width + avatarOffset if bounds.width <= popupWidth { rc = CGRect(x: 0, y: rc.origin.y, width: rc.width, height: rc.height) } return (rc, direction) } fileprivate func remakeConstraints(_ popupFrame: CGRect) { popupView.snp.remakeConstraints { make in make.leading.equalTo(view).offset(popupFrame.origin.x) make.top.equalTo(view).offset(popupFrame.origin.y) make.width.equalTo(popupFrame.width) make.height.equalTo(popupFrame.height) } if let _ = avatar.image, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { layoutInfo.layout(avatar: avatar, popup: popupView) } } private func makePointerPath(direction: PointerDirection, popupFrame : CGRect) -> UIBezierPath { let path = UIBezierPath() path.lineJoinStyle = CGLineJoin.bevel // previous code is supposed to assure that the popupFrame is not outside the origin. assert(popupFrame.origin.x < origin.x && popupFrame.origin.x + popupFrame.width > origin.x) let adjustedX = origin.x - popupFrame.origin.x if direction == .down { let adjustedApex = CGPoint(x: adjustedX, y: popupFrame.height + BaseModalPopup.pointerHeight - 1) path.move(to: adjustedApex) // down is up. let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } else { let adjustedApex = CGPoint(x: adjustedX, y: -BaseModalPopup.pointerHeight + 1) path.move(to: adjustedApex) let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } return path } @objc func tap() { dismiss(animated: true, completion: nil) } } //MARK: - rotation extension BaseModalPopup { override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } }
479b890143d8cf5651458d1f0f90e007
31.198556
103
0.641664
false
false
false
false
zirinisp/SlackKit
refs/heads/master
SlackKit/Sources/Client+EventHandling.swift
mit
1
// // Client+EventHandling.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation internal extension Client { //MARK: - Pong func pong(_ event: Event) { pong = event.replyTo } //MARK: - Messages func messageSent(_ event: Event) { guard let reply = event.replyTo, let message = sentMessages[NSNumber(value: reply).stringValue], let channel = message.channel, let ts = message.ts else { return } message.ts = event.ts message.text = event.text channels[channel]?.messages[ts] = message messageEventsDelegate?.sent(message, client: self) } func messageReceived(_ event: Event) { guard let channel = event.channel, let message = event.message, let id = channel.id, let ts = message.ts else { return } channels[id]?.messages[ts] = message messageEventsDelegate?.received(message, client:self) } func messageChanged(_ event: Event) { guard let id = event.channel?.id, let nested = event.nestedMessage, let ts = nested.ts else { return } channels[id]?.messages[ts] = nested messageEventsDelegate?.changed(nested, client:self) } func messageDeleted(_ event: Event) { guard let id = event.channel?.id, let key = event.message?.deletedTs, let message = channels[id]?.messages[key] else { return } _ = channels[id]?.messages.removeValue(forKey: key) messageEventsDelegate?.deleted(message, client:self) } //MARK: - Channels func userTyping(_ event: Event) { guard let channel = event.channel, let channelID = channel.id, let user = event.user, let userID = user.id , channels.index(forKey: channelID) != nil && !channels[channelID]!.usersTyping.contains(userID) else { return } channels[channelID]?.usersTyping.append(userID) channelEventsDelegate?.userTypingIn(channel, user: user, client: self) let timeout = DispatchTime.now() + Double(Int64(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: timeout, execute: { if let index = self.channels[channelID]?.usersTyping.index(of: userID) { self.channels[channelID]?.usersTyping.remove(at: index) } }) } func channelMarked(_ event: Event) { guard let channel = event.channel, let id = channel.id, let timestamp = event.ts else { return } channels[id]?.lastRead = event.ts channelEventsDelegate?.marked(channel, timestamp: timestamp, client: self) } func channelCreated(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id] = channel channelEventsDelegate?.created(channel, client: self) } func channelDeleted(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels.removeValue(forKey: id) channelEventsDelegate?.deleted(channel, client: self) } func channelJoined(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id] = event.channel channelEventsDelegate?.joined(channel, client: self) } func channelLeft(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } if let userID = authenticatedUser?.id, let index = channels[id]?.members?.index(of: userID) { channels[id]?.members?.remove(at: index) } channelEventsDelegate?.left(channel, client: self) } func channelRenamed(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.name = channel.name channelEventsDelegate?.renamed(channel, client: self) } func channelArchived(_ event: Event, archived: Bool) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.isArchived = archived channelEventsDelegate?.archived(channel, client: self) } func channelHistoryChanged(_ event: Event) { guard let channel = event.channel else { return } channelEventsDelegate?.historyChanged(channel, client: self) } //MARK: - Do Not Disturb func doNotDisturbUpdated(_ event: Event) { guard let dndStatus = event.dndStatus else { return } authenticatedUser?.doNotDisturbStatus = dndStatus doNotDisturbEventsDelegate?.updated(dndStatus, client: self) } func doNotDisturbUserUpdated(_ event: Event) { guard let dndStatus = event.dndStatus, let user = event.user, let id = user.id else { return } users[id]?.doNotDisturbStatus = dndStatus doNotDisturbEventsDelegate?.userUpdated(dndStatus, user: user, client: self) } //MARK: - IM & Group Open/Close func open(_ event: Event, open: Bool) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.isOpen = open groupEventsDelegate?.opened(channel, client: self) } //MARK: - Files func processFile(_ event: Event) { guard let file = event.file, let id = file.id else { return } if let comment = file.initialComment, let commentID = comment.id { if files[id]?.comments[commentID] == nil { files[id]?.comments[commentID] = comment } } files[id] = file fileEventsDelegate?.processed(file, client: self) } func filePrivate(_ event: Event) { guard let file = event.file, let id = file.id else { return } files[id]?.isPublic = false fileEventsDelegate?.madePrivate(file, client: self) } func deleteFile(_ event: Event) { guard let file = event.file, let id = file.id else { return } if files[id] != nil { files.removeValue(forKey: id) } fileEventsDelegate?.deleted(file, client: self) } func fileCommentAdded(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } files[id]?.comments[commentID] = comment fileEventsDelegate?.commentAdded(file, comment: comment, client: self) } func fileCommentEdited(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } files[id]?.comments[commentID]?.comment = comment.comment fileEventsDelegate?.commentAdded(file, comment: comment, client: self) } func fileCommentDeleted(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } _ = files[id]?.comments.removeValue(forKey: commentID) fileEventsDelegate?.commentDeleted(file, comment: comment, client: self) } //MARK: - Pins func pinAdded(_ event: Event) { guard let id = event.channelID, let item = event.item else { return } channels[id]?.pinnedItems.append(item) pinEventsDelegate?.pinned(item, channel: channels[id], client: self) } func pinRemoved(_ event: Event) { guard let id = event.channelID, let item = event.item else { return } if let pins = channels[id]?.pinnedItems.filter({$0 != item}) { channels[id]?.pinnedItems = pins } pinEventsDelegate?.unpinned(item, channel: channels[id], client: self) } //MARK: - Stars func itemStarred(_ event: Event, star: Bool) { guard let item = event.item, let type = item.type else { return } switch type { case "message": starMessage(item, star: star) case "file": starFile(item, star: star) case "file_comment": starComment(item) default: break } starEventsDelegate?.starred(item, starred: star, self) } func starMessage(_ item: Item, star: Bool) { guard let message = item.message, let ts = message.ts, let channel = item.channel , channels[channel]?.messages[ts] != nil else { return } channels[channel]?.messages[ts]?.isStarred = star } func starFile(_ item: Item, star: Bool) { guard let file = item.file, let id = file.id else { return } files[id]?.isStarred = star if let stars = files[id]?.stars { if star == true { files[id]?.stars = stars + 1 } else { if stars > 0 { files[id]?.stars = stars - 1 } } } } func starComment(_ item: Item) { guard let file = item.file, let id = file.id, let comment = item.comment, let commentID = comment.id else { return } files[id]?.comments[commentID] = comment } //MARK: - Reactions func addedReaction(_ event: Event) { guard let item = event.item, let type = item.type, let reaction = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else { return } switch type { case "message": guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else { return } message.reactions.append(Reaction(name: reaction, user: userID)) case "file": guard let id = item.file?.id else { return } files[id]?.reactions.append(Reaction(name: reaction, user: userID)) case "file_comment": guard let id = item.file?.id, let commentID = item.fileCommentID else { return } files[id]?.comments[commentID]?.reactions.append(Reaction(name: reaction, user: userID)) default: break } reactionEventsDelegate?.added(reaction, item: item, itemUser: itemUser, client: self) } func removedReaction(_ event: Event) { guard let item = event.item, let type = item.type, let key = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else { return } switch type { case "message": guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else { return } message.reactions = message.reactions.filter({$0.name != key && $0.user != userID}) case "file": guard let itemFile = item.file, let id = itemFile.id else { return } files[id]?.reactions = files[id]!.reactions.filter({$0.name != key && $0.user != userID}) case "file_comment": guard let id = item.file?.id, let commentID = item.fileCommentID else { return } files[id]?.comments[commentID]?.reactions = files[id]!.comments[commentID]!.reactions.filter({$0.name != key && $0.user != userID}) default: break } reactionEventsDelegate?.removed(key, item: item, itemUser: itemUser, client: self) } //MARK: - Preferences func changePreference(_ event: Event) { guard let name = event.name else { return } authenticatedUser?.preferences?[name] = event.value slackEventsDelegate?.preferenceChanged(name, value: event.value, client: self) } //Mark: - User Change func userChange(_ event: Event) { guard let user = event.user, let id = user.id else { return } let preferences = users[id]?.preferences users[id] = user users[id]?.preferences = preferences slackEventsDelegate?.userChanged(user, client: self) } //MARK: - User Presence func presenceChange(_ event: Event) { guard let user = event.user, let id = user.id, let presence = event.presence else { return } users[id]?.presence = event.presence slackEventsDelegate?.presenceChanged(user, presence: presence, client: self) } //MARK: - Team func teamJoin(_ event: Event) { guard let user = event.user, let id = user.id else { return } users[id] = user teamEventsDelegate?.userJoined(user, client: self) } func teamPlanChange(_ event: Event) { guard let plan = event.plan else { return } team?.plan = plan teamEventsDelegate?.planChanged(plan, client: self) } func teamPreferenceChange(_ event: Event) { guard let name = event.name else { return } team?.prefs?[name] = event.value teamEventsDelegate?.preferencesChanged(name, value: event.value, client: self) } func teamNameChange(_ event: Event) { guard let name = event.name else { return } team?.name = name teamEventsDelegate?.nameChanged(name, client: self) } func teamDomainChange(_ event: Event) { guard let domain = event.domain else { return } team?.domain = domain teamEventsDelegate?.domainChanged(domain, client: self) } func emailDomainChange(_ event: Event) { guard let domain = event.emailDomain else { return } team?.emailDomain = domain teamEventsDelegate?.emailDomainChanged(domain, client: self) } func emojiChanged(_ event: Event) { teamEventsDelegate?.emojiChanged(self) } //MARK: - Bots func bot(_ event: Event) { guard let bot = event.bot, let id = bot.id else { return } bots[id] = bot slackEventsDelegate?.botEvent(bot, client: self) } //MARK: - Subteams func subteam(_ event: Event) { guard let subteam = event.subteam, let id = subteam.id else { return } userGroups[id] = subteam subteamEventsDelegate?.event(subteam, client: self) } func subteamAddedSelf(_ event: Event) { guard let subteamID = event.subteamID, let _ = authenticatedUser?.userGroups else { return } authenticatedUser?.userGroups![subteamID] = subteamID subteamEventsDelegate?.selfAdded(subteamID, client: self) } func subteamRemovedSelf(_ event: Event) { guard let subteamID = event.subteamID else { return } _ = authenticatedUser?.userGroups?.removeValue(forKey: subteamID) subteamEventsDelegate?.selfRemoved(subteamID, client: self) } //MARK: - Team Profiles func teamProfileChange(_ event: Event) { guard let profile = event.profile else { return } for user in users { for key in profile.fields.keys { users[user.0]?.profile?.customProfile?.fields[key]?.updateProfileField(profile.fields[key]) } } teamProfileEventsDelegate?.changed(profile, client: self) } func teamProfileDeleted(_ event: Event) { guard let profile = event.profile else { return } for user in users { if let id = profile.fields.first?.0 { users[user.0]?.profile?.customProfile?.fields[id] = nil } } teamProfileEventsDelegate?.deleted(profile, client: self) } func teamProfileReordered(_ event: Event) { guard let profile = event.profile else { return } for user in users { for key in profile.fields.keys { users[user.0]?.profile?.customProfile?.fields[key]?.ordering = profile.fields[key]?.ordering } } teamProfileEventsDelegate?.reordered(profile, client: self) } //MARK: - Authenticated User func manualPresenceChange(_ event: Event) { guard let presence = event.presence, let user = authenticatedUser else { return } authenticatedUser?.presence = presence slackEventsDelegate?.manualPresenceChanged(user, presence: presence, client: self) } }
3d6fc603d2a6cc54d3485dc3497d7d39
31.768683
162
0.575749
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Observability/Sources/ObservabilityKit/Performance/Trace.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import ToolKit struct Trace { private class DebugTrace { private enum State { struct Started { let traceId: TraceID let startTime: Date } struct Ended { let traceId: TraceID let startTime: Date let endTime: Date let timeInterval: TimeInterval } case started(Started) case ended(Ended) } private var state: State func stop() { guard case .started(let started) = state else { return } let traceId = started.traceId let startTime = started.startTime let endTime = Date() let timeInterval = endTime.timeIntervalSince(startTime) let endState = State.Ended( traceId: traceId, startTime: startTime, endTime: endTime, timeInterval: timeInterval ) state = .ended(endState) Self.printTrace(ended: endState) } convenience init(traceId: TraceID) { self.init( state: .started(.init(traceId: traceId, startTime: Date())) ) } private init(state: State) { self.state = state } private static func printTrace(ended: State.Ended) { let traceId = ended.traceId let timeInterval = ended.timeInterval let seconds = timeInterval.string(with: 2) Logger.shared.debug( "Trace \(traceId), finished in \(seconds) seconds" ) } } private enum TraceType { case debugTrace(DebugTrace) case remoteTrace(RemoteTrace) func stop() { switch self { case .debugTrace(let debugTrace): debugTrace.stop() case .remoteTrace(let remoteTrace): remoteTrace.stop() } } static func debugTrace(with traceId: TraceID) -> Self { .debugTrace(DebugTrace(traceId: traceId)) } static func remoteTrace( with traceId: TraceID, properties: [String: String], create: PerformanceTracing.CreateRemoteTrace ) -> Self { let remoteTrace = create(traceId, properties) return .remoteTrace(remoteTrace) } } private let trace: TraceType private init(trace: TraceType) { self.trace = trace } func stop() { trace.stop() } static func createTrace( with traceId: TraceID, properties: [String: String], create: PerformanceTracing.CreateRemoteTrace ) -> Self { let traceType: TraceType = isDebug() ? .debugTrace(with: traceId) : .remoteTrace(with: traceId, properties: properties, create: create) return Self(trace: traceType) } private static func isDebug() -> Bool { var isDebug = false #if DEBUG isDebug = true #endif return isDebug } }
56c91565153cd8df47adcf2e3770010b
25.188525
77
0.537402
false
false
false
false
GhostSK/SpriteKitPractice
refs/heads/master
TileMap/TileMap/File.swift
apache-2.0
1
// // File.swift // TileMap // // Created by 胡杨林 on 17/3/22. // Copyright © 2017年 胡杨林. All rights reserved. // import Foundation import CoreGraphics //加载来自图片的瓦片地图 func tileMapLayerFromFileNamed(fileName:String) ->TileMapLayer? { let path = Bundle.main.path(forResource: fileName, ofType: nil) if path == nil { return nil } let fileContents = try? String(contentsOfFile: path!) let lines = Array<String>(fileContents!.components(separatedBy: "\n")) let atlasName = lines[0] let tileSizeComps = lines[1].components(separatedBy: "x") let width = Int(tileSizeComps[0]) let height = Int(tileSizeComps[1]) if width != nil && height != nil { let tileSize = CGSize(width: width!, height: height!) let tileCodes = lines[2..<lines.endIndex] return TileMapLayer(atlasName: atlasName, tileSize: tileSize, tileCodes: Array(tileCodes)) } return nil }
f398195c1187b2401cf62078a94d7c9e
30.793103
98
0.669197
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPerformanceTester/DeadlineNowBenchmark.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore final class DeadlineNowBenchmark: Benchmark { private let iterations: Int init(iterations: Int) { self.iterations = iterations } func setUp() throws { } func tearDown() { } func run() -> Int { var counter: UInt64 = 0 for _ in 0..<self.iterations { let now = NIODeadline.now().uptimeNanoseconds counter &+= now } return Int(truncatingIfNeeded: counter) } }
2af76cf60a36940fe9394daae33cd6fb
24.5
80
0.531476
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveMapKitTests/MKMapViewSpec.swift
gpl-3.0
4
import ReactiveSwift import ReactiveCocoa import ReactiveMapKit import Quick import Nimble import enum Result.NoError import MapKit @available(tvOS 9.2, *) class MKMapViewSpec: QuickSpec { override func spec() { var mapView: MKMapView! weak var _mapView: MKMapView? beforeEach { mapView = MKMapView(frame: .zero) _mapView = mapView } afterEach { autoreleasepool { mapView = nil } // FIXME: SDK_ISSUE // // Temporarily disabled since the expectation keeps failing with // Xcode 8.3 and macOS Sierra 10.12.4. #if !os(macOS) // using toEventually(beNil()) here // since it takes time to release MKMapView expect(_mapView).toEventually(beNil()) #endif } it("should accept changes from bindings to its map type") { expect(mapView.mapType) == MKMapType.standard let (pipeSignal, observer) = Signal<MKMapType, NoError>.pipe() mapView.reactive.mapType <~ pipeSignal observer.send(value: MKMapType.satellite) expect(mapView.mapType) == MKMapType.satellite observer.send(value: MKMapType.hybrid) expect(mapView.mapType) == MKMapType.hybrid } it("should accept changes from bindings to its zoom enabled state") { expect(mapView.isZoomEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isZoomEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isZoomEnabled) == false } it("should accept changes from bindings to its scroll enabled state") { expect(mapView.isScrollEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isScrollEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isScrollEnabled) == false } #if !os(tvOS) it("should accept changes from bindings to its pitch enabled state") { expect(mapView.isPitchEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isPitchEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isPitchEnabled) == false } it("should accept changes from bindings to its rotate enabled state") { expect(mapView.isRotateEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isRotateEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isRotateEnabled) == false } #endif } }
4ce7e8b0073b4957e96f739acd00a4e5
24.147368
73
0.710758
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Blockchain/DIKit/DIKit.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BitcoinCashKit import BitcoinChainKit import BitcoinKit import BlockchainNamespace import Combine import DIKit import ERC20Kit import EthereumKit import FeatureAppDomain import FeatureAppUI import FeatureAttributionData import FeatureAttributionDomain import FeatureAuthenticationData import FeatureAuthenticationDomain import FeatureCardIssuingUI import FeatureCoinData import FeatureCoinDomain import FeatureCryptoDomainData import FeatureCryptoDomainDomain import FeatureDashboardUI import FeatureDebugUI import FeatureKYCDomain import FeatureKYCUI import FeatureNFTData import FeatureNFTDomain import FeatureNotificationPreferencesData import FeatureNotificationPreferencesDomain import FeatureOnboardingUI import FeatureOpenBankingData import FeatureOpenBankingDomain import FeatureOpenBankingUI import FeatureProductsData import FeatureProductsDomain import FeatureReferralData import FeatureReferralDomain import FeatureSettingsDomain import FeatureSettingsUI import FeatureTransactionDomain import FeatureTransactionUI import FeatureUserDeletionData import FeatureUserDeletionDomain import FeatureWalletConnectData import FirebaseDynamicLinks import FirebaseMessaging import FirebaseRemoteConfig import MoneyKit import NetworkKit import ObservabilityKit import PlatformDataKit import PlatformKit import PlatformUIKit import RemoteNotificationsKit import RxToolKit import StellarKit import ToolKit import UIKit import WalletPayloadKit // MARK: - Settings Dependencies extension UIApplication: PlatformKit.AppStoreOpening {} extension Wallet: WalletRecoveryVerifing {} // MARK: - Dashboard Dependencies extension AnalyticsUserPropertyInteractor: FeatureDashboardUI.AnalyticsUserPropertyInteracting {} extension AnnouncementPresenter: FeatureDashboardUI.AnnouncementPresenting {} extension FeatureSettingsUI.BackupFundsRouter: FeatureDashboardUI.BackupRouterAPI {} // MARK: - AnalyticsKit Dependencies extension BlockchainSettings.App: AnalyticsKit.GuidRepositoryAPI {} // MARK: - Blockchain Module extension DependencyContainer { // swiftlint:disable closure_body_length static var blockchain = module { factory { NavigationRouter() as NavigationRouterAPI } factory { DeepLinkHandler() as DeepLinkHandling } factory { DeepLinkRouter() as DeepLinkRouting } factory { UIDevice.current as DeviceInfo } factory { PerformanceTracing.live as PerformanceTracingServiceAPI } single { () -> LogMessageServiceAPI in let loggers = LogMessageTracing.provideLoggers() return LogMessageTracing.live( loggers: loggers ) } factory { CrashlyticsRecorder() as MessageRecording } factory { CrashlyticsRecorder() as ErrorRecording } factory(tag: "CrashlyticsRecorder") { CrashlyticsRecorder() as Recording } factory { ExchangeClient() as ExchangeClientAPI } factory { RecoveryPhraseStatusProvider() as RecoveryPhraseStatusProviding } single { TradeLimitsMetadataService() as TradeLimitsMetadataServiceAPI } factory { SiftService() } factory { () -> FeatureAuthenticationDomain.SiftServiceAPI in let service: SiftService = DIKit.resolve() return service as FeatureAuthenticationDomain.SiftServiceAPI } factory { () -> PlatformKit.SiftServiceAPI in let service: SiftService = DIKit.resolve() return service as PlatformKit.SiftServiceAPI } single { SecondPasswordHelper() } factory { () -> SecondPasswordHelperAPI in let helper: SecondPasswordHelper = DIKit.resolve() return helper as SecondPasswordHelperAPI } factory { () -> SecondPasswordPresenterHelper in let helper: SecondPasswordHelper = DIKit.resolve() return helper as SecondPasswordPresenterHelper } single { () -> SecondPasswordPromptable in SecondPasswordPrompter( secondPasswordStore: DIKit.resolve(), secondPasswordPrompterHelper: DIKit.resolve(), secondPasswordService: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } single { SecondPasswordStore() as SecondPasswordStorable } single { () -> AppDeeplinkHandlerAPI in let appSettings: BlockchainSettings.App = DIKit.resolve() let isPinSet: () -> Bool = { appSettings.isPinSet } let deeplinkHandler = CoreDeeplinkHandler( markBitpayUrl: { BitpayService.shared.content = $0 }, isBitPayURL: BitPayLinkRouter.isBitPayURL, isPinSet: isPinSet ) let blockchainHandler = BlockchainLinksHandler( validHosts: BlockchainLinks.validLinks, validRoutes: BlockchainLinks.validRoutes ) return AppDeeplinkHandler( deeplinkHandler: deeplinkHandler, blockchainHandler: blockchainHandler, firebaseHandler: FirebaseDeeplinkHandler(dynamicLinks: DynamicLinks.dynamicLinks()) ) } // MARK: ExchangeCoordinator // MARK: - AuthenticationCoordinator factory { () -> AuthenticationCoordinating in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveAuthenticationCoordinating() as AuthenticationCoordinating } // MARK: - Dashboard factory { () -> AccountsRouting in let routing: TabSwapping = DIKit.resolve() return AccountsRouter( routing: routing ) } factory { UIApplication.shared as AppStoreOpening } factory { BackupFundsRouter( entry: .custody, navigationRouter: NavigationRouter() ) as FeatureDashboardUI.BackupRouterAPI } factory { AnalyticsUserPropertyInteractor() as FeatureDashboardUI.AnalyticsUserPropertyInteracting } factory { AnnouncementPresenter() as FeatureDashboardUI.AnnouncementPresenting } factory { SimpleBuyAnalyticsService() as PlatformKit.SimpleBuyAnalayticsServicing } // MARK: - AppCoordinator single { LoggedInDependencyBridge() as LoggedInDependencyBridgeAPI } factory { () -> TabSwapping in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveTabSwapping() as TabSwapping } factory { () -> AppCoordinating in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveAppCoordinating() as AppCoordinating } factory { () -> FeatureDashboardUI.WalletOperationsRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveWalletOperationsRouting() as FeatureDashboardUI.WalletOperationsRouting } factory { () -> BackupFlowStarterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveBackupFlowStarter() as BackupFlowStarterAPI } factory { () -> CashIdentityVerificationAnnouncementRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveCashIdentityVerificationAnnouncementRouting() as CashIdentityVerificationAnnouncementRouting } factory { () -> SettingsStarterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveSettingsStarter() as SettingsStarterAPI } factory { () -> DrawerRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveDrawerRouting() as DrawerRouting } factory { () -> LoggedInReloadAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveLoggedInReload() as LoggedInReloadAPI } factory { () -> ClearOnLogoutAPI in EmptyClearOnLogout() } factory { () -> QRCodeScannerRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveQRCodeScannerRouting() as QRCodeScannerRouting } factory { () -> ExternalActionsProviderAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveExternalActionsProvider() as ExternalActionsProviderAPI } factory { () -> SupportRouterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveSupportRouterAPI() } // MARK: - WalletManager single { WalletManager() } factory { () -> WalletManagerAPI in let manager: WalletManager = DIKit.resolve() return manager as WalletManagerAPI } factory { () -> LegacyMnemonicAccessAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet as LegacyMnemonicAccessAPI } factory { () -> WalletRepositoryProvider in let walletManager: WalletManager = DIKit.resolve() return walletManager as WalletRepositoryProvider } factory { () -> JSContextProviderAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager as JSContextProviderAPI } factory { () -> WalletRecoveryVerifing in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet as WalletRecoveryVerifing } factory { () -> WalletConnectMetadataAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.walletConnect as WalletConnectMetadataAPI } // MARK: - BlockchainSettings.App single { KeychainItemSwiftWrapper() as KeychainItemWrapping } factory { LegacyPasswordProvider() as LegacyPasswordProviding } single { BlockchainSettings.App() } factory { () -> AppSettingsAPI in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsAPI } factory { () -> AppSettingsAuthenticating in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsAuthenticating } factory { () -> PermissionSettingsAPI in let app: BlockchainSettings.App = DIKit.resolve() return app } factory { () -> AppSettingsSecureChannel in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsSecureChannel } // MARK: - Settings factory { () -> RecoveryPhraseVerifyingServiceAPI in let manager: WalletManager = DIKit.resolve() let backupService: VerifyMnemonicBackupServiceAPI = DIKit.resolve() return RecoveryPhraseVerifyingService( wallet: manager.wallet, verifyMnemonicBackupService: backupService, nativeWalletEnabledFlag: { nativeWalletFlagEnabled() } ) } // MARK: - AppFeatureConfigurator single { AppFeatureConfigurator( app: DIKit.resolve() ) } factory { () -> FeatureFetching in let featureFetching: AppFeatureConfigurator = DIKit.resolve() return featureFetching } factory { PolygonSupport(app: DIKit.resolve()) as MoneyKit.PolygonSupport } // MARK: - UserInformationServiceProvider // user state can be observed by multiple objects and the state is made up of multiple components // so, better have a single instance of this object. single { () -> UserAdapterAPI in UserAdapter( kycTiersService: DIKit.resolve(), paymentMethodsService: DIKit.resolve(), productsService: DIKit.resolve(), ordersService: DIKit.resolve() ) } factory { () -> SettingsServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> SettingsServiceCombineAPI in let settings: SettingsServiceAPI = DIKit.resolve() return settings as SettingsServiceCombineAPI } factory { () -> FiatCurrencyServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> SupportedFiatCurrenciesServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> MobileSettingsServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } // MARK: - BlockchainDataRepository factory { BlockchainDataRepository() as DataRepositoryAPI } // MARK: - Ethereum Wallet factory { () -> EthereumWalletBridgeAPI in let manager: WalletManager = DIKit.resolve() return manager.wallet.ethereum } factory { () -> EthereumWalletAccountBridgeAPI in let manager: WalletManager = DIKit.resolve() return manager.wallet.ethereum } // MARK: - Stellar Wallet factory { StellarWallet() as StellarWalletBridgeAPI } factory { () -> BitcoinWalletBridgeAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.bitcoin } factory { () -> WalletMnemonicProvider in let mnemonicAccess: MnemonicAccessAPI = DIKit.resolve() return { mnemonicAccess.mnemonic .eraseError() .map(BitcoinChainKit.Mnemonic.init) .eraseToAnyPublisher() } } factory { () -> BitcoinChainSendBridgeAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.bitcoin } single { BitcoinCashWallet() as BitcoinCashWalletBridgeAPI } // MARK: Wallet Upgrade factory { WalletUpgrading() as WalletUpgradingAPI } // MARK: Remote Notifications factory { ExternalNotificationServiceProvider() as ExternalNotificationProviding } factory { () -> RemoteNotificationEmitting in let relay: RemoteNotificationRelay = DIKit.resolve() return relay as RemoteNotificationEmitting } factory { () -> RemoteNotificationBackgroundReceiving in let relay: RemoteNotificationRelay = DIKit.resolve() return relay as RemoteNotificationBackgroundReceiving } single { RemoteNotificationRelay( app: DIKit.resolve(), cacheSuite: DIKit.resolve(), userNotificationCenter: UNUserNotificationCenter.current(), messagingService: Messaging.messaging(), secureChannelNotificationRelay: DIKit.resolve() ) } // MARK: Helpers factory { UIApplication.shared as ExternalAppOpener } factory { UIApplication.shared as URLOpener } factory { UIApplication.shared as OpenURLProtocol } // MARK: KYC Module factory { () -> FeatureSettingsUI.KYCRouterAPI in KYCAdapter() } factory { () -> FeatureKYCDomain.EmailVerificationAPI in EmailVerificationAdapter(settingsService: DIKit.resolve()) } // MARK: Onboarding Module // this must be kept in memory because of how PlatformUIKit.Router works, otherwise the flow crashes. single { () -> FeatureOnboardingUI.OnboardingRouterAPI in FeatureOnboardingUI.OnboardingRouter() } factory { () -> FeatureOnboardingUI.TransactionsRouterAPI in TransactionsAdapter( router: DIKit.resolve(), coincore: DIKit.resolve(), app: DIKit.resolve() ) } factory { () -> FeatureOnboardingUI.KYCRouterAPI in KYCAdapter() } // MARK: Transactions Module factory { () -> PaymentMethodsLinkingAdapterAPI in PaymentMethodsLinkingAdapter() } factory { () -> TransactionsAdapterAPI in TransactionsAdapter( router: DIKit.resolve(), coincore: DIKit.resolve(), app: DIKit.resolve() ) } factory { () -> PlatformUIKit.KYCRouting in KYCAdapter() } factory { () -> FeatureSettingsUI.PaymentMethodsLinkerAPI in PaymentMethodsLinkingAdapter() } factory { () -> FeatureTransactionUI.UserActionServiceAPI in TransactionUserActionService(userService: DIKit.resolve()) } factory { () -> FeatureTransactionDomain.TransactionRestrictionsProviderAPI in TransactionUserActionService(userService: DIKit.resolve()) } // MARK: FeatureAuthentication Module factory { () -> AutoWalletPairingServiceAPI in let manager: WalletManager = DIKit.resolve() return AutoWalletPairingService( walletPayloadService: DIKit.resolve(), walletPairingRepository: DIKit.resolve(), walletCryptoService: DIKit.resolve(), parsingService: DIKit.resolve() ) as AutoWalletPairingServiceAPI } factory { () -> CheckReferralClientAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) return CheckReferralClient(networkAdapter: adapter, requestBuilder: builder) } factory { () -> GuidServiceAPI in GuidService( sessionTokenRepository: DIKit.resolve(), guidRepository: DIKit.resolve() ) } factory { () -> SessionTokenServiceAPI in sessionTokenServiceFactory( sessionRepository: DIKit.resolve() ) } factory { () -> SMSServiceAPI in SMSService( smsRepository: DIKit.resolve(), credentialsRepository: DIKit.resolve(), sessionTokenRepository: DIKit.resolve() ) } factory { () -> TwoFAWalletServiceAPI in let manager: WalletManager = DIKit.resolve() return TwoFAWalletService( repository: DIKit.resolve(), walletRepository: manager.repository, walletRepo: DIKit.resolve(), nativeWalletFlagEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> WalletPayloadServiceAPI in let manager: WalletManager = DIKit.resolve() return WalletPayloadService( repository: DIKit.resolve(), walletRepository: manager.repository, walletRepo: DIKit.resolve(), credentialsRepository: DIKit.resolve(), nativeWalletEnabledUse: nativeWalletEnabledUseImpl ) } factory { () -> LoginServiceAPI in LoginService( payloadService: DIKit.resolve(), twoFAPayloadService: DIKit.resolve(), repository: DIKit.resolve() ) } factory { () -> EmailAuthorizationServiceAPI in EmailAuthorizationService(guidService: DIKit.resolve()) as EmailAuthorizationServiceAPI } factory { () -> DeviceVerificationServiceAPI in let sessionTokenRepository: SessionTokenRepositoryAPI = DIKit.resolve() return DeviceVerificationService( sessionTokenRepository: sessionTokenRepository ) as DeviceVerificationServiceAPI } factory { RecaptchaClient(siteKey: AuthenticationKeys.googleRecaptchaSiteKey) } factory { GoogleRecaptchaService() as GoogleRecaptchaServiceAPI } // MARK: Analytics single { () -> AnalyticsKit.GuidRepositoryAPI in let guidRepository: BlockchainSettings.App = DIKit.resolve() return guidRepository as AnalyticsKit.GuidRepositoryAPI } single { () -> AnalyticsEventRecorderAPI in let firebaseAnalyticsServiceProvider = FirebaseAnalyticsServiceProvider() let userAgent = UserAgentProvider().userAgent ?? "" let nabuAnalyticsServiceProvider = NabuAnalyticsProvider( platform: .wallet, basePath: BlockchainAPI.shared.apiUrl, userAgent: userAgent, tokenProvider: DIKit.resolve(), guidProvider: DIKit.resolve(), traitRepository: DIKit.resolve() ) return AnalyticsEventRecorder(analyticsServiceProviders: [ firebaseAnalyticsServiceProvider, nabuAnalyticsServiceProvider ]) } single { AppAnalyticsTraitRepository(app: DIKit.resolve()) } single { () -> TraitRepositoryAPI in let analytics: AppAnalyticsTraitRepository = DIKit.resolve() return analytics as TraitRepositoryAPI } // MARK: Account Picker factory { () -> AccountPickerViewControllable in let controller = FeatureAccountPickerControllableAdapter() return controller as AccountPickerViewControllable } // MARK: Open Banking single { () -> OpenBanking in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = OpenBankingClient( app: DIKit.resolve(), requestBuilder: builder, network: adapter.network ) return OpenBanking(app: DIKit.resolve(), banking: client) } // MARK: Coin View single { () -> HistoricalPriceClientAPI in let requestBuilder: NetworkKit.RequestBuilder = DIKit.resolve() let networkAdapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve() return HistoricalPriceClient( request: requestBuilder, network: networkAdapter ) } single { () -> HistoricalPriceRepositoryAPI in HistoricalPriceRepository(DIKit.resolve()) } single { () -> RatesClientAPI in let requestBuilder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let networkAdapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) return RatesClient( networkAdapter: networkAdapter, requestBuilder: requestBuilder ) } single { () -> RatesRepositoryAPI in RatesRepository(DIKit.resolve()) } single { () -> WatchlistRepositoryAPI in WatchlistRepository( WatchlistClient( networkAdapter: DIKit.resolve(tag: DIKitContext.retail), requestBuilder: DIKit.resolve(tag: DIKitContext.retail) ) ) } // MARK: Feature Product factory { () -> FeatureProductsDomain.ProductsServiceAPI in ProductsService( repository: ProductsRepository( client: ProductsAPIClient( networkAdapter: DIKit.resolve(tag: DIKitContext.retail), requestBuilder: DIKit.resolve(tag: DIKitContext.retail) ) ), featureFlagsService: DIKit.resolve() ) } // MARK: Feature NFT factory { () -> FeatureNFTDomain.AssetProviderServiceAPI in let repository: EthereumWalletAccountRepositoryAPI = DIKit.resolve() let publisher = repository .defaultAccount .map(\.publicKey) .eraseError() return AssetProviderService( repository: AssetProviderRepository( client: FeatureNFTData.APIClient( retailNetworkAdapter: DIKit.resolve(tag: DIKitContext.retail), defaultNetworkAdapter: DIKit.resolve(), retailRequestBuilder: DIKit.resolve(tag: DIKitContext.retail), defaultRequestBuilder: DIKit.resolve() ) ), ethereumWalletAddressPublisher: publisher ) } factory { () -> FeatureNFTDomain.ViewWaitlistRegistrationRepositoryAPI in let emailService: EmailSettingsServiceAPI = DIKit.resolve() let publisher = emailService .emailPublisher .eraseError() return ViewWaitlistRegistrationRepository( client: FeatureNFTData.APIClient( retailNetworkAdapter: DIKit.resolve(tag: DIKitContext.retail), defaultNetworkAdapter: DIKit.resolve(), retailRequestBuilder: DIKit.resolve(tag: DIKitContext.retail), defaultRequestBuilder: DIKit.resolve() ), emailAddressPublisher: publisher ) } // MARK: Feature Crypto Domain factory { () -> SearchDomainRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve() let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve() let client = SearchDomainClient(networkAdapter: adapter, requestBuilder: builder) return SearchDomainRepository(apiClient: client) } factory { () -> OrderDomainRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = OrderDomainClient(networkAdapter: adapter, requestBuilder: builder) return OrderDomainRepository(apiClient: client) } factory { () -> ClaimEligibilityRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = ClaimEligibilityClient(networkAdapter: adapter, requestBuilder: builder) return ClaimEligibilityRepository(apiClient: client) } // MARK: Feature Notification Preferences factory { () -> NotificationPreferencesRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = NotificationPreferencesClient(networkAdapter: adapter, requestBuilder: builder) return NotificationPreferencesRepository(client: client) } // MARK: Feature Referrals factory { () -> ReferralRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = ReferralClientClient(networkAdapter: adapter, requestBuilder: builder) return ReferralRepository(client: client) } factory { () -> ReferralServiceAPI in ReferralService( app: DIKit.resolve(), repository: DIKit.resolve() ) } // MARK: - Websocket single(tag: DIKitContext.websocket) { RequestBuilder(config: Network.Config.websocketConfig) } // MARK: Feature Attribution single { () -> AttributionServiceAPI in let errorRecorder = CrashlyticsRecorder() let skAdNetworkService = SkAdNetworkService(errorRecorder: errorRecorder) let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.websocket) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let featureFlagService: FeatureFlagsServiceAPI = DIKit.resolve() let attributionClient = AttributionClient( networkAdapter: adapter, requestBuilder: builder ) let attributionRepository = AttributionRepository(with: attributionClient) return AttributionService( skAdNetworkService: skAdNetworkService, attributionRepository: attributionRepository, featureFlagService: featureFlagService ) as AttributionServiceAPI } // MARK: User Deletion factory { () -> UserDeletionRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = UserDeletionClient(networkAdapter: adapter, requestBuilder: builder) return UserDeletionRepository(client: client) } // MARK: Native Wallet Debugging single { NativeWalletLogger() as NativeWalletLoggerAPI } // MARK: Pulse Network Debugging single { PulseNetworkDebugLogger() as NetworkDebugLogger } single { PulseNetworkDebugScreenProvider() as NetworkDebugScreenProvider } single { app } factory { () -> NativeWalletFlagEnabled in let app: AppProtocol = DIKit.resolve() let flag: Tag.Event = BlockchainNamespace.blockchain.app.configuration.native.wallet.payload.is.enabled return NativeWalletFlagEnabled( app.publisher(for: flag, as: Bool.self) .prefix(1) .replaceError(with: false) ) } single { () -> RequestBuilderQueryParameters in let app: AppProtocol = DIKit.resolve() return RequestBuilderQueryParameters( app.publisher( for: BlockchainNamespace.blockchain.app.configuration.localized.error.override, as: String.self ) .map { result -> [URLQueryItem]? in try? [URLQueryItem(name: "localisedError", value: result.get().nilIfEmpty)] } .replaceError(with: []) ) } } } extension UIApplication: OpenURLProtocol {}
f4be591e5d55ff4a77e2dc8b9b3fc369
34.832009
115
0.628928
false
false
false
false
livioso/cpib
refs/heads/master
Compiler/Compiler/extensions/characterExtension.swift
mit
1
import Foundation extension Character { enum Kind { case Skippable case Literal case Letter case Symbol case Other } func kind() -> Kind { if isSkipable() { return Kind.Skippable } if isLiteral() { return Kind.Literal } if isSymbol() { return Kind.Symbol } if isLetter() { return Kind.Letter } return Kind.Other } private func isSkipable() -> Bool { return ( (" " == self) || ("\t" == self) || ("\n" == self) ) } private func isLiteral() -> Bool { return ("0" <= self && self <= "9") } private func isLetter() -> Bool { return ( ("A" <= self && self <= "Z") || ("a" <= self && self <= "z") ) } private func isSymbol() -> Bool { var isMatch = false switch self { case "(": fallthrough case ")": fallthrough case "{": fallthrough case "}": fallthrough case ",": fallthrough case ":": fallthrough case ";": fallthrough case "=": fallthrough case "*": fallthrough case "+": fallthrough case "-": fallthrough case "/": fallthrough case "<": fallthrough case ">": fallthrough case "&": fallthrough case "|": fallthrough case ".": isMatch = true case _: isMatch = false } return isMatch } }
674e78b94b6c86303a1ff93df2ccb273
17.765625
43
0.582015
false
false
false
false
sambhav7890/RecurrenceRuleUI-iOS
refs/heads/master
RecurrenceRuleUI-iOS/Classes/RecurrencePicker.swift
mit
1
// // RecurrenceRuleUI.swift // RecurrenceRuleUI // // Created by Sambhav on 16/8/7. // Copyright © 2016 Practo. All rights reserved. // import UIKit import EventKit import RecurrenceRule_iOS open class RecurrencePicker: UITableViewController { open var language: RecurrencePickerLanguage = .english { didSet { InternationalControl.sharedControl.language = language } } open weak var delegate: RecurrencePickerDelegate? open var tintColor = UIColor.blue open var calendar = Calendar.current open var occurrenceDate = Date() open var backgroundColor: UIColor? open var separatorColor: UIColor? fileprivate var recurrenceRule: RecurrenceRule? fileprivate var selectedIndexPath = IndexPath(row: 0, section: 0) // MARK: - Initialization public convenience init(recurrenceRule: RecurrenceRule?) { self.init(style: .grouped) self.recurrenceRule = recurrenceRule } // MARK: - Life cycle open override func viewDidLoad() { super.viewDidLoad() commonInit() } open override func didMove(toParentViewController parent: UIViewController?) { if parent == nil { // navigation is popped if let rule = recurrenceRule { switch rule.frequency { case .daily: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth.removeAll() case .weekly: recurrenceRule?.byweekday = rule.byweekday.sorted(by: <) recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth.removeAll() case .monthly: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday = rule.bymonthday.sorted(by: <) recurrenceRule?.bymonth.removeAll() case .yearly: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth = rule.bymonth.sorted(by: <) default: break } } recurrenceRule?.startDate = Date() delegate?.recurrencePicker(self, didPickRecurrence: recurrenceRule) } } } extension RecurrencePicker { // MARK: - Table view data source and delegate open override func numberOfSections(in tableView: UITableView) -> Int { return 2 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return Constant.basicRecurrenceStrings().count } else { return 1 } } open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Constant.DefaultRowHeight } open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return section == 1 ? recurrenceRuleText() : nil } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: CellID.BasicRecurrenceCell) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: CellID.BasicRecurrenceCell) } if (indexPath as NSIndexPath).section == 0 { cell?.accessoryType = .none cell?.textLabel?.text = Constant.basicRecurrenceStrings()[(indexPath as NSIndexPath).row] } else { cell?.accessoryType = .disclosureIndicator cell?.textLabel?.text = LocalizedString("RecurrencePicker.TextLabel.Custom") } let checkmark = UIImage(named: "checkmark", in: Bundle(for: type(of: self)), compatibleWith: nil) cell?.imageView?.image = checkmark?.withRenderingMode(.alwaysTemplate) if indexPath == selectedIndexPath { cell?.imageView?.isHidden = false } else { cell?.imageView?.isHidden = true } return cell! } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let lastSelectedCell = tableView.cellForRow(at: selectedIndexPath) let currentSelectedCell = tableView.cellForRow(at: indexPath) lastSelectedCell?.imageView?.isHidden = true currentSelectedCell?.imageView?.isHidden = false selectedIndexPath = indexPath if (indexPath as NSIndexPath).section == 0 { updateRecurrenceRule(withSelectedIndexPath: indexPath) updateRecurrenceRuleText() navigationController?.popViewController(animated: true) } else { let customRecurrenceViewController = CustomRecurrenceViewController(style: .grouped) customRecurrenceViewController.occurrenceDate = occurrenceDate customRecurrenceViewController.tintColor = tintColor customRecurrenceViewController.backgroundColor = backgroundColor customRecurrenceViewController.separatorColor = separatorColor customRecurrenceViewController.delegate = self var rule = recurrenceRule ?? RecurrenceRule.dailyRecurrence() let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday, .day, .month], from: occurrenceDate) if rule.byweekday.count == 0 { let weekday = EKWeekday(rawValue: occurrenceDateComponents.weekday!)! rule.byweekday = [weekday] } if rule.bymonthday.count == 0 { if let monthday = occurrenceDateComponents.day { rule.bymonthday = [monthday] } } if rule.bymonth.count == 0 { if let month = occurrenceDateComponents.month { rule.bymonth = [month] } } customRecurrenceViewController.recurrenceRule = rule navigationController?.pushViewController(customRecurrenceViewController, animated: true) } tableView.deselectRow(at: indexPath, animated: true) } } extension RecurrencePicker { // MARK: - Helper fileprivate func commonInit() { navigationItem.title = LocalizedString("RecurrencePicker.Navigation.Title") navigationController?.navigationBar.tintColor = tintColor tableView.tintColor = tintColor if let backgroundColor = backgroundColor { tableView.backgroundColor = backgroundColor } if let separatorColor = separatorColor { tableView.separatorColor = separatorColor } updateSelectedIndexPath(withRule: recurrenceRule) } fileprivate func updateSelectedIndexPath(withRule recurrenceRule: RecurrenceRule?) { guard let recurrenceRule = recurrenceRule else { selectedIndexPath = IndexPath(row: 0, section: 0) return } if recurrenceRule.isDailyRecurrence() { selectedIndexPath = IndexPath(row: 1, section: 0) } else if recurrenceRule.isWeeklyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 2, section: 0) } else if recurrenceRule.isBiWeeklyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 3, section: 0) } else if recurrenceRule.isMonthlyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 4, section: 0) } else if recurrenceRule.isYearlyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 5, section: 0) } else if recurrenceRule.isWeekdayRecurrence() { selectedIndexPath = IndexPath(row: 6, section: 0) } else { selectedIndexPath = IndexPath(row: 0, section: 1) } } fileprivate func updateRecurrenceRule(withSelectedIndexPath indexPath: IndexPath) { guard indexPath.section == 0 else { return } switch indexPath.row { case 0: recurrenceRule = nil case 1: recurrenceRule = RecurrenceRule.dailyRecurrence() case 2: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday], from: occurrenceDate) if let weekDayRaw = occurrenceDateComponents.weekday, let weekday = EKWeekday(rawValue: weekDayRaw) { recurrenceRule = RecurrenceRule.weeklyRecurrence(weekday: weekday) } case 3: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday], from: occurrenceDate) if let weekDayRaw = occurrenceDateComponents.weekday, let weekday = EKWeekday(rawValue: weekDayRaw) { recurrenceRule = RecurrenceRule.biWeeklyRecurrence(weekday: weekday) } case 4: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.day], from: occurrenceDate) if let monthday = occurrenceDateComponents.day { recurrenceRule = RecurrenceRule.monthlyRecurrence(monthday: monthday) } case 5: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.month], from: occurrenceDate) if let month = occurrenceDateComponents.month { recurrenceRule = RecurrenceRule.yearlyRecurrence(month: month) } case 6: recurrenceRule = RecurrenceRule.weekdayRecurrence() default: break } } fileprivate func recurrenceRuleText() -> String? { return (selectedIndexPath as IndexPath).section == 1 ? recurrenceRule?.toText(on: occurrenceDate) : nil } fileprivate func updateRecurrenceRuleText() { let footerView = tableView.footerView(forSection: 1) tableView.beginUpdates() footerView?.textLabel?.text = recurrenceRuleText() tableView.endUpdates() footerView?.setNeedsLayout() } } extension RecurrencePicker: CustomRecurrenceViewControllerDelegate { func customRecurrenceViewController(_ controller: CustomRecurrenceViewController, didPickRecurrence recurrenceRule: RecurrenceRule) { self.recurrenceRule = recurrenceRule updateRecurrenceRuleText() } }
5b66412f998ca7dfc679cb29405e5afe
39.011673
137
0.659438
false
false
false
false
groovelab/SwiftBBS
refs/heads/master
SwiftBBS/SwiftBBS/BbsDetailViewController.swift
mit
1
// // BbsDetailViewController.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/16. // Copyright GrooveLab // import UIKit import PerfectLib class BbsDetailViewController: UIViewController { let END_POINT: String = "http://\(Config.END_POINT_HOST):\(Config.END_POINT_PORT)/bbs/detail/" let END_POINT_COMMENT: String = "http://\(Config.END_POINT_HOST):\(Config.END_POINT_PORT)/bbs/addcomment/" var bbsId: Int? var bbs: JSONDictionaryType? var commentArray: JSONArrayType? var doScrollBottom = false private var cellForHeight: BbsDetailTableViewCell! @IBOutlet weak private var titleLabel: UILabel! @IBOutlet weak private var commentLabel: UILabel! @IBOutlet weak private var userNameLabel: UILabel! @IBOutlet weak private var createdAtLabel: UILabel! @IBOutlet weak private var tableView: UITableView! @IBOutlet weak private var commentTextView: UITextView! @IBOutlet weak private var bottomMarginConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0)) toolBar.items = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil), UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(BbsDetailViewController.closeKeyboard(_:))) ] commentTextView.inputAccessoryView = toolBar commentTextView.text = nil cellForHeight = tableView.dequeueReusableCellWithIdentifier(BbsDetailTableViewCell.identifierForReuse) as! BbsDetailTableViewCell fetchData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BbsDetailViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BbsDetailViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo, let keyBoardRectValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else { return } let keyboardRect = keyBoardRectValue.CGRectValue() bottomMarginConstraint.constant = keyboardRect.height - (navigationController?.tabBarController?.tabBar.frame.height)! UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() } } func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else { return } bottomMarginConstraint.constant = 0.0 UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() } } func closeKeyboard(sender: UIBarButtonItem) { commentTextView.resignFirstResponder() } private func fetchData() { guard let bbsId = bbsId else { return } let req = NSMutableURLRequest(URL: NSURL(string: END_POINT + "\(bbsId)")!) req.HTTPMethod = "GET" req.addValue("application/json", forHTTPHeaderField: "Accept") req.addTokenToCookie() let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(req, completionHandler: { (data:NSData?, res:NSURLResponse?, error:NSError?) -> Void in if let error = error { print("Request failed with error \(error)") return; } guard let data = data, let stringData = String(data: data, encoding: NSUTF8StringEncoding) else { print("response is empty") return; } do { let jsonDecoded = try JSONDecoder().decode(stringData) if let jsonMap = jsonDecoded as? JSONDictionaryType { if let bbsDictionary = jsonMap.dictionary["bbs"] as? JSONDictionaryType { self.bbs = bbsDictionary } if let comments = jsonMap.dictionary["comments"] as? JSONArrayType { self.commentArray = comments dispatch_async(dispatch_get_main_queue(), { self.didFetchData() }) } } } catch let exception { print("JSON decoding failed with exception \(exception)") } }) task.resume() } private func didFetchData() { if let bbs = bbs { if let title = bbs.dictionary["title"] as? String { titleLabel.text = title } if let comment = bbs.dictionary["comment"] as? String { commentLabel.text = comment } if let userName = bbs.dictionary["userName"] as? String { userNameLabel.text = userName } if let createdAt = bbs.dictionary["createdAt"] as? String { createdAtLabel.text = createdAt } } tableView.reloadData() if doScrollBottom { doScrollBottom = false if let commentArray = commentArray where commentArray.array.count > 0 { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: commentArray.array.count - 1, inSection: 0), atScrollPosition: .Bottom, animated: true) } } } @IBAction private func commentAction(sender: UIButton) { doComment() } private func doComment() { guard let bbsId = bbsId, let comment = commentTextView.text else { return } if comment.isEmpty { return } let req = NSMutableURLRequest(URL: NSURL(string: END_POINT_COMMENT)!) req.HTTPMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Accept") req.addTokenToCookie() let postBody = "bbs_id=\(bbsId)&comment=\(comment)" req.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(req, completionHandler: { (data:NSData?, res:NSURLResponse?, error:NSError?) -> Void in if let error = error { print("Request failed with error \(error)") return; } guard let data = data, let stringData = String(data: data, encoding: NSUTF8StringEncoding) else { print("response is empty") return; } do { let jsonDecoded = try JSONDecoder().decode(stringData) if let jsonMap = jsonDecoded as? JSONDictionaryType { if let _ = jsonMap["commentId"] as? Int { dispatch_async(dispatch_get_main_queue(), { self.didComment() }) } } } catch let exception { print("JSON decoding failed with exception \(exception)") } }) task.resume() } private func didComment() { commentTextView.text = nil commentTextView.resignFirstResponder() doScrollBottom = true fetchData() } } extension BbsDetailViewController : UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let commentArray = commentArray else { return 0 } return commentArray.array.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { cellForHeight.prepareForReuse() configureCell(cellForHeight, indexPath: indexPath) return cellForHeight.fittingSizeForWith(view.frame.width).height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(BbsDetailTableViewCell.identifierForReuse, forIndexPath: indexPath) as! BbsDetailTableViewCell configureCell(cell, indexPath: indexPath) return cell } func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } private func configureCell(cell: BbsDetailTableViewCell, indexPath: NSIndexPath) { if let commentArray = commentArray, let comment = commentArray.array[indexPath.row] as? JSONDictionaryType { cell.item = comment.dictionary } } }
951b521251695541b03c0af62615c0e7
37.569106
180
0.611404
false
false
false
false
CanyFrog/HCComponent
refs/heads/master
HCSource/HCProgressView.swift
mit
1
// // HCProgressView.swift // HCComponents // // Created by Magee Huang on 5/9/17. // Copyright © 2017 Person Inc. All rights reserved. // // tips progressview import UIKit /// Progress view open class HCProgressView: UIView { public enum progressStyle{ case pie case ring } open var progress: CGFloat = 0.0 { willSet { if progress != newValue { setNeedsDisplay() } } } open var progressTintColor = UIColor.white { willSet { if progressTintColor != newValue && !progressTintColor.isEqual(newValue) { setNeedsDisplay() } } } open var backgroundTintColor = UIColor.white { willSet { if backgroundTintColor != newValue && !backgroundTintColor.isEqual(newValue) { setNeedsDisplay() } } } public var style: progressStyle = .ring public var lineWidth: CGFloat = 2.0 open override var intrinsicContentSize: CGSize { return CGSize(width: 37, height: 37) } public override init(frame: CGRect) { super.init(frame: frame) backgroundTintColor = UIColor.clear isOpaque = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func draw(_ rect: CGRect) { // back let processBackPath = UIBezierPath() processBackPath.lineWidth = lineWidth processBackPath.lineCapStyle = .round let centerPoint = CGPoint(x: centerX, y: centerY) let radius = (width - lineWidth) / 2 let startAngle = -CGFloat.pi/2 var endAngle = startAngle + CGFloat.pi * 2 processBackPath.addArc(withCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) backgroundTintColor.set() processBackPath.stroke() // process let processPath = UIBezierPath() processPath.lineCapStyle = .square processPath.lineWidth = lineWidth endAngle = progress * 2 * CGFloat.pi + startAngle processPath.addArc(withCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) progressTintColor.set() if style == .ring { processPath.stroke() } else { processPath.addLine(to: centerPoint) processPath.close() processPath.fill() } } } /// Tips progress view open class HCTipsProgessView: HCTipsView { public private(set) var progressView: HCProgressView = { let progress = HCProgressView(frame: CGRect.zero) progress.backgroundTintColor = UIColor.darkGray progress.progressTintColor = UIColor.red progress.style = .ring return progress }() public var progress: CGFloat = 0.0 { didSet { progressView.progress = progress } } public override init(frame: CGRect) { super.init(frame: frame) addArrangedSubview(progressView) stackInsert = UIEdgeInsetsMake(12, 12, 12, 12) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult public class func show(progress: CGFloat = 0.0, in view: UIView, animation: HCTipsAnimationType = .none) -> HCTipsProgessView { let tips = HCTipsProgessView(in: view) tips.progress = progress tips.showTipsView(animation) return tips } }
f7696b71bb0f248c9d411ecbf4eac6db
27.88189
132
0.60687
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Fitting/Cargo/FittingCargoActions.swift
lgpl-2.1
2
// // FittingCargoActions.swift // Neocom // // Created by Artem Shimanski on 4/17/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp struct FittingCargoActions: View { @ObservedObject var ship: DGMShip @ObservedObject var cargo: DGMCargo var completion: () -> Void @Environment(\.managedObjectContext) private var managedObjectContext @State private var selectedType: SDEInvType? @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState @State private var isEditing = false var body: some View { let type = cargo.type(from: managedObjectContext) let perItem = Double(cargo.volume) / Double(cargo.quantity) let bind = Binding<String>(get: { "\(self.cargo.quantity)" }) { (newValue) in self.cargo.quantity = NumberFormatter().number(from: newValue)?.intValue ?? 0 } return List { Button(action: {self.selectedType = type}) { HStack { type.map{Icon($0.image).cornerRadius(4)} type?.typeName.map{Text($0)} ?? Text("Unknown") } }.buttonStyle(PlainButtonStyle()) HStack { Text("Volume") Spacer() CargoVolume(ship: ship, cargo: cargo).foregroundColor(.secondary) } HStack { Text("Per Item") Spacer() Text(UnitFormatter.localizedString(from: perItem, unit: .cubicMeter, style: .long)).foregroundColor(.secondary) } HStack { Text("Quantity") Spacer() // TextField(<#T##title: StringProtocol##StringProtocol#>, text: <#T##Binding<String>#>, onEditingChanged: <#T##(Bool) -> Void#>, onCommit: <#T##() -> Void#>) TextField(NSLocalizedString("Quantity", comment:""), text: bind, onEditingChanged: { isEditing in withAnimation { self.isEditing = isEditing } }) .textFieldStyle(RoundedBorderTextFieldStyle()) .keyboardType(.numberPad) .frame(width: 100) .multilineTextAlignment(.center) Stepper("Quantity", value: $cargo.quantity).labelsHidden() if isEditing { Button(NSLocalizedString("Done", comment: "")) { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }.buttonStyle(BorderlessButtonStyle()).fixedSize() } else { Button(NSLocalizedString("Max", comment: "")) { let free = self.ship.cargoCapacity - self.ship.usedCargoCapacity + self.cargo.volume let qty = (free / perItem).rounded(.down) self.cargo.quantity = Int(max(qty, 1)) }.buttonStyle(BorderlessButtonStyle()).fixedSize() } } } .listStyle(GroupedListStyle()) .navigationBarTitle(Text("Actions")) .navigationBarItems(leading: BarButtonItems.close(completion), trailing: BarButtonItems.trash { self.completion() DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { self.ship.remove(self.cargo) } }) .sheet(item: $selectedType) { type in NavigationView { TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil}) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } #if DEBUG struct FittingCargoActions_Previews: PreviewProvider { static var previews: some View { let ship = DGMShip.testDominix() let cargo = ship.cargo[0] cargo.quantity = 10 return FittingCargoActions(ship: ship, cargo: cargo) {} .modifier(ServicesViewModifier.testModifier()) } } #endif
f49c1c025da31c816be4aff8df3f3ae3
37.936937
173
0.558769
false
false
false
false
alvinvarghese/Natalie
refs/heads/master
NatalieExample/NatalieExample/MainViewController.swift
mit
4
// // ViewController.swift // NatalieExample // // Created by Marcin Krzyzanowski on 15/04/15. // Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved. // import UIKit class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } //MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == MainViewController.Segue.ScreenOneSegue, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.yellowColor() } else if segue == MainViewController.Segue.ScreenOneSegueButton, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.brownColor() } else if segue == MainViewController.Segue.ScreenTwoSegue, let twoViewController = segue.destinationViewController as? ScreenTwoViewController { twoViewController.view.backgroundColor = UIColor.magentaColor() } else if segue == MainViewController.Segue.SceneOneGestureRecognizerSegue, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.greenColor() } } //MARK: Actions @IBAction func screen1ButtonPressed(button:UIButton) { self.performSegue(MainViewController.Segue.ScreenOneSegue) } @IBAction func screen22ButtonPressed(button:UIButton) { self.performSegue(MainViewController.Segue.ScreenTwoSegue, sender: nil) } }
1bf295334da431600eefe630a090d404
38.642857
169
0.737538
false
false
false
false
pourhadi/SuperSerial
refs/heads/master
Example/SuperSerialPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit import SuperSerial struct Person { let name:String let age:Int } extension Person: AutoSerializable { init?(withValuesForKeys:[String:Serializable]) { guard let name = withValuesForKeys["name"] as? String else { return nil } guard let age = withValuesForKeys["age"] as? Int else { return nil } self.name = name self.age = age } } let person = Person(name:"Bob", age:20) let serialized = person.ss_serialize() print(serialized)
3dd1e7325412f5195d9c01a424b58b6c
21.24
81
0.660072
false
false
false
false
scarviz/SampleBLEforiOS
refs/heads/master
SampleBLE/PeripheralManagerDelegate.swift
mit
1
// // PeripheralManagerDelegate.swift // SampleBLE // // Created by scarviz on 2014/09/08. // Copyright (c) 2014年 scarviz. All rights reserved. // import CoreBluetooth class PeripheralManagerDelegate : NSObject, CBPeripheralManagerDelegate{ /* BLEの状態変更時処理 */ func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!){ if (peripheral.state == CBPeripheralManagerState.PoweredOn) { NSLog("state PoweredOn") } } /* PeripheralManager登録完了時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didAddService service: CBService!, error: NSError!) { if error != nil { NSLog(error.localizedFailureReason!) return } var name = "SampleBLE" // アドバタイズを開始する peripheral.startAdvertising( [CBAdvertisementDataLocalNameKey:name , CBAdvertisementDataServiceUUIDsKey:[service.UUID] ]) NSLog("start Advertising") } /* アドバタイズ開始後処理 */ func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager!, error: NSError!) { if error != nil { NSLog(error.localizedFailureReason!) } else { NSLog("DidStartAdvertising no error") } } /* CentralからのRead要求時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didReceiveReadRequest request: CBATTRequest!) { // ReadでCentralに返す値(テスト用) var val:Byte = 0x10 request.value = NSData(bytes: &val, length: 1) // Centralに返す peripheral.respondToRequest(request, withResult: CBATTError.Success) } /* CentralからのWrite要求時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didReceiveWriteRequests requests: [AnyObject]!) { for item in requests { // Centralからのデータ取得 var res = NSString(data: item.value, encoding: NSUTF8StringEncoding) // TODO:取得したデータを処理する } } }
6a2b64283225d25d69603ad6f6d4d96c
27.136986
114
0.622017
false
false
false
false
ello/ello-ios
refs/heads/master
Specs/Controllers/Onboarding/OnboardingProfileScreenSpec.swift
mit
1
//// /// OnboardingProfileScreenSpec.swift // @testable import Ello import Quick import Nimble class OnboardingProfileScreenSpec: QuickSpec { class MockDelegate: OnboardingProfileDelegate { var didAssignName = false var didAssignBio = false var didAssignLinks = false var didAssignCoverImage = false var didAssignAvatar = false func present(controller: UIViewController) {} func dismissController() {} func assign(name: String?) -> ValidationState { didAssignName = true return (name?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(bio: String?) -> ValidationState { didAssignBio = true return (bio?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(links: String?) -> ValidationState { didAssignLinks = true return (links?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(coverImage: ImageRegionData) { didAssignCoverImage = true } func assign(avatarImage: ImageRegionData) { didAssignAvatar = true } } override func spec() { describe("OnboardingProfileScreen") { var subject: OnboardingProfileScreen! var delegate: MockDelegate! beforeEach { subject = OnboardingProfileScreen() delegate = MockDelegate() subject.delegate = delegate showView(subject) } context("snapshots") { validateAllSnapshots(named: "OnboardingProfileScreen") { return subject } } context("snapshots setting existing data") { validateAllSnapshots(named: "OnboardingProfileScreen with data") { subject.name = "name" subject.bio = "bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio" subject.links = "links links links links links links links links links links links links" subject.linksValid = true subject.coverImage = ImageRegionData( image: UIImage.imageWithColor( .blue, size: CGSize(width: 1000, height: 1000) )! ) subject.avatarImage = ImageRegionData(image: specImage(named: "specs-avatar")!) return subject } } context("setting text") { it("should notify delegate of name change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Name") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignName) == true } it("should notify delegate of bio change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Bio") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignBio) == true } it("should notify delegate of link change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Links") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignLinks) == true } it("should notify delegate of avatar change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .avatar, updateDelegate: true) expect(delegate.didAssignAvatar) == true } it("should notify delegate of coverImage change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .coverImage, updateDelegate: true) expect(delegate.didAssignCoverImage) == true } } } } }
75c4e779df757704b13e4e251ba72f66
40.470588
99
0.505167
false
false
false
false
LinDing/Positano
refs/heads/master
Positano/Extensions/UISegmentedControl+Yep.swift
mit
1
// // UISegmentedControl+Yep.swift // Yep // // Created by NIX on 16/8/3. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit extension UISegmentedControl { func yep_setTitleFont(_ font: UIFont, withPadding padding: CGFloat) { let attributes = [NSFontAttributeName: font] setTitleTextAttributes(attributes, for: .normal) var maxWidth: CGFloat = 0 for i in 0..<numberOfSegments { if let title = titleForSegment(at: i) { let width = (title as NSString).size(attributes: attributes).width + (padding * 2) maxWidth = max(maxWidth, width) } } for i in 0..<numberOfSegments { setWidth(maxWidth, forSegmentAt: i) } } }
5c7ce51fa3784a822fed57842b9a187c
23.15625
98
0.596378
false
false
false
false
inquisitiveSoft/SwiftCoreExtensions
refs/heads/dev
Extensions/String.swift
mit
1
// // String.swift // Syml // // Created by Harry Jordan on 26/08/2015. // Copyright © 2015 Inquisitive Software. All rights reserved. // import Foundation func NSRangeOfString(string: NSString!) -> NSRange { let range = NSRange(location: 0, length:string.length) return range } extension String { func isMatchedBy(_ pattern: String) -> Bool { do { let regex = try NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators) let matches = regex.numberOfMatches(in: self, options: [], range: NSRangeOfString(string: self as NSString)) return matches > 0 } catch {} return false } var numberOfWords: UInt { var numberOfWords: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: .byWords) { (_, _, _, _) in numberOfWords += 1 } return numberOfWords } var numberOfSentences: UInt { var numberOfSentences: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: [.bySentences, .substringNotRequired]) { (_, _, _, _) -> () in numberOfSentences += 1 } return numberOfSentences } var numberOfParagraphs: UInt { var numberOfParagraphs: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: [.byParagraphs, .substringNotRequired]) { (_, _, _, _) -> () in numberOfParagraphs += 1 } return numberOfParagraphs } var numberOfCharacters: UInt { return UInt(count) } var numberOfDecimalCharacters: Int { return numberOfCharacters(in: .decimalDigits) } func numberOfCharacters(in characterSet: CharacterSet, minimumRun: Int = 0) -> Int { var numberOfMatchingCharacters = 0 let scanner = Scanner(string: self) repeat { scanner.scanUpToCharacters(from: characterSet, into: nil) var matchingString: NSString? = nil if !scanner.isAtEnd && scanner.scanCharacters(from: characterSet, into: &matchingString), let matchingString = matchingString { numberOfMatchingCharacters += matchingString.length } } while (!scanner.isAtEnd) return numberOfMatchingCharacters } var looksLikeAnIdentifier: Bool { let knownPrefixes = ["text-"] var numberOfIdentifierCharacters = knownPrefixes.filter { self.hasPrefix($0) }.reduce(0) { $0 + $1.count } let identifierCharacterSets: [CharacterSet] = [ CharacterSet.decimalDigits, CharacterSet(charactersIn: "–-_"), CharacterSet.uppercaseLetters ] var combinedIdentifierCharacterSet = CharacterSet() for characterSet in identifierCharacterSets { combinedIdentifierCharacterSet.formUnion(characterSet) } numberOfIdentifierCharacters += self.numberOfCharacters(in: combinedIdentifierCharacterSet, minimumRun: 5) let stringLength = self.count if (stringLength > 0) && (numberOfIdentifierCharacters > 0) && (Double(numberOfIdentifierCharacters) / Double(stringLength) > 0.55) { return true } return false } func firstLine(upToCharacter desiredNumberOfCharacters: Int) -> String { var numberOfCharacters = 0 var desiredRange: Range = startIndex..<endIndex enumerateLines { (line, stop) -> () in if !line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { line.enumerateSubstrings(in: line.startIndex..<line.endIndex, options: [.byWords]) { (substring, _, enclosingRange, stopInternal) -> () in desiredRange = line.startIndex..<enclosingRange.upperBound numberOfCharacters += substring?.count ?? 0 if numberOfCharacters >= desiredNumberOfCharacters { stopInternal = true } } stop = true } } let resultingString = self[desiredRange].trimmingCharacters(in: .whitespacesAndNewlines) return resultingString } func substringForUntestedRange(range: NSRange) -> String? { let text = self as NSString let textRange = NSRangeOfString(string: text) let validRange = NSIntersectionRange(textRange, range) if validRange.length > 0 { return text.substring(with: validRange) } return nil } // MARK: String localization var localized: String { get { return localized() } } func localized(comment: String = "") -> String { return NSLocalizedString(self, comment: comment) } }
fae680b0787200a361ca552886cd61d2
29.881657
154
0.583062
false
false
false
false
winkelsdorf/SwiftWebViewProgress
refs/heads/master
SwiftWebViewProgress/SwiftWebViewProgress/SwiftWebViewProgress.swift
mit
1
// // SwiftWebViewProgress.swift // SwiftWebViewProgress // // Created by Daichi Ichihara on 2014/12/03. // Copyright (c) 2014 MokuMokuCloud. All rights reserved. // import UIKit protocol WebViewProgressDelegate { func webViewProgress(webViewProgress: WebViewProgress, updateProgress progress: Float) } class WebViewProgress: NSObject, UIWebViewDelegate { var progressDelegate: WebViewProgressDelegate? var webViewProxyDelegate: UIWebViewDelegate? var progress: Float = 0.0 private var loadingCount: Int! private var maxLoadCount: Int! private var currentUrl: NSURL? private var interactive: Bool! private let InitialProgressValue: Float = 0.1 private let InteractiveProgressValue: Float = 0.5 private let FinalProgressValue: Float = 0.9 private let completePRCURLPath = "/webviewprogressproxy/complete" // MARK: Initializer override init() { super.init() maxLoadCount = 0 loadingCount = 0 interactive = false } // MARK: Private Method private func startProgress() { if progress < InitialProgressValue { setProgress(InitialProgressValue) } } private func incrementProgress() { var progress = self.progress var maxProgress = interactive == true ? FinalProgressValue : InteractiveProgressValue let remainPercent = Float(loadingCount / maxLoadCount) let increment = (maxProgress - progress) / remainPercent progress += increment progress = fmin(progress, maxProgress) setProgress(progress) } private func completeProgress() { setProgress(1.0) } private func setProgress(progress: Float) { if progress > self.progress || progress == 0 { self.progress = progress progressDelegate?.webViewProgress(self, updateProgress: progress) } } // MARK: Public Method func reset() { maxLoadCount = 0 loadingCount = 0 interactive = false setProgress(0.0) } // MARK: - UIWebViewDelegate func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL!.path == completePRCURLPath { completeProgress() return false } var ret = true if webViewProxyDelegate!.respondsToSelector("webView:shouldStartLoadWithRequest:navigationType:") { ret = webViewProxyDelegate!.webView!(webView, shouldStartLoadWithRequest: request, navigationType: navigationType) } var isFragmentJump = false if let fragmentURL = request.URL?.fragment { let nonFragmentURL = request.URL?.absoluteString?.stringByReplacingOccurrencesOfString("#"+fragmentURL, withString: "") isFragmentJump = nonFragmentURL == webView.request!.URL?.absoluteString } var isTopLevelNavigation = request.mainDocumentURL! == request.URL var isHTTP = request.URL?.scheme == "http" || request.URL?.scheme == "https" if ret && !isFragmentJump && isHTTP && isTopLevelNavigation { currentUrl = request.URL reset() } return ret } func webViewDidStartLoad(webView: UIWebView) { if webViewProxyDelegate!.respondsToSelector("webViewDidStartLoad:") { webViewProxyDelegate!.webViewDidStartLoad!(webView) } loadingCount = loadingCount + 1 maxLoadCount = Int(fmax(Double(maxLoadCount), Double(loadingCount))) startProgress() } func webViewDidFinishLoad(webView: UIWebView) { if webViewProxyDelegate!.respondsToSelector("webViewDidFinishLoad:") { webViewProxyDelegate!.webViewDidFinishLoad!(webView) } loadingCount = loadingCount - 1 // incrementProgress() let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState") var interactive = readyState == "interactive" if interactive { self.interactive = true let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);" webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS) } var isNotRedirect: Bool if let _currentUrl = currentUrl { if _currentUrl == webView.request?.mainDocumentURL { isNotRedirect = true } else { isNotRedirect = false } } else { isNotRedirect = false } var complete = readyState == "complete" if complete && isNotRedirect { completeProgress() } } func webView(webView: UIWebView, didFailLoadWithError error: NSError) { if webViewProxyDelegate!.respondsToSelector("webView:didFailLoadWithError:") { webViewProxyDelegate!.webView!(webView, didFailLoadWithError: error) } loadingCount = loadingCount - 1 // incrementProgress() let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState") var interactive = readyState == "interactive" if interactive { self.interactive = true let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);" webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS) } var isNotRedirect: Bool if let _currentUrl = currentUrl { if _currentUrl == webView.request?.mainDocumentURL { isNotRedirect = true } else { isNotRedirect = false } } else { isNotRedirect = false } var complete = readyState == "complete" if complete && isNotRedirect { completeProgress() } } }
9df329aceef447509dbe206f04cde179
35.366667
331
0.615076
false
false
false
false
Sajjon/Zeus
refs/heads/master
Pods/Alamofire/Source/TaskDelegate.swift
apache-2.0
2
// // Error.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as /// executing all operations attached to the serial operation queue upon task completion. open class TaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. open let queue: OperationQueue var task: URLSessionTask let progress: Progress var data: Data? { return nil } var error: NSError? var initialResponseTime: CFAbsoluteTime? var credential: URLCredential? // MARK: Lifecycle init(task: URLSessionTask) { self.task = task self.progress = Progress(totalUnitCount: 0) self.queue = { let operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true operationQueue.qualityOfService = .utility return operationQueue }() } // MARK: NSURLSessionTaskDelegate var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? var taskDidCompleteWithError: ((URLSession, URLSessionTask, NSError?) -> Void)? @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } @objc(URLSession:task:didReceiveChallenge:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } else { if challenge.previousFailureCount > 0 { disposition = .rejectProtectionSpace } else { credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) if credential != nil { disposition = .useCredential } } } completionHandler(disposition, credential) } @objc(URLSession:task:needNewBodyStream:) func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { var bodyStream: InputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { self.error = error if let downloadDelegate = self as? DownloadTaskDelegate, let resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData] as? Data { downloadDelegate.resumeData = resumeData } } queue.isSuspended = false } } } // MARK: - class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { // MARK: Properties var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask } override var data: Data? { if dataStream != nil { return nil } else { return mutableData as Data } } var dataProgress: ((_ bytesReceived: Int64, _ totalBytesReceived: Int64, _ totalBytesExpectedToReceive: Int64) -> Void)? var dataStream: ((_ data: Data) -> Void)? private var totalBytesReceived: Int64 = 0 private var mutableData: Data private var expectedContentLength: Int64? // MARK: Lifecycle override init(task: URLSessionTask) { mutableData = Data() super.init(task: task) } // MARK: NSURLSessionDataDelegate var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: ((URLSession.ResponseDisposition) -> Void)) { var disposition: URLSession.ResponseDisposition = .allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data) } else { mutableData.append(data) } let bytesReceived = Int64(data.count) totalBytesReceived += bytesReceived let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived dataProgress?( bytesReceived, totalBytesReceived, totalBytesExpected ) } } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: ((CachedURLResponse?) -> Void)) { var cachedResponse: CachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } // MARK: - class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { // MARK: Properties var downloadTask: URLSessionDownloadTask? { return task as? URLSessionDownloadTask } var downloadProgress: ((Int64, Int64, Int64) -> Void)? var resumeData: Data? override var data: Data? { return resumeData } // MARK: NSURLSessionDownloadDelegate var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { do { let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) try FileManager.default.moveItem(at: location, to: destination) } catch { self.error = error as NSError } } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData( session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite ) } else { progress.totalUnitCount = totalBytesExpectedToWrite progress.completedUnitCount = totalBytesWritten downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } } func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else { progress.totalUnitCount = expectedTotalBytes progress.completedUnitCount = fileOffset } } } // MARK: - class UploadTaskDelegate: DataTaskDelegate { // MARK: Properties var uploadTask: URLSessionUploadTask? { return task as? URLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: NSURLSessionTaskDelegate var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? func URLSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } }
886b784bd8a980decf5f42d9a56725f7
34.92973
149
0.670679
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
refs/heads/master
Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Generators/RSTBChoiceStepGenerator.swift
apache-2.0
1
// // RSTBChoiceStepGenerator.swift // Pods // // Created by James Kizer on 1/9/17. // // import ResearchKit import Gloss open class RSTBChoiceStepGenerator: RSTBQuestionStepGenerator { open var allowsMultiple: Bool { fatalError("abstract class not implemented") } public typealias ChoiceItemFilter = ( (RSTBChoiceItemDescriptor) -> (Bool)) open func generateFilter(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ChoiceItemFilter? { return { choiceItem in return true } } open func generateChoices(items: [RSTBChoiceItemDescriptor], valueSuffix: String?, shouldShuffle: Bool?) -> [ORKTextChoice] { let shuffledItems = items.shuffled(shouldShuffle: shouldShuffle ?? false) return shuffledItems.map { item in let value: NSCoding & NSCopying & NSObjectProtocol = ({ if let suffix = valueSuffix, let stringValue = item.value as? String { return (stringValue + suffix) as NSCoding & NSCopying & NSObjectProtocol } else { return item.value } }) () return ORKTextChoice( text: item.text, detailText: item.detailText, value: value, exclusive: item.exclusive) } } override open func generateAnswerFormat(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKAnswerFormat? { guard let choiceStepDescriptor = RSTBChoiceStepDescriptor(json: jsonObject) else { return nil } let filteredItems: [RSTBChoiceItemDescriptor] = { if let itemFilter = self.generateFilter(type: type, jsonObject: jsonObject, helper: helper) { return choiceStepDescriptor.items.filter(itemFilter) } else { return choiceStepDescriptor.items } }() let choices = self.generateChoices(items: filteredItems, valueSuffix: choiceStepDescriptor.valueSuffix, shouldShuffle: choiceStepDescriptor.shuffleItems) guard choices.count > 0 else { return nil } let answerFormat = ORKAnswerFormat.choiceAnswerFormat( with: self.allowsMultiple ? ORKChoiceAnswerStyle.multipleChoice : ORKChoiceAnswerStyle.singleChoice, textChoices: choices ) return answerFormat } open override func processQuestionResult(type: String, result: ORKQuestionResult, helper: RSTBTaskBuilderHelper) -> JSON? { if let result = result as? ORKChoiceQuestionResult, let choices = result.choiceAnswers as? [NSCoding & NSCopying & NSObjectProtocol] { return [ "identifier": result.identifier, "type": type, "answer": choices ] } return nil } } open class RSTBSingleChoiceStepGenerator: RSTBChoiceStepGenerator { public override init(){} override open var supportedTypes: [String]! { return ["singleChoiceText"] } override open var allowsMultiple: Bool { return false } } open class RSTBMultipleChoiceStepGenerator: RSTBChoiceStepGenerator { public override init(){} override open var supportedTypes: [String]! { return ["multipleChoiceText"] } override open var allowsMultiple: Bool { return true } }
adfa15082767e4eee601eb50f5bbfb22
29.347107
161
0.590959
false
false
false
false
robbdimitrov/pixelgram-ios
refs/heads/master
PixelGram/Classes/Screens/Feed/FeedViewController.swift
mit
1
// // FeedViewController.swift // PixelGram // // Created by Robert Dimitrov on 10/27/17. // Copyright © 2017 Robert Dimitrov. All rights reserved. // import UIKit import RxSwift import RxCocoa class FeedViewController: CollectionViewController { var viewModel = FeedViewModel() private var dataSource: CollectionViewDataSource? private var selectedIndex: Int? // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() setupRefreshControl() setupViewModel() setupUserLoadedNotification() setupLogoutNotification() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if viewModel.numberOfItems <= 0 { viewModel.loadData() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: collectionView.frame.width) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) displayLoginScreen() } // MARK: - Notifications private func setupLogoutNotification() { NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: APIClient.UserLoggedInNotification), object: APIClient.shared, queue: nil, using: { [weak self] notification in self?.viewModel.page = 0 self?.viewModel.images.value.removeAll() self?.displayLoginScreen() }) } private func setupUserLoadedNotification() { NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: UserLoader.UserLoadedNotification), object: UserLoader.shared, queue: nil, using: { [weak self] notification in guard let user = notification.userInfo?["user"] as? User else { return } self?.reloadVisibleCells(user.id) }) } // MARK: - Data override func handleRefresh(_ sender: UIRefreshControl) { viewModel.page = 0 if viewModel.type != .single { viewModel.images.value.removeAll() } viewModel.loadData() } private func reloadVisibleCells(_ userId: String) { guard let collectionView = collectionView else { return } let visibleCells = collectionView.visibleCells for cell in visibleCells { if let cell = cell as? ImageViewCell, cell.viewModel?.image.owner == userId, let indexPath = collectionView.indexPath(for: cell) { setupCell(cell, forIndexPath: indexPath) } } } private func createDataSource() -> CollectionViewDataSource { let dataSource = CollectionViewDataSource(configureCell: { [weak self] (collectionView, indexPath) -> UICollectionViewCell in if indexPath.row == (self?.viewModel.images.value.count ?? 0) - 1 { self?.viewModel.loadData() } return (self?.configureCell(collectionView: collectionView, indexPath: indexPath))! }, numberOfItems: { [weak self] (collectionView, section) -> Int in return self?.viewModel.numberOfItems ?? 0 }) return dataSource } // MARK: - Cells private func configureCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageViewCell.reuseIdentifier, for: indexPath) setupCell(cell, forIndexPath: indexPath) return cell } private func setupCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) { guard let cell = cell as? ImageViewCell else { return } let imageViewModel = viewModel.imageViewModel(forIndex: indexPath.row) cell.configure(with: imageViewModel) cell.userButton?.rx.tap.subscribe(onNext: { [weak self] in self?.openUserProfile(atIndex: indexPath.row) }).disposed(by: cell.disposeBag) cell.likesButton?.rx.tap.subscribe(onNext: { [weak self] in self?.openLikedUsers(selectedIndex: indexPath.row) }).disposed(by: cell.disposeBag) cell.optionsButton?.rx.tap.subscribe(onNext: { [weak self] in self?.selectedIndex = indexPath.row self?.openOptions() }).disposed(by: cell.disposeBag) } private func updateCells(oldCount: Int, count: Int) { guard let collectionView = collectionView else { return } if oldCount == count { refreshCells(collectionView: collectionView) } else if oldCount < count { insertCells(collectionView: collectionView, oldCount: oldCount, count: count) } else if oldCount > count { collectionView.reloadData() } } private func insertCells(collectionView: UICollectionView, oldCount: Int, count: Int) { var indexPaths = [IndexPath]() for index in oldCount...(count - 1) { let indexPath = IndexPath(row: index, section: 0) indexPaths.append(indexPath) } if oldCount == 0 { collectionView.reloadData() } else { collectionView.insertItems(at: indexPaths) } } private func refreshCells(collectionView: UICollectionView) { for cell in collectionView.visibleCells { if let indexPath = collectionView.indexPath(for: cell) { setupCell(cell, forIndexPath: indexPath) } } } // MARK: - Config private func setupViewModel() { viewModel.loadingFinished = { [weak self] (oldCount, count) in if self?.collectionView?.refreshControl?.isRefreshing ?? false { self?.collectionView?.refreshControl?.endRefreshing() } self?.updateCells(oldCount: oldCount, count: count) } viewModel.loadingFailed = { [weak self] error in self?.showError(error: error) } } private func setupRefreshControl() { collectionView?.alwaysBounceVertical = true collectionView?.refreshControl = refreshControl } override func setupNavigationItem() { super.setupNavigationItem() title = viewModel.title if viewModel.type == .feed, let image = UIImage(named: "logo") { setupTitleView(with: image) } } override func configureCollectionView() { guard let collectionView = collectionView else { print("Error: collection view is nil") return } let dataSource = createDataSource() self.dataSource = dataSource collectionView.dataSource = dataSource } // MARK: - Actions private func displayLoginScreen() { if Session.shared.currentUser == nil { let viewController = instantiateViewController(withIdentifier: LoginViewController.storyboardIdentifier) present(NavigationController(rootViewController: viewController), animated: true, completion: nil) } } private func openOptions() { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) // Cancel action alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) // Delete action alertController.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] action in self?.deleteAction() }) present(alertController, animated: true, completion: nil) } private func deleteAction() { let alertController = UIAlertController(title: "Delete Post?", message: "Do you want to delete the post permanently?", preferredStyle: .alert) // Cancel action alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) // Delete action alertController.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] action in if let selectedIndex = self?.selectedIndex { self?.deleteImage(atIndex: selectedIndex) self?.selectedIndex = nil } }) present(alertController, animated: true, completion: nil) } private func deleteImage(atIndex index: Int) { let imageId = viewModel.images.value[index].id let indexPath = IndexPath(row: index, section: 0) view.window?.showLoadingHUD() APIClient.shared.deleteImage(withId: imageId, completion: { [weak self] in self?.view.window?.hideLoadingHUD() self?.viewModel.images.value.remove(at: index) self?.collectionView?.deleteItems(at: [indexPath]) if self?.viewModel.type == .single, self?.viewModel.numberOfItems == 0 { self?.navigationController?.popViewController(animated: true) } }) { [weak self] error in self?.view.window?.hideLoadingHUD() self?.showError(error: error) } } // MARK: - Navigation private func openUserProfile(atIndex index: Int) { let imageOwner = viewModel.images.value[index].owner openUserProfile(withUserId: imageOwner) } private func openUserProfile(withUserId userId: String) { let viewController = instantiateViewController(withIdentifier: ProfileViewController.storyboardIdentifier) (viewController as? ProfileViewController)?.userId = userId navigationController?.pushViewController(viewController, animated: true) } private func openLikedUsers(selectedIndex: Int) { let image = viewModel.images.value[selectedIndex] if image.likes < 1 { return } let viewController = instantiateViewController(withIdentifier: UsersViewController.storyboardIdentifier) (viewController as? UsersViewController)?.viewModel = UsersViewModel(with: image.id) navigationController?.pushViewController(viewController, animated: true) } // MARK: - Object lifecycle deinit { NotificationCenter.default.removeObserver(self) } }
3bee4b0ef7ae03fa157836a0a8853d63
34.163462
142
0.611977
false
false
false
false
hnney/SwiftReeder
refs/heads/master
SwiftReeder/Core/FeedManager.swift
apache-2.0
2
// // FeedManager.swift // SwiftReeder // // Created by Thilong on 14/6/5. // Copyright (c) 2014年 thilong. All rights reserved. // import Foundation var global_FeedManager : FeedManager! class FeedManager{ var _data : NSMutableArray = NSMutableArray() class func sharedManager()->FeedManager!{ if !global_FeedManager{ global_FeedManager = FeedManager() } return global_FeedManager; } init(){ } func addFeed(feed : Feed){ for fe : AnyObject in self._data { if fe.name == feed.name{ return; } } self._data.addObject(feed); self.saveAllFeeds(); } func removeFeedAtIndex(index : Int){ self._data.removeObjectAtIndex(index); self.saveAllFeeds(); } func feedsCount()->Int{ return self._data.count; } func feedAtIndex(index : Int)->Feed!{ return self._data.objectAtIndex(index) as Feed; } func saveAllFeeds(){ var path : String! = OCBridge.feedCachePath(false); if path{ NSFileManager.defaultManager().removeItemAtPath(path,error:nil); } NSKeyedArchiver.archiveRootObject(_data,toFile: path); } func loadAllFeeds(){ var path : String! = OCBridge.feedCachePath(true); if path{ var arrays = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as NSArray; _data.addObjectsFromArray(arrays); } } }
4567755e4429175870917f4d31d08a8a
21.652174
84
0.567222
false
false
false
false
Hout/DateInRegion
refs/heads/master
Pod/Classes/DateInRegionDescription.swift
mit
1
// // DateInRegionDescription.swift // Pods // // Created by Jeroen Houtzager on 26/10/15. // // import Foundation // MARK: - CustomStringConvertable delegate extension DateInRegion : CustomDebugStringConvertible { /// Returns a full description of the class /// public var description: String { return "\(self.toString()!); region: \(region)" } /// Returns a full debug description of the class /// public var debugDescription: String { var descriptor: [String] = [] let formatter = NSDateFormatter() formatter.dateStyle = .LongStyle formatter.timeStyle = .LongStyle formatter.locale = self.locale formatter.calendar = self.calendar formatter.timeZone = NSTimeZone(abbreviation: "UTC") descriptor.append("UTC\t\(formatter.stringFromDate(self.date))") formatter.timeZone = self.timeZone descriptor.append("Local\t\(formatter.stringFromDate(self.date))") descriptor.append("Calendar: \(calendar.calendarIdentifier)") descriptor.append("Time zone: \(timeZone.name)") descriptor.append("Locale: \(locale.localeIdentifier)") return descriptor.joinWithSeparator("\n") } }
ee9dc43a5d68a5a398ec22214f0cc6d3
26.488889
74
0.658852
false
false
false
false
stomp1128/TIY-Assignments
refs/heads/master
TackyTacTac/TackyTacTac/ViewController.swift
cc0-1.0
1
// // ViewController.swift // TackyTacTac // // Created by Chris Stomp on 10/26/15. // Copyright © 2015 The Iron Yard. All rights reserved. // // //import UIKit // //class ViewController: UIViewController { // // var grid = [[0,0,0], [0,0,0], [0,0,0]] //2 // // var isPlayer1Turn = true // step 2 set the rest of the properties // // var player1Score = 0 //2 // var player2Score = 0 //2 // var stalemateScore = 0 //2 // // let gameStatusLabel = UILabel(frame: CGRect(x: 0, y: 80, width: 200, height: 50)) //step 1 // // override func viewDidLoad() // { // super.viewDidLoad() // view.backgroundColor = UIColor.whiteColor() //step 3 background color // // gameStatusLabel.text = "Player 1 Turn" //step 4 // gameStatusLabel.textAlignment = .Center // // gameStatusLabel.center.x = view.center.x // // view.addSubview(gameStatusLabel) //step 5 add it as subview to make it visible on screen // // let screenHeight = Int(UIScreen.mainScreen().bounds.height) //step 6 // let screenWidth = Int(UIScreen.mainScreen().bounds.width) // // let buttonHW = 100 // let buttonSpacing = 4 // // let gridHW = (buttonHW * 3) + (buttonSpacing * 2) // // let leftSpacing = (screenWidth - gridHW) / 2 // let topSpacing = (screenHeight - gridHW) / 2 // // for (r, row) in grid.enumerate() // step 7 set up grid // { // for (c, _) in row.enumerate() // { // let x = c * (buttonHW + buttonSpacing) + leftSpacing // let y = r * (buttonHW + buttonSpacing) + topSpacing // let button = TTTButton(frame: CGRect(x: x, y: y, width: buttonHW, height: buttonHW)) //step 9 // button.backgroundColor = UIColor.cyanColor() // // button.row = r // button.col = c // // button.addTarget(self, action: "spacePressed:", forControlEvents: .TouchUpInside) // name of func in quotes, colon becuase it takes an argument // view.addSubview(button) // } // } // } // // override func didReceiveMemoryWarning() // { // super.didReceiveMemoryWarning() // // // MARK = Action Handlers // // func spacePressed(button: TTTButton) //step 10 // { // if button.player == 0 // { //// if isPlayer1Turn //// { //// button.player = 1 //// } //// else //// { //// button.player = 2 //// } // button.player = isPlayer1Turn ? 1 : 2 // // grid[button.row] [button.col] = isPlayer1Turn ? 1 : 2 //record which button has been pressed by which player // // isPlayer1Turn = !isPlayer1Turn // decide whose turn it is // // checkForWinner() //func to decide if there is a winner // // } // } // } // // // MARK - Misc. // // func checkForWinner() // { // let possibilities = [ // ((0,0),(0,1),(0,2)), // ((1,0),(1,1),(1,2)), // ((2,0),(2,1),(2,2)), // ((0,0),(1,0),(2,0)), // ((0,1),(1,1),(2,1)), // ((0,2),(1,2),(2,2)), // ((0,0),(1,1),(2,2)), // ((2,0),(1,1),(0,2)) // ] // // for possibility in possibilities // { // let (p1,p2,p3) = possibility // let value1 = grid[p1.0][p1.1] // let value2 = grid[p2.0][p2.1] // let value3 = grid[p3.0][p3.1] // // if value1 == value2 && value2 == value3 // { // if value1 != 0 // { // print("Player \(value1) wins!") // } // else // { // print("No winner: all zeros") // } // } // else // { // print("Does not match") // } // } // } // // //} // //class TTTButton: UIButton // step 8 set up new class and name it //{ // var row = 0 // var col = 0 // // var player = 0 { // didSet { // switch player { // case 1: backgroundColor = UIColor.magentaColor() // case 2: backgroundColor = UIColor.yellowColor() // default: backgroundColor = UIColor.cyanColor() // } // } // } // //} import UIKit class ViewController: UIViewController { var grid = [[0,0,0], [0,0,0], [0,0,0]] var playButtons = [TTTButton]() var isPlayer1Turn = true var player1Score = 0 var player2Score = 0 var stalemateScore = 0 let gameStatusLabel = UILabel(frame: CGRect(x: 0, y: 80, width: 200, height: 50)) let player1ScoreLabel = UILabel(frame: CGRect(x: 0, y: 560, width: 200, height: 50)) let player2ScoreLabel = UILabel(frame: CGRect(x: 0, y: 580, width: 200, height: 50)) let stalemateScoreLabel = UILabel(frame: CGRect(x: 0, y: 620, width: 200, height: 50)) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() gameStatusLabel.text = "Player 1 Turn" gameStatusLabel.textAlignment = .Center gameStatusLabel.center.x = view.center.x player1ScoreLabel.text = "Player 1 Score = 0" player1ScoreLabel.textAlignment = .Center player1ScoreLabel.center.x = view.center.x player2ScoreLabel.text = "Player 2 Score = 0" player2ScoreLabel.textAlignment = .Center player2ScoreLabel.center.x = view.center.x stalemateScoreLabel.text = "Stalemate = 0" stalemateScoreLabel.textAlignment = .Center stalemateScoreLabel.center.x = view.center.x let resetButton = UIButton(type: UIButtonType.System) as UIButton resetButton.frame = CGRectMake(0, 660, 100, 50) resetButton.backgroundColor = UIColor.cyanColor() resetButton.setTitle("Reset", forState: UIControlState.Normal) resetButton.addTarget(self, action: "resetButton:", forControlEvents: UIControlEvents.TouchUpInside) resetButton.center.x = view.center.x self.view.addSubview(resetButton) view.addSubview(gameStatusLabel) view.addSubview(player1ScoreLabel) view.addSubview(player2ScoreLabel) view.addSubview(stalemateScoreLabel) let screenHeight = Int(UIScreen.mainScreen().bounds.height) let screenWidth = Int(UIScreen.mainScreen().bounds.width) let buttonHW = 100 let buttonSpacing = 4 let gridHW = (buttonHW * 3) + (buttonSpacing * 2) let leftSpacing = (screenWidth - gridHW) / 2 let topSpacing = (screenHeight - gridHW) / 2 for (r, row) in grid.enumerate() { for (c, _) in row.enumerate() { let x = c * (buttonHW + buttonSpacing) + leftSpacing let y = r * (buttonHW + buttonSpacing) + topSpacing let button = TTTButton(frame: CGRect(x: x, y: y, width: buttonHW, height: buttonHW)) button.backgroundColor = UIColor.cyanColor() button.row = r button.col = c button.addTarget(self, action: "spacePressed:", forControlEvents: .TouchUpInside) view.addSubview(button) playButtons.append(button) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Action Handlers func spacePressed(button: TTTButton) { if button.player == 0 { // if isPlayer1Turn // { // button.player = 1 // } // else // { // button.player = 2 // } button.player = isPlayer1Turn ? 1 : 2 grid[button.row][button.col] = isPlayer1Turn ? 1 : 2 isPlayer1Turn = !isPlayer1Turn if isPlayer1Turn == true { gameStatusLabel.text = "Player 1 Turn" } if isPlayer1Turn == false { gameStatusLabel.text = "Player 2 Turn" } checkForWinner() } } func resetButton(sender:UIButton!) { for aButton in playButtons { grid = [[0,0,0], [0,0,0], [0,0,0]] aButton.player = 0 } } // MARK: - Misc. func checkForWinner() { var stalemateCount = 0 let possibilities = [ ((0,0),(0,1),(0,2)), ((1,0),(1,1),(1,2)), ((2,0),(2,1),(2,2)), ((0,0),(1,0),(2,0)), ((0,1),(1,1),(2,1)), ((0,2),(1,2),(2,2)), ((0,0),(1,1),(2,2)), ((2,0),(1,1),(0,2)) ] for possibility in possibilities { let (p1,p2,p3) = possibility let value1 = grid[p1.0][p1.1] let value2 = grid[p2.0][p2.1] let value3 = grid[p3.0][p3.1] if value1 == value2 && value2 == value3 { if value1 != 0 { //winner if value1 == 1 { gameStatusLabel.text = "Player \(value1) wins" player1Score++ player1ScoreLabel.text = "Player 1 Score = \(player1Score)" } else if value1 == 2 { gameStatusLabel.text = "Player \(value1) wins" player2Score++ player2ScoreLabel.text = "Player 2 Score = \(player2Score)" } } } else { if value1 != 0 && value2 != 0 && value3 != 0 { stalemateCount++ } } } if stalemateCount >= 7 { stalemateScore++ stalemateScoreLabel.text = "Stalemate = \(stalemateScore)" gameStatusLabel.text = "Stalemate" } } } class TTTButton: UIButton { var row = 0 var col = 0 var player = 0 { didSet { switch player { case 1: backgroundColor = UIColor.magentaColor() case 2: backgroundColor = UIColor.yellowColor() default: backgroundColor = UIColor.cyanColor() } } } func getRandomColor() -> UIColor { let randomRed:CGFloat = CGFloat(drand48()) let randomGreen:CGFloat = CGFloat(drand48()) let randomBlue:CGFloat = CGFloat(drand48()) return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0) } }
4e8d314a66755b98c8c2acbeab0321cb
28.886364
161
0.459738
false
false
false
false
mgsergio/omim
refs/heads/master
iphone/Maps/Classes/Components/ExpandableTextView/ExpandableTextView.swift
apache-2.0
1
import UIKit @IBDesignable final class ExpandableTextView: UIView { @IBInspectable var text: String = "" { didSet { guard oldValue != text else { return } update() } } @IBInspectable var textColor: UIColor? { get { return settings.textColor } set { settings.textColor = newValue ?? settings.textColor update() } } @IBInspectable var expandText: String { get { return settings.expandText } set { settings.expandText = newValue update() } } @IBInspectable var expandTextColor: UIColor? { get { return settings.expandTextColor } set { settings.expandTextColor = newValue ?? settings.expandTextColor update() } } @IBInspectable var numberOfCompactLines: Int { get { return settings.numberOfCompactLines } set { settings.numberOfCompactLines = newValue update() } } var textFont: UIFont { get { return settings.textFont } set { settings.textFont = newValue update() } } var settings = ExpandableTextViewSettings() { didSet { update() } } var onUpdate: (() -> Void)? override var frame: CGRect { didSet { guard frame.size != oldValue.size else { return } update() } } override var bounds: CGRect { didSet { guard bounds.size != oldValue.size else { return } update() } } private var isCompact = true { didSet { guard oldValue != isCompact else { return } update() } } private func createTextLayer() -> CALayer { let size: CGSize let container = CALayer() container.anchorPoint = CGPoint() container.contentsScale = UIScreen.main.scale if isCompact { size = text.size(width: frame.width, font: textFont, maxNumberOfLines: numberOfCompactLines) let fullSize = text.size(width: frame.width, font: textFont, maxNumberOfLines: 0) if size.height < fullSize.height { let expandSize = expandText.size(width: frame.width, font: textFont, maxNumberOfLines: 1) let layer = CATextLayer() layer.position = CGPoint(x: 0, y: size.height) layer.bounds = CGRect(origin: CGPoint(), size: expandSize) layer.anchorPoint = CGPoint() layer.string = expandText layer.font = CGFont(textFont.fontName as CFString) layer.fontSize = textFont.pointSize layer.foregroundColor = expandTextColor?.cgColor layer.contentsScale = UIScreen.main.scale container.addSublayer(layer) } } else { size = text.size(width: frame.width, font: textFont, maxNumberOfLines: 0) } let layer = CATextLayer() layer.bounds = CGRect(origin: CGPoint(), size: size) layer.anchorPoint = CGPoint() layer.string = text layer.isWrapped = true layer.truncationMode = kCATruncationEnd layer.font = CGFont(textFont.fontName as CFString) layer.fontSize = textFont.pointSize layer.foregroundColor = textColor?.cgColor layer.contentsScale = UIScreen.main.scale container.addSublayer(layer) var containerSize = CGSize() container.sublayers?.forEach { layer in containerSize.width = max(containerSize.width, layer.frame.maxX) containerSize.height = max(containerSize.height, layer.frame.maxY) } container.frame.size = containerSize return container } public override func awakeFromNib() { super.awakeFromNib() setup() } public convenience init() { self.init(frame: CGRect()) } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { layer.backgroundColor = UIColor.clear.cgColor isOpaque = true gestureRecognizers = nil addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap))) update() } private var viewSize = CGSize() private func updateImpl() { let sublayer = createTextLayer() layer.sublayers = [sublayer] viewSize = sublayer.bounds.size invalidateIntrinsicContentSize() onUpdate?() } @objc private func doUpdate() { DispatchQueue.main.async { self.updateImpl() } } func update() { let sel = #selector(doUpdate) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: sel, object: nil) perform(sel, with: nil, afterDelay: 1 / 120) } override var intrinsicContentSize: CGSize { return viewSize } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() updateImpl() } @objc private func onTap() { isCompact = false } }
d2f68bc560cd37bec7e76f6ad751ce56
23.721053
98
0.657654
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/MediaPackageVod/MediaPackageVod_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for MediaPackageVod public struct MediaPackageVodErrorType: AWSErrorType { enum Code: String { case forbiddenException = "ForbiddenException" case internalServerErrorException = "InternalServerErrorException" case notFoundException = "NotFoundException" case serviceUnavailableException = "ServiceUnavailableException" case tooManyRequestsException = "TooManyRequestsException" case unprocessableEntityException = "UnprocessableEntityException" } private let error: Code public let context: AWSErrorContext? /// initialize MediaPackageVod public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } public static var forbiddenException: Self { .init(.forbiddenException) } public static var internalServerErrorException: Self { .init(.internalServerErrorException) } public static var notFoundException: Self { .init(.notFoundException) } public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) } public static var unprocessableEntityException: Self { .init(.unprocessableEntityException) } } extension MediaPackageVodErrorType: Equatable { public static func == (lhs: MediaPackageVodErrorType, rhs: MediaPackageVodErrorType) -> Bool { lhs.error == rhs.error } } extension MediaPackageVodErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
646252e39e48d34569deaa8fead4b41d
37.227273
117
0.680539
false
false
false
false
siemensikkema/Fairness
refs/heads/master
FairnessTests/TransactionCalculatorTests.swift
mit
1
import XCTest class TransactionCalculatorTests: XCTestCase { class ParticipantTransactionModelForTesting: ParticipantTransactionModel { var didCallReset = false init() { super.init(participant: Participant(name: "")) } override func reset() { didCallReset = true } } var sut: TransactionCalculator! var notificationCenter: FairnessNotificationCenterForTesting! var participantTransactionModels: [ParticipantTransactionModelForTesting]! override func setUp() { notificationCenter = FairnessNotificationCenterForTesting() participantTransactionModels = [ParticipantTransactionModelForTesting(), ParticipantTransactionModelForTesting()] sut = TransactionCalculator(notificationCenter: notificationCenter) sut.participantTransactionModels = participantTransactionModels sut.togglePayerAtIndex(0) sut.togglePayeeAtIndex(1) sut.cost = 1.23 } } extension TransactionCalculatorTests { func testNumberOfParticipantTransactionModelsEqualsNumberOfParticipants() { XCTAssertEqual(sut.participantTransactionModels.count, 2) } func testHasPayerReturnsTrueWhenOneParticipantsIsPayer() { XCTAssertTrue(sut.hasPayer) } func testHasPayerReturnsFalseWhenNoParticipantsArePayer() { sut.togglePayerAtIndex(0) XCTAssertFalse(sut.hasPayer) } func testTransactionWithPayerAndPayeeAndNonZeroCostIsValid() { XCTAssertTrue(sut.isValid) } func testTransactionIsInvalidWithoutPayer() { sut.togglePayerAtIndex(0) XCTAssertFalse(sut.isValid) } func testTransactionIsInvalidWithoutPayee() { sut.togglePayeeAtIndex(1) XCTAssertFalse(sut.isValid) } func testTransactionIsInvalidWithZeroCost() { sut.cost = 0 XCTAssertFalse(sut.isValid) } func testTransactionIsInvalidWhenPayerIsTheOnlyPayee() { sut.togglePayeeAtIndex(0) sut.togglePayeeAtIndex(1) XCTAssertFalse(sut.isValid) } func testTransactionIsValidWhenPayerIsOneOfThePayees() { sut.togglePayeeAtIndex(0) XCTAssertTrue(sut.isValid) } func testTransactionAmountsForSimpleTransactionAreCorrect() { XCTAssertEqual(sut.participantTransactionModels.map { $0.amountOrNil! }, [1.23, -1.23]) } func testTransactionAmountsForSharedTransactionAreCorrect() { sut.togglePayeeAtIndex(0) XCTAssertEqual(sut.participantTransactionModels.map { $0.amountOrNil! }, [0.615, -0.615]) } func testAmounts() { XCTAssertEqual(sut.amounts, [1.23,-1.23]) } func testResetSetsCostToZero() { notificationCenter.transactionDidEndCallback?() XCTAssertEqual(sut.cost, 0.0) } func testResetResetsParticipantViewModels() { notificationCenter.transactionDidEndCallback?() XCTAssertEqual(participantTransactionModels.map { $0.didCallReset }, [true, true]) } }
bb6303fc9cd0bb5dc35f3503b5a7445f
29.535354
121
0.70814
false
true
false
false
elpassion/el-space-ios
refs/heads/master
ELSpaceTests/TestCases/ViewModels/ProjectSearchViewModelSpec.swift
gpl-3.0
1
@testable import ELSpace import Quick import Nimble import RxSwift import RxCocoa class ProjectSearchViewModelSpec: QuickSpec { override func spec() { describe("ProjectSearchViewModel") { var projectSearchController: ProjectSearchControllerStub! var sut: ProjectSearchViewModel! var projectId: Int! beforeEach { projectId = 4 projectSearchController = ProjectSearchControllerStub() sut = ProjectSearchViewModel(projectId: projectId, projectSearchController: projectSearchController) } context("when projects are supplied") { var project1: ProjectDTO! var project2: ProjectDTO! var project3: ProjectDTO! var caughtProjects: [ProjectDTO]! beforeEach { project1 = ProjectDTO.fakeProjectDto(name: "One", id: 1) project2 = ProjectDTO.fakeProjectDto(name: "Two", id: 2) project3 = ProjectDTO.fakeProjectDto(name: "Three", id: 3) _ = sut.projects.drive(onNext: { caughtProjects = $0 }) projectSearchController.stubbedProjects.onNext([project1, project2, project3]) } afterEach { caughtProjects = nil } it("should emit all projects") { expect(caughtProjects).to(haveCount(3)) } context("when search text is supplied") { context("correct capital letter text") { beforeEach { sut.searchText.onNext("T") } it("should emit filtered projects") { expect(caughtProjects).to(haveCount(2)) expect(caughtProjects[0].id) == project2.id expect(caughtProjects[1].id) == project3.id } } context("correct lower letter text") { beforeEach { sut.searchText.onNext("t") } it("should emit filtered projects") { expect(caughtProjects).to(haveCount(2)) expect(caughtProjects[0].id) == project2.id expect(caughtProjects[1].id) == project3.id } } context("empty text") { beforeEach { sut.searchText.onNext("") } it("should emit filtered projects") { expect(caughtProjects).to(haveCount(3)) expect(caughtProjects[0].id) == project1.id expect(caughtProjects[1].id) == project2.id expect(caughtProjects[2].id) == project3.id } } } context("when project is selected") { var caughtProject: ProjectDTO! beforeEach { _ = sut.didSelectProject.drive(onNext: { caughtProject = $0 }) sut.selectProject.onNext(project2) } it("should emit correct project") { expect(caughtProject!.id) == project2.id } } } } } }
516d66f3e8215388a28a3ddf0dadb85f
35.868687
116
0.453973
false
false
false
false
SwiftOnEdge/Edge
refs/heads/master
Sources/HTTP/Routing/ErrorEndpoint.swift
mit
1
// // ErrorEndpoint.swift // Edge // // Created by Tyler Fleming Cloutier on 12/18/17. // import Foundation import StreamKit import Regex import PathToRegex struct ErrorEndpoint: HandlerNode { let handler: ErrorHandler weak var parent: Router? let method: Method? func setParameters(on request: Request, match: Match) { request.parameters = [:] } func shouldHandleAndAddParams(request: Request, error: Error) -> Bool { if let method = method, request.method != method { return false } return true } func handle( requests: Signal<Request>, errors: Signal<(Request, Error)>, responses: Signal<Response> ) -> ( handled: Signal<Response>, errored: Signal<(Request, Error)>, unhandled: Signal<Request> ) { let (shouldHandle, unhandled) = errors.partition(self.shouldHandleAndAddParams) let (handled, errored) = handle(errors: shouldHandle) let (mergedResponses, responsesInput) = Signal<Response>.pipe() responses.add(observer: responsesInput) handled.add(observer: responsesInput) let (mergedErrored, erroredInput) = Signal<(Request, Error)>.pipe() unhandled.add(observer: erroredInput) errored.add(observer: erroredInput) return (mergedResponses, mergedErrored, requests) } init(parent: Router? = nil, method: Method? = nil, _ handler: ErrorHandler) { self.handler = handler self.method = method self.parent = parent } } extension ErrorEndpoint { func handle(errors: Signal<(Request, Error)>) -> (Signal<Response>, Signal<(Request, Error)>) { let responses: Signal<Response> let (newErrors, newErrorsInput) = Signal<(Request, Error)>.pipe() switch handler { case .sync(let syncTransform): responses = errors.flatMap { (request, error) -> Response? in do { let response = try syncTransform(request, error) response.request = request return response } catch { newErrorsInput.sendNext((request, error)) return nil } } case .async(let asyncTransform): responses = errors.flatMap { (request, error) -> Signal<Response?> in return Signal { observer in asyncTransform(request, error).then { $0.request = request observer.sendNext($0) observer.sendCompleted() }.catch { error in newErrorsInput.sendNext((request, error)) observer.sendNext(nil) observer.sendCompleted() } return nil } }.flatMap { (response: Response?) in response } } return (responses, newErrors) } } extension ErrorEndpoint: CustomStringConvertible { var description: String { if let method = method { return "\(method) '\(routePath)'" } return "ERROR '\(routePath)'" } }
e8cabee32eaf59ae4e501c5b128ed483
29.766355
99
0.555286
false
false
false
false
sdduursma/Scenic
refs/heads/master
Scenic/SceneModel.swift
mit
1
import Foundation public struct SceneModel { public var sceneName: String public var children: [SceneModel] public var customData: [AnyHashable: AnyHashable]? public init(sceneName: String, children: [SceneModel] = [], customData: [AnyHashable: AnyHashable]? = nil) { self.sceneName = sceneName self.children = children self.customData = customData } } extension SceneModel: Equatable { public static func ==(left: SceneModel, right: SceneModel) -> Bool { return left.sceneName == right.sceneName && left.children == right.children && isCustomDataEqual(left, right) } private static func isCustomDataEqual(_ left: SceneModel, _ right: SceneModel) -> Bool { if let leftCustomData = left.customData, let rightCustomData = right.customData, leftCustomData == rightCustomData { return true } else if left.customData == nil && right.customData == nil { return true } else { return false } } } extension SceneModel { public func withSceneName(_ name: String) -> SceneModel { var new = self new.sceneName = name return new } public func withChildren(_ children: [SceneModel]) -> SceneModel { var new = self new.children = children return new } public func withCustomData(_ customData: [AnyHashable: AnyHashable]?) -> SceneModel { var new = self new.customData = customData return new } public func update(_ name: String, with closure: (SceneModel) -> SceneModel) -> SceneModel { if sceneName == name { return closure(self) } return withChildren(children.map { $0.update(name, with: closure)}) } } extension SceneModel { public func applyTabBarDidSelectIndex(to tabBarName: String, event: NavigationEvent) -> SceneModel { if event.eventName == TabBarScene.didSelectIndexEventName, let index = event.customData?["selectedIndex"] as? Int { return selectIndex(index, ofTabBar: tabBarName) } return self } public func selectIndex(_ tabBarIndex: Int, ofTabBar tabBarName: String) -> SceneModel { return update(tabBarName) { tabBar in var customData = tabBar.customData ?? [:] customData["selectedIndex"] = tabBarIndex return tabBar.withCustomData(customData) } } } extension SceneModel { public func applyStackDidPop(to stackName: String, event: NavigationEvent) -> SceneModel { if event.eventName == StackScene.didPopEventName, let toIndex = event.customData?["toIndex"] as? Int { return popStack(stackName, to: toIndex) } return self } public func popStack(_ stackName: String, to index: Int) -> SceneModel { return update(stackName) { stack in guard stack.children.indices.contains(index) else { return stack } return stack.withChildren(Array(stack.children.prefix(through: index))) } } }
d07f0995c26055b90c23979a49e21c99
30.48
117
0.623253
false
false
false
false
vakoc/particle-swift-cli
refs/heads/master
Sources/WebhookCommands.swift
apache-2.0
1
// This source file is part of the vakoc.com open source project(s) // // Copyright © 2016 Mark Vakoc. All rights reserved. // Licensed under Apache License v2.0 // // See http://www.vakoc.com/LICENSE.txt for license information import Foundation import ParticleSwift fileprivate let productIdArgument = Argument(name: .productId, helpText: "Product ID or slug (only for product webhooks)", options: [.hasValue]) fileprivate let subHelp = "Get a list of the webhooks that you have created, either as a user or for a product." let showWebhooksCommand = Command(name: .showWebhooks, summary: "Show Webhooks", arguments: [productIdArgument], subHelp: subHelp) {(arguments, extras, callback) in let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared) particleCloud.webhooks(productIdOrSlug: arguments[productIdArgument]) { (result) in switch (result) { case .success(let webhooks): let stringValue = "\(webhooks)" callback( .success(string: stringValue, json: webhooks.map { $0.jsonRepresentation } )) case .failure(let err): callback( .failure(Errors.showWebhooksFailed(err))) } } } fileprivate let webhookIdArgument = Argument(name: .webhookId, helpText: "The webhook identifier", options: [.hasValue]) fileprivate let subHelp2 = "Get the webhook by identifier that you have created, either as a user or for a product." let getWebhookCommand = Command(name: .getWebhook, summary: "Get Webhook", arguments: [productIdArgument, webhookIdArgument], subHelp: subHelp2) {(arguments, extras, callback) in guard let webhookID = arguments[webhookIdArgument] else { callback( .failure(Errors.invalidWebhookId)) return } let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared) particleCloud.webhook(webhookID, productIdOrSlug: arguments[productIdArgument]) { (result) in switch (result) { case .success(let webhook): let stringValue = "\(webhook)" callback( .success(string: stringValue, json: webhook.jsonRepresentation )) case .failure(let err): callback( .failure(Errors.getWebhookFailed(err))) } } } fileprivate let jsonFileArgument = Argument(name: .jsonFile, helpText: "Filename of JSON file defining the webhook relative to the current working directory", options: [.hasValue]) fileprivate let eventArgument = Argument(name: .event, helpText: "The name of the event", options: [.hasValue]) fileprivate let urlArgument = Argument(name: .url, helpText: "The name URL webhook", options: [.hasValue]) fileprivate let requestTypeArgument = Argument(name: .requestType, helpText: "The HTTP method type (GET/POST/PUT/DELETE)", options: [.hasValue]) fileprivate let subHelp3 = "Creates a webhook using either a JSON file, arguments, or a combination of both. If --event and --url arguments are specified those will be used, otherwise all parameters must come from a JSON file that includes at least those two entries. If event, url, and a JSON file are supplied the JSON file will augment the webhook definition." // TODO: document the JSON file structure let createWebhookCommand = Command(name: .createWebhook, summary: "Create a Webhook", arguments: [productIdArgument, jsonFileArgument, eventArgument, urlArgument, requestTypeArgument], subHelp: subHelp3) {(arguments, extras, callback) in var webhook: Webhook? if let event = arguments[eventArgument], let url = arguments[urlArgument], let parsedURL = URL(string: url) { let requestType = Webhook.RequestType(rawValue: arguments[requestTypeArgument] ?? "GET") webhook = Webhook(event: event, url: parsedURL, requestType: requestType ?? .get) } if let json = arguments[jsonFileArgument] { let current = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) if let jsonUrl = URL(string: json, relativeTo: current), let data = try? Data(contentsOf: jsonUrl), let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String,Any>, let j = json { if var hook = webhook { hook.configure(with: j) } else { webhook = Webhook(with: j) } } else { return callback(.failure(Errors.failedToParseJsonFile)) } } guard let hook = webhook else { return callback(.failure(Errors.failedToDefinedWebhook)) } let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared) particleCloud.create(webhook: hook, productIdOrSlug: arguments[productIdArgument]) { result in switch (result) { case .success(let webhook): let stringValue = "\(webhook)" callback( .success(string: stringValue, json: webhook.jsonRepresentation )) case .failure(let err): callback( .failure(Errors.createWebhookFailed(err))) } } } fileprivate let subHelp4 = "Deletes a Webhook with the specified id" let deleteWebhookCommand = Command(name: .deleteWebhook, summary: "Delete a Webhook", arguments: [productIdArgument,webhookIdArgument], subHelp: subHelp4) {(arguments, extras, callback) in guard let webhookId = arguments[webhookIdArgument] else { return callback(.failure(Errors.invalidWebhookId)) } let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared) particleCloud.delete(webhookID: webhookId, productIdOrSlug: arguments[productIdArgument]) { result in switch (result) { case .success: callback(.success(string: "ok", json:["ok" : true])) case .failure(let err): callback(.failure(Errors.deleteWebhookFailed(err))) } } }
53df7f57ec9624b07afb90661f0896b5
48.728814
365
0.691036
false
false
false
false
nkirby/Humber
refs/heads/master
_lib/HMGithub/_src/Sync/SyncController+Notifications.swift
mit
1
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import ReactiveCocoa import Result import HMCore // ======================================================= public protocol GithubNotificationsSyncProviding { func syncAccountNotifications() -> SignalProducer<Void, SyncError> } extension SyncController: GithubNotificationsSyncProviding { public func syncAccountNotifications() -> SignalProducer<Void, SyncError> { guard let api = ServiceController.component(GithubAPINotificationProviding.self), let data = ServiceController.component(GithubNotificationDataProviding.self) else { return SignalProducer.empty } return api.getNotifications() .observeOn(CoreScheduler.background()) .mapError { _ in return SyncError.Unknown } .flatMap(.Latest, transform: { responses -> SignalProducer<Void, SyncError> in return SignalProducer { observer, _ in data.saveAccountNotifications(notificationResponses: responses, write: true) observer.sendNext() observer.sendCompleted() } }) } }
5706c6dd5fc0b82bd806f4c41bd6d3a2
34.918919
96
0.563582
false
false
false
false
bradya/tracker
refs/heads/master
tracker/DetailViewController.swift
mit
1
// // DetailViewController.swift // tracker // // Created by Brady Archambo on 9/2/14. // Copyright (c) 2014 Boa. All rights reserved. // import UIKit class DetailViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var noteTextView: UITextView! let placeholder: String = "Type here..." var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { self.automaticallyAdjustsScrollViewInsets = false // Update the user interface for the detail item. if let detail: AnyObject = self.detailItem { if let textView = self.noteTextView { let note: AnyObject! = detail.valueForKey("note") textView.text = note != nil ? note.description : "" textView.contentInset = UIEdgeInsetsMake(8, 0, 8, 0) textView.scrollIndicatorInsets = UIEdgeInsetsMake(8, 0, 8, 0) textView.delegate = self } } } override func viewWillAppear(animated: Bool) { self.noteTextView.becomeFirstResponder() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } func textViewDidChange(textView: UITextView) { if let detail: AnyObject = self.detailItem { detail.setValue(self.noteTextView.text, forKey: "note") } } func keyboardWillShow(note: NSNotification) { if let userInfo: NSDictionary = note.userInfo { if let frame: CGRect = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue() { var contentInsets: UIEdgeInsets = self.noteTextView.contentInset contentInsets.bottom = CGRectGetHeight(frame) self.noteTextView.contentInset = contentInsets self.noteTextView.scrollIndicatorInsets = contentInsets } } } func keyboardWillHide(note: NSNotification) { var contentInsets = self.noteTextView.contentInset contentInsets.bottom = 0.0; self.noteTextView.contentInset = contentInsets; self.noteTextView.scrollIndicatorInsets = contentInsets; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
ea44786cf5881e472713fd2ba4fdb284
32.697674
154
0.624914
false
false
false
false
oskarpearson/rileylink_ios
refs/heads/master
MinimedKit/Messages/GetPumpModelCarelinkMessageBody.swift
mit
1
// // GetPumpModelCarelinkMessageBody.swift // RileyLink // // Created by Pete Schwamb on 3/12/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class GetPumpModelCarelinkMessageBody: CarelinkLongMessageBody { public let model: String public required init?(rxData: Data) { guard rxData.count == type(of: self).length, let mdl = String(data: rxData.subdata(in: 2..<5), encoding: String.Encoding.ascii) else { model = "" super.init(rxData: rxData) return nil } model = mdl super.init(rxData: rxData) } public required init?(rxData: NSData) { fatalError("init(rxData:) has not been implemented") } }
9500821bd42d87daf7e677587ee464af
26.357143
101
0.617493
false
false
false
false
CoderST/DYZB
refs/heads/master
DYZB/DYZB/Class/Main/View/STCollectionView.swift
mit
1
// // STCollectionView.swift // DYZB // // Created by xiudou on 2017/7/13. // Copyright © 2017年 xiudo. All rights reserved. // import UIKit fileprivate let STCollectionViewCellIdentifier = "STCollectionViewCellIdentifier" fileprivate let STLocationReusableViewIdentifier = "STLocationReusableViewIdentifier" @objc protocol STCollectionViewDataSource : class { /*********必须实现***********/ // func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int /// 多少行 @objc func collectionView(_ stCollectionView: STCollectionView, numberOfItemsInSection section: Int) -> Int /// 每行的标题 @objc func collectionViewTitleInRow(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->String /*********选择实现***********/ /// 普通图片 // @objc optional func imageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String /// 高亮图片 // @objc optional func highImageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String /// 多少区间 @objc optional func numberOfSections(in stCollectionView: STCollectionView) -> Int /// 是否有箭头 @objc optional func isHiddenArrowImageView(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->Bool } @objc protocol STCollectionViewDelegate : class{ /// 点击事件 @objc optional func stCollection(_ stCollectionView : STCollectionView, didSelectItemAt indexPath: IndexPath) // 区间头部head的文字 @objc optional func stCollectionHeadInSection(_ stCollectionView: STCollectionView, at indexPath: IndexPath) -> String } class STCollectionView: UIView { weak var dataSource : STCollectionViewDataSource? weak var delegate : STCollectionViewDelegate? // MARK:- 懒加载 lazy var collectionView : UICollectionView = { // 设置layout属性 let layout = XDPlanFlowLayout() layout.naviHeight = 64 let width = sScreenW // 默认值(如果改动可以添加代理方法) layout.itemSize = CGSize(width: width, height: 44) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.headerReferenceSize = CGSize(width: sScreenW, height: 20) // 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y:0 , width: 0 , height: 0), collectionViewLayout: layout) collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor(r: 239, g: 239, b: 239) // 注册cell collectionView.register(STCollectionViewCell.self, forCellWithReuseIdentifier: STCollectionViewCellIdentifier) collectionView.register(LocationReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier) return collectionView; }() override func layoutSubviews() { super.layoutSubviews() collectionView.frame = bounds } override init(frame: CGRect) { super.init(frame: frame) addSubview(collectionView) // 设置数据源 collectionView.dataSource = self collectionView.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension STCollectionView : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int{ let sectionCount = dataSource?.numberOfSections?(in: self) if sectionCount == nil || sectionCount == 0 { return 1 }else{ return sectionCount! } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ guard let itemsCount = dataSource?.collectionView(self, numberOfItemsInSection: section) else { return 0 } return itemsCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: STCollectionViewCellIdentifier, for: indexPath) as! STCollectionViewCell cell.contentView.backgroundColor = UIColor.randomColor() // title let text = dataSource?.collectionViewTitleInRow(self, indexPath) ?? "" cell.titleLabel.text = text // 是否右箭头 if let isHidden = dataSource?.isHiddenArrowImageView?(self, indexPath){ cell.arrowImageView.isHidden = isHidden }else{ cell.arrowImageView.isHidden = true } // 必须添加下面这句话,不然系统不知道什么时候刷新cell(参考:http://www.jianshu.com/writer#/notebooks/8510661/notes/14529933/preview) cell.setNeedsLayout() return cell } } extension STCollectionView : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.stCollection?(self, didSelectItemAt: indexPath) } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier, for: indexPath) as! LocationReusableView view.titleString = delegate?.stCollectionHeadInSection?(self, at: indexPath) return view } }
17ec28e7d585181778ebd64dfd1b782d
34.981132
208
0.683447
false
false
false
false
bwide/Sorting-Algorithms-Playground
refs/heads/master
Sorting algorithms.playground/Pages/BubbleSort.xcplaygroundpage/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport let arraySize = 50 let array = VisualSortableArray.init(arraySize: arraySize) func compare(i: Int, j: Int) -> Int{ return array.compare(i: i, j: j) } func swap(i: Int, j: Int){ array.swap(i: i, j: j) } func select(i: Int, j: Int) -> Bool { return array.select(i: i, j: j) } PlaygroundPage.current.liveView = array.view DispatchQueue.global(qos: .background).async { sleep(2) while true { var swapped = false for i in 1..<array.count { select(i: i, j: i-1) if compare(i: i, j: i-1) < 0{ swap(i: i, j: i-1) swapped = true } } if !swapped { break } } }
81097bb97a6289c244e5d2f98d8fee36
17.282609
58
0.514863
false
false
false
false
Nyx0uf/MPDRemote
refs/heads/master
src/common/extensions/FileManager+Extensions.swift
mit
1
// FileManager+Extensions.swift // Copyright (c) 2017 Nyx0uf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension FileManager { func sizeOfDirectoryAtURL(_ directoryURL: URL) -> Int { var result = 0 let props = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey] do { let ar = try self.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: props, options: []) for url in ar { var isDir: ObjCBool = false self.fileExists(atPath: url.path, isDirectory: &isDir) if isDir.boolValue { result += self.sizeOfDirectoryAtURL(url) } else { result += try self.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! Int } } } catch let error { Logger.shared.log(type: .error, message: "Can't get directory size (\(error.localizedDescription)") } return result } }
0fb2cc3c953a0c2bb500812d5b00acc1
33.438596
123
0.737646
false
false
false
false
devpunk/cartesian
refs/heads/master
cartesian/View/DrawProject/Menu/VDrawProjectMenuEditBar.swift
mit
1
import UIKit class VDrawProjectMenuEditBar:UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { private let model:MDrawProjectMenuEditBar private weak var controller:CDrawProject! private weak var collectionView:VCollection! private let kBorderHeight:CGFloat = 1 private let kCellWidth:CGFloat = 85 private let kDeselectTime:TimeInterval = 0.2 init(controller:CDrawProject) { model = MDrawProjectMenuEditBar() super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1)) let collectionView:VCollection = VCollection() collectionView.alwaysBounceHorizontal = true collectionView.delegate = self collectionView.dataSource = self collectionView.registerCell(cell:VDrawProjectMenuEditBarCell.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.scrollDirection = UICollectionViewScrollDirection.horizontal } addSubview(border) addSubview(collectionView) NSLayoutConstraint.topToTop( view:border, toView:self) NSLayoutConstraint.height( view:border, constant:kBorderHeight) NSLayoutConstraint.equalsHorizontal( view:border, toView:self) NSLayoutConstraint.equals( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: private private func modelAtIndex(index:IndexPath) -> MDrawProjectMenuEditBarItem { let item:MDrawProjectMenuEditBarItem = model.items[index.item] return item } //MARK: collectionView delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let height:CGFloat = collectionView.bounds.maxY let size:CGSize = CGSize(width:kCellWidth, height:height) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = model.items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MDrawProjectMenuEditBarItem = modelAtIndex(index:indexPath) let cell:VDrawProjectMenuEditBarCell = collectionView.dequeueReusableCell( withReuseIdentifier: VDrawProjectMenuEditBarCell.reusableIdentifier, for:indexPath) as! VDrawProjectMenuEditBarCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.isUserInteractionEnabled = false let item:MDrawProjectMenuEditBarItem = modelAtIndex(index:indexPath) item.selected(controller:controller) DispatchQueue.main.asyncAfter( deadline:DispatchTime.now() + kDeselectTime) { [weak collectionView] in collectionView?.selectItem( at:nil, animated:true, scrollPosition:UICollectionViewScrollPosition()) collectionView?.isUserInteractionEnabled = true } } }
c649081a82cfb7dbdedb69840f7b21d1
31.666667
155
0.658418
false
false
false
false
byvapps/ByvManager-iOS
refs/heads/master
ByvManager/Classes/Device.swift
mit
1
// // Device.swift // Pods // // Created by Adrian Apodaca on 24/10/16. // // import Foundation import Alamofire import SwiftyJSON public struct Device { public static var autoResetBadge = true var deviceId: String? var uid: String var name: String? var os: String var osVersion: String var device: String var manufacturer: String var model: String var appVersion: String? var appVersionCode: String? var createdAt: Date? var updatedAt: Date? var active: Bool var lastConnectionStart: Date? var lastConnectionEnd: Date? var pushId: String? var badge: Int var languageCode: String? var preferredLang: String? var countryCode: String? var regionCode: String? var currencyCode: String? var timezone: String? // MARK: - init // // Init device. If stored get static data from Defaults, else get uid // public init() { var jsonStr:String = "" if let str = UserDefaults.standard.string(forKey: "deviceJsonData") { jsonStr = str } let stored = JSON(parseJSON: jsonStr) if let id = stored["_id"].string { self.deviceId = id } if let uid = stored["uid"].string { self.uid = uid } else { self.uid = ByvKeychainManager.sharedInstance.getDeviceIdentifierFromKeychain() } if let active = stored["active"].int{ self.active = active == 1 } else { self.active = true } if let badge = stored["badge"].int { self.badge = badge } else { self.badge = 0 } if let pushId = stored["pushId"].string { self.pushId = pushId } if let preferredLang = stored["preferredLang"].string { self.preferredLang = preferredLang } let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" if let createdAt = stored["createdAt"].string { self.createdAt = formatter.date(from: createdAt) } if let updatedAt = stored["updatedAt"].string { self.updatedAt = formatter.date(from: updatedAt) } if let lastConnectionStart = stored["lastConnectionStart"].string { self.lastConnectionStart = formatter.date(from: lastConnectionStart) } if let lastConnectionEnd = stored["lastConnectionEnd"].string { self.lastConnectionEnd = formatter.date(from: lastConnectionEnd) } name = UIDevice.current.name os = "iOS" osVersion = UIDevice.current.systemVersion device = UIDevice.current.model manufacturer = "Apple" model = UIDevice.current.localizedModel appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String appVersionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String languageCode = Locale.current.languageCode countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String regionCode = Locale.current.regionCode currencyCode = Locale.current.currencyCode timezone = TimeZone.current.identifier } // MARK: - private // // create or update in server // private func storeInServer() { var params: Params = self.parameters() if Device.autoResetBadge { params["badge"] = NSNumber(integerLiteral: 0) UIApplication.shared.applicationIconBadgeNumber = 0 } var path: String var method: HTTPMethod if let deviceId = self.deviceId { method = .put path = "\(url_devices())/\(deviceId)" } else { method = .post path = url_devices() } ConManager.connection(path, params: params, method: method, encoding: JSONEncoding.default, success: { (responseData) in if let data: Data = responseData?.data { do { let json = try JSON(data: data) self.store(json) } catch { } } }) } // // convert Device to Parameters // private func parameters() -> Parameters { var response: Parameters = Parameters() if let name = self.name { response["name"] = name } response["uid"] = uid response["active"] = active if let pushId = self.pushId { response["pushId"] = pushId } response["badge"] = badge response["os"] = os response["osVersion"] = osVersion response["device"] = device response["manufacturer"] = manufacturer response["model"] = model if let appVersion = self.appVersion { response["appVersion"] = appVersion } if let appVersionCode = self.appVersionCode { response["appVersionCode"] = appVersionCode } if let languageCode = self.languageCode { response["languageCode"] = languageCode } if let preferredLang = self.preferredLang { response["preferredLang"] = preferredLang } if let countryCode = self.countryCode { response["countryCode"] = countryCode } if let regionCode = self.regionCode { response["regionCode"] = regionCode } if let currencyCode = self.currencyCode { response["currencyCode"] = currencyCode } if let timezone = self.timezone { response["timezone"] = timezone } return response } private func store(_ json: JSON?) { if json?["_id"].string != nil { let defs = UserDefaults.standard defs.set(json?.rawString(), forKey: "deviceJsonData") defs.synchronize() } else { print("Error storing device Json") } } // MARK: - public static public static func setDeviceActive(_ active: Bool) { var device = Device() device.active = active device.badge = 0 device.storeInServer() } public static func setPushId(_ pushId: String) { var device = Device() device.pushId = pushId device.storeInServer() } }
2c057c83e79f239c7a8c2a44ce1fbd69
29.411504
90
0.535865
false
false
false
false
moked/iuob
refs/heads/master
iUOB 2/Controllers/CoursesVC.swift
mit
1
// // CoursesVC.swift // iUOB 2 // // Created by Miqdad Altaitoon on 8/10/16. // Copyright © 2016 Miqdad Altaitoon. All rights reserved. // import UIKit import Alamofire import MBProgressHUD class CoursesVC: UITableViewController { // MARK: - Properties var department:Department! var courses: [Course] = [] // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() googleAnalytics() self.title = department.name getCourses() } func googleAnalytics() { if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!) let builder: NSObject = GAIDictionaryBuilder.createScreenView().build() tracker.send(builder as! [NSObject : AnyObject]) } } // MARK: - Load Data func getCourses() { MBProgressHUD.showAdded(to: self.view, animated: true) Alamofire.request(department.url, parameters: nil) .validate() .responseString { response in MBProgressHUD.hide(for: self.view, animated: true) if response.result.error == nil { self.courses = UOBParser.parseCourses(response.result.value!) self.tableView.reloadData() } else { print("error man") } } } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return courses.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell", for: indexPath) cell.textLabel?.text = "\(courses[(indexPath as NSIndexPath).row].code) - \(courses[(indexPath as NSIndexPath).row].name)" cell.detailTextLabel?.text = courses[(indexPath as NSIndexPath).row].preRequisite return cell } // Mark: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowTiming" { let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)! as IndexPath let destinationViewController = segue.destination as! TimingVC destinationViewController.course = courses[(indexPath as NSIndexPath).row] } } }
fb6a31877753cee2f130838b870df278
29.280899
130
0.588868
false
false
false
false
hacktoolkit/hacktoolkit-ios_lib
refs/heads/master
Hacktoolkit/lib/GitHub/models/GitHubOrganization.swift
mit
1
// // GitHubOrganization.swift // // Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai) // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import Foundation protocol GitHubOrganizationDelegate { func didFinishFetching() } class GitHubOrganization: GitHubResource { var delegate: GitHubOrganizationDelegate? // https://developer.github.com/v3/orgs/ let GITHUB_ORGANIZATION_RESOURCE_BASE = "/orgs/" // meta var handle: String // Organization attributes var login: String! var id: Int! var url: String! var avatarUrl: String! var name: String! var company: String! var blog: String! var location: String! var email: String! var publicRepos: Int! var publicGists: Int! var followers: Int! var following: Int! var htmlURL: String! // Organization relations lazy var repositories: [GitHubRepository] = [GitHubRepository]() init(name: String, onInflated: ((GitHubResource) -> ())? = nil) { self.handle = name super.init(onInflated) } init(fromDict organizationDict: NSDictionary) { self.handle = "" super.init() inflater(organizationDict as AnyObject) } override func getResourceURL() -> String { var resource = "\(GITHUB_ORGANIZATION_RESOURCE_BASE)\(self.handle)" return resource } override func inflater(result: AnyObject) { var resultJSON = result as NSDictionary self.login = resultJSON["login"] as? String self.id = resultJSON["id"] as? Int self.url = resultJSON["url"] as? String self.avatarUrl = resultJSON["avatar_url"] as? String self.name = resultJSON["name"] as? String self.company = resultJSON["company"] as? String self.blog = resultJSON["blog"] as? String self.location = resultJSON["location"] as? String self.email = resultJSON["email"] as? String self.publicRepos = resultJSON["publicRepos"] as? Int self.publicGists = resultJSON["publicGists"] as? Int self.followers = resultJSON["followers"] as? Int self.following = resultJSON["following"] as? Int self.htmlURL = resultJSON["htmlURL"] as? String super.inflater(resultJSON) } func getRepositories(onInflated: ([GitHubRepository]) -> ()) { var resource = "\(self.getResourceURL())/repos" GitHubClient.sharedInstance.makeApiRequest(resource, callback: { (results: AnyObject) -> () in var resultsJSONArray = results as? [NSDictionary] if resultsJSONArray != nil { var repositories = resultsJSONArray!.map { (repositoryDict: NSDictionary) -> GitHubRepository in GitHubRepository(repositoryDict: repositoryDict) } self.repositories = repositories if self.delegate != nil { self.delegate!.didFinishFetching() } } else { HTKNotificationUtils.displayNetworkErrorMessage() } }) } } //{ // "login": "github", // "id": 1, // "url": "https://api.github.com/orgs/github", // "avatar_url": "https://github.com/images/error/octocat_happy.gif", // "name": "github", // "company": "GitHub", // "blog": "https://github.com/blog", // "location": "San Francisco", // "email": "[email protected]", // "public_repos": 2, // "public_gists": 1, // "followers": 20, // "following": 0, // "html_url": "https://github.com/octocat", // "created_at": "2008-01-14T04:33:35Z", // "type": "Organization" //}
2b8508ab6990da20c5a15685cf18d67d
30.504274
75
0.606891
false
false
false
false
jmgc/swift
refs/heads/master
test/Constraints/async.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -enable-experimental-concurrency // REQUIRES: concurrency func doAsynchronously() async { } func doSynchronously() { } func testConversions() async { let _: () -> Void = doAsynchronously // expected-error{{invalid conversion from 'async' function of type '() async -> ()' to synchronous function type '() -> Void'}} let _: () async -> Void = doSynchronously // okay } // Overloading @available(swift, deprecated: 4.0, message: "synchronous is no fun") func overloadedSame(_: Int = 0) -> String { "synchronous" } func overloadedSame() async -> String { "asynchronous" } func overloaded() -> String { "synchronous" } func overloaded() async -> Double { 3.14159 } @available(swift, deprecated: 4.0, message: "synchronous is no fun") func overloadedOptDifference() -> String { "synchronous" } func overloadedOptDifference() async -> String? { nil } func testOverloadedSync() { _ = overloadedSame() // expected-warning{{synchronous is no fun}} let _: String? = overloadedOptDifference() // expected-warning{{synchronous is no fun}} let _ = overloaded() let fn = { overloaded() } let _: Int = fn // expected-error{{value of type '() -> String'}} let fn2 = { print("fn2") _ = overloaded() } let _: Int = fn2 // expected-error{{value of type '() -> ()'}} let fn3 = { await overloaded() } let _: Int = fn3 // expected-error{{value of type '() async -> Double'}} let fn4 = { print("fn2") _ = await overloaded() } let _: Int = fn4 // expected-error{{value of type '() async -> ()'}} } func testOverloadedAsync() async { _ = await overloadedSame() // no warning let _: String? = await overloadedOptDifference() // no warning let _ = await overloaded() let _ = overloaded() // expected-error{{call is 'async' but is not marked with 'await'}}{{11-11=await }} let fn = { overloaded() } let _: Int = fn // expected-error{{value of type '() -> String'}} let fn2 = { print("fn2") _ = overloaded() } let _: Int = fn2 // expected-error{{value of type '() -> ()'}} let fn3 = { await overloaded() } let _: Int = fn3 // expected-error{{value of type '() async -> Double'}} let fn4 = { print("fn2") _ = await overloaded() } let _: Int = fn4 // expected-error{{value of type '() async -> ()'}} } func takesAsyncClosure(_ closure: () async -> String) -> Int { 0 } func takesAsyncClosure(_ closure: () -> String) -> String { "" } func testPassAsyncClosure() { let a = takesAsyncClosure { await overloadedSame() } let _: Double = a // expected-error{{convert value of type 'Int'}} let b = takesAsyncClosure { overloadedSame() } // expected-warning{{synchronous is no fun}} let _: Double = b // expected-error{{convert value of type 'String'}} } struct FunctionTypes { var syncNonThrowing: () -> Void var syncThrowing: () throws -> Void var asyncNonThrowing: () async -> Void var asyncThrowing: () async throws -> Void mutating func demonstrateConversions() { // Okay to add 'async' and/or 'throws' asyncNonThrowing = syncNonThrowing asyncThrowing = syncThrowing syncThrowing = syncNonThrowing asyncThrowing = asyncNonThrowing // Error to remove 'async' or 'throws' syncNonThrowing = asyncNonThrowing // expected-error{{invalid conversion}} syncThrowing = asyncThrowing // expected-error{{invalid conversion}} syncNonThrowing = syncThrowing // expected-error{{invalid conversion}} asyncNonThrowing = syncThrowing // expected-error{{invalid conversion}} } }
b80e528f73c69da85f9634ed5a3c4ae3
29.606838
167
0.643675
false
false
false
false
lemberg/obd2-swift-lib
refs/heads/master
OBD2-Swift/Classes/Common/Macros.swift
mit
1
// // Macros.swift // OBD2Swift // // Created by Max Vitruk on 08/06/2017. // Copyright © 2017 Lemberg. All rights reserved. // import Foundation //------------------------------------------------------------------------------ // Macros // Macro to test if a given PID, when decoded, is an // alphanumeric string instead of a numeric value func IS_ALPHA_VALUE(pid : UInt8) -> Bool{ return (pid == 0x03 || pid == 0x12 || pid == 0x13 || pid == 0x1C || pid == 0x1D || pid == 0x1E) } // Macro to test if a given PID has two measurements in the returned data func IS_MULTI_VALUE_SENSOR(pid : UInt8) -> Bool { return (pid >= 0x14 && pid <= 0x1B) || (pid >= 0x24 && pid <= 0x2B) || (pid >= 0x34 && pid <= 0x3B) } func IS_INT_VALUE(pid : Int8, sensor : OBD2Sensor) -> Bool { return (pid >= 0x04 && pid <= 0x13) || (pid >= 0x1F && pid <= 0x23) || (pid >= 0x2C && pid <= 0x33) || (pid >= 0x3C && pid <= 0x3F) || (pid >= 0x43 && pid <= 0x4E) || (pid >= 0x14 && pid <= 0x1B && sensor.rawValue == 0x02) || (pid >= 0x24 && pid <= 0x2B && sensor.rawValue == 0x02) || (pid >= 0x34 && pid <= 0x3B && sensor.rawValue == 0x02) } func MORE_PIDS_SUPPORTED(_ data : [UInt8]) -> Bool { guard data.count > 3 else {return false} return ((data[3] & 1) != 0) } func NOT_SEARCH_PID(_ pid : Int) -> Bool { return (pid != 0x00 && pid != 0x20 && pid != 0x40 && pid != 0x60 && pid != 0x80 && pid != 0xA0 && pid != 0xC0 && pid != 0xE0) } let kCarriageReturn = "\r" let DTC_SYSTEM_MASK : UInt8 = 0xC0 let DTC_DIGIT_0_1_MASK : UInt8 = 0x3F let DTC_DIGIT_2_3_MASK : UInt8 = 0xFF
255196c8f235f524cb23063b4db3b021
28.4
97
0.539889
false
false
false
false
liusally/SLCarouselView
refs/heads/master
Examples/SLCarouselViewExample/SLCarouselViewExample/ViewController.swift
mit
1
// // ViewController.swift // SLCarouselViewExample // // Created by Shali Liu on 7/19/17. // Copyright © 2017 Shali Liu. All rights reserved. // import UIKit import AVFoundation import SDWebImage import SLCarouselView class ViewController: UIViewController { @IBOutlet var carouselView: SLCarouselView! fileprivate var playerArr = [AVPlayer?]() override func viewDidLoad() { super.viewDidLoad() // Data examples let data: [Dictionary<String, String>] = [ ["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/20065243_243723416143011_6663416918206054400_n.jpg"], ["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19984908_462044610837470_639420776679735296_n.jpg"], ["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19955017_1738275873137290_7355135153712136192_n.jpg"], ["type": "video", "url": "https://scontent.cdninstagram.com/t50.2886-16/19179996_870131086458262_8352073221473828864_n.mp4"] ] setupCarouselView(data: data) } private func setupCarouselView(data: [Dictionary<String, String>]) { for index in 0...(data.count - 1) { let item = data[index] if (item["type"] == "image") { // image let imageUrl = item["url"] let imageSlide = UIImageView() imageSlide.contentMode = UIViewContentMode.scaleAspectFill imageSlide.clipsToBounds = true imageSlide.sd_setImage(with: URL(string: imageUrl!)) self.carouselView.appendContent(view: imageSlide) } if (item["type"] == "video") { // video let videoView = UIView() self.carouselView.appendContent(view: videoView) let videoUrl = item["url"] let player = AVPlayer(url: URL(string: videoUrl!)!) self.playerArr.append(player) // Mute video player.volume = 0 let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = videoView.bounds videoView.layer.addSublayer(playerLayer) // Resize video to frame playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill // Loop playing video NotificationCenter.default.addObserver(self, selector: #selector(self.loopPlayVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) player.play() } } } func loopPlayVideo() { for player in self.playerArr { player?.seek(to: kCMTimeZero) player?.play() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7ad03e6c7481d2e2210828db8ec7cb99
34.417582
185
0.568415
false
false
false
false
Ellestad1995/supreme-invention
refs/heads/master
selectiveCollectionView/selectiveCollectionView/collView.swift
mit
1
// // collView.swift // selectiveCollectionView // // Created by Joakim Nereng Ellestad on 05.01.2017. // Copyright © 2017 Joakim Ellestad. All rights reserved. // import UIKit class collView: UICollectionView { override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.setupCollectionView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { //self.setupCollectionView() } override func layoutSubviews() { super.layoutSubviews() //add shadow self.layer.shadowColor = UIColor.black.cgColor self.layer.masksToBounds = false self.clipsToBounds = true self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 3.0 self.layer.shouldRasterize = false self.layer.shadowOffset = CGSize(width: 0, height: 1) self.layer.shadowPath = UIBezierPath(rect: self.layer.bounds).cgPath } func setupCollectionView(){ //setup the class self.showsVerticalScrollIndicator = false self.backgroundColor = UIColor.white self.allowsSelection = false self.translatesAutoresizingMaskIntoConstraints = false //registering two cells self.register(newcell.self, forCellWithReuseIdentifier: "newcell") self.register(defaultcell.self, forCellWithReuseIdentifier: "defaultcell") } }
213647e328f3913b44629b86fbb8ceda
28.314815
87
0.676563
false
false
false
false
smoope/ios-sdk
refs/heads/master
Pod/Classes/SPMessage.swift
apache-2.0
1
/* * Copyright 2016 smoope GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation public class SPMessage: SPCreated { public var parts: [Part] = [] public init(parts: [Part]) { self.parts = parts super.init() } public required init(data: [String: AnyObject]) { if let parts = data["_embedded"]!["parts"] as? [AnyObject] { self.parts = parts .map { v in Part(data: v as! [String: AnyObject]) } } super.init(data: data) } public override func unmap() -> [String: AnyObject] { var result: [String: AnyObject] = [:] if !parts.isEmpty { result["parts"] = parts.map({ part in part.unmap() }) } return result .append(super.unmap()) } public class Part: SPBase { private var mimeType: String private var encoding: String? private var body: String? private var filename: String? private var url: String? private init(mimeType: String, encoding: String? = nil, body: String? = nil, filename: String? = nil, url: String? = nil) { self.mimeType = mimeType self.encoding = encoding self.body = body self.filename = filename self.url = url super.init() } public required init(data: Dictionary<String, AnyObject>) { self.mimeType = data["mimeType"] as! String if let encoding = data["encoding"] { self.encoding = encoding as? String } if let body = data["body"] { self.body = body as? String } if let filename = data["filename"] { self.filename = filename as? String } super.init(data: data) } public override func unmap() -> [String: AnyObject] { var result: [String: AnyObject] = ["mimeType": mimeType] if let encoding = self.encoding { result["encoding"] = encoding } if let body = self.body { result["body"] = body } if let filename = self.filename { result["filename"] = filename } if let url = self.url { result["url"] = url } return result .append(super.unmap()) } public static func text(text: String) -> Part { return Part(mimeType: "text/plain", body: text) } public static func media(mimeType: String, filename: String, url: String) -> Part { return Part(mimeType: mimeType, filename: filename, url: url) } } }
990b0acddcb14f8448ec001b5f01ad05
25.359649
127
0.6002
false
false
false
false
vmachiel/swift
refs/heads/main
LearningSwift.playground/Pages/Operators.xcplaygroundpage/Contents.swift
mit
1
// Basic operators: var a = 10 a = a + 1 a = a - 1 a = a * 2 a = a / 2 var b = 13 / 3 // floor devision, won't do float automatically because strong typing! b = b % 3 // modulus or remain // Like python, you can shorten the x = x + 10 thing b = 10 b += 10 b -= 10 // adding doubles var c = 1.1 var d = 2.2 var e = c + d // String concatination var name1 = "Machiel van Dorst" var name2 = "Annabel Dellebeke" var bothNames = name1 + " en " + name2 // comparison operators that return Booleans: e > 3 e < 3 e <= 3 e >= 3 e == 3 e != 3 name1 == "Machiel van Dorst" // true! // Use the ! operator before any Boolean to flip it: var stayOutTooLate = true // true !stayOutTooLate // false // or and operators: stayOutTooLate && true !stayOutTooLate && true stayOutTooLate || true !stayOutTooLate || true // Interpolation: basically python f-strings. Do in place calculations and manipulation of // variables and convert them into String, and print out the whole thing. // More efficient than concatinating, and allows for calculations var name = "Machiel van Dorst" "Your name is \(name)" // Another example: var age = 29 var latitude = 51.16643 print("Your name is \(name) and your age is \(age) and you're at latitude \(latitude)") print("In three years time, you'll be \(age + 3) years old") // Array operation: var songs = ["Shake it Off", "You Belong with Me", "Back to December"] var songs2 = ["Today was a Fairytale", "Welcome to New York", "Fifteen"] var both = songs + songs2 songs += ["Snorsex"] // Ternary operator: Assign something if to var or constant if expression is true // or false. If true, assign what is before after ?, else assign what is after : let currentWeather = "Sunny" let currentMood = currentWeather == "Sunny" ? "Happy" : "Cranky" // Happy // Comparing tuples: (1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" are not compared (3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird" (4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog' let firstName = "Paul" let secondName = "Sophie" print(firstName == secondName) print(firstName != secondName) print(firstName < secondName) print(firstName >= secondName)
4587e6d3c918d23efbe3a74eaf935695
24.806818
100
0.67151
false
false
false
false
migchaves/SwiftCoreData
refs/heads/master
Swift CoreData Example/DataBase/DBManager.swift
mit
1
// // DBManager.swift // Swift CoreData Example // // Created by Miguel Chaves on 19/01/16. // Copyright © 2016 Miguel Chaves. All rights reserved. // import UIKit import CoreData class DBManager: NSObject { // MARK: - Class Properties var managedObjectContext: NSManagedObjectContext var managedObjectModel: NSManagedObjectModel var persistentStoreCoordinator: NSPersistentStoreCoordinator // MARK: - Init class override init() { self.managedObjectModel = NSManagedObjectModel.init(contentsOfURL: DBManager.getModelUrl())! self.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: self.managedObjectModel) do { try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: DBManager.storeURL(), options: nil) } catch let error as NSError { print(error) abort() } self.managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType) self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator self.managedObjectContext.mergePolicy = NSOverwriteMergePolicy } // MARK: - Shared Instance class var sharedInstance: DBManager { struct Singleton { static let instance = DBManager() } return Singleton.instance } // MARK: - Create and Save objects func managedObjectOfType(objectType: String) -> NSManagedObject { let newObject = NSEntityDescription.insertNewObjectForEntityForName(objectType, inManagedObjectContext: self.managedObjectContext) return newObject } func temporaryManagedObjectOfType(objectType: String) -> NSManagedObject { let description = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let temporaryObject = NSManagedObject.init(entity: description!, insertIntoManagedObjectContext: nil) return temporaryObject } func insertManagedObject(object: NSManagedObject) { self.managedObjectContext.insertObject(object) saveContext() } func saveContext() { if (!self.managedObjectContext.hasChanges) { return } else { do { try self.managedObjectContext.save() } catch let exception as NSException { print("Error while saving \(exception.userInfo) : \(exception.reason)") } catch { print("Error while saving data!") } } } // MARK: - Retrieve data func allEntriesOfType(objectType: String) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true do { let result = try self.managedObjectContext.executeFetchRequest(request) return result } catch { print("Error executing request in the Data Base.") } return [] } func getEntryOfType(objectType: String, propertyName: String, propertyValue: AnyObject) -> [AnyObject] { let entety = NSEntityDescription.entityForName(objectType, inManagedObjectContext: self.managedObjectContext) let request = NSFetchRequest.init() request.entity = entety request.includesPendingChanges = true let predicate = NSPredicate(format: "\(propertyName) == \(propertyValue)") request.predicate = predicate do { let result = try self.managedObjectContext.executeFetchRequest(request) var returnArray: [AnyObject] = [AnyObject]() for element in result { returnArray.append(element) } return returnArray } catch { print("Error executing request in the Data Base") } return [] } func deleteAllEntriesOfType(objectType: String) { let elements = allEntriesOfType(objectType) if (elements.count > 0) { for element in elements { self.managedObjectContext.deleteObject(element as! NSManagedObject) } saveContext() } } func deleteObject(object: NSManagedObject) { self.managedObjectContext.deleteObject(object) saveContext() } // MARK: - Private functions static private func getModelUrl() -> NSURL { return NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")! } static private func storeURL () -> NSURL? { let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last let storeUrl = applicationDocumentsDirectory?.URLByAppendingPathComponent("Model.sqlite") return storeUrl } }
c5d82919842c61aea567d350494be5ae
31.149701
144
0.623207
false
false
false
false
VinlorJiang/DouYuWL
refs/heads/master
DouYuWL/DouYuWL/Classes/Main/ViewModel/BaseViewModel.swift
mit
1
// // BaseViewModel.swift // DouYuWL // // Created by dinpay on 2017/7/24. // Copyright © 2017年 apple. All rights reserved. // import UIKit class BaseViewModel { lazy var anchorGroupModels : [AnchorGroupModel] = [AnchorGroupModel]() } extension BaseViewModel { func loadAnchorData(isGroupData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) { NetWorkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in // 1.对界面进行处理 guard let resultDic = result as? [String : Any] else { return } guard let dataArray = resultDic["data"] as? [[String : Any]] else { return } // 2.判断是否分组数据 if isGroupData { // 2.1.遍历数组中的字典 for dic in dataArray { self.anchorGroupModels.append(AnchorGroupModel(dict:dic)) } } else { // 2.1.创建组 let group = AnchorGroupModel() // 2.2.遍历dataArray的所有的字典 for dic in dataArray { group.anchors.append(AnchorModel(dict : dic)) } // 2.3.将group,添加到anchorGroups self.anchorGroupModels.append(group) } // 3.完成回调 finishedCallback() } } }
ee5af1d147f1ec00cb4b9aa9aadd863d
31.857143
140
0.536957
false
false
false
false
DanisFabric/RainbowNavigation
refs/heads/master
RainbowNavigation/UINavigationBar+Rainbow.swift
mit
1
// // UINavigationBar+Rainbow.swift // Pods // // Created by Danis on 15/11/25. // // import Foundation private var kRainbowAssociatedKey = "kRainbowAssociatedKey" public class Rainbow: NSObject { var navigationBar: UINavigationBar init(navigationBar: UINavigationBar) { self.navigationBar = navigationBar super.init() } fileprivate var navigationView: UIView? fileprivate var statusBarView: UIView? public var backgroundColor: UIColor? { get { return navigationView?.backgroundColor } set { if navigationView == nil { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationView = UIView(frame: CGRect(x: 0, y: -UIApplication.shared.statusBarFrame.height, width: navigationBar.bounds.width, height: navigationBar.bounds.height + UIApplication.shared.statusBarFrame.height)) navigationView?.isUserInteractionEnabled = false navigationView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] navigationBar.insertSubview(navigationView!, at: 0) } navigationView!.backgroundColor = newValue } } public var statusBarColor: UIColor? { get { return statusBarView?.backgroundColor } set { if statusBarView == nil { statusBarView = UIView(frame: CGRect(x: 0, y: -UIApplication.shared.statusBarFrame.height, width: navigationBar.bounds.width, height: UIApplication.shared.statusBarFrame.height)) statusBarView?.isUserInteractionEnabled = false statusBarView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] if let navigationView = navigationView { navigationBar.insertSubview(statusBarView!, aboveSubview: navigationView) } else { navigationBar.insertSubview(statusBarView!, at: 0) } } statusBarView?.backgroundColor = newValue } } public func clear() { navigationBar.setBackgroundImage(nil, for: .default) navigationBar.shadowImage = nil navigationView?.removeFromSuperview() navigationView = nil statusBarView?.removeFromSuperview() statusBarView = nil } } extension UINavigationBar { public var rb: Rainbow { get { if let rainbow = objc_getAssociatedObject(self, &kRainbowAssociatedKey) as? Rainbow { return rainbow } let rainbow = Rainbow(navigationBar: self) objc_setAssociatedObject(self, &kRainbowAssociatedKey, rainbow, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return rainbow } } }
0a890ac83d165b4cef9d9665f86b0465
34.158537
225
0.621922
false
false
false
false