repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
matrix-org/matrix-ios-sdk
MatrixSDKTests/MXPollBuilderTests.swift
1
8958
// // Copyright 2021 The Matrix.org Foundation C.I.C // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation class MXPollBuilderTest: XCTestCase { let builder = PollBuilder() func testBaseCase() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Alice", answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", answerIdentifiers: ["1"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 7), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.maxAllowedSelections, 7) XCTAssertEqual(poll.text, "Question") XCTAssertEqual(poll.kind, .disclosed) XCTAssertEqual(poll.answerOptions.first?.id, "1") XCTAssertEqual(poll.answerOptions.first?.text, "First answer") XCTAssertEqual(poll.answerOptions.first?.count, 2) XCTAssertEqual(poll.answerOptions.last?.id, "2") XCTAssertEqual(poll.answerOptions.last?.text, "Second answer") XCTAssertEqual(poll.answerOptions.last?.count, 0) } func testSpoiledResponseEmpty() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 1, answerIdentifiers: []))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 0) XCTAssertEqual(poll.answerOptions.last?.count, 0) } func testSpoiledResponseTooManyAnswer() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 1, answerIdentifiers: ["1", "2"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 0) XCTAssertEqual(poll.answerOptions.last?.count, 0) } func testSpoiledAnswersInvalidAnswerIdentifiers() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 1, answerIdentifiers: ["1", "2", "3"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 0) XCTAssertEqual(poll.answerOptions.last?.count, 0) } func testRepeatedAnswerIdentifiers() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", answerIdentifiers: ["1", "1", "1"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 100), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 1) XCTAssertEqual(poll.answerOptions.last?.count, 0) } func testRandomlyRepeatedAnswerIdentifiers() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", answerIdentifiers: ["1", "1", "2", "1", "2", "2", "1", "2"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 100), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 1) XCTAssertEqual(poll.answerOptions.last?.count, 1) } func testAnswerOrder() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 4, answerIdentifiers: ["2"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 2, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 1, answerIdentifiers: []))!) // Too few events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 3, answerIdentifiers: ["1", "2"]))!) // Too many let poll = builder.build(pollStartEventContent: pollStartEventContent(), events: events, currentUserIdentifier: "") XCTAssertEqual(poll.answerOptions.first?.count, 0) XCTAssertEqual(poll.answerOptions.last?.count, 1) } func testClosedPoll() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollEndEvent(timestamp: 1))) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 10, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 10, answerIdentifiers: []))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Alice", timestamp:10, answerIdentifiers: ["1", "2"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 10), events: events, currentUserIdentifier: "") XCTAssert(poll.isClosed) XCTAssertEqual(poll.answerOptions.first!.count, 1) XCTAssert(poll.answerOptions.first!.isWinner) XCTAssertEqual(poll.answerOptions.last!.count, 0) XCTAssert(!poll.answerOptions.last!.isWinner) } func testCurrentUserSingleSelection() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", answerIdentifiers: ["1"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 7), events: events, currentUserIdentifier: "Bob") XCTAssertEqual(poll.answerOptions.first?.isCurrentUserSelection, true) XCTAssertEqual(poll.answerOptions.last?.isCurrentUserSelection, false) } func testCurrentUserMultlipleSelection() { var events = [MXEvent]() events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 0, answerIdentifiers: ["1"]))!) events.append(MXEvent(fromJSON: pollResponseEventWithSender("Bob", timestamp: 1, answerIdentifiers: ["2", "1"]))!) let poll = builder.build(pollStartEventContent: pollStartEventContent(maxSelections: 7), events: events, currentUserIdentifier: "Bob") XCTAssertEqual(poll.answerOptions.first?.isCurrentUserSelection, true) XCTAssertEqual(poll.answerOptions.last?.isCurrentUserSelection, true) } // MARK: - Private private func pollStartEventContent(maxSelections: UInt = 1) -> MXEventContentPollStart { let answerOptions = [MXEventContentPollStartAnswerOption(uuid: "1", text: "First answer"), MXEventContentPollStartAnswerOption(uuid: "2", text: "Second answer")] return MXEventContentPollStart(question: "Question", kind: kMXMessageContentKeyExtensiblePollKindDisclosed, maxSelections: NSNumber(value: maxSelections), answerOptions: answerOptions) } private func pollResponseEventWithSender(_ sender: String, timestamp: Int = 0, answerIdentifiers:[String]) -> [String: Any] { return [ "event_id": "$eventId", "type": kMXEventTypeStringPollResponse, "sender": sender, "origin_server_ts": timestamp, "content": [kMXMessageContentKeyExtensiblePollResponse: [kMXMessageContentKeyExtensiblePollAnswers: answerIdentifiers]] ] } private func pollEndEvent(timestamp: Int = 0) -> [String: Any] { return [ "event_id": "$eventId", "type": kMXEventTypeStringPollEnd, "origin_server_ts": timestamp, "content": [kMXMessageContentKeyExtensiblePollEnd: [:]] ] } }
apache-2.0
a0d8d4b64c24de3742b2f1902a217abc
50.482759
142
0.674146
5.202091
false
true
false
false
cconeil/Standard-Template-Protocols
STP Example/STP Example/AwesomeViewController.swift
1
1611
// // AwesomeViewController.swift // STP Example // // Created by Chris O'Neil on 10/22/15. // Copyright © 2015 Because. All rights reserved. // import UIKit import STP class MyAwesomeView: UIView, Moveable, Pinchable, Rotatable, Tappable, Forceable {} class AwesomeViewController: UIViewController { let awesomeView = MyAwesomeView() var types:[GestureRecognizerType]? override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(types:[GestureRecognizerType]) { self.init(nibName: nil, bundle: nil) self.types = types } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.title = "Your Custom View" let awesomeView = MyAwesomeView(frame: CGRectMake(0.0, 0.0, 150.0, 150.0)) awesomeView.center = self.view.center awesomeView.backgroundColor = UIColor.blueColor() self.view.addSubview(awesomeView) for type in self.types! { switch type { case .Moveable: awesomeView.makeMoveable() case .Pinchable: awesomeView.makePinchable() case .Rotatable: awesomeView.makeRotatable() case .Tappable: awesomeView.makeTappable() case .Forceable: awesomeView.makeForceable() } } } }
mit
3638d7c249478c30909b559607508fd1
27.245614
84
0.621739
4.535211
false
false
false
false
apascual/braintree_ios
UnitTests/Helpers/MockDelegates.swift
1
3143
import XCTest @objc class MockAppSwitchDelegate : NSObject, BTAppSwitchDelegate { var willPerformAppSwitchExpectation : XCTestExpectation? = nil var didPerformAppSwitchExpectation : XCTestExpectation? = nil var willProcessAppSwitchExpectation : XCTestExpectation? = nil // XCTestExpectations verify that delegates callbacks are made; the below bools verify that they are NOT made var willPerformAppSwitchCalled = false var didPerformAppSwitchCalled = false var willProcessAppSwitchCalled = false var lastAppSwitcher : AnyObject? = nil override init() { } init(willPerform: XCTestExpectation?, didPerform: XCTestExpectation?) { willPerformAppSwitchExpectation = willPerform didPerformAppSwitchExpectation = didPerform } @objc func appSwitcherWillPerformAppSwitch(_ appSwitcher: Any) { lastAppSwitcher = appSwitcher as AnyObject? willPerformAppSwitchExpectation?.fulfill() willPerformAppSwitchCalled = true } @objc func appSwitcher(_ appSwitcher: Any, didPerformSwitchTo target: BTAppSwitchTarget) { lastAppSwitcher = appSwitcher as AnyObject? didPerformAppSwitchExpectation?.fulfill() didPerformAppSwitchCalled = true } @objc func appSwitcherWillProcessPaymentInfo(_ appSwitcher: Any) { lastAppSwitcher = appSwitcher as AnyObject? willProcessAppSwitchExpectation?.fulfill() willProcessAppSwitchCalled = true } } @objc class MockViewControllerPresentationDelegate : NSObject, BTViewControllerPresentingDelegate { var requestsPresentationOfViewControllerExpectation : XCTestExpectation? = nil var requestsDismissalOfViewControllerExpectation : XCTestExpectation? = nil var lastViewController : UIViewController? = nil var lastPaymentDriver : AnyObject? = nil func paymentDriver(_ driver: Any, requestsDismissalOf viewController: UIViewController) { lastPaymentDriver = driver as AnyObject? lastViewController = viewController requestsDismissalOfViewControllerExpectation?.fulfill() } func paymentDriver(_ driver: Any, requestsPresentationOf viewController: UIViewController) { lastPaymentDriver = driver as AnyObject? lastViewController = viewController requestsPresentationOfViewControllerExpectation?.fulfill() } } @objc class MockIdealPaymentRequestDelegate : NSObject, BTIdealRequestDelegate { var id: String? var idExpectation : XCTestExpectation? func idealPaymentStarted(_ result: BTIdealResult) { self.id = result.idealId idExpectation?.fulfill() } } @objc class MockPayPalApprovalHandlerDelegate : NSObject, BTPayPalApprovalHandler { var handleApprovalExpectation : XCTestExpectation? = nil var url : NSURL? = nil var cancel : Bool = false func handleApproval(_ request: PPOTRequest, paypalApprovalDelegate delegate: BTPayPalApprovalDelegate) { if (cancel) { delegate.onApprovalCancel() } else { delegate.onApprovalComplete(url as! URL) } handleApprovalExpectation?.fulfill() } }
mit
afbae8374c70eb63571ec4109ad03b5e
37.802469
113
0.740375
5.735401
false
true
false
false
miller-ms/ViewAnimator
ViewAnimator/ColorCell.swift
1
5169
// // ColorCell.swift // ViewAnimator // // Created by William Miller DBA Miller Mobilesoft on 5/16/17. // // This application is intended to be a developer tool for evaluating the // options for creating an animation or transition using the UIView static // methods UIView.animate and UIView.transition. // Copyright © 2017 William Miller DBA Miller Mobilesoft // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // If you would like to reach the developer you may email me at // [email protected] or visit my website at // http://millermobilesoft.com // import UIKit class ColorCell: UITableViewCell { @IBOutlet weak var lblRGB: UILabel! @IBOutlet weak var lblAlpha: UILabel! @IBOutlet weak var viewColor: UIView! @IBOutlet weak var sliderAlpha: UISlider! var alphaProperty:CGFloat = 1.0 { didSet { guard (lblAlpha != nil) else { return } let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 formatter.maximumIntegerDigits = 1 formatter.minimumIntegerDigits = 1 lblAlpha.text = formatter.string(from: NSNumber(value: Double(alphaProperty))) viewColor.alpha = alphaProperty } } var colorProperty:UIColor = UIColor.white { didSet { guard (lblRGB != nil) && (viewColor != nil) else { return } viewColor.backgroundColor = colorProperty let red = colorProperty.cgColor.components?[0] let green = colorProperty.cgColor.components?[1] let blue = colorProperty.cgColor.components?[2] let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 0 formatter.minimumFractionDigits = 0 formatter.maximumIntegerDigits = 3 formatter.minimumIntegerDigits = 1 var rgbDescription = "R: " + formatter.string(from: NSNumber(value: (UInt(red! * 255))))! rgbDescription += " G: " + formatter.string(from: NSNumber(value: (UInt(green! * 255))))! rgbDescription += " B: " + formatter.string(from: NSNumber(value: (UInt(blue! * 255))))! lblRGB.text = rgbDescription } } func showData () { let red = viewColor.backgroundColor?.cgColor.components?[0] let green = viewColor.backgroundColor?.cgColor.components?[1] let blue = viewColor.backgroundColor?.cgColor.components?[2] let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 0 formatter.minimumFractionDigits = 0 formatter.maximumIntegerDigits = 3 formatter.minimumIntegerDigits = 1 var rgbDescription = "R: " + formatter.string(from: NSNumber(value: (UInt(red! * 255))))! rgbDescription += " G: " + formatter.string(from: NSNumber(value: (UInt(green! * 255))))! rgbDescription += " B: " + formatter.string(from: NSNumber(value: (UInt(blue! * 255))))! lblRGB.text = rgbDescription formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 formatter.maximumIntegerDigits = 1 formatter.minimumIntegerDigits = 1 lblAlpha.text = formatter.string(from: NSNumber(value: sliderAlpha.value)) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func alphaChanged(_ sender: UISlider) { alphaProperty = CGFloat(sender.value) } @IBAction func alphaEndChanged(_ sender: UISlider) { alphaProperty = CGFloat(sender.value) } @IBAction func alphaStartChanged(_ sender: UISlider) { alphaProperty = CGFloat(sender.value) } }
gpl-3.0
bc2391650e003eea482730c725e56cca
30.512195
102
0.596556
5.22548
false
false
false
false
firebase/quickstart-ios
database/DatabaseExampleSwiftUI/DatabaseExample/Shared/Views/PostsView.swift
1
2271
// // Copyright (c) 2021 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI struct PostsView: View { @StateObject var postList = PostListViewModel() @StateObject var user = UserViewModel() // define variables for creating a new post for iOS #if os(iOS) || os(tvOS) @State private var newPostsViewPresented = false #endif var title: String var postsType: PostsType var body: some View { NavigationView { let postListView = List { ForEach(postList.posts) { post in PostCell(post: post) } } .onAppear { postList.getPosts(postsType: postsType) } .onDisappear { postList.onViewDisappear() } .navigationTitle(title) #if os(iOS) || os(tvOS) postListView .toolbar { ToolbarItemGroup(placement: .navigationBarLeading) { Button(action: { user.logout() }) { HStack { Image(systemName: "chevron.left") Text("Logout") } } } ToolbarItemGroup(placement: .navigationBarTrailing) { Button(action: { newPostsViewPresented = true }) { Image(systemName: "plus") } .sheet(isPresented: $newPostsViewPresented) { NewPostsView(postList: postList, isPresented: $newPostsViewPresented) } } } #elseif os(macOS) postListView #endif } } } struct PostsView_Previews: PreviewProvider { static var previews: some View { PostsView(title: "Recents", postsType: PostsType.recentPosts) } }
apache-2.0
4c6d5d6c80cdd503c98c04482d037975
27.3875
85
0.59181
4.49703
false
false
false
false
djtone/VIPER
VIPER-SWIFT/Classes/Modules/List/Application Logic/Manager/ListDataManager.swift
2
1338
// // ListDataManager.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/5/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation class ListDataManager : NSObject { var coreDataStore : CoreDataStore? func todoItemsBetweenStartDate(startDate: NSDate, endDate: NSDate, completion: (([TodoItem]) -> Void)!) { let calendar = NSCalendar.autoupdatingCurrentCalendar() let beginning = calendar.dateForBeginningOfDay(startDate) let end = calendar.dateForEndOfDay(endDate) let predicate = NSPredicate(format: "(date >= %@) AND (date <= %@)", beginning, end) let sortDescriptors = [] coreDataStore?.fetchEntriesWithPredicate(predicate, sortDescriptors: sortDescriptors as [AnyObject], completionBlock: { entries in let todoItems = self.todoItemsFromDataStoreEntries(entries) completion(todoItems) }) } func todoItemsFromDataStoreEntries(entries: [ManagedTodoItem]) -> [TodoItem] { var todoItems : [TodoItem] = [] for managedTodoItem in entries { let todoItem = TodoItem(dueDate: managedTodoItem.date, name: managedTodoItem.name) todoItems.append(todoItem) } return todoItems } }
mit
c58337fbb67a8563f028a4dfd974a775
31.658537
109
0.638266
5.10687
false
false
false
false
rolandpeelen/WatchSpringboard-Swift
SwiftSpringboard/Springboard/SpringboardItemView.swift
1
2740
// // SpringboardItemView.swift // SwiftSpringboard // // Created by Joachim Boggild on 11/08/15. // Copyright (c) 2015 Joachim Boggild. All rights reserved. // import Foundation import UIKit public class SpringboardItemView: UIView { var icon: UIImageView! var label: UILabel! var identifier: String = ""; private var _visualEffectView: UIView? private var _visualEffectMaskView: UIImageView? private let _ITEM_DIAMETER: CGFloat = 120; let kLMSpringboardItemViewSmallThreshold: CGFloat = 0.75; private var _scale: CGFloat var scale: CGFloat { get { return _scale; } set { setScale(scale, animated: false); } } private var _item: PSpringboardItem? var item: PSpringboardItem? { get { return _item; } set { _item = newValue; setTitle(_item?.label); } } init() { _scale = 1; super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) label = UILabel(); label.opaque = false; label.backgroundColor = nil; label.textColor = UIColor.whiteColor(); label.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize()); addSubview(label); icon = UIImageView(); addSubview(icon) } required public init(coder aDecoder: NSCoder) { _scale = 1; super.init(coder: aDecoder); } public override init(frame: CGRect) { _scale = 1; super.init(frame: frame); } func setScale(scale: CGFloat, animated: Bool) { if(_scale != scale) { let wasSmallBefore = (_scale < kLMSpringboardItemViewSmallThreshold); _scale = scale; setNeedsLayout() if((_scale < kLMSpringboardItemViewSmallThreshold) != wasSmallBefore) { if animated { UIView.animateWithDuration(0.3) { self.layoutIfNeeded(); if (self._scale < self.kLMSpringboardItemViewSmallThreshold) { self.label.alpha = 0; } else { self.label.alpha = 1; }; } } else { if(_scale < kLMSpringboardItemViewSmallThreshold) { label.alpha = 0; } else { label.alpha = 1; } } } } } private func setTitle(title: String?) { label.text = title ?? ""; } public override func layoutSubviews() { super.layoutSubviews() let size = self.bounds.size icon.center = CGPointMake(size.width*0.5, size.height*0.5); icon.bounds = CGRectMake(0, 0, size.width, size.height); _visualEffectView?.center = icon.center; _visualEffectView?.bounds = icon.bounds; _visualEffectMaskView?.center = icon.center; _visualEffectMaskView?.bounds = icon.bounds; label.sizeToFit() label.center = CGPointMake(size.width*0.5, size.height+4); let ascale = _ITEM_DIAMETER/size.width; icon.transform = CGAffineTransformMakeScale(ascale, ascale); _visualEffectView?.transform = icon.transform; } }
bsd-3-clause
12ebf56ba289a4509bbcccb9e7b18e9c
20.928
72
0.667883
3.309179
false
false
false
false
lakesoft/LKUserDefaultOption
Pod/Classes/LKUserDefaultSettingViewController.swift
1
1805
// // LKUserDefaultSettingViewController.swift // VideoEver // // Created by Hiroshi Hashiguchi on 2015/07/20. // Copyright (c) 2015年 lakesoft. All rights reserved. // import UIKit public class LKUserDefaultSettingViewController: UITableViewController { public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedCell = tableView.cellForRowAtIndexPath(indexPath) // NOTE: swift 2.0 // NG) option as? <LKUserDefaultOptionSingleSelection, LKUserDefaultOptionLabel ...test protocol> if let cell = selectedCell as? LKUserDefaultOptionSingleSelectionCell { let viewController = LKUserDefaultOptionSingleSelectionViewController() let option = LKUserDefaultOptionManager.getOption(cell.userDefaultOptionKeyName) if let model = option as? LKUserDefaultOptionModel, selection = option as? LKUserDefaultOptionSingleSelection { viewController.model = model viewController.selection = selection navigationController?.pushViewController(viewController, animated: true) } } else if let cell = selectedCell as? LKUserDefaultOptionMultipleSelectionCell { let viewController = LKUserDefaultOptionMultipleSelectionViewController() let option = LKUserDefaultOptionManager.getOption(cell.userDefaultOptionKeyName) if let model = option as? LKUserDefaultOptionModel, selection = option as? LKUserDefaultOptionMultipleSelection { viewController.model = model viewController.selection = selection navigationController?.pushViewController(viewController, animated: true) } } } }
mit
5c55f26abe1ef6aacfeb59bcc032be4b
45.230769
125
0.703272
6.348592
false
false
false
false
Marketcloud/marketcloud-swift-application
mCloudSampleApp/Product.swift
1
8558
import UIKit import Marketcloud //Product class open class Product { var id: Int? var description: String? var name: String? var images: [String]? var price: Double? var stock_level:Int? var quantity:Int? var hasVariants:Bool? var show:Bool //keeps track of the downloaded products open static var products = [Product]() //initialize a Product object taken from the API. (not for user's cart) internal init(id:Int, description:String, name:String, images:[String], price:Double, stock_level:Int, hasVariants:Bool) { self.id = id self.description = description self.name = name self.images = images self.price = price self.stock_level = stock_level self.hasVariants = hasVariants self.show = true } //Initialize a Product object for the user's cart internal init(id:Int, description:String, name:String, images:[String], price:Double, quantity:Int, hasVariants:Bool) { self.id = id self.description = description self.name = name self.images = images self.price = price self.quantity = quantity self.hasVariants = hasVariants self.show = true } //Method for filtering the products (not used yet...) open static func getProductsByFilters(_ marketcloud:Marketcloud, filter:Int, filterField:Int){ switch filter { case 1 : let mainList = marketcloud.getProductById(filterField) print(mainList) if (mainList["errors"] == nil) { elabProducts(mainList: mainList) } else { print("no results") return } case 2 : let mainList = marketcloud.getProductsByCategory(filterField) if (mainList["count"]! as! Int != 0) { elabProducts(mainList: mainList) } else { print("no results") return } default : print("error: set 1 for getProductById, 2 for getProductsByCategory") } } //counts how many products have been downloaded open static func getProductsCount() -> Int { return products.count } //downloads the products then calls elabProducts in order to make objects from them open static func getProducts(_ marketcloud:Marketcloud) -> Bool{ let productList = marketcloud.getProducts() return(elabProducts(mainList: productList)) } /* Elaborates the downloaded products and creates objects from them. If some fields are missing the object won't be created (there will be only valid objects...) */ fileprivate static func elabProducts(mainList:NSDictionary) -> Bool { print(mainList) products = [Product]() //print(mainList["data"]!.count) //check for a single filtered object guard (mainList["count"] != nil && mainList["data"] != nil) else { return elabOneProduct(mainList) } let items:Int = (mainList["data"]! as AnyObject).count for i in 0 ..< items { //print("Cycle \(i)") //let temp:NSDictionary = (mainList["data"]! as! NSDictionary)[i] as! NSDictionary let preTemp:NSArray = mainList["data"]! as! NSArray let temp:NSDictionary = preTemp[i] as! NSDictionary //print(temp) guard temp.value(forKey: "id") != nil else { print("id is nil - Skipping Object") continue } let tempId:Int = temp.value(forKey: "id") as! Int var tempDescription:String = "No description available" if(temp.value(forKey: "description") == nil) { print("temp[description]!! == nil - Replacing Description") } if (temp.value(forKey: "description") != nil ) { tempDescription = temp.value(forKey: "description") as! String } guard temp.value(forKey: "name") != nil else { //print("name is nil - Skipping Object") continue } let tempName:String = temp.value(forKey: "name") as! String var hasVariants:Bool = false if (temp.value(forKey: "has_variants") != nil) { hasVariants = temp.value(forKey: "has_variants") as! Bool } var tempImages = [String]() if (temp.value(forKey: "images") == nil) { //print("IMAGES IS NIL") } else { tempImages = temp.value(forKey: "images") as! [String] } guard temp.value(forKey: "price") != nil else { print("price is nil") continue } let tempPrice:Double = temp.value(forKey: "price") as! Double var stock_level:Int = 100 if(!(temp.value(forKey: "stock_level") is NSNull) && temp.value(forKey: "stock_level") != nil) { stock_level = temp.value(forKey: "stock_level") as! Int } let product = Product(id: tempId, description: tempDescription, name: tempName, images: tempImages, price: tempPrice, stock_level: stock_level, hasVariants: hasVariants) //print("Finished") products.append(product) } print("elabProducts is over! \n collected \(products.count) items!") return true } //Elaborates only one product fileprivate static func elabOneProduct(_ mainList:NSDictionary) -> Bool { // print("Did I crash? count -> \(mainList["count"])") if (mainList["data"] == nil) { print("Connection error") return false } let temp:NSDictionary = mainList["data"]! as! NSDictionary guard temp.value(forKey: "id") != nil else { return false } let tempId:Int = temp.value(forKey: "id") as! Int // print(tempId) var tempDescription:String = "No description available" if(temp.value(forKey: "description") == nil) { print("temp[description]!! == nil") } if (temp["description"]! != nil) { tempDescription = temp["description"]! as! String } guard temp.value(forKey: "name") != nil else { //print("name is nil -> returning\n------------------\n") return false } let tempName:String = temp.value(forKey: "name") as! String var tempImages = [String]() if (temp.value(forKey: "images") == nil) { //print("images is nil") } else { tempImages = temp["images"]! as! [String] } guard temp.value(forKey: "price") != nil else { //print("price is nil") return false } let tempPrice:Double = temp["price"]! as! Double var hasVariants:Bool = false if (temp.value(forKey: "has_variants") != nil) { hasVariants = temp.value(forKey: "has_variants") as! Bool } guard temp.value(forKey: "stock_level") != nil else { //print("stock_quantity is nil") return false } let stock_level:Int = temp.value(forKey: "stock_level") as! Int let product = Product(id: tempId, description: tempDescription, name: tempName, images: tempImages, price: tempPrice, stock_level:stock_level, hasVariants: hasVariants) products.append(product) return true } static func filter(_ filter: String) { let newFilter = filter.lowercased() print("Filter method for \(newFilter)") let itemsTotal = products.count for i in 0 ..< itemsTotal { if products[i].name!.lowercased().range(of: newFilter) == nil { products[i].show = false } else { print("Ok for \(products[i].name!)") products[i].show = true } } } static func removeFilters() { let itemsTotal = products.count for i in 0 ..< itemsTotal { products[i].show = true } } }
apache-2.0
9c520e661df0562ce761363bd4cc5a9c
33.647773
181
0.536574
4.684182
false
false
false
false
Jackysonglanlan/Scripts
swift/learn/functions.swift
1
1278
func tuple() -> (foo: Int, bar: String) { return (123, "abc") } var ret = tuple() print(ret.foo, ret.bar) func optionalTuple() -> (foo: Int, bar: String)? { return (456, "eff") } if let op = optionalTuple() { print(op.foo, op.bar) } let funcAsData = tuple // auto type refer let funcAsData2: () -> (Int, String)? = optionalTuple // manual // Place parameters that don’t have default values at the beginning of a function’s parameter list, // before the parameters that have default values func defaultParam(_ foo: Int = 1) -> Int { return foo } print(defaultParam()) // pack parameters into array, like js // A function may have at most one variadic parameter. func arithmeticMean(_ numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } print(arithmeticMean(1, 2, 3, 4, 5)) // You can only pass a variable as the argument for an in-out parameter // 用 C++ 术语来解释,就是你只能传一个左值,因为右值没有地址 func swapAnything<T>(_ a: inout T, _ b: inout T) { let temporaryB = b b = a a = temporaryB } var a = 1, b = 2 var s1 = "aaa", s2 = "bbb" swapAnything(&a, &b) print("\(a), \(b)") swapAnything(&s1, &s2) print("\(s1), \(s2)")
unlicense
3a51c7410d69b27f064af93c2f9e72c4
22.056604
99
0.651391
3.017284
false
false
false
false
aleph7/PlotKit
PlotKit/Views/PointSetView.swift
1
5719
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of PlotKit. The full PlotKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation /// PointSetView draws a discrete set of 2D points, optionally connecting them with lines. PointSetView does not draw axes or any other plot decorations, use a `PlotView` for that. open class PointSetView: DataView { open var pointSet: PointSet { didSet { needsDisplay = true } } public init() { pointSet = PointSet() super.init(frame: NSRect(x: 0, y: 0, width: 512, height: 512)) } public init(pointSet: PointSet) { self.pointSet = pointSet super.init(frame: NSRect(x: 0, y: 0, width: 512, height: 512)) self.xInterval = pointSet.xInterval self.yInterval = pointSet.yInterval } public init(pointSet: PointSet, xInterval: ClosedRange<Double>, yInterval: ClosedRange<Double>) { self.pointSet = pointSet super.init(frame: NSRect(x: 0, y: 0, width: 512, height: 512)) self.xInterval = xInterval self.yInterval = yInterval } open override func pointAt(_ location: NSPoint) -> Point? { var minDistance = CGFloat.greatestFiniteMagnitude var minPoint: Point? = nil for point in pointSet.points { let viewPoint = convertDataPointToView(point) let d = hypot(location.x - viewPoint.x, location.y - viewPoint.y) if d < 8 && d < minDistance { minDistance = d minPoint = point } } return minPoint } open override func draw(_ rect: CGRect) { let context = NSGraphicsContext.current()?.cgContext context?.setLineWidth(pointSet.lineWidth) if let color = pointSet.lineColor { color.setStroke() context?.addPath(path) context?.strokePath() } if let color = pointSet.fillColor { color.setFill() context?.addPath(closedPath) context?.fillPath() } drawPoints(context) } var path: CGPath { let path = CGMutablePath() if pointSet.points.isEmpty { return path } let first = pointSet.points.first! let startPoint = convertDataPointToView(first) path.move(to: startPoint) for point in pointSet.points { let point = convertDataPointToView(point) path.addLine(to: point) } return path } var closedPath: CGPath { let path = CGMutablePath() if pointSet.points.isEmpty { return path } let first = pointSet.points.first! let startPoint = convertDataPointToView(Point(x: first.x, y: 0)) path.move(to: startPoint) for point in pointSet.points { let point = convertDataPointToView(point) path.addLine(to: point) } let last = pointSet.points.last! let endPoint = convertDataPointToView(Point(x: last.x, y: 0)) path.addLine(to: endPoint) path.closeSubpath() return path } // MARK: - Point drawing func drawPoints(_ context: CGContext?) { if let color = pointSet.pointColor { color.setFill() } else if let color = pointSet.lineColor { color.setFill() } else { NSColor.black.setFill() } for point in pointSet.points { let point = convertDataPointToView(point) drawPoint(context, center: point) } } func drawPoint(_ context: CGContext?, center: CGPoint) { switch pointSet.pointType { case .none: break case .ring(let radius): self.drawCircle(context, center: center, radius: radius) case .disk(let radius): self.drawDisk(context, center: center, radius: radius) case .square(let side): self.drawSquare(context, center: center, side: side) case .filledSquare(let side): self.drawFilledSquare(context, center: center, side: side) } } func drawCircle(_ context: CGContext?, center: CGPoint, radius: Double) { let rect = NSRect( x: center.x - CGFloat(radius), y: center.y - CGFloat(radius), width: 2 * CGFloat(radius), height: 2 * CGFloat(radius)) context?.strokeEllipse(in: rect) } func drawDisk(_ context: CGContext?, center: CGPoint, radius: Double) { let rect = NSRect( x: center.x - CGFloat(radius), y: center.y - CGFloat(radius), width: 2 * CGFloat(radius), height: 2 * CGFloat(radius)) context?.fillEllipse(in: rect) } func drawSquare(_ context: CGContext?, center: CGPoint, side: Double) { let rect = NSRect( x: center.x - CGFloat(side/1), y: center.y - CGFloat(side/1), width: CGFloat(side), height: CGFloat(side)) context?.stroke(rect) } func drawFilledSquare(_ context: CGContext?, center: CGPoint, side: Double) { let rect = NSRect( x: center.x - CGFloat(side/1), y: center.y - CGFloat(side/1), width: CGFloat(side), height: CGFloat(side)) context?.fill(rect) } // MARK: - NSCoding public required init?(coder: NSCoder) { pointSet = PointSet() super.init(coder: coder) } }
mit
122ec50a2c742f2441c363e613e813f6
28.78125
180
0.578699
4.530903
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Views/SFBulletinView.swift
1
5371
// // SFModalView.swift // SwifterUI // // Created by brandon maldonado alonso on 16/02/18. // Copyright © 2018 Brandon Maldonado Alonso. All rights reserved. // import UIKit open class SFBulletinView: SFPopView { // MARK: - Instance Properties public final lazy var closeButton: SFFluidButton = { let button = SFFluidButton(automaticallyAdjustsColorStyle: self.automaticallyAdjustsColorStyle) button.imageView.image = SFAssets.imageOfClose.withRenderingMode(.alwaysTemplate) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 16 button.clipsToBounds = true return button }() public final lazy var doneButton: SFFluidButton = { let button = SFFluidButton(automaticallyAdjustsColorStyle: self.automaticallyAdjustsColorStyle) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 16 button.title = "Listo" return button }() public final lazy var titleLabel: SFLabel = { let label = SFLabel(automaticallyAdjustsColorStyle: self.automaticallyAdjustsColorStyle) label.font = .boldSystemFont(ofSize: 23) label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 1 return label }() public final lazy var messageLabel: SFLabel = { let label = SFLabel(automaticallyAdjustsColorStyle: self.automaticallyAdjustsColorStyle) label.font = .systemFont(ofSize: 17) label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.useAlternativeColors = true label.numberOfLines = 0 label.textAlignment = .center return label }() private var buttons: [SFFluidButton] = [] // MARK: - Initializers public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero, middleView: UIView? = nil, buttons: [SFFluidButton] = []) { self.buttons = buttons super.init(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle, useAlternativeColors: useAlternativeColors, frame: frame, middleView: middleView ?? SFView(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle)) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Instance Methods open override func prepareSubviews() { contentView.addSubview(closeButton) contentView.addSubview(titleLabel) contentView.addSubview(messageLabel) contentView.addSubview(middleView) if buttons.count > 0 { middleView.translatesAutoresizingMaskIntoConstraints = false buttons.forEach({ (button) in button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 16 button.useHighlightTextColor = true middleView.addSubview(button) }) } else { contentView.addSubview(doneButton) } super.prepareSubviews() } open override func setConstraints() { super.setConstraints() closeButton.setWidth(SFDimension(value: 32)) closeButton.setHeight(SFDimension(value: 32)) closeButton.clipBottom(to: .top, of: messageLabel, margin: 12) closeButton.clipRight(to: .right, margin: 12) titleLabel.clipRight(to: .right, margin: 24) titleLabel.clipLeft(to: .left, margin: 24) titleLabel.clipCenterY(to: .centerY, of: closeButton) messageLabel.clipRight(to: .right, margin: 12) messageLabel.clipLeft(to: .left, margin: 12) messageLabel.clipBottom(to: .top, of: middleView, margin: 12) contentView.removeConstraint(type: .bottom) contentView.removeConstraint(type: .top) contentView.removeConstraint(type: .centerY) contentView.clipBottom(to: .bottom, margin: 12) contentView.clipTop(to: .top, of: closeButton, margin: -12) if buttons.count > 0 { middleView.clipBottom(to: .bottom, margin: 12) for (index, button) in buttons.enumerated() { button.clipRight(to: .right) button.clipLeft(to: .left) button.setHeight(SFDimension(value: 48)) if index == 0 { button.clipBottom(to: .bottom) } else { button.clipBottom(to: .top, of: buttons[index - 1], margin: 12) } if index == buttons.count - 1 { middleView.clipTop(to: .top, of: button) } } } else { doneButton.clipSides(exclude: [.top], margin: UIEdgeInsets(top: 0, left: 12, bottom: 12, right: 12)) doneButton.setHeight(SFDimension(value: 48)) middleView.clipBottom(to: .top, of: doneButton) middleView.setHeight(SFDimension(value: 200)) } } }
mit
e14c415f5084735dff3df5f866af7a58
36.291667
116
0.61676
5.337972
false
false
false
false
DopamineLabs/DopamineKit-iOS
BoundlessKit/Classes/Integration/Dashboard/Reinforcement/Rewards/CandyBar.swift
1
18850
// // CandyBar.swift // BoundlessKit // // Created by Akash Desai on 10/11/17. // import Foundation import UIKit @objc public enum CandyBarState : Int { case showing, hidden, gone } /// Wheter the candybar should appear at the top or the bottom of the screen. /// /// - Top: The candybar will appear at the top. /// - Bottom: The candybar will appear at the bottom. @objc public enum CandyBarPosition : Int{ case top = 0, bottom } /// A level of 'springiness' for CandyBars. /// /// - None: The candybar will slide in and not bounce. /// - Slight: The candybar will bounce a little. /// - Heavy: The candybar will bounce a lot. @objc public enum CandyBarSpringiness : Int{ case none, slight, heavy fileprivate var springValues: (damping: CGFloat, velocity: CGFloat) { switch self { case .none: return (damping: 1.0, velocity: 1.0) case .slight: return (damping: 0.7, velocity: 1.5) case .heavy: return (damping: 0.6, velocity: 2.0) } } } /// CandyBar is a dropdown notification view, like a banner. @objc open class CandyBar: UIView { /// A CandyBar with the provided `title`, `subtitle`, and an optional `image`, ready to be presented with `show()`. /// /// - parameters: /// - title?: The title of the candybar. Defaults to `nil`. /// - subtitle?: The subtitle of the candybar. Defaults to `nil`. /// - image?: The image on the left of the candybar. Defaults to `nil`. /// - position: Whether the candybar should be displayed on the top or bottom. Defaults to `.Top`. /// - backgroundColor?: The color of the candybar's background view. Defaults to `UIColor.blackColor()`. /// - didTapBlock?: An action to be called when the user taps on the candybar. Defaults to `nil`. /// public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, position: CandyBarPosition = .top, backgroundColor: UIColor = UIColor.from(rgb: "#1689ce") ?? UIColor.blue, didDismissBlock: (() -> ())? = nil) { self.didDismissBlock = didDismissBlock self.image = image super.init(frame: CGRect.zero) resetShadows() addGestureRecognizers() initializeSubviews() resetTintColor() titleLabel.text = title detailLabel.text = subtitle self.position = position backgroundView.backgroundColor = backgroundColor backgroundView.alpha = 0.95 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Displays the candybar notification /// /// - parameters: /// - duration?: How long to show the candybar. If `nil`, then the candybar will be dismissed when the user taps it or until `.dismiss()` is called. /// Defaults to `nil`. /// open func show(duration: TimeInterval = 0) { DispatchQueue.main.async { UIWindow.topWindow!.addSubview(self) self.forceUpdates() let (damping, velocity) = self.springiness.springValues UIView.animate(withDuration: self.animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: { self.candybarState = .showing }, completion: { finished in if (duration == 0) { return } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) { self.dismiss() } }) } } /// Dismisses the candybar and executes the `didDismissBlock` /// open func dismiss() { let (damping, velocity) = self.springiness.springValues UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .allowUserInteraction, animations: { self.candybarState = .hidden }, completion: { finished in self.candybarState = .gone self.removeFromSuperview() self.didDismissBlock?() }) } /// How long the slide down animation should last. open var animationDuration: TimeInterval = 0.4 /// Whether the candybar should appear at the top or the bottom of the screen. Defaults to `.Top`. open var position = CandyBarPosition.top /// How 'springy' the candybar should display. Defaults to `.Slight` open var springiness = CandyBarSpringiness.slight /// The color of the text as well as the image tint color if `shouldTintImage` is `true`. open var textColor = UIColor.white { didSet { resetTintColor() } } /// Whether or not the candybar should show a shadow when presented. open var hasShadows = true { didSet { resetShadows() } } /// The text to display at the top line open var titleText: String? { get { return titleLabel.text } set(text) { titleLabel.text = text } } /// The text to display at the bottom line and in smaller text open var subtitleText: String? { get { return detailLabel.text } set(text) { detailLabel.text = text } } /// The color of the background view. Defaults to `nil`. override open var backgroundColor: UIColor? { get { return backgroundView.backgroundColor } set { backgroundView.backgroundColor = newValue } } /// The opacity of the background view. Defaults to 0.95. override open var alpha: CGFloat { get { return backgroundView.alpha } set { backgroundView.alpha = newValue } } /// A block to call when the user taps on the candybar. open var didTapBlock: (() -> ())? /// A block to call after the candybar has finished dismissing and is off screen. open var didDismissBlock: (() -> ())? /// Whether or not the candybar should dismiss itself when the user taps. Defaults to `true`. open var dismissesOnTap = true /// Whether or not the candybar should dismiss itself when the user swipes up. Defaults to `true`. open var dismissesOnSwipe = true /// Whether or not the candybar should tint the associated image to the provided `textColor`. Defaults to `true`. open var shouldTintImage = false { didSet { resetTintColor() } } /** Internal functions below Created by Harlan Haskins and modified by Akash Desai */ fileprivate let contentView = UIView() fileprivate let labelView = UIView() fileprivate let backgroundView = UIView() /// The label that displays the candybar's title. public let titleLabel: UILabel = { let label = UILabel() var titleFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline) titleFont = titleFont.withSize(26) label.font = titleFont label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() /// The label that displays the candybar's subtitle. public let detailLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() /// The image on the left of the candybar. var image: UIImage? /// The image view that displays the `image`. public let imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit return imageView }() internal var candybarState = CandyBarState.hidden { didSet { if candybarState != oldValue { forceUpdates() } } } fileprivate func forceUpdates() { guard let superview = superview, let showingConstraint = showingConstraint, let hiddenConstraint = hiddenConstraint else { return } switch candybarState { case .hidden: superview.removeConstraint(showingConstraint) superview.addConstraint(hiddenConstraint) case .showing: superview.removeConstraint(hiddenConstraint) superview.addConstraint(showingConstraint) case .gone: superview.removeConstraint(hiddenConstraint) superview.removeConstraint(showingConstraint) superview.removeConstraints(commonConstraints) } setNeedsLayout() setNeedsUpdateConstraints() superview.layoutIfNeeded() updateConstraintsIfNeeded() } @objc internal func didTap(_ recognizer: UITapGestureRecognizer) { if dismissesOnTap { dismiss() } didTapBlock?() } @objc internal func didSwipe(_ recognizer: UISwipeGestureRecognizer) { if dismissesOnSwipe { dismiss() } } fileprivate func addGestureRecognizers() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.didTap(_:)))) let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.didSwipe(_:))) swipe.direction = .up addGestureRecognizer(swipe) } fileprivate func resetTintColor() { titleLabel.textColor = textColor detailLabel.textColor = textColor imageView.image = shouldTintImage ? image?.withRenderingMode(.alwaysTemplate) : image imageView.tintColor = shouldTintImage ? textColor : nil } fileprivate func resetShadows() { layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0 layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowRadius = 4 } fileprivate var contentTopOffsetConstraint: NSLayoutConstraint! fileprivate var minimumHeightConstraint: NSLayoutConstraint! fileprivate func initializeSubviews() { let views = [ "backgroundView": backgroundView, "contentView": contentView, "imageView": imageView, "labelView": labelView, "titleLabel": titleLabel, "detailLabel": detailLabel ] translatesAutoresizingMaskIntoConstraints = false addSubview(backgroundView) minimumHeightConstraint = backgroundView.constraintWithAttribute(.height, .greaterThanOrEqual, to: 80) addConstraint(minimumHeightConstraint) // Arbitrary, but looks nice. addConstraints(backgroundView.constraintsEqualToSuperview()) backgroundView.backgroundColor = backgroundColor backgroundView.addSubview(contentView) labelView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(labelView) labelView.addSubview(titleLabel) labelView.addSubview(detailLabel) backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]|", views: views)) backgroundView.addConstraint(contentView.constraintWithAttribute(.bottom, .equal, to: .bottom, of: backgroundView)) contentTopOffsetConstraint = contentView.constraintWithAttribute(.top, .equal, to: .top, of: backgroundView) backgroundView.addConstraint(contentTopOffsetConstraint) let leftConstraintText: String if image == nil { leftConstraintText = "|" } else { contentView.addSubview(imageView) contentView.addConstraint(imageView.constraintWithAttribute(.leading, .equal, to: contentView, constant: 15.0)) contentView.addConstraint(imageView.constraintWithAttribute(.centerY, .equal, to: contentView)) imageView.addConstraint(imageView.constraintWithAttribute(.width, .equal, to: 100.0)) imageView.addConstraint(imageView.constraintWithAttribute(.height, .equal, to: .width)) leftConstraintText = "[imageView]" } let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|" contentView.translatesAutoresizingMaskIntoConstraints = false contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, views: views)) if image == nil { contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=10)-[labelView]-(>=10)-|", views: views)) } else { contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(>=10)-[imageView]-(>=10)-|", views: views)) } backgroundView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .alignAllCenterY, views: views)) for view in [titleLabel, detailLabel] { let constraintFormat = "H:|[label]-(8)-|" contentView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat(constraintFormat, options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["label": view])) } labelView.addConstraints(NSLayoutConstraint.defaultConstraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", views: views)) } // required public init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } fileprivate var showingConstraint: NSLayoutConstraint? fileprivate var hiddenConstraint: NSLayoutConstraint? fileprivate var commonConstraints = [NSLayoutConstraint]() override open func didMoveToSuperview() { super.didMoveToSuperview() guard let superview = superview, candybarState != .gone else { return } commonConstraints = self.constraintsWithAttributes([.leading, .trailing], .equal, to: superview) superview.addConstraints(commonConstraints) switch self.position { case .top: showingConstraint = self.constraintWithAttribute(.top, .equal, to: .top, of: superview) let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen. hiddenConstraint = self.constraintWithAttribute(.bottom, .equal, to: .top, of: superview, constant: yOffset) case .bottom: showingConstraint = self.constraintWithAttribute(.bottom, .equal, to: .bottom, of: superview) let yOffset: CGFloat = 7.0 // Offset the bottom constraint to make room for the shadow to animate off screen. hiddenConstraint = self.constraintWithAttribute(.top, .equal, to: .bottom, of: superview, constant: yOffset) } } open override func layoutSubviews() { super.layoutSubviews() adjustHeightOffset() layoutIfNeeded() } fileprivate func adjustHeightOffset() { guard let superview = superview, let UIApplicationShared = Application.shared else { return } if superview === UIWindow.topWindow && self.position == .top { let statusBarSize = UIApplicationShared.statusBarFrame.size let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice. contentTopOffsetConstraint.constant = heightOffset minimumHeightConstraint.constant = statusBarSize.height > 0 ? 80 : 40 } else { contentTopOffsetConstraint.constant = 0 minimumHeightConstraint.constant = 0 } } } extension NSLayoutConstraint { class func defaultConstraintsWithVisualFormat(_ format: String, options: NSLayoutConstraint.FormatOptions = NSLayoutConstraint.FormatOptions(), metrics: [String: AnyObject]? = nil, views: [String: AnyObject] = [:]) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: metrics, views: views) } } extension UIView { func constraintsEqualToSuperview(_ edgeInsets: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] { self.translatesAutoresizingMaskIntoConstraints = false var constraints = [NSLayoutConstraint]() if let superview = self.superview { constraints.append(self.constraintWithAttribute(.leading, .equal, to: superview, constant: edgeInsets.left)) constraints.append(self.constraintWithAttribute(.trailing, .equal, to: superview, constant: edgeInsets.right)) constraints.append(self.constraintWithAttribute(.top, .equal, to: superview, constant: edgeInsets.top)) constraints.append(self.constraintWithAttribute(.bottom, .equal, to: superview, constant: edgeInsets.bottom)) } return constraints } func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to constant: CGFloat, multiplier: CGFloat = 1.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to otherAttribute: NSLayoutConstraint.Attribute, of item: AnyObject? = nil, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item ?? self, attribute: otherAttribute, multiplier: multiplier, constant: constant) } func constraintWithAttribute(_ attribute: NSLayoutConstraint.Attribute, _ relation: NSLayoutConstraint.Relation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false return NSLayoutConstraint(item: self, attribute: attribute, relatedBy: relation, toItem: item, attribute: attribute, multiplier: multiplier, constant: constant) } func constraintsWithAttributes(_ attributes: [NSLayoutConstraint.Attribute], _ relation: NSLayoutConstraint.Relation, to item: AnyObject, multiplier: CGFloat = 1.0, constant: CGFloat = 0.0) -> [NSLayoutConstraint] { return attributes.map { self.constraintWithAttribute($0, relation, to: item, multiplier: multiplier, constant: constant) } } }
mit
aaaf262dc079725dba9f238e2934a74d
42.533487
268
0.664828
5.353593
false
false
false
false
GetZero/-Swift-LeetCode
LeetCode/Extension.swift
1
1787
// // ArrayExtension.swift // LeetCode // // Created by 韦曲凌 on 2017/1/3. // Copyright © 2017年 Wake GetZero. All rights reserved. // import Foundation enum OrderBy { case Ascending, Descending } extension Array { func createOrderArray(lenght: Int, orderBy: OrderBy) -> [Int] { var arr: [Int] = [] if orderBy == .Ascending { for i in 0 ... lenght { arr.append(i) } } else { for i in 0 ... lenght { arr.append(lenght - i) } } return arr } func createDisorderArray(lenght: Int, maxValue: UInt64) -> [Int] { var arr: [Int] = [] for _ in 0 ..< lenght { arr.append(Int(UInt64().random(lower: 0, upper: maxValue))) } return arr } mutating func exchanged(firstIndex: Int, secondIndex: Int) { guard firstIndex >= 0 && firstIndex < self.count && secondIndex >= 0 && secondIndex < self.count else { return } let temp = self[firstIndex] self[firstIndex] = self[secondIndex] self[secondIndex] = temp } } extension UInt64 { func random(lower: UInt64 = min, upper: UInt64 = max) -> UInt64 { var m: UInt64 let u = upper - lower var r = arc4random(type: UInt64()) if u > UInt64(Int64.max) { m = 1 + ~u } else { m = ((.max - (u * 2)) + 1) % u } while r < m { r = arc4random(type: UInt64()) } return (r % u) + lower } private func arc4random(type: UInt64) -> UInt64 { var r: UInt64 = 0 arc4random_buf(&r, MemoryLayout<UInt64>.size) return r } }
apache-2.0
a294e9a3f674c74285399bd9da56eae5
22.706667
111
0.493813
3.840173
false
false
false
false
trenskow/Slaminate
Slaminate/Interpolatable.swift
1
14744
// // Interpolation.swift // Slaminate // // Created by Kristian Trenskow on 06/02/16. // Copyright © 2016 Trenskow.io. All rights reserved. // import Foundation protocol Interpolatable { var canInterpolate: Bool { get } func interpolate(to: Interpolatable, at position: Double) -> Interpolatable var objectValue: AnyObject { get } } extension Interpolatable { var canInterpolate: Bool { return true } var objectValue: AnyObject { return self as AnyObject } } extension Bool: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return (position > 0.5 ? to : self) } var objectValue: AnyObject { return NSNumber(value: self) } } extension Double: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return (to as! Double - self) * position + self } var objectValue: AnyObject { return NSNumber(value: self) } } extension Float: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return (to as! Float - self) * Float(position) + self } var objectValue: AnyObject { return NSNumber(value: self) } } extension CGFloat: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return (to as! CGFloat - self) * CGFloat(position) + self } var objectValue: AnyObject { return NSNumber(value: Double(self)) } } extension CGPoint: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return CGPoint( x: x.interpolate(to: (to as! CGPoint).x, at: position) as! CGFloat, y: y.interpolate(to: (to as! CGPoint).y, at: position) as! CGFloat ) } var objectValue: AnyObject { return NSValue(cgPoint: self) } } extension CGSize: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return CGSize( width: width.interpolate(to: (to as! CGSize).width, at: position) as! CGFloat, height: height.interpolate(to: (to as! CGSize).height, at: position) as! CGFloat ) } var objectValue: AnyObject? { return NSValue(cgSize: self) } } extension CGRect: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return CGRect( origin: origin.interpolate(to: (to as! CGRect).origin, at: position) as! CGPoint, size: size.interpolate(to: (to as! CGRect).size, at: position) as! CGSize ) } var objectValue: AnyObject { return NSValue(cgRect: self) } } private struct Quaternion: Equatable, Interpolatable { var x: CGFloat = 0.0 var y: CGFloat = 0.0 var z: CGFloat = 0.0 var w: CGFloat = 0.0 fileprivate func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return Quaternion( x: x.interpolate(to: (to as! Quaternion).x, at: position) as! CGFloat, y: y.interpolate(to: (to as! Quaternion).y, at: position) as! CGFloat, z: z.interpolate(to: (to as! Quaternion).z, at: position) as! CGFloat, w: w.interpolate(to: (to as! Quaternion).w, at: position) as! CGFloat ) } } private func ==(lhs: Quaternion, rhs: Quaternion) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w } extension CATransform3D : Interpolatable { fileprivate init(a: [CGFloat]) { m11 = a[0]; m12 = a[1]; m13 = a[2]; m14 = a[3] m21 = a[4]; m22 = a[5]; m23 = a[6]; m24 = a[7] m31 = a[8]; m32 = a[9]; m33 = a[10]; m34 = a[11] m41 = a[12]; m42 = a[13]; m43 = a[14]; m44 = a[15] } fileprivate func toArray() -> [CGFloat] { return [ m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44, ] } fileprivate func transpose(_ m: CATransform3D) -> CATransform3D { var mT = m.toArray() var rT = CATransform3D().toArray() for i: Int in 0...15 { let col = i % 4 let row = i / 4 let j = col * 4 + row rT[j] = mT[i] } return CATransform3D(a: rT) } fileprivate func matrixQuaternion(_ m: CATransform3D) -> Quaternion { var q = Quaternion() if (m.m11 + m.m22 + m.m33 > 0) { let t = m.m11 + m.m22 + m.m33 + 1.0 let s = 0.5 / sqrt(t) q.w = s * t q.z = (m.m12 - m.m21) * s q.y = (m.m31 - m.m13) * s q.x = (m.m23 - m.m32) * s } else if (m.m11 > m.m22 && m.m11 > m.m33) { let t = m.m11 - m.m22 - m.m33 + 1.0 let s = 0.5 / sqrt(t) q.x = s * t q.y = (m.m12 + m.m21) * s q.z = (m.m31 + m.m13) * s q.w = (m.m23 - m.m32) * s } else if (m.m22 > m.m33) { let t = -m.m11 + m.m22 - m.m33 + 1.0 let s = 0.5 / sqrt(t) q.y = s * t q.x = (m.m12 + m.m21) * s q.w = (m.m31 - m.m13) * s q.z = (m.m23 + m.m32) * s } else { let t = -m.m11 - m.m22 + m.m33 + 1.0 let s = 0.5 / sqrt(t) q.z = s * t q.w = (m.m12 - m.m21) * s q.x = (m.m31 + m.m13) * s q.y = (m.m23 + m.m32) * s } return q } fileprivate func quaternionMatrix(_ q: Quaternion) -> CATransform3D { var m = CATransform3D() m.m11 = 1.0 - 2.0 * pow(q.y, 2.0) - 2.0 * pow(q.z, 2.0) m.m12 = 2.0 * q.x * q.y + 2.0 * q.w * q.z m.m13 = 2.0 * q.x * q.z - 2.0 * q.w * q.y m.m14 = 0.0 m.m21 = 2.0 * q.x * q.y - 2.0 * q.w * q.z m.m22 = 1.0 - 2.0 * pow(q.x, 2.0) - 2.0 * pow(q.z, 2.0) m.m23 = 2.0 * q.y * q.z + 2.0 * q.w * q.x m.m24 = 0.0 m.m31 = 2.0 * q.x * q.z + 2.0 * q.w * q.y m.m32 = 2.0 * q.y * q.z - 2.0 * q.w * q.x m.m33 = 1.0 - 2.0 * pow(q.x, 2.0) - 2.0 * pow(q.y, 2.0) m.m34 = 0.0 m.m41 = 0.0 m.m42 = 0.0 m.m43 = 0.0 m.m44 = 1.0 return m } fileprivate func interpolateQuaternion(_ a: Quaternion, b: Quaternion, position: Double) -> Quaternion { var q = Quaternion() let dp = Double(a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w) var theta = acos(dp) if (theta == 0.0) { return a } if (theta < 1.0) { theta *= -1.0 } let st = sin(theta) let sut = sin(position * theta) let sout = sin((1.0 - position) * theta) let coeff1 = CGFloat(sout / st) let coeff2 = CGFloat(sut / st) q.x = coeff1 * a.x + coeff2 * b.x q.y = coeff1 * a.y + coeff2 * b.y q.z = coeff1 * a.z + coeff2 * b.z q.w = coeff1 * a.w + coeff2 * b.w let qLen:CGFloat = sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w) q.x /= qLen q.y /= qLen q.z /= qLen q.w /= qLen return q } fileprivate init(tf: CATransform3D, s: Quaternion) { m11 = tf.m11 / s.x m12 = tf.m12 / s.x m13 = tf.m13 / s.x m14 = 0.0 m21 = tf.m21 / s.y m22 = tf.m22 / s.y m23 = tf.m23 / s.y m24 = 0.0 m31 = tf.m31 / s.z m32 = tf.m32 / s.z m33 = tf.m33 / s.z m34 = 0.0 m41 = 0.0 m42 = 0.0 m43 = 0.0 m44 = 1.0 } func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { var fromTf = self var toTf = to as! CATransform3D fromTf = transpose(fromTf) toTf = transpose(toTf) let from = Quaternion(x: fromTf.m14, y: fromTf.m24, z: fromTf.m34, w: 0.0) let to = Quaternion(x: toTf.m14, y: toTf.m24, z: toTf.m34, w: 0.0) let vT = from.interpolate(to: to, at: position) as! Quaternion let fromS = Quaternion( x: sqrt(pow(fromTf.m11, 2.0) + pow(fromTf.m12, 2.0) + pow(fromTf.m13, 2.0)), y: sqrt(pow(fromTf.m21, 2.0) + pow(fromTf.m22, 2.0) + pow(fromTf.m23, 2.0)), z: sqrt(pow(fromTf.m31, 2.0) + pow(fromTf.m32, 2.0) + pow(fromTf.m33, 2.0)), w: 0.0 ) let toS = Quaternion( x: sqrt(pow(toTf.m11, 2.0) + pow(toTf.m12, 2.0) + pow(toTf.m13, 2.0)), y: sqrt(pow(toTf.m21, 2.0) + pow(toTf.m22, 2.0) + pow(toTf.m23, 2.0)), z: sqrt(pow(toTf.m31, 2.0) + pow(toTf.m32, 2.0) + pow(toTf.m33, 2.0)), w: 0.0 ) let vS = fromS.interpolate(to: toS, at: position) as! Quaternion let fromRotation = CATransform3D(tf: fromTf, s: fromS) let toRotation = CATransform3D(tf: toTf, s: toS) var fromQuat = matrixQuaternion(fromRotation) var toQuat = matrixQuaternion(toRotation) let fromQuatLen: CGFloat = sqrt(fromQuat.x*fromQuat.x + fromQuat.y*fromQuat.y + fromQuat.z*fromQuat.z + fromQuat.w*fromQuat.w) fromQuat.x /= fromQuatLen fromQuat.y /= fromQuatLen fromQuat.z /= fromQuatLen fromQuat.w /= fromQuatLen let toQuatLen: CGFloat = sqrt(toQuat.x*toQuat.x + toQuat.y*toQuat.y + toQuat.z*toQuat.z + toQuat.w*toQuat.w) toQuat.x /= toQuatLen toQuat.y /= toQuatLen toQuat.z /= toQuatLen toQuat.w /= toQuatLen let valueQuat = interpolateQuaternion(fromQuat, b: toQuat, position: position) var valueTf = quaternionMatrix(valueQuat) valueTf.m11 *= vS.x valueTf.m12 *= vS.x valueTf.m13 *= vS.x valueTf.m21 *= vS.y valueTf.m22 *= vS.y valueTf.m23 *= vS.y valueTf.m31 *= vS.z valueTf.m32 *= vS.z valueTf.m33 *= vS.z valueTf.m14 = vT.x valueTf.m24 = vT.y valueTf.m34 = vT.z valueTf = transpose(valueTf) return valueTf } var objectValue: AnyObject { return NSValue(caTransform3D: self) } } extension UIColor: Interpolatable { fileprivate struct Components { var red:CGFloat = 0.0 var blue:CGFloat = 0.0 var green:CGFloat = 0.0 var alpha:CGFloat = 0.0 } fileprivate var components: Components { var components = Components() getRed(&components.red, green: &components.green, blue: &components.blue, alpha: &components.alpha) return components } func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { let from = components let to = (to as! UIColor).components return type(of: self).init( red: from.red.interpolate(to: to.red, at: position) as! CGFloat, green: from.green.interpolate(to: to.green, at: position) as! CGFloat, blue: from.blue.interpolate(to: to.blue, at: position) as! CGFloat, alpha: from.alpha.interpolate(to: to.alpha, at: position) as! CGFloat ) } } extension CGColor: Interpolatable { func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { return (UIColor(cgColor: self).interpolate(to: UIColor(cgColor: to as! CGColor), at: position) as! UIColor).cgColor } var objectValue: AnyObject { return self } } extension NSValue: Interpolatable { fileprivate var typeEncoding: String { get { return String(cString: objCType, encoding: String.Encoding.utf8)! // Fix 32-bit .replacingOccurrences(of: "NS", with: "CG") .replacingOccurrences(of: "ff", with: "dd") } } fileprivate func value<T>(_ initialValue: T) -> T { var val = initialValue getValue(&val) return val } var canInterpolate: Bool { return [ "f", "d", "{CGPoint=dd}", "{CGSize=dd}", "{CGRect={CGPoint=dd}{CGSize=dd}}", "{CATransform3D=dddddddddddddddd}" ].contains(typeEncoding) } func interpolate(to: Interpolatable, at position: Double) -> Interpolatable { // If number - but not same type. if let to = to as? NSNumber, let from = self as? NSNumber { if from.typeEncoding == "c" && to.typeEncoding == "c" { return NSNumber(value: from.boolValue.interpolate(to: to.boolValue, at: position) as! Bool as Bool) } if from.typeEncoding != "d" || to.typeEncoding != "d" { return NSNumber(value: from.doubleValue.interpolate(to: to.doubleValue, at: position) as! Double as Double) } } guard typeEncoding == (to as! NSValue).typeEncoding else { fatalError("Cannot interpolate NSValue instances of different type encoding.") } switch typeEncoding { case "f", "d": let val = value(Double()).interpolate(to: (to as! NSValue).value(Double()), at: position) return NSNumber(value: val as! Double) case "{CGPoint=dd}", "{CGPoint=ff}", "{NSPoint=ff}", "{NSPoint=dd}": let val = value(CGPoint()).interpolate(to: (to as! NSValue).value(CGPoint()), at: position) return NSValue(cgPoint: val as! CGPoint) case "{CGSize=dd}": let val = value(CGSize()).interpolate(to: (to as! NSValue).value(CGSize()), at: position) return NSValue(cgSize: val as! CGSize) case "{CGRect={CGPoint=dd}{CGSize=dd}}": let val = value(CGRect()).interpolate(to: (to as! NSValue).value(CGRect()), at: position) return NSValue(cgRect: val as! CGRect) case "{CATransform3D=dddddddddddddddd}": let val = value(CATransform3D()).interpolate(to: (to as! NSValue).value(CATransform3D()), at: position) return NSValue(caTransform3D: val as! CATransform3D) default: fatalError("Interpolation does not support type encoding \(typeEncoding).") break } } }
mit
4c8c4a032f9e9d265e4371096fec57c6
32.130337
134
0.521875
3.505231
false
false
false
false
seguemodev/Meducated-Ninja
iOS/Zippy/CabinetPickerViewController.swift
1
12649
// // CabinetPickerViewController.swift // Zippy // // Created by Geoffrey Bender on 6/19/15. // Copyright (c) 2015 Segue Technologies, Inc. All rights reserved. // import UIKit class CabinetPickerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Interface Outlets @IBOutlet weak var tableView: UITableView! // MARK: - Variables let userDefaults = NSUserDefaults.standardUserDefaults() var cabinetArray = [String]() var medication: Medication! var selectedCabinet = "" // MARK: - Lifecycle Methods // Each time view appears override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // For dynamic table row height self.tableView.estimatedRowHeight = 80 self.tableView.rowHeight = UITableViewAutomaticDimension var leftBarButton = UIBarButtonItem(title:"Cancel", style:UIBarButtonItemStyle.Plain, target:self, action:"cancel") self.navigationItem.leftBarButtonItem = leftBarButton var rightBarButton = UIBarButtonItem(title:"Save", style:UIBarButtonItemStyle.Plain, target:self, action:"saveMedicationToCabinet:") self.navigationItem.rightBarButtonItem = rightBarButton var normalButtonBackground = UIImage(named:"BlueButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10)) self.navigationItem.leftBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default) self.navigationItem.rightBarButtonItem!.setBackgroundImage(normalButtonBackground, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default) var pressedButtonBackground = UIImage(named:"GreenButtonBackground")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 10, 0, 10)) self.navigationItem.leftBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default) self.navigationItem.rightBarButtonItem!.setBackgroundImage(pressedButtonBackground, forState: UIControlState.Highlighted, barMetrics: UIBarMetrics.Default) if let font = UIFont(name:"RobotoSlab-Bold", size:14.0) { self.navigationItem.leftBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal) self.navigationItem.rightBarButtonItem!.setTitleTextAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:UIColor.whiteColor()], forState:UIControlState.Normal) } // If we have saved medicine cabinets if self.userDefaults.valueForKey("cabinetArray") != nil { // Set saved cabinets to local array self.cabinetArray = self.userDefaults.valueForKey("cabinetArray") as! [String] } } // MARK: - Table View Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.cabinetArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cabinetCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = self.cabinetArray[indexPath.row].capitalizedString if self.cabinetArray[indexPath.row] == self.selectedCabinet { cell.accessoryView = UIImageView(image:UIImage(named:"CheckedButton")) } else { cell.accessoryView = UIImageView(image:UIImage(named:"UncheckedButton")) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Set selected cabinet self.selectedCabinet = self.cabinetArray[indexPath.row] // Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells) self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None) self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Middle, animated:true) } // MARK: - My Methods // Dismiss view when cancel button is clicked func cancel() { self.navigationController?.popViewControllerAnimated(true) } // Show prompt for user to create new medicine cabinet @IBAction func createNewCabinet(sender: AnyObject) { // Create the alert controller var alert = UIAlertController(title:"Create Medicine Cabinet", message:nil, preferredStyle:.Alert) // Add the text field alert.addTextFieldWithConfigurationHandler({(textField) -> Void in textField.autocapitalizationType = UITextAutocapitalizationType.Words textField.keyboardAppearance = UIKeyboardAppearance.Dark textField.text = "" }) // Add a cancel button alert.addAction(UIAlertAction(title:"Cancel", style:.Default, handler:nil)) // Add a create button with callback alert.addAction(UIAlertAction(title:"Create", style:.Default, handler:{(action) -> Void in // Get text field from alert controller let textField = alert.textFields![0] as! UITextField // Complete creating the tag self.completeCreateNewCabinet(textField.text) })) // Present the alert view so user can enter the category name self.presentViewController(alert, animated:true, completion:nil) } // Completion handler for new cabinet creation func completeCreateNewCabinet(fieldText:String) { // Make sure user entered text if fieldText.isEmpty { // Alert user that the cabinet name is required var foundAlert = UIAlertController(title:"Attention Required", message:"Please enter a cabinet name.", preferredStyle:UIAlertControllerStyle.Alert) foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil)) self.presentViewController(foundAlert, animated:true, completion:nil) } else { // Trim string var cabinet = fieldText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // Set variable to track number of duplicates encountered var duplicates = 0 // Set variable to track highest duplicate label var highestNumber = 0 // Loop our cabinet array to check for duplicates for item in self.cabinetArray { // Get the cabinet name without the parentheses let rawStringArray = item.componentsSeparatedByString("(") // Trim the string to eliminate whitespace let trimmedRawString = rawStringArray[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // If our entered text matches a cabinet in our array if cabinet.lowercaseString == trimmedRawString { // Increase duplicate count duplicates++ // If our raw string array has more then one item, then it had parentheses if rawStringArray.count > 1 { // Get its number let labelNumber = rawStringArray[1].componentsSeparatedByString(")")[0].toInt() // Track the highest label number if labelNumber > highestNumber { highestNumber = labelNumber! } } if highestNumber >= duplicates { duplicates = highestNumber + 1 } } } // If we found duplicates if duplicates > 0 { // Modify cabinet string let modifiedCabinet = "\(cabinet.lowercaseString) (\(duplicates))" // Append the modified string to our array self.cabinetArray.insert(modifiedCabinet, atIndex:0) } else { // Append the string to our array self.cabinetArray.insert(cabinet.lowercaseString, atIndex:0) } // Set selected cabinet to newly created cabinet self.selectedCabinet = self.cabinetArray.first! // Scroll to first row self.tableView.setContentOffset(CGPointZero, animated:true) // Reload the table with the new cabinet (using this method for proper autoheight calculation on table cells) self.tableView.reloadSections(NSIndexSet(indexesInRange:NSMakeRange(0, self.tableView.numberOfSections())), withRowAnimation:.None) let medToMove = self.cabinetArray.first self.cabinetArray.removeAtIndex(0) self.cabinetArray.append(medToMove!) // Save medicine cabinet array to persistent store self.userDefaults.setValue(self.cabinetArray, forKey: "cabinetArray") // Automatically save the medication to the new cabinet self.saveMedicationToCabinet(self) } } // Save the medication to the selected medicine cabinet @IBAction func saveMedicationToCabinet(sender: AnyObject) { // Make sure user selected a cabinet if self.selectedCabinet.isEmpty { // Alert user that the cabinet name is required var foundAlert = UIAlertController(title:"Attention Required", message:"Please choose a cabinet to save to.", preferredStyle:UIAlertControllerStyle.Alert) foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil)) self.presentViewController(foundAlert, animated:true, completion:nil) } else { // Set the medication object's medicine cabinet to selected picker row value self.medication.medicineCabinet = self.selectedCabinet // Create empty saved medication array var savedMedications = [Medication]() // If we have a stored medication array, then load the contents into our empty array if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey("medicationArray") as? NSData { savedMedications = NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as! [Medication] } // Add saved medication to our array savedMedications.append(self.medication) // Save the modified medication array let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(savedMedications as NSArray) self.userDefaults.setObject(archivedObject, forKey:"medicationArray") self.userDefaults.synchronize() // Alert user that the medication has been saved let indexPath = self.tableView.indexPathForSelectedRow() // Create confirmation var foundAlert = UIAlertController(title:"Success", message:"You have successfully saved this medication to \(self.selectedCabinet.capitalizedString).", preferredStyle:UIAlertControllerStyle.Alert) // Create handler for OK button foundAlert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:{(action) -> Void in // Dismiss the view self.navigationController?.popViewControllerAnimated(true) })) // Show confirmation self.presentViewController(foundAlert, animated:true, completion:nil) } } }
cc0-1.0
98d908c828b6db8daf462bb09226ae94
43.227273
209
0.63167
6.173255
false
false
false
false
fmscode/JSONtoFoundation
JSONtoFoundation/UnderscoreReplacement.swift
1
1033
// // UnderscoreReplacement.swift // JSON Convert // // Created by Frank Michael on 8/23/14. // Copyright (c) 2014 Frank Michael Sanchez. All rights reserved. // import Foundation extension String { func underscoreReplacement() -> String { let stringAsNSString: NSString = self if let range = self.rangeOfString("_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) { println(range) let underScoreRange = range.startIndex let beforeUnder = self.substringToIndex(underScoreRange) let afterUnder = self.substringFromIndex(underScoreRange.successor()).capitalizedString var cleaned = "\(beforeUnder)\(afterUnder)" if let range = cleaned.rangeOfString("_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) { cleaned = cleaned.underscoreReplacement() return cleaned } return cleaned; } return self; } }
mit
935435c08744d7dad81f29a45f69c7ef
35.928571
135
0.649564
5.08867
false
false
false
false
ddimitrov90/EverliveSDK
Tests/Pods/EverliveSDK/EverliveSDK/EverliveApp.swift
2
1310
// // EverliveApp.swift // EverliveSwift // // Created by Dimitar Dimitrov on 2/15/16. // Copyright © 2016 ddimitrov. All rights reserved. // import Foundation import EVReflection public class EverliveApp { var appId: String public private(set) var connection: EverliveConnection required public init(appId: String) { self.appId = appId self.connection = EverliveConnection(appId: self.appId, baseUrl: self._apiServerUrl, apiVersion: self._apiVersion) EVReflection.setBundleIdentifier(EverliveApp.self) ConversionOptions.DefaultNSCoding = [.PropertyMapping] } public func Data<T>() -> DataHandler<T>{ return DataHandler<T>(connection: self.connection) } public func Users<T>() -> UsersHandler<T> { return UsersHandler(connection: self.connection) } public func Authentication() -> AuthenticationHandler { return AuthenticationHandler(connection: self.connection) } public func Files() -> FilesHandler { return FilesHandler(connection: self.connection) } public func Push() -> PushHandler { return PushHandler(connection: self.connection) } let _apiServerUrl: String = "http://api.everlive.com" let _apiVersion: String = "/v1" }
mit
ca852ed81c1b3f58bea2e9f65142e1f4
27.478261
122
0.669213
4.452381
false
false
false
false
humeng12/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
1
5292
// // PageContentView.swift // DouYuZB // // Created by 胡猛 on 2016/11/29. // Copyright © 2016年 HuMeng. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView:PageContentView,progress : CGFloat,sourceIndex : Int,targetIndex : Int) } fileprivate let ContentCellID = "ContentCellID" class PageContentView: UIView { fileprivate var childVcs:[UIViewController] fileprivate weak var parentViewController:UIViewController? fileprivate var startOffsetX : CGFloat = 0 weak var delegate: PageContentViewDelegate? fileprivate var isForbidScrollDelegate : Bool = false fileprivate lazy var collectionView:UICollectionView = {[weak self] in //1 创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //2 创建UICollectionView let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:ContentCellID ) return collectionView }() init(frame: CGRect, childVcs: [UIViewController],parentViewController:UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView { fileprivate func setupUI() { //1 将所有的子控制器添加父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //2 添加UICollectionView,用于在cell中存放控制器的view addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView:UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) //先移除 for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell; } } // UICollectionViewDelegate方法 extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate {return} //1 获取数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 //2 判断是左滑还是右滑 let currentoffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentoffsetX > startOffsetX { //计算比例 progress = currentoffsetX / scrollViewW - floor(currentoffsetX / scrollViewW) //计算sourceIndex sourceIndex = Int(currentoffsetX / scrollViewW) //计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if currentoffsetX - startOffsetX == scrollViewW { progress = 1.0 targetIndex = sourceIndex } } else { progress = 1 - (currentoffsetX / scrollViewW - floor(currentoffsetX / scrollViewW)) targetIndex = Int(currentoffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //对外暴露的方法 处理滚动 extension PageContentView { func setCurrentIndex(currentIndex :Int) { isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false) } }
mit
23911f6f367ab42807a0f72d0aaca108
28.411429
124
0.631047
6.048179
false
false
false
false
1amageek/StripeAPI
StripeAPI/Models/CORE_RESOURCES/Charge.swift
1
8710
// // Charge.swift // StripeAPI // // Created by 1amageek on 2017/10/01. // Copyright © 2017年 Stamp Inc. All rights reserved. // import Foundation import APIKit public struct Charge: StripeModel, ListProtocol { public static var path: String { return "/charges"} private enum CodingKeys: String, CodingKey { case id case object case amount case amountRefunded = "amount_refunded" case application case applicationFee = "application_fee" case balanceTransaction = "balance_transaction" case captured case created case currency case customer case description case destination case dispute case failureCode = "failure_code" case failureMessage = "failure_message" case fraudDetails = "fraud_details" case invoice case livemode case metadata case onBehalfOf = "on_behalf_of" case order case outcome case paid case receiptEmail = "receipt_email" case receiptNumber = "receipt_number" case refunded case refunds case review case shipping case source case sourceTransfer = "source_transfer" case statementDescriptor = "statement_descriptor" case status case transferGroup = "transfer_group" } public let id: String public let object: String public let amount: Double public let amountRefunded: Double public let application: String? public let applicationFee: String? public let balanceTransaction: String? public let captured: Bool public let created: TimeInterval public let currency: Currency public let customer: String public let description: String? public let destination: String? public let dispute: String? public let failureCode: String? public let failureMessage: String? public let fraudDetails: FraudDetails public let invoice: String? public let livemode: Bool public let metadata: [String: String]? public let onBehalfOf: String? public let order: String? public let outcome: Outcome public let paid: Bool public let receiptEmail: String? public let receiptNumber: String? public let refunded: Bool? public let refunds: List<Refund> public let review: String? public let shipping: Shipping? public let source: Card public let sourceTransfer: String? public let statementDescriptor: String? public let status: Status public let transferGroup: String? public enum Status: String, Codable { case succeeded case pending case failed } public struct FraudDetails: Codable { private enum CodingKeys: String, CodingKey { case userReport = "user_report" case stripeReport = "stripe_report" } public let userReport: UserReport? public let stripeReport: StripeReport? public enum UserReport: String, Codable { case safe case fraudulent } public enum StripeReport: String, Codable { case fraudulent } } } extension Charge { // MARK: - Create public struct Create: StripeParametersAPI { public typealias Response = Charge public var method: HTTPMethod { return .post } public var path: String { return Charge.path } public var _parameters: Any? public init(amount: Double, currency: Currency, customer: String) { self._parameters = Parameters(amount: amount, currency: currency, customer: customer) } public init(amount: Double, currency: Currency, source: String) { self._parameters = Parameters(amount: amount, currency: currency, source: source) } public init(parameters: Parameters) { self._parameters = parameters } public struct Parameters: Codable { private enum CodingKeys: String, CodingKey { case amount case currency case applicationFee = "application_fee" case capture case description case destination case transferGroup = "transfer_group" case onBehalfOf = "on_behalf_of" case metadata case receiptEmail = "receipt_email" case shipping case customer case source case statementDescriptor = "statement_descriptor" } public let amount: Double public let currency: Currency public var applicationFee: String? = nil public var capture: Bool? = nil public var description: String? = nil public var destination: Destination? = nil public var transferGroup: String? = nil public var onBehalfOf: String? = nil public var metadata: [String: String]? = nil public var receiptEmail: String? = nil public var shipping: Shipping? = nil public let customer: String? public let source: String? public var statementDescriptor: String? = nil public init(amount: Double, currency: Currency, customer: String) { self.amount = amount self.currency = currency self.customer = customer self.source = nil } public init(amount: Double, currency: Currency, source: String) { self.amount = amount self.currency = currency self.customer = nil self.source = source } public struct Destination: Codable { public let account: String public var amount: Double? = nil } } } // MARK: - Retrieve public struct Retrieve: StripeAPI { public typealias Response = Charge public var method: HTTPMethod { return .get } public var path: String { return "\(Charge.path)/\(id)" } public let id: String public init(id: String) { self.id = id } } // MARK: - Update public struct Update: StripeParametersAPI { public typealias Response = Charge public var method: HTTPMethod { return .post } public var path: String { return "\(Charge.path)/\(id)" } public let id: String public var _parameters: Any? public init(id: String, parameters: Parameters) { self.id = id self._parameters = parameters } public struct Parameters: Codable { private enum CodingKeys: String, CodingKey { case description case fraudDetails = "fraud_details" case metadata case receiptEmail = "receipt_email" case shipping case transferGroup = "transfer_group" } public var description: String? = nil public var fraudDetails: FraudDetails? = nil public var metadata: [String: String]? = nil public var receiptEmail: String? = nil public var shipping: Shipping? = nil public var transferGroup: String? = nil } } // MARK: - Capture public struct Capture: StripeParametersAPI { public typealias Response = Charge public var method: HTTPMethod { return .post } public var path: String { return "\(Charge.path)/\(id)/capture" } public let id: String public var _parameters: Any? public init(id: String, parameters: Parameters? = nil) { self.id = id self._parameters = parameters } public struct Parameters: Codable { private enum CodingKeys: String, CodingKey { case amount case applicationFee = "application_fee" case destination case receiptEmail = "receipt_email" case statementDescriptor = "statement_descriptor" } public var amount: Double? = nil public var applicationFee: String? = nil public var destination: Destination? = nil public var receiptEmail: String? = nil public var statementDescriptor: String? = nil public struct Destination: Codable { public let account: String public var amount: Double? = nil } } } }
mit
0835ba3b120c05e3977f3d0201ebb060
28.120401
97
0.58585
5.398016
false
false
false
false
IvonLiu/moscrop-secondary-ios
MoscropSecondary/TeacherTableViewController.swift
1
9534
// // TeacherTableViewController.swift // MoscropSecondary // // Created by Jason Wong on 2015-10-06. // Copyright (c) 2015 Ivon Liu. All rights reserved. // import UIKit import Parse import Foundation class TeacherTableViewController: UITableViewController, UISearchBarDelegate { var teachers = [PFObject]() var wifiChecked = true @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Swipe Gesture let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) leftSwipe.direction = .Left let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) rightSwipe.direction = .Right view.addGestureRecognizer(leftSwipe) view.addGestureRecognizer(rightSwipe) // Retrieve NSUserDefaults let defaults = NSUserDefaults.standardUserDefaults() if (defaults.objectForKey("WifiOnly") != nil) { wifiChecked = defaults.boolForKey("WifiOnly") } loadTeachers() } func handleSwipe(sender:UISwipeGestureRecognizer){ let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController vc.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve vc.modalPresentationStyle = UIModalPresentationStyle.FullScreen if (sender.direction == .Left) { vc.selectedIndex = 4 self.presentViewController(vc, animated: true, completion: nil) } if (sender.direction == .Right) { vc.selectedIndex = 2 self.presentViewController(vc, animated: true, completion: nil) } } override func viewDidAppear(animated: Bool) { searchBar.delegate = self } // populates teachers array with parse data func loadTeachers() { let query = PFQuery(className:"teachers") query.includeKey("Dept") query.orderByAscending("LastName") if Utils.checkConnection() == NetworkStatus.WiFiConnection && Utils.isConnectedToNetwork(){ query.cachePolicy = .NetworkOnly } else if Utils.checkConnection() == NetworkStatus.WWANConnection { if self.wifiChecked { query.cachePolicy = .CacheOnly } else { query.cachePolicy = .NetworkOnly } } else { query.cachePolicy = .CacheOnly } print(query.hasCachedResult) if self.searchBar.text != "" { query.whereKey("searchText", containsString: self.searchBar.text!.lowercaseString) } query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in if error == nil { if objects == nil || objects!.count == 0 { query.clearCachedResult() } self.teachers.removeAll(keepCapacity: false) self.teachers = Array(objects!.generate()) self.tableView.reloadData() } else { print("Error: \(error!) \(error!.userInfo)") } } } func searchBarTextDidEndEditing(searchBar: UISearchBar) { // Dismiss the keyboard searchBar.resignFirstResponder() // Force reload of table data loadTeachers() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { // Dismiss the keyboard searchBar.resignFirstResponder() // Force reload of table data loadTeachers() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { // Clear any search criteria searchBar.text = "" // Dismiss the keyboard searchBar.resignFirstResponder() // Force reload of table data loadTeachers() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.teachers.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("teacher", forIndexPath: indexPath) as! TeacherTableViewCell let teacher = teachers[indexPath.row] if let prefix = teacher["Prefix"] as? String{ if let firstName = teacher["FirstName"] as? String{ if let lastName = teacher["LastName"] as? String{ var teacherName = prefix + ". " + String(firstName[firstName.startIndex.advancedBy(0)]) + ". " + lastName cell.teacherNameLabel.text = teacherName cell.teacherName = teacherName } } } // print(teacher["searchText"]) if let dept = teacher["Department"] as? String{ cell.fieldWorkLabel.text = dept cell.department = dept var url : NSURL? if let deptObj = teacher["Dept"] as? PFObject{ if let icon = deptObj["image"] as? String{ url = NSURL(string: icon) // print(url) } } if url != nil { cell.fieldImage.layer.cornerRadius = 21 cell.fieldImage.kf_setImageWithURL(url!, placeholderImage: UIImage (named: "default_teacher")) } } if let rooms = teacher["Rooms"] as? Array<String>{ cell.rooms = rooms } else { cell.rooms = [] } if let email = teacher["Email"] as? String { cell.email = email } else { cell.email = "" } if let website = teacher["Sites"] as? String{ cell.website = website } else { cell.website = "" } // cell.selectionStyle = UITableViewCellSelectionStyle.None // Configure the cell... return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 58.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! TeacherTableViewCell var message = "" if cell.department != "" { message += "\n Department \n" + cell.department } if !cell.rooms.isEmpty { message += "\n\n Room \n" + cell.combineRooms() } if cell.email != "" { message += "\n\n Email \n" + cell.email } if cell.website != "" { message += "\n\n Site \n" + cell.website } let alert = UIAlertController(title: cell.teacherName, message: message, preferredStyle: .Alert) if cell.email != "" { let emailAction = UIAlertAction(title: "Email Now", style: .Default) { (action) -> Void in //direct them to sending email self.tableView.deselectRowAtIndexPath(indexPath, animated: true) // does not work in simulator; only on device let url = NSURL(string: "mailto:" + cell.email) UIApplication.sharedApplication().openURL(url!) } alert.addAction(emailAction) } if cell.website != "" { let siteAction = UIAlertAction(title: "Enter Site", style: .Default) { (action) -> Void in //direct them to site self.tableView.deselectRowAtIndexPath(indexPath, animated: true) UIApplication.sharedApplication().openURL(NSURL(string: cell.website)!) } alert.addAction(siteAction) } let defaultAction = UIAlertAction(title: "OK", style: .Default) {(action) -> Void in self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } alert.addAction(defaultAction) presentViewController(alert, animated: true, completion: nil) if ThemeManager.currentTheme() == ThemeType.Black { alert.view.tintColor = UIColor.blackColor() } } }
mit
0777836cd211d9603ff27c5f6d81fd1e
31.989619
125
0.549402
5.760725
false
false
false
false
YusukeHosonuma/swift-commons
SwiftCommons/Array+.swift
2
1568
// // Array+.swift // SwiftCommons // // Created by Yusuke on 8/24/15. // Copyright © 2015 Yusuke. All rights reserved. // import Foundation public extension Array { public subscript(orNil index: Int) -> Element? { return (index < 0 || count <= index) ? nil : self[index] } public func inits() -> Array { return Array(self[0..<(count - 1)]) } public func tail() -> Array { return (count <= 1) ? [] : Array(self[1..<count]) } public func take(_ n: Int) -> Array { return Array(self[0..<Swift.min(n, count)]) } public func drop(_ n: Int) -> Array { if n == 0 { return self } else { return Array(self[n..<count]) } } public func forEach(_ f: (Element) -> ()) { for n: Element in self { f(n) } } /// Alias for reduce, like Haskell. public func foldl<T>(_ acc: T, f: (_ a: T, _ b: Element) -> T) -> T { return reduce(acc, f) } /// foldr from Haskell. public func foldr<T>(_ acc: T, f: (_ a: T, _ b: Element) -> T) -> T { return reversed().reduce(acc, f) } /// foldl1 from Haskell. public func foldl1(_ f: (_ a: Element, _ b: Element) -> Element) -> Element { var x = first! for e in tail() { x = f(x, e) } return x } /// foldr1 from Haskell. public func foldr1(_ f: (_ a: Element, _ b: Element) -> Element) -> Element { return reversed().foldl1(f) } }
mit
0536cd64e0da931a0ef43a9238dfbe80
22.742424
81
0.483727
3.610599
false
false
false
false
eoger/firefox-ios
Client/Frontend/Browser/OpenWithSettingsViewController.swift
2
4372
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class OpenWithSettingsViewController: ThemedTableViewController { typealias MailtoProviderEntry = (name: String, scheme: String, enabled: Bool) var mailProviderSource = [MailtoProviderEntry]() fileprivate let prefs: Prefs fileprivate var currentChoice: String = "mailto" init(prefs: Prefs) { self.prefs = prefs super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsOpenWithSectionName tableView.accessibilityIdentifier = "OpenWithPage.Setting.Options" let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight) let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame) headerView.titleLabel.text = Strings.SettingsOpenWithPageTitle.uppercased() headerView.showTopBorder = false headerView.showBottomBorder = true let footerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame) footerView.showTopBorder = true footerView.showBottomBorder = false tableView.tableHeaderView = headerView tableView.tableFooterView = footerView NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) appDidBecomeActive() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.prefs.setString(currentChoice, forKey: PrefsKeys.KeyMailToOption) } @objc func appDidBecomeActive() { reloadMailProviderSource() updateCurrentChoice() tableView.reloadData() } func updateCurrentChoice() { var previousChoiceAvailable: Bool = false if let prefMailtoScheme = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { mailProviderSource.forEach({ (name, scheme, enabled) in if scheme == prefMailtoScheme { previousChoiceAvailable = enabled } }) } if !previousChoiceAvailable { self.prefs.setString(mailProviderSource[0].scheme, forKey: PrefsKeys.KeyMailToOption) } if let updatedMailToClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { self.currentChoice = updatedMailToClient } } func reloadMailProviderSource() { if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { mailProviderSource = dictRoot.map { dict in let nsDict = dict as! NSDictionary return (name: nsDict["name"] as! String, scheme: nsDict["scheme"] as! String, enabled: canOpenMailScheme(nsDict["scheme"] as! String)) } } } func canOpenMailScheme(_ scheme: String) -> Bool { if let url = URL(string: scheme) { return UIApplication.shared.canOpenURL(url) } return false } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ThemedTableViewCell() let option = mailProviderSource[indexPath.row] cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.name, enabled: option.enabled) cell.accessoryType = (currentChoice == option.scheme && option.enabled) ? .checkmark : .none cell.isUserInteractionEnabled = option.enabled return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mailProviderSource.count } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.currentChoice = mailProviderSource[indexPath.row].scheme tableView.reloadData() } }
mpl-2.0
4c619351d5215b7c38c51a02af614f1a
36.367521
143
0.677264
5.569427
false
false
false
false
ejensen/cleartext-mac
Simpler/LanguagePopupButton.swift
1
1340
// // LanguagePopupButton.swift // Simpler // // Created by Morten Just Petersen on 11/26/15. // Copyright © 2015 Morten Just Petersen. All rights reserved. // import Cocoa class LanguagePopupButton: NSPopUpButton { required init?(coder: NSCoder) { super.init(coder: coder) setup() } override func mouseUp(theEvent: NSEvent) { Swift.print("mouse is up") } override func didCloseMenu(menu: NSMenu, withEvent event: NSEvent?) { styleItems() } func setup(){ self.wantsLayer = true populateItems() styleItems() style() } func style(){ layer?.backgroundColor = NSColor(red:0.902, green:0.902, blue:0.902, alpha:0.5).CGColor } func populateItems(){ for l in C.languages { self.addItemWithTitle(l.name) } } func styleItems(){ let menuAttributes = [ NSForegroundColorAttributeName : C.languageItemColor ] for item in self.itemArray { let s = NSMutableAttributedString(string: item.title, attributes: menuAttributes) item.attributedTitle = s } } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) // Drawing code here. } }
gpl-3.0
06ec900a8578896855a0540b64f099e3
20.95082
95
0.579537
4.523649
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Controllers/Model/Locations/TrolleyLocationServiceFake.swift
1
2217
// // TrolleyLocationServiceFake.swift // TrolleyTracker // // Created by Austin Younts on 10/28/15. // Copyright © 2015 Code For Greenville. All rights reserved. // import Foundation import CoreLocation class TrolleyLocationServiceFake: TrolleyLocationService { private var updateTimer: Timer? private var lastUpdateIndex: Int = 0 private var lastUpdateIndex1: Int = 2 var trolleyObservers = ObserverSet<[Trolley]>() var trolleyPresentObservers = ObserverSet<Bool>() func startTrackingTrolleys() { updateTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(TrolleyLocationServiceFake.updateTrolleys), userInfo: nil, repeats: true) updateTrolleys() } func stopTrackingTrolley() { updateTimer?.invalidate() } func resetTrolleys() { } @objc private func updateTrolleys() { trolleyPresentObservers.notify(true) // trolleyObservers.notify(Trolley(identifier: 1, location: locations[nextLocationIndex()], name: "Trolley 1", number: 1)) // trolleyObservers.notify(Trolley(identifier: 2, location: locations[nextLocationIndex()], name: "Trolley 2", number: 2)) // trolleyObservers.notify([Trolley(identifier: 1, location: locations[0], name: "Trolley 1", number: 1)]) // trolleyObservers.notify([Trolley(identifier: 2, location: locations[3], name: "Trolley 2", number: 2)]) } private func nextLocationIndex() -> Int { let currentIndex = lastUpdateIndex lastUpdateIndex = lastUpdateIndex >= (locations.count - 1) ? 0 : lastUpdateIndex + 1 return currentIndex } private func nextLocationIndex1() -> Int { let currentIndex = lastUpdateIndex1 lastUpdateIndex1 = lastUpdateIndex1 >= (locations.count - 1) ? 0 : lastUpdateIndex1 + 1 return currentIndex } var locations: [CLLocation] = [ CLLocation(latitude: 34.8595832, longitude: -82.3952439), CLLocation(latitude: 34.8503157, longitude: -82.3992308), CLLocation(latitude: 34.8466131, longitude: -82.400934), CLLocation(latitude: 34.8416466, longitude: -82.407466) ] }
mit
ee4f72643bfbcd166861f664e9b53a84
35.327869
167
0.672834
4.540984
false
false
false
false
curiousurick/BluetoothBackupSensor-iOS
CSS427Bluefruit_Connect/BLE Test/MqttSettingsEditValueCell.swift
5
986
// // MqttServiceEditValueCell.swift // Adafruit Bluefruit LE Connect // // Created by Antonio García on 30/07/15. // Copyright (c) 2015 Adafruit Industries. All rights reserved. // import UIKit class MqttSettingsEditValueCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var valueTextField: UITextField? @IBOutlet weak var typeTextField: UITextField? func reset() { valueTextField?.text = nil valueTextField?.placeholder = nil valueTextField?.keyboardType = UIKeyboardType.Default; typeTextField?.text = nil typeTextField?.inputView = nil typeTextField?.inputAccessoryView = nil } /* override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } */ }
mit
2abbd11f2ed0c6dbd32df98aaf923793
24.921053
64
0.675127
4.852217
false
false
false
false
Fri3ndlyGerman/OpenWeatherSwift
Sources/HPOpenWeather/DataTypes/WeatherIcon.swift
1
2647
#if canImport(UIKit) import SwiftUI import UIKit extension WeatherCondition { /// The corresponding system weather icon @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public var systemIcon: WeatherSystemIcon? { return WeatherIcon.make(from: iconString) } } public enum WeatherIcon: String { case clearSky = "01" case fewClouds = "02" case scatteredClouds = "03" case brokenClouds = "04" case showerRain = "09" case rain = "10" case thunderstorm = "11" case snow = "13" case mist = "50" init?(apiCode: String) { let code = String(apiCode.dropLast()) self.init(rawValue: code) } @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) var day: WeatherSystemIcon { return WeatherSystemIcon(icon: self, night: false) } @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) var night: WeatherSystemIcon { return WeatherSystemIcon(icon: self, night: true) } @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) static func make(from iconName: String) -> WeatherSystemIcon? { guard iconName.count == 3, let iconType = WeatherIcon(apiCode: iconName) else { return nil } let isNightIcon = iconName.last! == "n" return isNightIcon ? iconType.night : iconType.day } } @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public struct WeatherSystemIcon { private let icon: WeatherIcon private let isNightIcon: Bool fileprivate init(icon: WeatherIcon, night: Bool) { self.icon = icon self.isNightIcon = night } public var regularUIIcon: UIImage { UIImage(systemName: iconName(filled: false))! } public var filledUIIcon: UIImage { UIImage(systemName: iconName(filled: true))! } public func iconName(filled: Bool) -> String { var iconName = "" switch self.icon { case .clearSky: iconName = isNightIcon ? "moon" : "sun.max" case .fewClouds: iconName = isNightIcon ? "cloud.moon" : "cloud.sun" case .scatteredClouds: iconName = "cloud" case .brokenClouds: iconName = "smoke" case .showerRain: iconName = "cloud.rain" case .rain: iconName = isNightIcon ? "cloud.moon.rain" : "cloud.sun.rain" case .thunderstorm: iconName = "cloud.bolt.rain" case .snow: return "snow" case .mist: iconName = "cloud.fog" } if filled { iconName.append(".fill") } return iconName } } #endif
mit
eaa94c074d7a4e165bf420884d5491ea
24.209524
87
0.588591
4.09119
false
false
false
false
instacrate/tapcrate-api
Sources/api/Collections/TagCollection.swift
1
3118
// // TagCollection.swift // tapcrate-api // // Created by Hakon Hanesand on 6/3/17. // // import HTTP import Vapor import Fluent final class TagCollection: EmptyInitializable { required init() { } typealias Wrapped = HTTP.Responder func build(_ builder: RouteBuilder) { builder.group("products") { products in products.post(Product.parameter, "tags") { request in let product: Product = try request.parameters.next() let delete = request.query?["delete"]?.bool ?? false let rawTags = request.json if (delete) { try product.tags().all().forEach { try product.tags().remove($0) } } let tags: [Tag] if let _tagIds: [Int]? = try? rawTags?.array?.converted(in: emptyContext), let tagIds = _tagIds { let ids = try tagIds.converted(to: Array<Node>.self, in: jsonContext) tags = try Tag.makeQuery().filter(.subset(Tag.idKey, .in, ids)).all() } else if let _tags: [Node] = rawTags?.node.array { tags = try _tags.map { let tag = try Tag(node: $0) try tag.save() return tag } } else { throw Abort.custom(status: .badRequest, message: "Invalid json, must be array of new tags to create, or array of existing tag_ids") } try tags.forEach { try product.tags().add($0) } return try product.tags().all().makeResponse() } products.post(Product.parameter, "tags", Tag.parameter) { request in let product: Product = try request.parameters.next() let tag: Tag = try request.parameters.next() guard try product.maker_id == request.maker().id() else { throw Abort.custom(status: .unauthorized, message: "Can not modify another user's product.") } try Pivot<Tag, Product>.attach(tag, product) return try product.tags().all().makeResponse() } products.delete(Product.parameter, "tags", Tag.parameter) { request in let product: Product = try request.parameters.next() let tag: Tag = try request.parameters.next() guard try product.maker_id == request.maker().id() else { throw Abort.custom(status: .unauthorized, message: "Can not modify another user's product.") } try Pivot<Tag, Product>.detach(tag, product) return try product.tags().all().makeResponse() } } } }
mit
efa2e10df40e6797a5c92fef93463119
36.119048
151
0.471777
5.170813
false
false
false
false
GongChengKuangShi/DYZB
DouYuTV/DouYuTV/Classes/Mains/View/PageContentView.swift
1
6197
// // PageContentView.swift // DouYuTV // // Created by xrh on 2017/9/5. // Copyright © 2017年 xiangronghua. All rights reserved. // //视屏地址:http://study.163.com/course/courseLearn.htm?courseId=1003309014&from=study#/learn/video?lessonId=1003764483&courseId=1003309014 import UIKit private let ContentCellID = "ContentCellID" protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } class PageContentView: UIView { //MARK:- 懒加载属性 var chidldVs: [UIViewController] var startOffsetX: CGFloat = 0 /* HomeViewController对pageContentView是强引用,而pageContentView对UIViewController(也就是HomeViewController)也是强引用,所以会造成一个循环引用,会造成两个对象不能销毁掉 */ weak var parenViewController : UIViewController? var isForbidScrollDelegate : Bool = false weak var delegate : PageContentViewDelegate? /* 因为创建懒加载是一个闭包,所以self.用法可能会造成循环引用,所以需要把它变成弱引用 */ lazy var collectionView: UICollectionView = { [weak self] in // 1 let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal // 2 let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //-- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) { self.chidldVs = childVcs self.parenViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // -- 设置UI界面 extension PageContentView { // 1、将所有的子控制器添加到父控制器中 func setupUI() { for chidldVc in chidldVs { parenViewController?.addChildViewController(chidldVc) } //2、添加UIControllerView,用于在Cell中存储控制器的View addSubview(collectionView) collectionView.frame = bounds } } // -- CollectionViewDataSource extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return chidldVs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVC = chidldVs[indexPath.row] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //0、判断是否是点击事件 if isForbidScrollDelegate { return } // 1、定义获取需要的数据 var progress: CGFloat = 0 var sourceIndex: Int = 0 var targetIndex: Int = 0 //2、判断左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1、计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2、计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3、计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= chidldVs.count { targetIndex = chidldVs.count - 1 } //4、如果完全滑过去了 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { //右滑 // 1、计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2、计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) //3、计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= chidldVs.count { sourceIndex = chidldVs.count - 1 } } //3、将progress、sourceIndex、targetIndex传递给titleView print("progress:\(progress) sourceIndex\(sourceIndex) targetIndex:\(targetIndex)") delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // 对外接口方法 extension PageContentView { func setupCurrentIndex(currentIndex: Int) { //1、记录需要禁止执行代理方法 isForbidScrollDelegate = true //2、滚动到正确的位置 let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
e860b3949164ec4e2622caec29649cf2
29.684492
134
0.633322
5.570874
false
false
false
false
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/UserSectionController.swift
4
1623
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class UserSectionController: ListSectionController { private var user: User? private let isReorderable: Bool required init(isReorderable: Bool = false) { self.isReorderable = isReorderable super.init() } override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: DetailLabelCell.self, for: self, at: index) as? DetailLabelCell else { fatalError() } cell.title = user?.name cell.detail = "@" + (user?.handle ?? "") return cell } override func didUpdate(to object: Any) { self.user = object as? User } override func canMoveItem(at index: Int) -> Bool { return isReorderable } }
mit
4f2a20020a31d6c893659238b05840c7
32.8125
138
0.703635
4.745614
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Utility/LoadoutCoding/PlainText.swift
2
5886
// // PlainText.swift // Neocom // // Created by Artem Shimanski on 4/16/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import Foundation import CoreData import Expressible import Dgmpp private let slotsOrder: [DGMModule.Slot] = [.low, .med, .hi, .rig, .subsystem, .service] struct LoadoutPlainTextEncoder: LoadoutEncoder { var managedObjectContext: NSManagedObjectContext func encode(_ ship: Ship) throws -> Data { guard let shipType = try managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(ship.typeID)).first() else {throw RuntimeError.invalidLoadoutFormat} let typeName = shipType.originalTypeName ?? "" let shipName = ship.name?.isEmpty == false ? ship.name : typeName var output = "[\(typeName), \(shipName ?? "")]\n" for slot in slotsOrder { ship.modules?[slot]?.forEach { module in guard let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(module.typeID)).first() else {return} let s = type.typeName ?? "" for _ in 0..<module.count { output += s + "\n" } } output += "\n" } let drones = Dictionary(ship.drones?.map{($0.typeID, $0.count)} ?? [], uniquingKeysWith: {a, b in a + b}) let charges = Dictionary(ship.modules?.values.joined().compactMap{$0.charge}.map{($0.typeID, $0.count)} ?? [], uniquingKeysWith: {a, b in a + b}) var cargo = Dictionary(ship.cargo?.map{($0.typeID, $0.count)} ?? [], uniquingKeysWith: {a, b in a + b}) cargo.merge(charges) {$0 + $1} func dump(_ items: [Int: Int]) -> String { items.compactMap { (typeID, count) -> String? in guard let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(typeID)).first() else {return nil} return "\(type.originalTypeName ?? "") x\(count)" }.joined(separator: "\n") } if !drones.isEmpty { output += dump(drones) + "\n\n" } if !cargo.isEmpty { output += dump(cargo) + "\n" } guard let data = output.data(using: .utf8) else {throw RuntimeError.invalidLoadoutFormat} return data } } struct LoadoutPlainTextDecoder: LoadoutDecoder { var managedObjectContext: NSManagedObjectContext func decode(from data: Data) throws -> Ship { guard let string = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) else {throw RuntimeError.invalidLoadoutFormat} func getType<T: StringProtocol>(_ name: T) throws -> SDEInvType? { try managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.originalTypeName == String(name)).first() } let re0 = try! NSRegularExpression(pattern: "\\[\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]", options: []) let re1 = try! NSRegularExpression(pattern: "(.*)\\s+x(\\d*)", options: []) let re2 = try! NSRegularExpression(pattern: "x(\\d*)\\s+(.*)", options: []) func extractRow(_ s: String) throws -> (SDEInvType, Int) { let typeName: String let nsString = s as NSString let count: Int if let match = re1.matches(in: s, options: [], range: NSRange(location: 0, length: s.count)).first { typeName = nsString.substring(with: match.range(at: 1)) count = Int(nsString.substring(with: match.range(at: 2))) ?? 1 } else if let match = re2.matches(in: s, options: [], range: NSRange(location: 0, length: s.count)).first { typeName = nsString.substring(with: match.range(at: 2)) count = Int(nsString.substring(with: match.range(at: 1))) ?? 1 } else { typeName = s count = 1 } guard let type = try getType(typeName) else {throw RuntimeError.invalidLoadoutFormat} return (type, count) } let rows = string.components(separatedBy: "\n") if let s = rows.first, let match = re0.matches(in: s, options: [], range: NSRange(location: 0, length: s.count)).first { let nsString = s as NSString let typeName = nsString.substring(with: match.range(at: 1)) let shipName = nsString.substring(with: match.range(at: 2)) guard let shipType = try getType(typeName) else {throw RuntimeError.invalidLoadoutFormat} let groups = rows.dropFirst().split(separator: "", maxSplits: .max, omittingEmptySubsequences: false) let modules = Dictionary(zip(slotsOrder, groups)) {a, _ in a} .mapValues { rows in rows.filter{!$0.hasPrefix("[")}.compactMap {try? extractRow($0)}.map { Ship.Module(typeID: Int($0.0.typeID), count: $0.1) } }.filter{!$0.value.isEmpty} var remains = groups.dropFirst(slotsOrder.count) let drones = remains.first?.compactMap{try? extractRow($0)}.map{Ship.Drone(typeID: Int($0.0.typeID), count: $0.1)} remains = remains.dropFirst() let cargo = remains.joined().compactMap{try? extractRow($0)}.map{Ship.Item(typeID: Int($0.0.typeID), count: $0.1)} return Ship(typeID: Int(shipType.typeID), name: shipName.isEmpty ? nil : shipName, modules: modules, drones: drones, cargo: cargo, implants: nil, boosters: nil) } else { throw RuntimeError.invalidLoadoutFormat } } }
lgpl-2.1
70688504281c7cd0b37fdec37a5c0276
44.620155
180
0.565675
4.356033
false
false
false
false
devpunk/punknote
punknote/View/Create/VCreateCellBackgroundCell.swift
1
2495
import UIKit class VCreateCellBackgroundCell:UICollectionViewCell { private weak var background:UIView? private weak var imageIndicator:UIImageView! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let imageIndicator:UIImageView = UIImageView() imageIndicator.translatesAutoresizingMaskIntoConstraints = false imageIndicator.clipsToBounds = true imageIndicator.isUserInteractionEnabled = false imageIndicator.contentMode = UIViewContentMode.bottomRight imageIndicator.image = #imageLiteral(resourceName: "assetGenericCreateSelected") self.imageIndicator = imageIndicator addSubview(imageIndicator) NSLayoutConstraint.equals( view:imageIndicator, toView:self) } required init?(coder aDecoder: NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private private func hover() { if isSelected || isHighlighted { background?.layer.borderWidth = 2 imageIndicator.isHidden = false } else { background?.layer.borderWidth = 0 imageIndicator.isHidden = true } } //MARK: public func config(model:MCreateBackgroundProtocol) { self.background?.removeFromSuperview() let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY let height_2:CGFloat = height / 2.0 let remainWidth:CGFloat = width - height let marginLeft:CGFloat = remainWidth / 2.0 let background:UIView = model.view() background.layer.borderColor = UIColor.black.cgColor background.layer.cornerRadius = height_2 self.background = background insertSubview(background, at:0) NSLayoutConstraint.equalsVertical( view:background, toView:self) NSLayoutConstraint.leftToLeft( view:background, toView:self, constant:marginLeft) NSLayoutConstraint.width( view:background, constant:height) hover() } }
mit
7a15d2f238d17cb47d0010b10ad77355
24.459184
88
0.585571
5.829439
false
false
false
false
springware/cloudsight-swift
Example-swift/Pods/CloudSight/CloudSight/CloudSightQuery.swift
2
2651
// // CloudSightQuery.swift // CloudSight // // Created by OCR Labs on 3/7/17. // Copyright © 2017 OCR Labs. All rights reserved. // import UIKit import CoreLocation import CoreGraphics public class CloudSightQuery : NSObject, CloudSightImageRequestDelegate { let kTPQueryCancelledError = 9030; var request: CloudSightImageRequest? = nil var response: CloudSightImageResponse? = nil var destroy: CloudSightDelete? = nil var queryDelegate: CloudSightQueryDelegate public var title: String = "" public var skipReason: String = "" public var token: String = "" public var remoteUrl: String = "" public init(image: NSData, atLocation location: CGPoint, withDelegate delegate: CloudSightQueryDelegate, atPlacemark placemark: CLLocation, withDeviceId deviceId: String) { self.queryDelegate = delegate super.init() self.request = CloudSightImageRequest(image: image, atLocation:location, withDelegate:self, atPlacemark:placemark, withDeviceId:deviceId) } deinit { } func cancelAndDestroy() { self.request!.cancel() self.response!.cancel() self.destroy = CloudSightDelete(token: self.token); self.destroy!.startRequest() } func stop() { self.cancelAndDestroy() let error = NSError(domain: NSBundle(forClass: self.dynamicType).bundleIdentifier!, code: kTPQueryCancelledError, userInfo: [NSLocalizedDescriptionKey : "User cancelled request"]) self.queryDelegate.cloudSightQueryDidFail(self, withError:error) } public func start() { self.request!.startRequest() } func description1() -> String { return String(format: "token: '%@', remoteUrl: '%@', title:'%@', skipReason:'%@'", self.token, self.remoteUrl, self.title, self.skipReason) } func name() -> String { if self.title.isEmpty { return self.skipReason } return self.title } func cloudSightRequest(sender:CloudSightImageRequest, didReceiveToken token:String, withRemoteURL url: String) { self.response = CloudSightImageResponse(token: token, withDelegate:self.queryDelegate, forQuery:self) self.response!.pollForResponse() self.token = token; self.remoteUrl = url; self.queryDelegate.cloudSightQueryDidFinishUploading(self) } func cloudSightRequest(sender: CloudSightImageRequest, didFailWithError error:NSError) { self.queryDelegate.cloudSightQueryDidFail(self, withError:error); } }
mit
343f6613a3131c23888f6b7cb1878169
29.113636
187
0.663396
4.732143
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Other/Sort.swift
1
2316
// // Sort.swift // Algorithm // // Created by 朱双泉 on 26/02/2018. // Copyright © 2018 Castie!. All rights reserved. // import Foundation func selectSort(list: inout [Int]) { let n = list.count for i in 0..<(n-1) { var j = i + 1 for _ in j..<n { if list[i] > list[j] { list[i] ^= list[j] list[j] ^= list[i] list[i] ^= list[j] } j += 1 } } } func optimizationSelectSort(list: inout [Int]) { let n = list.count var idx = 0 for i in 0..<(n - 1) { idx = i; var j = i + 1 for _ in j..<n { if list[idx] > list[j] { idx = j; } j += 1 } if idx != i { list[i] ^= list[idx] list[idx] ^= list[i] list[i] ^= list[idx] } } } func popSort(list: inout [Int]) { let n = list.count for i in 0..<n-1 { var j = 0 for _ in 0..<(n-1-i) { if list[j] > list[j+1] { list[j] ^= list[j+1] list[j+1] ^= list[j] list[j] ^= list[j+1] } j += 1 } } } func optimizationPopSort(list: inout [Int]) { let n = list.count for i in 0..<n-1 { var flag = 0 var j = 0 for _ in 0..<(n-1-i) { if list[j] > list[j+1] { list[j] ^= list[j+1] list[j+1] ^= list[j] list[j] ^= list[j+1] flag = 1 } j += 1 } if flag == 0 { break } } } func quickSort(list: inout [Int]) { func sort(list: inout [Int], low: Int, high: Int) { if low < high { let pivot = list[low] var l = low; var h = high while l < h { while list[h] >= pivot && l < h {h -= 1} list[l] = list[h] while list[l] <= pivot && l < h {l += 1} list[h] = list[l] } list[h] = pivot print(list) sort(list: &list, low: low, high: l-1) sort(list: &list, low: l+1, high: high) } } sort(list: &list, low: 0, high: list.count - 1) }
mit
44bd43afd1d9b80298b2bf53121b09aa
20.579439
56
0.369857
3.298571
false
false
false
false
liruqi/actor-platform
actor-apps/app-ios/ActorCore/Providers/CocoaFileSystemRuntime.swift
11
5793
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation // Public methods for working with files class CocoaFiles { class func pathFromDescriptor(path: String) -> String { var documentsFolders = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) if (documentsFolders.count > 0) { let appPath = documentsFolders[0].asNS.stringByDeletingLastPathComponent return appPath + path } else { fatalError("Unable to load Application path") } } } // Implementation of FileSystem storage @objc class CocoaFileSystemRuntime : NSObject, ARFileSystemRuntime { var appPath: String = "" let manager = NSFileManager.defaultManager() override init() { super.init() var documentsFolders = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) if (documentsFolders.count > 0) { appPath = documentsFolders[0].asNS.stringByDeletingLastPathComponent } else { fatalError("Unable to load Application path") } } func createTempFile() -> ARFileSystemReference! { let fileName = "/tmp/\(NSUUID().UUIDString)" NSFileManager.defaultManager().createFileAtPath(appPath + fileName, contents: NSData(), attributes: nil) return CocoaFile(path: fileName) } func commitTempFile(sourceFile: ARFileSystemReference!, withFileId fileId: jlong, withFileName fileName: String!) -> ARFileSystemReference! { // Finding file available name var index = 0; while(manager.fileExistsAtPath("\(appPath)/Documents/\(index)_\(fileName)")) { index = index + 1; } let resultPath = "/Documents/\(index)_\(fileName)"; // Moving file to new place do { try manager.moveItemAtPath(appPath + sourceFile.getDescriptor()!, toPath: appPath + resultPath) return CocoaFile(path: resultPath) } catch _ { return nil } } func fileFromDescriptor(descriptor: String!) -> ARFileSystemReference! { return CocoaFile(path: descriptor); } func isFsPersistent() -> Bool { return true; } } class CocoaFile : NSObject, ARFileSystemReference { let path: String; let realPath: String; init(path:String) { self.path = path self.realPath = CocoaFiles.pathFromDescriptor(path) } func getDescriptor() -> String! { return path; } func isExist() -> Bool { return NSFileManager().fileExistsAtPath(realPath); } func getSize() -> jint { do { let attrs = try NSFileManager().attributesOfItemAtPath(realPath) return jint(NSDictionary.fileSize(attrs)()) } catch _ { return 0 } } func openWriteWithSize(size: jint) -> AROutputFile! { let fileHandle = NSFileHandle(forWritingAtPath: realPath); if (fileHandle == nil) { return nil } fileHandle!.seekToFileOffset(UInt64(size)) fileHandle!.seekToFileOffset(0) return CocoaOutputFile(fileHandle: fileHandle!); } func openRead() -> ARInputFile! { let fileHandle = NSFileHandle(forReadingAtPath: realPath); if (fileHandle == nil) { return nil } return CocoaInputFile(fileHandle: fileHandle!); } } class CocoaOutputFile : NSObject, AROutputFile { let fileHandle: NSFileHandle; init(fileHandle:NSFileHandle){ self.fileHandle = fileHandle; } func writeWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset dataOffset: jint, withLength dataLen: jint) -> Bool { let toWrite = NSMutableData(length: Int(dataLen))!; var srcBuffer = UnsafeMutablePointer<UInt8>(data.buffer()); var destBuffer = UnsafeMutablePointer<UInt8>(toWrite.bytes); for _ in 0..<dataLen { destBuffer.memory = srcBuffer.memory; destBuffer++; srcBuffer++; } fileHandle.seekToFileOffset(UInt64(fileOffset)); fileHandle.writeData(toWrite) return true; } func close() -> Bool { self.fileHandle.synchronizeFile() self.fileHandle.closeFile() return true; } } class CocoaInputFile :NSObject, ARInputFile { let fileHandle:NSFileHandle; init(fileHandle:NSFileHandle){ self.fileHandle = fileHandle; } func readWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset offset: jint, withLength len: jint, withCallback callback: ARFileReadCallback!) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) { self.fileHandle.seekToFileOffset(UInt64(fileOffset)); let readed:NSData = self.fileHandle.readDataOfLength(Int(len)); var srcBuffer = UnsafeMutablePointer<UInt8>(readed.bytes); var destBuffer = UnsafeMutablePointer<UInt8>(data.buffer()); let len = min(Int(len), Int(readed.length)); for _ in offset..<offset+len { destBuffer.memory = srcBuffer.memory; destBuffer++; srcBuffer++; } callback.onFileReadWithOffset(fileOffset, withData: data, withDataOffset: offset, withLength: jint(len)) } } func close() -> Bool { self.fileHandle.closeFile() return true; } }
mit
b4e9649fe7c1388d8fd587c9af03f187
29.983957
168
0.61419
5.256806
false
false
false
false
mothule/RNMoVali
RNMoVali/RNConstraintRegex.swift
1
909
// // RNConstraintRegex.swift // RNMoVali // // Created by mothule on 2016/08/24. // Copyright © 2016年 mothule. All rights reserved. // import Foundation open class RNConstraintRegex : RNConstraintable { fileprivate let errorMessage:String fileprivate let pattern:String fileprivate let options:NSRegularExpression.Options? public init(pattern:String, errorMessage:String, options:NSRegularExpression.Options? = nil){ self.pattern = pattern self.errorMessage = errorMessage self.options = options } open func constrain(_ object: Any?) -> RNConstraintResult { let ret:RNConstraintResult = RNConstraintResult() if let string = object as? String { if Regex.make(pattern, options: options).isMatch(string) == false { ret.invalidate(self.errorMessage) } } return ret } }
apache-2.0
f33b2b1b8f47693af3454a32654f23fd
27.3125
97
0.660044
4.463054
false
false
false
false
mitchellporter/FillableLoaders
Source/RoundedLoader.swift
5
2190
// // RoundedLoader.swift // PQFFillableLoaders // // Created by Pol Quintana on 2/8/15. // Copyright (c) 2015 Pol Quintana. All rights reserved. // import Foundation import UIKit public class RoundedLoader: FillableLoader { /// Height of the rounded edge of the spike public var spikeHeight: CGFloat = 5.0 internal override func generateLoader() { extraHeight = spikeHeight layoutPath() } internal override func layoutPath() { super.layoutPath() shapeLayer.path = shapePath() } // MARK: Animate internal override func startAnimating() { if !animate { return } if swing { startswinging() } startMoving(true) } //MARK: Spikes internal func shapePath() -> CGMutablePath { let width = loaderView.frame.width let height = loaderView.frame.height let path = CGPathCreateMutable() let waves = 32 CGPathMoveToPoint(path, nil, 0, height/2) var widthDiff = width/CGFloat(waves*2) var nextCPX = widthDiff var nextCPY = height/2 + spikeHeight var nextX = nextCPX + widthDiff var nextY = height/2 for i: Int in 1...waves { CGPathAddQuadCurveToPoint(path, nil, nextCPX, nextCPY, nextX, nextY) nextCPX = nextX + widthDiff nextCPY = (i%2 == 0) ? height/2 + spikeHeight : height/2 - spikeHeight nextX = nextCPX + widthDiff } CGPathAddLineToPoint(path, nil, width + 100, height/2) CGPathAddLineToPoint(path, nil, width + 100, height*2) CGPathAddLineToPoint(path, nil, 0, height*2) CGPathCloseSubpath(path) return path } //MARK: Animations Delegate override public func animationDidStop(anim: CAAnimation, finished flag: Bool) { if !animate { return } let key = anim.valueForKey("animation") as! String if key == "up" { startMoving(false) } if key == "down" { startMoving(true) } if key == "rotation" { startswinging() } } }
mit
d91eb2b2960b89305a9001b5bdf18126
26.049383
83
0.578995
4.506173
false
false
false
false
xwu/swift
stdlib/public/core/Pointer.swift
1
12297
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if SWIFT_ENABLE_REFLECTION public typealias _CustomReflectableOrNone = CustomReflectable #else public typealias _CustomReflectableOrNone = Any #endif /// A stdlib-internal protocol modeled by the intrinsic pointer types, /// UnsafeMutablePointer, UnsafePointer, UnsafeRawPointer, /// UnsafeMutableRawPointer, and AutoreleasingUnsafeMutablePointer. public protocol _Pointer : Hashable, Strideable, CustomDebugStringConvertible, _CustomReflectableOrNone { /// A type that represents the distance between two pointers. typealias Distance = Int associatedtype Pointee /// The underlying raw pointer value. var _rawValue: Builtin.RawPointer { get } /// Creates a pointer from a raw value. init(_ _rawValue: Builtin.RawPointer) } extension _Pointer { /// Creates a new typed pointer from the given opaque pointer. /// /// - Parameter from: The opaque pointer to convert to a typed pointer. @_transparent public init(_ from: OpaquePointer) { self.init(from._rawValue) } /// Creates a new typed pointer from the given opaque pointer. /// /// - Parameter from: The opaque pointer to convert to a typed pointer. If /// `from` is `nil`, the result of this initializer is `nil`. @_transparent public init?(_ from: OpaquePointer?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Creates a new pointer from the given address, specified as a bit /// pattern. /// /// The address passed as `bitPattern` must have the correct alignment for /// the pointer's `Pointee` type. That is, /// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`. /// /// - Parameter bitPattern: A bit pattern to use for the address of the new /// pointer. If `bitPattern` is zero, the result is `nil`. @_transparent public init?(bitPattern: Int) { if bitPattern == 0 { return nil } self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue)) } /// Creates a new pointer from the given address, specified as a bit /// pattern. /// /// The address passed as `bitPattern` must have the correct alignment for /// the pointer's `Pointee` type. That is, /// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`. /// /// - Parameter bitPattern: A bit pattern to use for the address of the new /// pointer. If `bitPattern` is zero, the result is `nil`. @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue)) } /// Creates a new pointer from the given pointer. /// /// - Parameter other: The typed pointer to convert. @_transparent public init(@_nonEphemeral _ other: Self) { self.init(other._rawValue) } /// Creates a new pointer from the given pointer. /// /// - Parameter other: The typed pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?(@_nonEphemeral _ other: Self?) { guard let unwrapped = other else { return nil } self.init(unwrapped._rawValue) } } // well, this is pretty annoying extension _Pointer /*: Equatable */ { // - Note: This may be more efficient than Strideable's implementation // calling self.distance(). /// Returns a Boolean value indicating whether two pointers are equal. /// /// - Parameters: /// - lhs: A pointer. /// - rhs: Another pointer. /// - Returns: `true` if `lhs` and `rhs` reference the same memory address; /// otherwise, `false`. @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } } extension _Pointer /*: Comparable */ { // - Note: This is an unsigned comparison unlike Strideable's // implementation. /// Returns a Boolean value indicating whether the first pointer references /// an earlier memory location than the second pointer. /// /// - Parameters: /// - lhs: A pointer. /// - rhs: Another pointer. /// - Returns: `true` if `lhs` references a memory address earlier than /// `rhs`; otherwise, `false`. @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return Bool(Builtin.cmp_ult_RawPointer(lhs._rawValue, rhs._rawValue)) } } extension _Pointer /*: Strideable*/ { /// Returns a pointer to the next consecutive instance. /// /// The resulting pointer must be within the bounds of the same allocation as /// this pointer. /// /// - Returns: A pointer advanced from this pointer by /// `MemoryLayout<Pointee>.stride` bytes. @_transparent public func successor() -> Self { return advanced(by: 1) } /// Returns a pointer to the previous consecutive instance. /// /// The resulting pointer must be within the bounds of the same allocation as /// this pointer. /// /// - Returns: A pointer shifted backward from this pointer by /// `MemoryLayout<Pointee>.stride` bytes. @_transparent public func predecessor() -> Self { return advanced(by: -1) } /// Returns the distance from this pointer to the given pointer, counted as /// instances of the pointer's `Pointee` type. /// /// With pointers `p` and `q`, the result of `p.distance(to: q)` is /// equivalent to `q - p`. /// /// Typed pointers are required to be properly aligned for their `Pointee` /// type. Proper alignment ensures that the result of `distance(to:)` /// accurately measures the distance between the two pointers, counted in /// strides of `Pointee`. To find the distance in bytes between two /// pointers, convert them to `UnsafeRawPointer` instances before calling /// `distance(to:)`. /// /// - Parameter end: The pointer to calculate the distance to. /// - Returns: The distance from this pointer to `end`, in strides of the /// pointer's `Pointee` type. To access the stride, use /// `MemoryLayout<Pointee>.stride`. @_transparent public func distance(to end: Self) -> Int { return Int(Builtin.sub_Word(Builtin.ptrtoint_Word(end._rawValue), Builtin.ptrtoint_Word(_rawValue))) / MemoryLayout<Pointee>.stride } /// Returns a pointer offset from this pointer by the specified number of /// instances. /// /// With pointer `p` and distance `n`, the result of `p.advanced(by: n)` is /// equivalent to `p + n`. /// /// The resulting pointer must be within the bounds of the same allocation as /// this pointer. /// /// - Parameter n: The number of strides of the pointer's `Pointee` type to /// offset this pointer. To access the stride, use /// `MemoryLayout<Pointee>.stride`. `n` may be positive, negative, or /// zero. /// - Returns: A pointer offset from this pointer by `n` instances of the /// `Pointee` type. @_transparent public func advanced(by n: Int) -> Self { return Self(Builtin.gep_Word( self._rawValue, n._builtinWordValue, Pointee.self)) } } extension _Pointer /*: Hashable */ { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(UInt(bitPattern: self)) } @inlinable public func _rawHashValue(seed: Int) -> Int { return Hasher._hash(seed: seed, UInt(bitPattern: self)) } } extension _Pointer /*: CustomDebugStringConvertible */ { /// A textual representation of the pointer, suitable for debugging. public var debugDescription: String { return _rawPointerToString(_rawValue) } } #if SWIFT_ENABLE_REFLECTION extension _Pointer /*: CustomReflectable */ { public var customMirror: Mirror { let ptrValue = UInt64( bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue)))) return Mirror(self, children: ["pointerValue": ptrValue]) } } #endif extension Int { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_transparent public init<P: _Pointer>(bitPattern pointer: P?) { if let pointer = pointer { self = Int(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 } } } extension UInt { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_transparent public init<P: _Pointer>(bitPattern pointer: P?) { if let pointer = pointer { self = UInt(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 } } } // Pointer arithmetic operators (formerly via Strideable) extension Strideable where Self: _Pointer { @_transparent public static func + (@_nonEphemeral lhs: Self, rhs: Self.Stride) -> Self { return lhs.advanced(by: rhs) } @_transparent public static func + (lhs: Self.Stride, @_nonEphemeral rhs: Self) -> Self { return rhs.advanced(by: lhs) } @_transparent public static func - (@_nonEphemeral lhs: Self, rhs: Self.Stride) -> Self { return lhs.advanced(by: -rhs) } @_transparent public static func - (lhs: Self, rhs: Self) -> Self.Stride { return rhs.distance(to: lhs) } @_transparent public static func += (lhs: inout Self, rhs: Self.Stride) { lhs = lhs.advanced(by: rhs) } @_transparent public static func -= (lhs: inout Self, rhs: Self.Stride) { lhs = lhs.advanced(by: -rhs) } } /// Derive a pointer argument from a convertible pointer type. @_transparent public // COMPILER_INTRINSIC func _convertPointerToPointerArgument< FromPointer: _Pointer, ToPointer: _Pointer >(_ from: FromPointer) -> ToPointer { return ToPointer(from._rawValue) } /// Derive a pointer argument from the address of an inout parameter. @_transparent public // COMPILER_INTRINSIC func _convertInOutToPointerArgument< ToPointer: _Pointer >(_ from: Builtin.RawPointer) -> ToPointer { return ToPointer(from) } /// Derive a pointer argument from a value array parameter. /// /// This always produces a non-null pointer, even if the array doesn't have any /// storage. @_transparent public // COMPILER_INTRINSIC func _convertConstArrayToPointerArgument< FromElement, ToPointer: _Pointer >(_ arr: [FromElement]) -> (AnyObject?, ToPointer) { let (owner, opaquePointer) = arr._cPointerArgs() let validPointer: ToPointer if let addr = opaquePointer { validPointer = ToPointer(addr._rawValue) } else { let lastAlignedValue = ~(MemoryLayout<FromElement>.alignment - 1) let lastAlignedPointer = UnsafeRawPointer(bitPattern: lastAlignedValue)! validPointer = ToPointer(lastAlignedPointer._rawValue) } return (owner, validPointer) } /// Derive a pointer argument from an inout array parameter. /// /// This always produces a non-null pointer, even if the array's length is 0. @_transparent public // COMPILER_INTRINSIC func _convertMutableArrayToPointerArgument< FromElement, ToPointer: _Pointer >(_ a: inout [FromElement]) -> (AnyObject?, ToPointer) { // TODO: Putting a canary at the end of the array in checked builds might // be a good idea // Call reserve to force contiguous storage. a.reserveCapacity(0) _debugPrecondition(a._baseAddressIfContiguous != nil || a.isEmpty) return _convertConstArrayToPointerArgument(a) } /// Derive a UTF-8 pointer argument from a value string parameter. @_transparent public // COMPILER_INTRINSIC func _convertConstStringToUTF8PointerArgument< ToPointer: _Pointer >(_ str: String) -> (AnyObject?, ToPointer) { let utf8 = Array(str.utf8CString) return _convertConstArrayToPointerArgument(utf8) }
apache-2.0
79c64c456f2f9e8628c68e761d85a44c
31.618037
80
0.674717
4.243271
false
false
false
false
swiftcodex/Swift-Radio-Pro
SwiftRadio/UIImageView+Download.swift
1
1089
// // UIImageView+AlbumArtDownload.swift // Swift Radio // // Created by Matthew Fecher on 3/31/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit extension UIImageView { func loadImageWithURL(url: URL, callback: @escaping (UIImage) -> ()) { let session = URLSession.shared let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in if error == nil && url != nil { if let data = NSData(contentsOf: url!) { if let image = UIImage(data: data as Data) { DispatchQueue.main.async(execute: { if let strongSelf = self { strongSelf.image = image callback(image) } }) } } } }) downloadTask.resume() } }
mit
c7f4cba82ad3213e9525a1447bbbf2c1
26.923077
79
0.442608
5.5
false
false
false
false
suifengqjn/swiftDemo
基本语法/9类和结构体/类和结构体.playground/Contents.swift
1
1077
//: Playground - noun: a place where people can play import UIKit ///定义语法 //类与结构体有着相似的定义语法,你可以通过使用关键词 class来定义类使用 struct来定义结构体。并在一对大括号内定义它们的具体内容。 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } ///类与结构体实例 let someResolution = Resolution() let someVideoMode = VideoMode() ///结构体类型的成员初始化器 let vga = Resolution(width: 33, height: 40) print(vga) ///结构体和枚举是值类型 //值类型是一种当它被指定到常量或者变量,或者被传递给函数时会被拷贝的类型。 ///类是引用类型 //变量或者本身被传递到一个函数的时候它是不会被拷贝的。 //有时候找出两个常量或者变量是否引用自同一个类实例非常有用, ///Swift提供了两个特点运算符 ///相同于 ( ===) ///不相同于( !==)
apache-2.0
a8a81bfc99a24fdefe9eab7d1c37070c
13.276596
71
0.698957
2.673307
false
false
false
false
zanadu/ImageCropView
ImageCropView/ImageCaptionCropView.swift
1
5038
// // ImageCaptionCropView.swift // zanadu // // Created by Benjamin Lefebvre on 5/5/15. // Copyright (c) 2015 zanadu. All rights reserved. // import Foundation /** * Subclass of ImageCropView with a bottom right button that display/hide a textfield on click */ open class ImageCaptionCropView: ImageCropView { let buttonWidth: CGFloat = 36 let padding: CGFloat = 10 var caption: String = "" var editing = false var container: UIView! var button: UIButton! var field: UITextField! var editIcon: UIImage! var validateIcon: UIImage! open var containerBackgroundColor = UIColor.black { didSet { container.backgroundColor = containerBackgroundColor } } open var fieldTintColor = UIColor.white { didSet { field.tintColor = fieldTintColor } } open func fieldText() -> String? { return field.text } open func isEditing() -> Bool { return editing } func onImageTapped(_ sender: AnyObject?) { } /** Setup the cropview and the button, field & container - parameter image: the image to crop - parameter editIcon: the caption edit button icon - parameter validateIcon: the validate input button icon */ open func setup(_ image: UIImage, tapDelegate: ImageCropViewTapProtocol? = nil, editIcon: UIImage, validateIcon: UIImage) { // init super.setup(image, tapDelegate: tapDelegate) self.editIcon = editIcon self.validateIcon = validateIcon // setup container container = UIView(frame: closeFieldFrame()) container.backgroundColor = containerBackgroundColor container.layer.cornerRadius = buttonWidth / 2 // setup button button = UIButton(frame: CGRect(x: 0, y: 0, width: buttonWidth, height: buttonWidth)) button.imageView?.contentMode = UIViewContentMode.scaleAspectFit button.setImage(editIcon, for: UIControlState()) button.imageEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) button.addTarget(self, action: #selector(ImageCaptionCropView.onButtonPressed(_:)), for: .touchUpInside) //setup field field = UITextField(frame: CGRect(x: padding * 2, y: 0, width: 0, height: buttonWidth)) field.textColor = UIColor.white field.tintColor = fieldTintColor field.keyboardAppearance = UIKeyboardAppearance.dark field.delegate = self container.addSubview(field) container.addSubview(button) self.addSubview(container) } override open func enableEditing() { super.enableEditing() container.isHidden = false } override open func disableEditing() { super.disableEditing() container.isHidden = true } func onButtonPressed(_ sender: UIButton!) { UIView.animate(withDuration: 0.4, animations: { () -> Void in if self.editing { self.container.frame = self.closeFieldFrame() self.field.frame.size.width = 0 self.button.frame.origin.x = 0 self.button.setImage(self.editIcon, for: UIControlState()) } else { self.container.frame = self.openFieldFrame() self.field.frame.size.width = self.frame.width - self.padding * 5 - self.buttonWidth self.button.frame.origin.x = self.field.frame.origin.x + self.field.frame.size.width + self.padding self.button.setImage(self.validateIcon, for: UIControlState()) } self.layoutIfNeeded() }, completion: { (complete) -> Void in print("animation finished", terminator: "") self.editing = !self.editing if self.editing { self.field.becomeFirstResponder() self.isScrollEnabled = false } else { self.field.resignFirstResponder() self.isScrollEnabled = true } }) } fileprivate func closeFieldFrame() -> CGRect { return CGRect(x: frame.width - buttonWidth - padding + contentOffset.x, y: frame.height - buttonWidth - padding + contentOffset.y, width: buttonWidth, height: buttonWidth) } fileprivate func openFieldFrame() -> CGRect { return CGRect(x: self.padding, y: self.container.frame.origin.y, width: self.frame.width - self.padding * 2, height: self.container.frame.height) } //MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { container.frame = self.editing ? self.openFieldFrame() : self.closeFieldFrame() } } extension ImageCaptionCropView : UITextFieldDelegate { public func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.onButtonPressed(nil) return false } }
mit
bf2c1958a44c3b8db3e2ca170ec78b37
32.364238
179
0.617507
4.834933
false
false
false
false
yunhan0/ChineseChess
ChineseChess/Model/Pieces/King.swift
1
1253
// // King.swift // ChineseChess // // Created by Yunhan Li on 5/15/17. // Copyright © 2017 Yunhan Li. All rights reserved. // import Foundation class King : Piece { override func nextPossibleMoves(boardStates: [[Piece?]]) -> [Vector2] { // King can move 1 step in four directions. let possibleMoves: [Vector2] = [ Vector2(x: position.x + 1, y: position.y), Vector2(x: position.x - 1, y: position.y), Vector2(x: position.x, y: position.y + 1), Vector2(x: position.x, y: position.y - 1)] var ret : [Vector2] = [] for _move in possibleMoves { if isValidMove(_move, boardStates) { ret.append(_move) } } return ret } override func isValidMove(_ move: Vector2, _ boardStates: [[Piece?]]) -> Bool { // King can only move inside forbidden area if !Board.isForbidden(position: move) { return false } let nextState = boardStates[move.x][move.y] if nextState != nil { if nextState?.owner == self.owner { return false } } return true } }
mit
92a6170e06d882e4d676013bfc58fe29
25.638298
83
0.510383
4.104918
false
false
false
false
codercd/xmppChat
Chat/Classes/Contacts/ContactTableViewController.swift
1
3747
// // ContactTableViewController.swift // Chat // // Created by LiChendi on 16/3/23. // Copyright © 2016年 lcd. All rights reserved. // import UIKit class ContactTableViewController: UITableViewController { let contactCellIdentifier = "ContactTableViewCell" override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() // tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: Identifier.contactCell.rawValue) tableView.registerNib(UINib(nibName: "ContactTableViewCell", bundle: nil), forCellReuseIdentifier: contactCellIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 10 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 80 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(contactCellIdentifier, forIndexPath: indexPath) as! ContactTableViewCell cell.IconImageView.image = UIImage(named: "ihead_007") return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
b1248131a2b354a2e4a42dbec4ef0646
35.349515
157
0.698451
5.655589
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/NSMutableAttributedStringTests.swift
2
2432
import Foundation import XCTest class NSMutableAttributedStringTests: XCTestCase { func testApplyStylesToMatchesWithPattern() { // Assemble an Attributed string with bold markup markers let message = "This is a string that **contains bold substrings**" let regularStyle: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 14), .foregroundColor: UIColor.gray ] let boldStyle: [NSAttributedString.Key: Any] = [ .font: UIFont.boldSystemFont(ofSize: 14), .foregroundColor: UIColor.black ] let attributedMessage = NSMutableAttributedString(string: message, attributes: regularStyle) let rawMessage = attributedMessage.string as NSString // Apply the Bold Style let boldPattern = "(\\*{1,2}).+?\\1" attributedMessage.applyStylesToMatchesWithPattern(boldPattern, styles: boldStyle) // Verify the regular style let regularExpectedRange = rawMessage.range(of: "This is a string that ") var regularEffectiveRange = NSMakeRange(0, rawMessage.length) let regularEffectiveStyle = attributedMessage.attributes(at: regularExpectedRange.location, effectiveRange: &regularEffectiveRange) XCTAssert(isEqual(regularEffectiveStyle, regularStyle), "Invalid Style Detected") XCTAssert(regularExpectedRange.location == regularEffectiveRange.location, "Invalid effective range") // Verify the bold style let boldExpectedRange = rawMessage.range(of: "**contains bold substrings**") var boldEffectiveRange = NSMakeRange(0, rawMessage.length) let boldEffectiveStyle = attributedMessage.attributes(at: boldExpectedRange.location, effectiveRange: &boldEffectiveRange) XCTAssert(isEqual(boldEffectiveStyle, boldStyle), "Invalid Style Detected") XCTAssert(boldExpectedRange.location == boldEffectiveRange.location, "Invalid effective range") } /// /// private func isEqual(_ lhs: [NSAttributedString.Key: Any], _ rhs: [NSAttributedString.Key: Any]) -> Bool { guard lhs.count == rhs.count else { return false } for (key, value) in lhs { let left = rhs[key] as AnyObject let right = value as AnyObject if !left.isEqual(right) { return false } } return true } }
gpl-2.0
2f8e4116855071ae8134b1b3f17fcecb
37
139
0.667763
5.163482
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/Logging/WPCrashLoggingProvider.swift
1
2159
import UIKit import AutomatticTracks /// A wrapper around the logging stack – provides shared initialization and configuration for Tracks Crash and Event Logging struct WPLoggingStack { static let QueuedLogsDidChangeNotification = NSNotification.Name("WPCrashLoggingQueueDidChange") let crashLogging: CrashLogging let eventLogging: EventLogging private let eventLoggingDataProvider = EventLoggingDataProvider.fromDDFileLogger(WPLogger.shared().fileLogger) private let eventLoggingDelegate = EventLoggingDelegate() init() { let eventLogging = EventLogging(dataSource: eventLoggingDataProvider, delegate: eventLoggingDelegate) self.eventLogging = eventLogging self.crashLogging = CrashLogging(dataProvider: WPCrashLoggingDataProvider(), eventLogging: eventLogging) /// Upload any remaining files any time the app becomes active let willEnterForeground = UIApplication.willEnterForegroundNotification NotificationCenter.default.addObserver(forName: willEnterForeground, object: nil, queue: nil, using: self.willEnterForeground) } func start() throws { _ = try crashLogging.start() } private func willEnterForeground(note: Foundation.Notification) { self.eventLogging.uploadNextLogFileIfNeeded() DDLogDebug("📜 Resumed encrypted log upload queue due to app entering foreground") } } struct WPCrashLoggingDataProvider: CrashLoggingDataProvider { let sentryDSN: String = ApiCredentials.sentryDSN var userHasOptedOut: Bool { return UserSettings.userHasOptedOutOfCrashLogging } var buildType: String = BuildConfiguration.current.rawValue var shouldEnableAutomaticSessionTracking: Bool { return !UserSettings.userHasOptedOutOfCrashLogging } var currentUser: TracksUser? { let context = ContextManager.sharedInstance().mainContext guard let account = try? WPAccount.lookupDefaultWordPressComAccount(in: context) else { return nil } return TracksUser(userID: account.userID.stringValue, email: account.email, username: account.username) } }
gpl-2.0
34473d0ce07386ec6fb73d4e27769348
35.508475
134
0.752553
5.551546
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/ClicksStatsRecordValue+CoreDataClass.swift
2
3631
import Foundation import CoreData public class ClicksStatsRecordValue: StatsRecordValue { public var clickedURL: URL? { guard let url = urlString as String? else { return nil } return URL(string: url) } public var iconURL: URL? { guard let url = iconUrlString as String? else { return nil } return URL(string: url) } } extension ClicksStatsRecordValue { convenience init(managedObjectContext: NSManagedObjectContext, remoteClick: StatsClick) { self.init(context: managedObjectContext) self.clicksCount = Int64(remoteClick.clicksCount) self.label = remoteClick.title self.urlString = remoteClick.clickedURL?.absoluteString self.iconUrlString = remoteClick.iconURL?.absoluteString let children = remoteClick.children.map { ClicksStatsRecordValue(managedObjectContext: managedObjectContext, remoteClick: $0) } self.children = NSOrderedSet(array: children) } } extension StatsClick { init?(clicksStatsRecordValue: ClicksStatsRecordValue) { guard let title = clicksStatsRecordValue.label else { return nil } let children = clicksStatsRecordValue.children?.array as? [ClicksStatsRecordValue] ?? [] self.init(title: title, clicksCount: Int(clicksStatsRecordValue.clicksCount), clickedURL: clicksStatsRecordValue.clickedURL, iconURL: clicksStatsRecordValue.iconURL, children: children.compactMap { StatsClick(clicksStatsRecordValue: $0) }) } } extension StatsTopClicksTimeIntervalData: TimeIntervalStatsRecordValueConvertible { var recordPeriodType: StatsRecordPeriodType { return StatsRecordPeriodType(remoteStatus: period) } var date: Date { return periodEndDate } func statsRecordValues(in context: NSManagedObjectContext) -> [StatsRecordValue] { var mappedClicks: [StatsRecordValue] = clicks.map { ClicksStatsRecordValue(managedObjectContext: context, remoteClick: $0) } let otherAndTotalCount = OtherAndTotalViewsCountStatsRecordValue(context: context, otherCount: otherClicksCount, totalCount: totalClicksCount) mappedClicks.append(otherAndTotalCount) return mappedClicks } init?(statsRecordValues: [StatsRecordValue]) { guard let firstParent = statsRecordValues.first?.statsRecord, let period = StatsRecordPeriodType(rawValue: firstParent.period), let date = firstParent.date, let otherAndTotalCount = statsRecordValues.compactMap({ $0 as? OtherAndTotalViewsCountStatsRecordValue }).first else { return nil } let clicks: [StatsClick] = statsRecordValues .compactMap { $0 as? ClicksStatsRecordValue } .compactMap { StatsClick(clicksStatsRecordValue: $0) } self = StatsTopClicksTimeIntervalData(period: period.statsPeriodUnitValue, periodEndDate: date as Date, clicks: clicks, totalClicksCount: Int(otherAndTotalCount.totalCount), otherClicksCount: Int(otherAndTotalCount.otherCount)) } static var recordType: StatsRecordType { return .clicks } }
gpl-2.0
4b806318dfcfbb88c3f1920c339d4a91
33.913462
135
0.621592
5.847021
false
false
false
false
lmihalkovic/WWDC-tvOS
WWDC/Search.swift
1
7454
// // Search.swift // WWDC // // Created by Laurent Mihalkovic on 3/19/16. // Copyright © 2016 Laurent Mihalkovic. All rights reserved. // import UIKit import RealmSwift class SearchResultsViewController : UICollectionViewController, UISearchResultsUpdating, SearchResultCellDelegate { private var filteredDataItems: Results<Session>? = AppModel.sharedModel.allSessions private let cellDecorator = SearchResultCellDecorator() var searchString = "" { didSet { guard searchString != oldValue else { return } if searchString.isEmpty { filteredDataItems = AppModel.sharedModel.allSessions } else { AppModel.sharedModel.sessionsMatchingSearchString(searchString, onComplete: { [weak self] data in self?.filteredDataItems = data self?.collectionView?.reloadData() }) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) searchString = "" } func updateSearchResultsForSearchController(searchController: UISearchController) { searchString = searchController.searchBar.text ?? "" } // MARK: Collection data source override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (filteredDataItems?.count)! } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // Dequeue a cell from the collection view. return collectionView.dequeueReusableCellWithReuseIdentifier("SearchResultCell", forIndexPath: indexPath) } override func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { guard let cell = cell as? SearchResultCell else { fatalError("Expected to display a `SearchResultCell`.") } let item = filteredDataItems?[indexPath.row] // Configure the cell. cellDecorator.configureCell(cell, usingCellActionDelegate:self, withDataItem: item!) } override func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true; } func cellPressEnded(cell:SearchResultCell, withButton button:UIPressType) { if let session = cell.data as? Session { let key = "\(session.year)-\(session.id)" switch button { case UIPressType.PlayPause: // TODO: fix this if let url = NSURL(string: "wwdc://show/\(key)") { // if let url = NSURL(string: "wwdc://play/\(key)") { UIApplication.sharedApplication().openURL(url) } case UIPressType.Select: if let url = NSURL(string: "wwdc://show/\(key)") { UIApplication.sharedApplication().openURL(url) } default: break } } } } protocol SearchResultCellDelegate:class { func cellPressEnded(cell:SearchResultCell, withButton:UIPressType) } class SearchResultCell : UICollectionViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var subTitle: UILabel! @IBOutlet weak var btn: UIButton! var data:AnyObject? weak var delegate: SearchResultCellDelegate? func prepareCellForUse() { delegate = nil data = nil } override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { animateSelection(true) super.pressesBegan(presses, withEvent: event) } override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { animateSelection(false) for press in presses { if(press.type == UIPressType.Select || press.type == UIPressType.PlayPause) { delegate?.cellPressEnded(self, withButton: press.type) } else { super.pressesEnded(presses, withEvent: event) } } } override func pressesCancelled(presses: Set<UIPress>, withEvent event: UIPressesEvent?) { animateSelection(false) } override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator) if let prevFocusedView = context.previouslyFocusedView as? SearchResultCell { prevFocusedView.showFocusOff() } if let nextFocusedView = context.nextFocusedView as? SearchResultCell { nextFocusedView.showFocusOn() } } } extension UICollectionViewCell { func animateSelection(selected: Bool) { do { let from = !selected ? CGSizeMake(0,3) : CGSizeMake(-2,15) let to = selected ? CGSizeMake(0,3) : CGSizeMake(-2,15) layer.shadowOffset = to let anim = CABasicAnimation(keyPath: "shadowOffset") anim.duration = 0.2 anim.fromValue = NSValue(CGSize: from) layer.addAnimation(anim, forKey: "shadowOffset") } do { let from: CGFloat = !selected ? 6.0 : 15.0 let to: CGFloat = selected ? 6.0 : 15.0 layer.shadowRadius = to let anim = CABasicAnimation(keyPath: "shadowRadius") anim.duration = 0.2 anim.fromValue = from layer.addAnimation(anim, forKey: "shadowRadius") } } func showFocusOn() { UIView.animateWithDuration(0.2, animations: { self.transform = CGAffineTransformMakeScale(1.1, 1.1) }) let mask = CAShapeLayer() mask.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10.0).CGPath self.contentView.backgroundColor = UIColor.whiteColor() self.contentView.layer.mask = mask self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 20.0).CGPath self.layer.shadowOffset = CGSizeMake(0, 15) self.layer.shadowOpacity = 1//0.6 self.layer.shadowRadius = 15.0 self.layer.shadowColor = UIColor.lightGrayColor().CGColor } func showFocusOff() { UIView.animateWithDuration(0.2, animations: { self.transform = CGAffineTransformIdentity }) self.contentView.backgroundColor = nil self.contentView.layer.mask = nil self.layer.shadowPath = nil self.layer.shadowOffset = CGSizeMake(0, 0) self.layer.shadowOpacity = 0 self.layer.shadowRadius = 0 self.layer.shadowColor = nil } } class SearchResultCellDecorator { func configureCell(cell:SearchResultCell, usingCellActionDelegate delegate: SearchResultCellDelegate?, withDataItem session:Session) { cell.title.text = session.title cell.subTitle.text = session.subtitle cell.data = session cell.delegate = delegate } }
bsd-2-clause
10f39a8f9172804d231d3b7ff29d305f
33.827103
155
0.630216
5.342652
false
false
false
false
jinseokpark6/u-team
Code/AppDelegate.swift
1
9723
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) var layerClient: LYRClient! // MARK TODO: Before first launch, update LayerAppIDString, ParseAppIDString or ParseClientKeyString values // TODO:If LayerAppIDString, ParseAppIDString or ParseClientKeyString are not set, this app will crash" let LayerAppIDString: NSURL! = NSURL(string: "layer:///apps/staging/3fe22e64-3b83-11e5-bf76-2d4d7f0072d6") let ParseAppIDString: String = "8FCgK7xgSL8K1q7gxQVTPGcondOe7U9TvRFX5gNI" let ParseClientKeyString: String = "bIX7LFCtnoVKG7v5tnOrMtUG7kDyn4vOk6AO3G8c" //Please note, You must set `LYRConversation *conversation` as a property of the ViewController. var conversation: LYRConversation! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { setupParse() setupLayer() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "Avenir Next", size: 25) as! AnyObject] UINavigationBar.appearance().barTintColor = UIColor(red: 69.0/255, green: 175.0/255, blue: 220.0/255, alpha: 1) UINavigationBar.appearance().tintColor = UIColor.whiteColor() // Badge Count let badgeCount = application.applicationIconBadgeNumber application.applicationIconBadgeNumber = 0 // let controller = storyboard.instantiateInitialViewController() as! ViewController controller.layerClient = layerClient self.window!.rootViewController = UINavigationController(rootViewController: controller) self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() // Register for Push Notitications if application.applicationState != UIApplicationState.Background { // Track an app open here if we launch with a push, unless // "content_available" was used to trigger a background push (introduced in iOS 7). // In that case, we skip tracking here to avoid double counting the app-open. let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus") let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:") var pushPayload = false if let options = launchOptions { pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil } if (preBackgroundPush || oldPushHandlerOnly || pushPayload) { PFAnalytics.trackAppOpenedWithLaunchOptionsInBackground([NSObject : AnyObject]?(), block: { (Bool, NSError) -> Void in }) } } if application.respondsToSelector("registerUserNotificationSettings:") { let userNotificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { let types: UIRemoteNotificationType = [.Badge, .Alert, .Sound] application.registerForRemoteNotificationTypes(types) } return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // Store the deviceToken in the current installation and save it to Parse. let currentInstallation: PFInstallation = PFInstallation.currentInstallation() currentInstallation.setDeviceTokenFromData(deviceToken) currentInstallation.saveInBackgroundWithBlock { (success, error) -> Void in if success { print("Successfully added installation") } } // Send device token to Layer so Layer can send pushes to this device. // For more information about Push, check out: // https://developer.layer.com/docs/ios/guides#push-notification assert(self.layerClient != nil, "The Layer client has not been initialized!") do { try self.layerClient.updateRemoteNotificationDeviceToken(deviceToken) print("Application did register for remote notifications: \(deviceToken)") } catch let error as NSError { print("Failed updating device token with error: \(error)") } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { let success = self.layerClient.synchronizeWithRemoteNotification(userInfo, completion: { (changes, error) -> Void in if (changes != nil) { if [changes.count] != nil { // var message = self.messageFromRemoteNotification(userInfo) completionHandler(UIBackgroundFetchResult.NewData) } else { completionHandler(UIBackgroundFetchResult.NoData) } } else { completionHandler(UIBackgroundFetchResult.Failed) } }) if !success { completionHandler(UIBackgroundFetchResult.NoData) } } func messageFromRemoteNotification(remoteNotification:NSDictionary) -> LYRMessage { let LQSPushMessageIdentifierKeyPath:NSString = "layer.message_identifier" // Retrieve message URL from Push Notification let messageURL = NSURL(string: "", relativeToURL: remoteNotification.valueForKeyPath(LQSPushMessageIdentifierKeyPath as String) as? NSURL) // Retrieve LYRMessage from Message URL let query = LYRQuery(queryableClass: LYRMessage.self) query.predicate = LYRPredicate(property: "identifier", predicateOperator: LYRPredicateOperator.IsIn, value: NSSet(object: messageURL!)) var messages: NSOrderedSet = NSOrderedSet() do { try messages = self.layerClient.executeQuery(query) if messages.count != 0 { print("Query contains \(messages.count) messages") let message = messages.firstObject as! LYRMessage let messagePart = message.parts[0] as! LYRMessagePart print("Pushed Message Contents: \(NSString(data: messagePart.data, encoding: NSUTF8StringEncoding)))") } } catch let error as NSError { print("Failed receiving message with error: \(error)") } return messages.firstObject as! LYRMessage } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { if error.code == 3010 { print("Push notifications are not supported in the iOS Simulator.") } else { print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error) } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { NSNotificationCenter.defaultCenter().postNotificationName("getMessage", object: nil) PFPush.handlePush(userInfo) if application.applicationState == UIApplicationState.Inactive { PFAnalytics.trackAppOpenedWithRemoteNotificationPayloadInBackground([NSObject : AnyObject]?(), block: { (Bool, NSError) -> Void in }) } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func setupParse() { // Enable Parse local data store for user persistence Parse.enableLocalDatastore() Parse.setApplicationId(ParseAppIDString, clientKey: ParseClientKeyString) // Set default ACLs let defaultACL: PFACL = PFACL() defaultACL.setPublicReadAccess(true) PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true) } func setupLayer() { layerClient = LYRClient(appID: LayerAppIDString) layerClient.autodownloadMIMETypes = NSSet(objects: ATLMIMETypeImagePNG, ATLMIMETypeImageJPEG, ATLMIMETypeImageJPEGPreview, ATLMIMETypeImageGIF, ATLMIMETypeImageGIFPreview, ATLMIMETypeLocation) as! Set<NSObject> } }
apache-2.0
4c7c78a715af2798ff9e99128a963bb3
40.909483
285
0.728685
5.160828
false
false
false
false
jakehirzel/swift-tip-calculator
CheckPlease WatchKit App Extension/ComplicationController.swift
1
1729
// // ComplicationController.swift // CheckPlease WatchKit App Extension // // Created by Jake Hirzel on 7/3/16. // Copyright © 2016 Jake Hirzel. All rights reserved. // import ClockKit class ComplicationController: NSObject { // MARK: - Placeholder Templates func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached var template: CLKComplicationTemplate? = nil switch complication.family { case .modularSmall: let modularTemplate = CLKComplicationTemplateModularSmallSimpleImage() modularTemplate.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Modular")!) template = modularTemplate case .modularLarge: template = nil case .utilitarianSmall: let utilitarianTemplate = CLKComplicationTemplateUtilitarianSmallFlat() utilitarianTemplate.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Utilitarian")!) utilitarianTemplate.textProvider = CLKSimpleTextProvider(text: "CkPls") template = utilitarianTemplate case .utilitarianLarge: template = nil case .circularSmall: let circularTemplate = CLKComplicationTemplateCircularSmallRingImage() circularTemplate.imageProvider = CLKImageProvider(onePieceImage: UIImage(named: "Complication/Circular")!) template = circularTemplate default: handler(nil) } handler(template) } }
mit
21392b778b2544ecfe7201c418464cf2
37.4
125
0.681713
5.897611
false
false
false
false
puyanLiu/LPYFramework
第三方框架改造/pull-to-refresh-master/ESPullToRefreshExample/ESPullToRefreshExample/Custom/WeChat/WeChatTableViewController.swift
4
3879
// // WeChatTableViewController.swift // ESPullToRefreshExample // // Created by lihao on 16/5/9. // Copyright © 2016年 egg swift. All rights reserved. // import UIKit class WeChatTableViewController: UITableViewController { var array = [String]() var page = 1 override func viewDidLoad() { super.viewDidLoad() self.view.translatesAutoresizingMaskIntoConstraints = false self.view.backgroundColor = UIColor.init(red: 46/255.0, green: 49/255.0, blue: 50/255.0, alpha: 1.0) self.tableView.register(UINib.init(nibName: "DefaultTableViewCell", bundle: nil), forCellReuseIdentifier: "DefaultTableViewCell") // Header like WeChat let header = WeChatTableHeaderView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: self.view.bounds.size.width, height: 260))) self.tableView.tableHeaderView = header /// Add some data for _ in 1...8{ self.array.append(" ") } let _ = self.tableView.es_addPullToRefresh(animator: WCRefreshHeaderAnimator.init(frame: CGRect.zero)) { [weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self?.page = 1 self?.array.removeAll() for _ in 1...8{ self?.array.append(" ") } self?.tableView.reloadData() self?.tableView.es_stopPullToRefresh(completion: true) } } self.tableView.refreshIdentifier = NSStringFromClass(DefaultTableViewController.self) // Set refresh identifier self.tableView.expriedTimeInterval = 20.0 // 20 second alive. let _ = self.tableView.es_addInfiniteScrolling() { [weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self?.page += 1 if self?.page ?? 0 <= 3 { for _ in 1...8{ self?.array.append(" ") } self?.tableView.reloadData() self?.tableView.es_stopLoadingMore() } else { self?.tableView.es_noticeNoMoreData() } } } self.tableView.es_footer?.backgroundColor = UIColor.white // Custom footer background color } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.tableView.es_autoPullToRefresh() } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DefaultTableViewCell", for: indexPath as IndexPath) cell.backgroundColor = UIColor.init(white: 250.0 / 255.0, alpha: 1.0) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) let vc = WebViewController.init() self.navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
c2dbc9a525e907d5f2d0a70facecc440
37.376238
157
0.614035
5.007752
false
false
false
false
freak4pc/netfox
netfox/Core/NFXGenericController.swift
1
2808
// // NFXGenericController.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import Cocoa #endif class NFXGenericController: NFXViewController { var selectedModel: NFXHTTPModel = NFXHTTPModel() override func viewDidLoad() { super.viewDidLoad() #if os(iOS) self.edgesForExtendedLayout = UIRectEdge() self.view.backgroundColor = NFXColor.NFXGray95Color() #elseif os(OSX) self.view.wantsLayer = true self.view.layer?.backgroundColor = NFXColor.NFXGray95Color().cgColor #endif } func selectedModel(_ model: NFXHTTPModel) { self.selectedModel = model } func formatNFXString(_ string: String) -> NSAttributedString { var tempMutableString = NSMutableAttributedString() tempMutableString = NSMutableAttributedString(string: string) let l = string.count let regexBodyHeaders = try! NSRegularExpression(pattern: "(\\-- Body \\--)|(\\-- Headers \\--)", options: NSRegularExpression.Options.caseInsensitive) let matchesBodyHeaders = regexBodyHeaders.matches(in: string, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, l)) as Array<NSTextCheckingResult> for match in matchesBodyHeaders { #if !swift(>=4.0) tempMutableString.addAttribute(NSFontAttributeName, value: NFXFont.NFXFontBold(size: 14), range: match.range) tempMutableString.addAttribute(NSForegroundColorAttributeName, value: NFXColor.NFXOrangeColor(), range: match.range) #else tempMutableString.addAttribute(NSAttributedStringKey.font, value: NFXFont.NFXFontBold(size: 14), range: match.range) tempMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: NFXColor.NFXOrangeColor(), range: match.range) #endif } let regexKeys = try! NSRegularExpression(pattern: "\\[.+?\\]", options: NSRegularExpression.Options.caseInsensitive) let matchesKeys = regexKeys.matches(in: string, options: NSRegularExpression.MatchingOptions.withoutAnchoringBounds, range: NSMakeRange(0, l)) as Array<NSTextCheckingResult> for match in matchesKeys { #if !swift(>=4.0) tempMutableString.addAttribute(NSForegroundColorAttributeName, value: NFXColor.NFXBlackColor(), range: match.range) #else tempMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: NFXColor.NFXBlackColor(), range: match.range) #endif } return tempMutableString } @objc func reloadData() { } }
mit
2e1fd671362325bf158e498b292ebef6
36.932432
195
0.670823
5.150459
false
false
false
false
seanmcneil/Thrimer
Sources/Thrimer/Thrimer.swift
1
4288
import Combine import Foundation /// Represents the life cycle of the timer public enum ThrimerAction { /// Timer is not running case idle /// Timer has been started case start /// Timer has been paused. Will include `TimerInterval` for remaining time case pause(TimeInterval) /// Timer has completed and will no longer run case completed /// Timer has been stopped case stop } extension ThrimerAction: Equatable {} public class Thrimer: ObservableObject { /// Provides a value representing the current state of the `Timer` @Published public private(set) var thrimerAction: ThrimerAction = .idle /// Remaining duration of current `Timer` private var interval: TimeInterval /// Indicates if `Timer` is repeating private var repeats = false /// Set when a timer starts running. Used for calculating remaining time on resumed timer. private var startTime: Date? { didSet { if startTime != nil { thrimerAction = .start } } } /// Tracks remaining time on a paused `Timer` private var pausedInterval: TimeInterval? { didSet { if let pausedInterval = pausedInterval { thrimerAction = .pause(pausedInterval) } } } /// Tracks timer publishers for cancellation private var cancellables = Set<AnyCancellable>() /// Indicates when `Timer` has been paused public var isPaused: Bool { pausedInterval != nil } /// Indicates if `Timer` is running public var isRunning: Bool { !cancellables.isEmpty } /// Computed property indicates time remaining. Will be nil if no timer is active. public var timeRemaining: TimeInterval? { if let startTime = startTime { let interval = Date().timeIntervalSince(startTime) return round(interval * 1000) / 1000 } return nil } /// Initialize Thrimer object /// /// - Parameters: /// - interval: Duration of timer in seconds /// - repeats: Should timer repeat. Default value is false /// - autostart: Should timer start immediately. Default value is true public init(interval: TimeInterval, repeats: Bool = false, autostart: Bool = true) { self.interval = interval self.repeats = repeats if autostart { start() } } deinit { cancel() } /// Starts a timer /// /// This will cancel any currently running timers and start /// a new one. public func start() { // Ensure there is no existing timer running cancel() Timer.publish(every: interval, on: .main, in: .default) .autoconnect() .sink { [weak self] _ in self?.handleTimerCompletion() } .store(in: &cancellables) startTime = Date() } /// Stops a timer public func stop() { cancel() thrimerAction = .stop } /// Pauses active timer public func pause() { if isRunning, let startTime = startTime { cancel() pausedInterval = Date().timeIntervalSince(startTime) } } /// Resumes a paused timer public func resume() { if let pausedInterval = pausedInterval { interval = pausedInterval start() } } // MARK: Private functions /// Called when timer completes private func handleTimerCompletion() { if repeats { thrimerAction = .completed startTime = Date() } else { cancel() thrimerAction = .completed thrimerAction = .idle } } /// Called when timer needs to be disposed of private func cancel() { cancellables.forEach { cancellable in cancellable.cancel() } cancellables.removeAll() reset() } /// Resets time variables private func reset() { if startTime != nil { startTime = nil } if pausedInterval != nil { pausedInterval = nil } } }
mit
c61ca7f729193e7f71ecbbf8351c29f4
24.223529
94
0.568797
5.333333
false
false
false
false
samodom/TestableUIKit
TestableUIKit/UIResponder/UIViewController/UIViewControllerAddChildViewControllerSpy.swift
1
3091
// // UIViewControllerAddChildViewControllerSpy.swift // TestableUIKit // // Created by Sam Odom on 2/25/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import TestSwagger import FoundationSwagger public extension UIViewController { private static let addChildViewControllerCalledString = UUIDKeyString() private static let addChildViewControllerCalledKey = ObjectAssociationKey(addChildViewControllerCalledString) private static let addChildViewControllerCalledReference = SpyEvidenceReference(key: addChildViewControllerCalledKey) private static let addChildViewControllerChildString = UUIDKeyString() private static let addChildViewControllerChildKey = ObjectAssociationKey(addChildViewControllerChildString) private static let addChildViewControllerChildReference = SpyEvidenceReference(key: addChildViewControllerChildKey) /// Spy controller for ensuring a controller has called its superclass's /// implementation of `addChildViewController(_:)`. public enum AddChildViewControllerSpyController: SpyController { public static let rootSpyableClass: AnyClass = UIViewController.self public static let vector = SpyVector.indirect public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(UIViewController.addChildViewController(_:)), spy: #selector(UIViewController.spy_addChildViewController(_:)) ) ] as Set public static let evidence = [ addChildViewControllerCalledReference, addChildViewControllerChildReference ] as Set public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `addChildViewController(_:)` public func spy_addChildViewController(_ child: UIViewController) { superclassAddChildViewControllerCalled = true superclassAddChildViewControllerChild = child spy_addChildViewController(child) } /// Indicates whether the `addChildViewController(_:)` method has been called on this object's superclass. public final var superclassAddChildViewControllerCalled: Bool { get { return loadEvidence(with: UIViewController.addChildViewControllerCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: UIViewController.addChildViewControllerCalledReference) } } /// Provides the child controller passed to `addChildViewController(_:)` if called. public final var superclassAddChildViewControllerChild: UIViewController? { get { return loadEvidence(with: UIViewController.addChildViewControllerChildReference) as? UIViewController } set { let reference = UIViewController.addChildViewControllerChildReference guard let child = newValue else { return removeEvidence(with: reference) } saveEvidence(child, with: reference) } } }
mit
471a3dfc0d74195533ba40883312d9ab
38.615385
121
0.716828
6.732026
false
false
false
false
jmayoralas/Sems
Sems/Bus/Ram.swift
1
1332
// // Ram.swift // Z80VirtualMachineKit // // Created by Jose Luis Fernandez-Mayoralas on 1/5/16. // Copyright © 2016 lomocorp. All rights reserved. // import Foundation protocol MemoryProtocol : BusComponentBase { var buffer: [UInt8] { get set } } extension MemoryProtocol { func dumpFromAddress(_ fromAddress: Int, count: Int) -> [UInt8] { let topAddress = Int(self.base_address) + self.block_size - 1 let myFromAddress = (fromAddress < 0 ? 0 : fromAddress) - Int(self.base_address) var myToAddress = fromAddress + (count > buffer.count ? buffer.count : count) - 1 - Int(self.base_address) myToAddress = myToAddress > topAddress ? topAddress : myToAddress return Array(buffer[myFromAddress...myToAddress]) } } class Ram : MemoryProtocol { var buffer : [UInt8] var base_address: UInt16 var block_size: Int init(base_address: UInt16, block_size: Int) { self.base_address = base_address self.block_size = block_size buffer = Array(repeating: 0x00, count: block_size) } func write(_ address: UInt16, value: UInt8) { buffer[Int(address) - Int(self.base_address)] = value } func read(_ address: UInt16) -> UInt8 { return buffer[Int(address) - Int(base_address)] } }
gpl-3.0
a93af875e20168fdcb2d3ea8238080e1
28.577778
114
0.635612
3.607046
false
false
false
false
dasdom/GlobalADN
GlobalADN/Model/PostBuilder.swift
1
2427
// // PostBuilder.swift // GlobalADN // // Created by dasdom on 20.06.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit protocol CanBuildPost { func postFromDictionary(dictionary: NSDictionary) -> Post? } class PostBuilder : CanBuildPost { let userBuilder = UserBuilder() let mentionBuilder = MentionBuilder() func postFromDictionary(dictionary: NSDictionary) -> Post? { var post: Post = Post() let canonicalURLString = dictionary["canonical_url"] as? String let id = dictionary["id"] as? String let text = dictionary["text"] as? String let threadId = dictionary["thread_id"] as? String let user = userBuilder.userFromDictionary(dictionary["user"] as NSDictionary) let rawMentionsArray = (dictionary["entities"] as NSDictionary)["mentions"] as NSArray var mentionsArray = [Mention]() for mentionsDictionary: AnyObject in rawMentionsArray { // println("mentionsDictionary \(mentionsDictionary)") if let mention = mentionBuilder.mentionFromDictionary(mentionsDictionary as NSDictionary) { mentionsArray.append(mention) } } // println("\(canonicalURLString) && \(id) && \(text) && \(threadId)") if canonicalURLString != nil && id != nil && text != nil && threadId != nil && user != nil { post.canonicalURL = NSURL(string: canonicalURLString!) post.id = id!.toInt()! post.text = text! post.threadId = threadId!.toInt()! post.user = user! post.mentions = mentionsArray post.attributedText = { let theAttributedText = NSMutableAttributedString(string: text!) for mention in mentionsArray { theAttributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: NSMakeRange(mention.position, mention.length)) } theAttributedText.addAttribute(NSFontAttributeName, value: UIFont.preferredFontForTextStyle(UIFontTextStyleBody), range: NSMakeRange(0, theAttributedText.length)) return theAttributedText }() } else { return nil } return post } }
mit
8a8dd272208d7588b7748a78842a2790
37.539683
178
0.596621
5.334066
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/FoundationUUIDTests.swift
1
2268
import XCTest import Foundation import GRDB class FoundationUUIDTests: GRDBTestCase { private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws { try makeDatabaseQueue().read { db in if let expectedUUID = expectedUUID { let decodedUUID = try UUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) XCTAssertEqual(decodedUUID, expectedUUID) } else if value == nil { let decodedUUID = try Optional<UUID>.fetchAll(db, sql: "SELECT NULL")[0] XCTAssertNil(decodedUUID) } } let decodedUUID = UUID.fromDatabaseValue(value?.databaseValue ?? .null) XCTAssertEqual(decodedUUID, expectedUUID) } private func assertRoundTrip(_ uuid: UUID) throws { let string = uuid.uuidString var uuid_t = uuid.uuid let data = withUnsafeBytes(of: &uuid_t) { Data(bytes: $0.baseAddress!, count: $0.count) } try assert(string, isDecodedAs: uuid) try assert(string.lowercased(), isDecodedAs: uuid) try assert(string.uppercased(), isDecodedAs: uuid) try assert(uuid, isDecodedAs: uuid) try assert(uuid as NSUUID, isDecodedAs: uuid) try assert(data, isDecodedAs: uuid) } func testSuccess() throws { try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!) try assertRoundTrip(UUID()) try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: UUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")) } func testFailure() throws { try assert(nil, isDecodedAs: nil) try assert(DatabaseValue.null, isDecodedAs: nil) try assert(1, isDecodedAs: nil) try assert(100000.1, isDecodedAs: nil) try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil) try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil) try assert("foo", isDecodedAs: nil) try assert("bar".data(using: .utf8)!, isDecodedAs: nil) try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil) try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil) } }
mit
5c3072c4a4233ebf28ff6e5ea7eec9b8
41.792453
129
0.638007
4.153846
false
true
false
false
popricoly/Contacts
Sources/Contacts/OMContactsStorage.swift
1
6515
// // OMContactsStorage.swift // Contacts // // Created by Olexandr Matviichuk on 7/25/17. // Copyright © 2017 Olexandr Matviichuk. All rights reserved. // import UIKit import CoreData private let kOMContactEntityName = "OMContact" public class OMContactsStorage: NSObject { public static let sharedStorage = OMContactsStorage() public func saveContactWith(firstName: String, lastName: String, phoneNumber: String, StreetAddress1: String, StreetAddress2: String, city: String, state: String, zipCode: String) { let contact = NSEntityDescription.insertNewObject(forEntityName: kOMContactEntityName, into: persistentContainer.viewContext) as! OMContact let contactID = String(mutableContacts.count + 1) contact.contactID = contactID contact.firstName = firstName contact.lastName = lastName contact.phoneNumber = phoneNumber contact.streetAddress1 = StreetAddress1 contact.streetAddress2 = StreetAddress2 contact.state = state contact.city = city contact.zipCode = zipCode saveContext() let localContact = OMLocalContact() localContact.contactID = contactID localContact.firstName = firstName localContact.lastName = lastName localContact.phoneNumber = phoneNumber localContact.streetAddress1 = StreetAddress1 localContact.streetAddress2 = StreetAddress2 localContact.city = city localContact.state = state localContact.zipCode = zipCode mutableContacts.append(localContact) } private var mutableContacts = [OMLocalContact]() public func contacts() -> Array<OMLocalContact> { return mutableContacts } public func updateContact(contact: OMLocalContact, firstName: String, lastName: String, phoneNumber: String, StreetAddress1: String, StreetAddress2: String, city: String, state: String, zipCode: String) { let index = mutableContacts.index(of: contact) let contactsFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: kOMContactEntityName) do { if let contacts = try persistentContainer.viewContext.fetch(contactsFetchRequest) as? [OMContact] { let contact = contacts[index!] contact.firstName = firstName contact.lastName = lastName contact.phoneNumber = phoneNumber contact.streetAddress1 = StreetAddress1 contact.streetAddress2 = StreetAddress2 contact.state = state contact.city = city contact.zipCode = zipCode saveContext() let localContact = mutableContacts[index!] localContact.firstName = firstName localContact.lastName = lastName localContact.phoneNumber = phoneNumber localContact.streetAddress1 = StreetAddress1 localContact.streetAddress2 = StreetAddress2 localContact.city = city localContact.state = state localContact.zipCode = zipCode } } catch { print("fetch error : \(error)") } } public func deleteContact(contact: OMLocalContact) { let index = mutableContacts.index(of: contact) mutableContacts.remove(at: index!) let contactsFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: kOMContactEntityName) do { if let contacts = try persistentContainer.viewContext.fetch(contactsFetchRequest) as? [OMContact] { persistentContainer.viewContext.delete(contacts[index!]) saveContext() } } catch { print("fetch error : \(error)") } } private func loadContacts() { let contactsFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: kOMContactEntityName) do { if let contacts = try persistentContainer.viewContext.fetch(contactsFetchRequest) as? [OMContact] { for contact in contacts { let localContact = OMLocalContact() localContact.contactID = contact.contactID! localContact.firstName = contact.firstName! localContact.lastName = contact.lastName! localContact.phoneNumber = contact.phoneNumber! localContact.streetAddress1 = contact.streetAddress1! localContact.streetAddress2 = contact.streetAddress2! localContact.state = contact.state! localContact.city = contact.city! localContact.zipCode = contact.zipCode! mutableContacts.append(localContact) } } } catch { print("fetch error : \(error)") } } private override init() { super.init() loadContacts() NotificationCenter.default.addObserver(self, selector: #selector(appWillTerminate), name: .UIApplicationWillTerminate, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: .UIApplicationDidEnterBackground, object: nil) } @objc private func appWillTerminate() { NotificationCenter.default.removeObserver(self) print("App will terminate") saveContext() } @objc private func appDidEnterBackground() { print("app did enter background") saveContext() } // MARK: - Core Data stack private lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Contacts") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support private func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
591b0fdc873c6d1fc68edb4824399ea3
38.96319
208
0.621584
5.857914
false
false
false
false
mohsenShakiba/ListView
Example/ListView/CustomViewController.swift
1
3136
//// //// CustomViewController.swift //// ListView //// //// Created by mohsen shakiba on 2/18/1396 AP. //// Copyright © 1396 CocoaPods. All rights reserved. //// // //import Foundation //import UIKit // //class CustomViewController: UIViewController, { // // var scrollView: UIScrollView! // var firstItem: CGFloat = 0 // var lastOffset: CGFloat = 14 // // var registeredCells: [String] = [] // var rows: [CustomView] = [] // // override func viewDidLoad() { // // self.view.addSubview(scrollView) // for i in 0...14 { // let view = getView(type: "CView") as! CustomView // view.frame = CGRect(x: 0, y: CGFloat(50 * i), width: self.view.bounds.width, height: 50) // view.backgroundColor = UIColor.blue // scrollView.addSubview(view) // } // } // // // // // //} // //class LVController: UIView, UIScrollViewDelegate { // // var scrollView: UIScrollView! // var visvibleSection = VisvibleSection() // var items: [CustomView] = [] // // override init(frame: CGRect) { // scrollView = UIScrollView(frame: frame) // scrollView.contentSize = CGSize(width: frame.width, height: 3000) // scrollView.delegate = self // scrollView.backgroundColor = .white // } // // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // // override func layoutSubviews() { // // } // // func scrollViewDidScroll(_ scrollView: UIScrollView) { // let offset = scrollView.contentOffset // let topPos = offset.y // let bottomPos = offset.y + self.bounds.height // } // // func addRow(index: Int, type: AnyClass) { // // } // // private func getView(type: String) -> UIView { // return UINib(nibName: type, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView // } // //} // //class VisvibleSection { // // var topItemIndex: Int // var bottomItemIndex: Int // // init() { // topItemIndex = 0 // bottomItemIndex = 0 // } // // // //} // //class CustomView { // // var id: String // var index: Int = 0 // var view: UIView? // var viewType: AnyClass? // var nextOperation: NextOperation = .add // // init() { // id = generateId() // } // // private func generateId() -> String { // // let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" // let len = UInt32(letters.length) // // var randomString = "" // // for _ in 0 ..< 10 { // let rand = arc4random_uniform(len) // var nextChar = letters.character(at: Int(rand)) // randomString += NSString(characters: &nextChar, length: 1) as String // } // // return randomString // } // //} // //enum NextOperation { // // case none // case add // case remove // //}
mit
bf1c55f94119396b713eb8dab337cf3e
24.08
106
0.533333
3.645349
false
false
false
false
Otbivnoe/XShared
XShared/SourceEditorCommand.swift
1
3577
// // SourceEditorCommand.swift // XShared // // Created by Nikita Ermolenko on 31/12/2016. // Copyright © 2016 Nikita Ermolenko. All rights reserved. // import Foundation import XcodeKit import AppKit class SourceEditorCommand: NSObject, XCSourceEditorCommand { func perform(with invocation: XCSourceEditorCommandInvocation, completionHandler: @escaping (Error?) -> Void ) -> Void { let selectedText = self.selectedText(from: invocation.buffer) if !selectedText.isEmpty { var pasteboardString = "" pasteboardString += "```" pasteboardString += "\n" pasteboardString += selectedText pasteboardString += "\n" pasteboardString += "```" NSPasteboard.general.declareTypes([NSPasteboard.PasteboardType.string], owner: nil) NSPasteboard.general.setString(pasteboardString, forType: NSPasteboard.PasteboardType.string) } completionHandler(nil) } private func selectedText(from buffer: XCSourceTextBuffer) -> String { var text = "" for (index, selection) in buffer.selections.enumerated() { if index > 0 { text.append("\n") } let range = selection as! XCSourceTextRange if range.start.line == range.end.line { let line = buffer.substring(by: range.start.line, from: range.start.column, to: range.end.column) text.append(line) continue } let firstLine = buffer.substring(by: range.start.line, from: range.start.column) text.append(firstLine) if range.end.line - range.start.line > 1 { for line in (range.start.line+1)...(range.end.line-1) { let line = buffer.lines[line] as! String text.append(line) } } let lastLine = buffer.substring(by: range.end.line, from: 0, to: range.end.column) text.append(lastLine) } text = text.trimmingCharacters(in: CharacterSet(charactersIn: "\n")) var minSpaceCount = Int.max var array = text.components(separatedBy: "\n") array.forEach { text in let count = text.beginingSpaceCount() if minSpaceCount > count { minSpaceCount = count } } array = array.map { text in text.trimming(by: minSpaceCount) } return array.joined(separator: "\n") } } fileprivate extension String { func beginingSpaceCount() -> Int { var count = 0 for character in characters { guard String(character) == " " else { break } count += 1 } return count } func trimming(by count: Int) -> String { return substring(from: count) } func substring(from: Int, to: Int? = nil) -> String { let lineLetters = characters.map { String($0) } let lineLettersSlice = lineLetters[from..<(to ?? characters.count)] return lineLettersSlice.joined() } } fileprivate extension XCSourceTextBuffer { func substring(by index: Int, from: Int, to: Int? = nil) -> String { var index = index if index == lines.count { index -= 1 } let line = lines[index] as! String return line.substring(from: from, to: to) } }
mit
8f6fb8a130ec58e4823cc943453b8ff3
30.368421
124
0.555928
4.780749
false
false
false
false
gpancio/iOS-Prototypes
GPUIKit/GPUIKit/Classes/GradientView.swift
1
901
// // GradientView.swift // GPUIKit // // Created by Graham Pancio on 2016-04-27. // Copyright © 2016 Graham Pancio. All rights reserved. // import UIKit public class GradientView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } private func setupView() { autoresizingMask = [.FlexibleWidth, .FlexibleHeight] guard let theLayer = self.layer as? CAGradientLayer else { return; } theLayer.colors = [UIColor.clearColor().CGColor, UIColor.blackColor().CGColor] theLayer.locations = [0.0, 1.0] theLayer.frame = self.bounds } override public class func layerClass() -> AnyClass { return CAGradientLayer.self } }
mit
91605b1addaa7d2ba04ea3b58d173945
22.684211
86
0.604444
4.455446
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/CredentialsStore/StaticUbiquitousKeyValueStore.swift
1
1397
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation /// Provides a way to test usage of UbiquitousKeyValueStore on non-release builds. class StaticUbiquitousKeyValueStore: UbiquitousKeyValueStore { // MARK: Types private typealias DataFormat = [String: [String: Any]] // MARK: Static Properties static let shared: UbiquitousKeyValueStore = StaticUbiquitousKeyValueStore() // MARK: Private Static Properties private static let userDefaults: UserDefaults! = UserDefaults(suiteName: StaticUbiquitousKeyValueStore.userDefaultsKey) private static let userDefaultsKey: String = "StaticUbiquitousKeyValueStore" // MARK: Private Properties private var data: DataFormat = [:] private let userDefaults: UserDefaults // MARK: Init private init(userDefaults: UserDefaults = StaticUbiquitousKeyValueStore.userDefaults) { self.userDefaults = userDefaults data = userDefaults.dictionary(forKey: StaticUbiquitousKeyValueStore.userDefaultsKey) as? DataFormat ?? [:] } func set(_ aDictionary: [String: Any]?, forKey aKey: String) { data[aKey] = aDictionary } func dictionary(forKey aKey: String) -> [String: Any]? { data } func synchronize() -> Bool { userDefaults.set(data, forKey: StaticUbiquitousKeyValueStore.userDefaultsKey) return true } }
lgpl-3.0
ed3560bb27d647bbbbcb9cdd57071f97
30.022222
123
0.719198
5.47451
false
false
false
false
Groupr-Purdue/Groupr-Backend
Sources/Library/Models/Event.swift
1
2651
import Vapor import Fluent import HTTP public final class Event: Model { public var id: Node? public var exists: Bool = false /// The attached course id (where it was sent/triggered). public var group_id: String /// The attached user id (who sent/triggered it). public var user_id: String /// The event message (its contents). public var message: String /// The event timestamp (when it happened). public var timestamp: Int /// The designated initializer. public init(group_id: String, user_id: String, message: String, timestamp: Int) { self.id = nil self.group_id = group_id self.user_id = user_id self.message = message self.timestamp = timestamp } /// Internal: Fluent::Model::init(Node, Context). public init(node: Node, in context: Context) throws { self.id = try? node.extract("id") self.group_id = try node.extract("group_id") self.user_id = try node.extract("user_id") self.message = try node.extract("message") self.timestamp = try node.extract("timestamp") } /// Internal: Fluent::Model::makeNode(Context). public func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "group_id": group_id, "user_id": user_id, "message": message, "timestamp": timestamp, ]) } /// Define a one-to-one ER relationship with Course. public func course() throws -> Parent<Group> { return try parent(self.id) /*group_id*/ } /// Define a one-to-one ER relationship with User. public func user() throws -> Parent<User> { return try parent(self.id) /*user_id*/ } } extension Event: Preparation { /// Create the User schema when required in the database. public static func prepare(_ database: Database) throws { try database.create("events", closure: { (events) in events.id() events.parent(Course.self) events.parent(User.self) events.string("message", length: nil, optional: true, unique: false, default: nil) events.int("timestamp", optional: true, unique: false, default: nil) }) } /// Delete/revert the User schema when required in the database. public static func revert(_ database: Database) throws { try database.delete("events") } } public extension Request { public func event() throws -> Event { guard let json = self.json else { throw Abort.badRequest } return try Event(node: json) } }
mit
12a0fa118ed8592e6e603a6df5ffe1a7
29.471264
94
0.605432
4.161695
false
false
false
false
lquigley/Game
Game/Game/SpriteKit/SKYGameScene.swift
1
9310
// // SKYGameScene.swift // Sky High // // Created by Luke Quigley on 9/18/14. // Copyright (c) 2014 Quigley. All rights reserved. // import SpriteKit protocol SKYGameSceneScoreDelegate { func updatedScore(score: Int) func startedGame() func endedGame() func balloonSizeChanged(size: Int) } class SKYGameScene: SKScene, SKPhysicsContactDelegate, SKYBalloonDelegate { var _lastBirdSecond:CFTimeInterval = 0.0 var _lastCloudSecond:CFTimeInterval = 0.0 var _sameTouch:Bool = false var _score:Int = 0 var _level:Int = 0 var _started:Bool = false var scoreDelegate:SKYGameSceneScoreDelegate? var balloon:SKYBalloon = SKYBalloon() var ground:SKYGround = SKYGround() override init(size: CGSize) { super.init(size: size) } required init?(coder: NSCoder) { super.init(coder: coder) } override func didMoveToView(view: SKView) { let midPoint = CGPointMake(CGRectGetMidX(self.view!.bounds), CGRectGetMidY(self.view!.bounds)) self.physicsWorld.contactDelegate = self; let leftWall = SKYWall(size: CGSizeMake(10, CGRectGetHeight(self.view!.frame))) leftWall.position = CGPointMake(-10, 0); addChild(leftWall) let rightWall = SKYWall(size: CGSizeMake(10, CGRectGetHeight(self.view!.frame))) rightWall.position = CGPointMake(CGRectGetWidth(self.view!.frame) / 2 + 10, 0); addChild(rightWall) let bottom = SKYWall(size: CGSizeMake(CGRectGetWidth(self.view!.frame), 10)) bottom.position = CGPointMake(0, -10); addChild(bottom) self.reset() } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if (!balloon.exploded) { self.balloon.physicsBody!.resting = true if !_started { self.start() _started = true } self.assessTouches(touches) } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if (!balloon.exploded) { self.assessTouches(touches) } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { if (!balloon.exploded) { self.assessTouches(touches) let action = SKAction.rotateToAngle(0, duration: 2.0) self.balloon.runAction(action) } } func assessTouches(touches:NSSet) { for touch: AnyObject in touches { var location = touch.locationInNode(self) //Offset the finger to 100 points below the balloon. location.y = CGRectGetHeight(self.frame) * 0.33 //Keep it in bounds let screenSize = self.view!.bounds; if location.x < 0 { location.x = 0 } else if location.x > CGRectGetWidth(screenSize) { location.x = CGRectGetWidth(screenSize) } if location.y < 0 { location.y = 0 } else if location.y > CGRectGetHeight(screenSize) { location.y = CGRectGetHeight(screenSize) } let action = SKAction.moveTo(location, duration: 0.0) self.balloon.runAction(action, completion: { () -> Void in self.balloon.physicsBody!.resting = true }) } } override func update(currentTime: CFTimeInterval) { if (_started) { self.enumerateChildNodesWithName("GoodNode", usingBlock: { (node:SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in if CGRectGetMaxY(node.frame) < 0 { node.removeFromParent() } }) self.enumerateChildNodesWithName("BadNode", usingBlock: { (node:SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in if CGRectGetMaxY(node.frame) < 0 { node.removeFromParent() } }) //One cloud/two second if currentTime - _lastCloudSecond > 0.5 { addCloud() _lastCloudSecond = currentTime } //One cloud/two second if currentTime - _lastBirdSecond > 1.5 { addBaddie() _lastBirdSecond = currentTime } self.score += 1 self.scoreDelegate?.updatedScore(_score) } } func addCloud() { let diceRoll = Int(arc4random_uniform(UInt32(CGRectGetWidth(view!.frame)))) let cloud = SKYCloud() cloud.position = CGPointMake(CGFloat(diceRoll), CGRectGetHeight(view!.frame)) addChild(cloud) } func addBaddie() { var baddie:SKYBaddie switch _level { case 1: baddie = SKYBird2() break case 2: baddie = SKYPlane() break case 3: baddie = SKYEel() break case 4: baddie = SKYPlanet() break default: baddie = SKYBird() break } if (baddie.physicsBody?.velocity.dx == 0) { // No velocity so put it somewhere in the middle and let it fall. let xValueRoll = CGFloat(arc4random_uniform(UInt32(CGRectGetWidth(view!.frame)))) baddie.position = CGPointMake(xValueRoll, CGRectGetHeight(view!.frame)) } else { let yValueRoll = CGRectGetHeight(view!.frame) - CGFloat(arc4random_uniform(200)) if (baddie.direction == SKYBaddieDirection.Left) { baddie.position = CGPointMake(0, yValueRoll) } else { baddie.position = CGPointMake(CGRectGetWidth(view!.frame), yValueRoll) } } addChild(baddie) } func reset() { balloon.reset() _started = false physicsWorld.gravity = CGVectorMake(0, 0) enumerateChildNodesWithName("GoodNode", usingBlock: { (node:SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in node.removeFromParent() }) enumerateChildNodesWithName("BadNode", usingBlock: { (node:SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in node.removeFromParent() }) let midPoint = CGPointMake(CGRectGetMidX(view!.bounds) / 2, CGRectGetMidY(view!.bounds) / 2) //Set up ground let action:SKAction = SKAction.moveTo(CGPointMake(190, 60), duration: 0) ground.runAction(action) ground.physicsBody?.resting = true if ground.parent == nil { addChild(ground) } //Set up balloon balloon.delegate = self balloon.position = midPoint balloon.reset() if balloon.parent == nil { addChild(balloon) } let highestScore = NSUserDefaults.standardUserDefaults().integerForKey(SKYUserDefaultKeys.highScore) if _score > highestScore { NSUserDefaults.standardUserDefaults().setInteger(_score, forKey: SKYUserDefaultKeys.highScore) NSUserDefaults.standardUserDefaults().synchronize() } scoreDelegate?.updatedScore(_score) _score = 0 } func start() { physicsWorld.gravity = CGVectorMake(0, -5) scoreDelegate?.startedGame() } func didBeginContact(contact: SKPhysicsContact) { let nodeA = contact.bodyA.node let nodeB = contact.bodyB.node if nodeA!.isKindOfClass(SKYBalloon) { if nodeB != nil && nodeB!.isKindOfClass(SKYCloud) { balloon.increaseSize() } else if nodeB != nil && nodeB!.isKindOfClass(SKYBaddie) { balloon.decreaseSize() } nodeB?.removeFromParent() } } func balloonExploded(balloon: SKYBalloon) { NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "endGame", userInfo: nil, repeats: false) } func endGame() { self.reset() self.scoreDelegate?.endedGame() } var score:Int { get { return _score } set { if (_score != newValue) { _score = newValue let expectedLevel = Int(floorf(Float(_score) / Float(SKYLevelConstants.levelPoints))) if (expectedLevel > _level) { self.level = expectedLevel } } } } var level:Int { get { return _level } set { if (_level != newValue) { _level = newValue //Drop a level icon let levelRope = SKYLevelRope() levelRope.level = _level levelRope.position = CGPointMake (CGRectGetWidth(self.view!.frame) / 2, CGRectGetHeight(self.view!.frame)) addChild(levelRope) } } } }
mit
ce92de5cd7b907d3a6533c4d4da0e2e4
30.883562
122
0.544791
4.923321
false
false
false
false
coach-plus/ios
Pods/Hero/Sources/Extensions/UIView+Hero.swift
1
7714
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class SnapshotWrapperView: UIView { let contentView: UIView init(contentView: UIView) { self.contentView = contentView super.init(frame: contentView.frame) addSubview(contentView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() contentView.bounds.size = bounds.size contentView.center = bounds.center } } extension UIView: HeroCompatible { } public extension HeroExtension where Base: UIView { /** **ID** is the identifier for the view. When doing a transition between two view controllers, Hero will search through all the subviews for both view controllers and matches views with the same **heroID**. Whenever a pair is discovered, Hero will automatically transit the views from source state to the destination state. */ var id: String? { get { return objc_getAssociatedObject(base, &type(of: base).AssociatedKeys.heroID) as? String } set { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroID, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** **isEnabled** allows to specify whether a view and its subviews should be consider for animations. If true, Hero will search through all the subviews for heroIds and modifiers. Defaults to true */ var isEnabled: Bool { get { return objc_getAssociatedObject(base, &type(of: base).AssociatedKeys.heroEnabled) as? Bool ?? true } set { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroEnabled, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** **isEnabledForSubviews** allows to specify whether a view's subviews should be consider for animations. If true, Hero will search through all the subviews for heroIds and modifiers. Defaults to true */ var isEnabledForSubviews: Bool { get { return objc_getAssociatedObject(base, &type(of: base).AssociatedKeys.heroEnabledForSubviews) as? Bool ?? true } set { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroEnabledForSubviews, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Use **modifiers** to specify animations alongside the main transition. Checkout `HeroModifier.swift` for available modifiers. */ var modifiers: [HeroModifier]? { get { return objc_getAssociatedObject(base, &type(of: base).AssociatedKeys.heroModifiers) as? [HeroModifier] } set { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroModifiers, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** **modifierString** provides another way to set **modifiers**. It can be assigned through storyboard. */ var modifierString: String? { get { fatalError("Reverse lookup is not supported") } set { modifiers = newValue?.parse() } } /// Used for .overFullScreen presentation internal var storedAlpha: CGFloat? { get { if let doubleValue = (objc_getAssociatedObject(base, &type(of: base).AssociatedKeys.heroStoredAlpha) as? NSNumber)?.doubleValue { return CGFloat(doubleValue) } return nil } set { if let newValue = newValue { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroStoredAlpha, NSNumber(value: newValue.native), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } else { objc_setAssociatedObject(base, &type(of: base).AssociatedKeys.heroStoredAlpha, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } } public extension UIView { fileprivate struct AssociatedKeys { static var heroID = "heroID" static var heroModifiers = "heroModifers" static var heroStoredAlpha = "heroStoredAlpha" static var heroEnabled = "heroEnabled" static var heroEnabledForSubviews = "heroEnabledForSubviews" } // TODO: can be moved to internal later (will still be accessible via IB) @available(*, renamed: "hero.id") @IBInspectable var heroID: String? { get { return hero.id } set { hero.id = newValue } } // TODO: can be moved to internal later (will still be accessible via IB) @available(*, renamed: "hero.isEnabled") @IBInspectable var isHeroEnabled: Bool { get { return hero.isEnabled } set { hero.isEnabled = newValue } } // TODO: can be moved to internal later (will still be accessible via IB) @available(*, renamed: "hero.isEnabledForSubviews") @IBInspectable var isHeroEnabledForSubviews: Bool { get { return hero.isEnabledForSubviews } set { hero.isEnabledForSubviews = newValue } } @available(*, renamed: "hero.modifiers") var heroModifiers: [HeroModifier]? { get { return hero.modifiers } set { hero.modifiers = newValue } } // TODO: can be moved to internal later (will still be accessible via IB) @available(*, renamed: "hero.modifierString") @IBInspectable var heroModifierString: String? { get { fatalError("Reverse lookup is not supported") } set { hero.modifiers = newValue?.parse() } } internal func slowSnapshotView() -> UIView { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0) guard let currentContext = UIGraphicsGetCurrentContext() else { UIGraphicsEndImageContext() return UIView() } layer.render(in: currentContext) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageView = UIImageView(image: image) imageView.frame = bounds return SnapshotWrapperView(contentView: imageView) } internal func snapshotView() -> UIView? { let snapshot = snapshotView(afterScreenUpdates: true) if #available(iOS 11.0, *), let oldSnapshot = snapshot { // in iOS 11, the snapshot taken by snapshotView(afterScreenUpdates) won't contain a container view return SnapshotWrapperView(contentView: oldSnapshot) } else { return snapshot } } internal var flattenedViewHierarchy: [UIView] { guard hero.isEnabled else { return [] } if #available(iOS 9.0, *), isHidden && (superview is UICollectionView || superview is UIStackView || self is UITableViewCell) { return [] } else if isHidden && (superview is UICollectionView || self is UITableViewCell) { return [] } else if hero.isEnabledForSubviews { return [self] + subviews.flatMap { $0.flattenedViewHierarchy } } else { return [self] } } @available(*, renamed: "hero.storedAplha") internal var heroStoredAlpha: CGFloat? { get { return hero.storedAlpha } set { hero.storedAlpha = newValue } } }
mit
e29afecb746297834b7550ad314a933d
38.357143
156
0.716749
4.616397
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/ResetPasswordTableViewController.swift
1
10883
// // ResetPasswordTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/05/28. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class ResetPasswordTableViewController: BaseTableViewController, UITextFieldDelegate { enum Item: Int { case Username = 0, Email, Endpoint, Spacer1, Button, _Num } var username = "" var email = "" var endpoint = "" override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.navigationController?.navigationBarHidden = false self.title = NSLocalizedString("Forgot password", comment: "Forgot password") self.tableView.registerNib(UINib(nibName: "TextFieldTableViewCell", bundle: nil), forCellReuseIdentifier: "TextFieldTableViewCell") self.tableView.registerNib(UINib(nibName: "ButtonTableViewCell", bundle: nil), forCellReuseIdentifier: "ButtonTableViewCell") self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None self.tableView.backgroundColor = Color.tableBg } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return Item._Num.rawValue } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = UITableViewCell() // Configure the cell... switch indexPath.row { case Item.Username.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("username", comment: "username") c.textField.keyboardType = UIKeyboardType.Default c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = username c.textField.tag = indexPath.row c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_1") cell = c case Item.Email.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("email", comment: "email") c.textField.keyboardType = UIKeyboardType.EmailAddress c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = email c.textField.tag = indexPath.row c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_2") cell = c case Item.Endpoint.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("TextFieldTableViewCell", forIndexPath: indexPath) as! TextFieldTableViewCell c.textField.placeholder = NSLocalizedString("endpoint", comment: "endpoint") c.textField.keyboardType = UIKeyboardType.URL c.textField.returnKeyType = UIReturnKeyType.Done c.textField.secureTextEntry = false c.textField.autocorrectionType = UITextAutocorrectionType.No c.textField.text = endpoint c.textField.tag = indexPath.row c.textField.delegate = self c.textField.addTarget(self, action: "textFieldChanged:", forControlEvents: UIControlEvents.EditingChanged) c.bgImageView.image = UIImage(named: "signin_table_3") cell = c case Item.Button.rawValue: let c = tableView.dequeueReusableCellWithIdentifier("ButtonTableViewCell", forIndexPath: indexPath) as! ButtonTableViewCell c.button.setTitle(NSLocalizedString("Reset", comment: "Reset"), forState: UIControlState.Normal) c.button.titleLabel?.font = UIFont.systemFontOfSize(17.0) c.button.setTitleColor(Color.buttonText, forState: UIControlState.Normal) c.button.setTitleColor(Color.buttonDisableText, forState: UIControlState.Disabled) c.button.setBackgroundImage(UIImage(named: "btn_signin"), forState: UIControlState.Normal) c.button.setBackgroundImage(UIImage(named: "btn_signin_highlight"), forState: UIControlState.Highlighted) c.button.setBackgroundImage(UIImage(named: "btn_signin_disable"), forState: UIControlState.Disabled) c.button.enabled = self.validate() c.button.addTarget(self, action: "resetButtonPushed:", forControlEvents: UIControlEvents.TouchUpInside) cell = c default: break } cell.selectionStyle = UITableViewCellSelectionStyle.None cell.backgroundColor = Color.clear return cell } //MARK: - Table view delegate override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 64.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView: GroupedHeaderView = GroupedHeaderView.instanceFromNib() as! GroupedHeaderView headerView.label.text = NSLocalizedString("Reset password", comment: "Reset password") return headerView } //MARK: - Table view delegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.row { case Item.Username.rawValue: return 48.0 case Item.Email.rawValue: return 48.0 case Item.Endpoint.rawValue: return 48.0 case Item.Button.rawValue: return 40.0 default: return 12.0 } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ private func validate()-> Bool { if username.isEmpty || email.isEmpty || endpoint.isEmpty { return false } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func textFieldChanged(field: UITextField) { switch field.tag { case Item.Username.rawValue: username = field.text! case Item.Email.rawValue: email = field.text! case Item.Endpoint.rawValue: endpoint = field.text! default: break } let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow:Item.Button.rawValue , inSection: 0)) as! ButtonTableViewCell cell.button.enabled = self.validate() } private func resetPassword(username: String, email: String, endpoint: String) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true SVProgressHUD.showWithStatus(NSLocalizedString("Reset password...", comment: "Reset password...")) let api = DataAPI.sharedInstance api.APIBaseURL = endpoint let failure: (JSON!-> Void) = { (error: JSON!)-> Void in LOG("failure:\(error.description)") SVProgressHUD.showErrorWithStatus(error["message"].stringValue) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } api.recoverPassword(username, email: email, success: {_ in UIApplication.sharedApplication().networkActivityIndicatorVisible = false SVProgressHUD.dismiss() self.navigationController?.popViewControllerAnimated(true) }, failure: failure ) } @IBAction func resetButtonPushed(sender: AnyObject) { self.resetPassword(username, email: email, endpoint: endpoint) } }
mit
6646b423153c3a7751a3e9c98a5a9849
40.060377
157
0.662163
5.61745
false
false
false
false
a2/Simon
Simon WatchKit App Extension/GameInterfaceController.swift
1
6881
import SimonKit import WatchKit import UIKit let GameHistoryKey = "GameHistoryKey" @asmname("UIAccessibilityPostNotification") func UIAccessibilityPostNotification(notification: UIAccessibilityNotifications, argument: AnyObject?) class GameInterfaceController: WKInterfaceController { let userDefaults = NSUserDefaults(suiteName: "group.us.pandamonia.Simon")! var game = Game<Color>() var guess = [Color]() var didTapMenuItem = false // MARK: - IBOutlets @IBOutlet weak var redImage: WKInterfaceImage! @IBOutlet weak var redButton: WKInterfaceButton! @IBOutlet weak var greenImage: WKInterfaceImage! @IBOutlet weak var greenButton: WKInterfaceButton! @IBOutlet weak var yellowImage: WKInterfaceImage! @IBOutlet weak var yellowButton: WKInterfaceButton! @IBOutlet weak var blueImage: WKInterfaceImage! @IBOutlet weak var blueButton: WKInterfaceButton! @IBOutlet weak var scoreLabel: WKInterfaceLabel! // MARK: - Actions func colorButtonTapped(color: Color) { guess.append(color) // Validate let isValid: Bool = { for (c1, c2) in zip(guess, game.history[0..<guess.count]) { if c1 != c2 { return false } } return true }() if !isValid { // Game over userDefaults.removeObjectForKey(GameHistoryKey) userDefaults.synchronize() disableAllButtons() let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { WKInterfaceController.reloadRootControllers([("mainMenu", self.game.history.count - 1)]) self.game = Game() self.updatePoints(0) } } else if guess.count == game.history.count { updatePoints(game.history.count) disableAllButtons() guess.removeAll(keepCapacity: true) game.addRound() let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue(), playHistory) } } func updatePoints(score: Int) { let pointsText = String.localizedStringWithFormat(NSLocalizedString("%d pts.", comment: "Score in points; {score} is replaced with the number of completed rounds"), score) scoreLabel.setText(String.localizedStringWithFormat(NSLocalizedString("Score: %@", comment: "Score label; text; {score} is replaced with the number of completed rounds"), pointsText)) } @IBAction func redButtonTapped() { colorButtonTapped(.Red) } @IBAction func greenButtonTapped() { colorButtonTapped(.Green) } @IBAction func yellowButtonTapped() { colorButtonTapped(.Yellow) } @IBAction func blueButtonTapped() { colorButtonTapped(.Blue) } @IBAction func startNewGame() { didTapMenuItem = true userDefaults.removeObjectForKey(GameHistoryKey) userDefaults.synchronize() game = Game() game.addRound() updatePoints(0) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue(), playHistory) } @IBAction func openMainMenu() { didTapMenuItem = true let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { WKInterfaceController.reloadRootControllersWithNames(["mainMenu"], contexts: nil) } } // MARK: - Playback func enableAllButtons() { for button in [redButton, greenButton, yellowButton, blueButton] { button.setEnabled(true) } } func flashImage(color: Color) { func animate(image: WKInterfaceImage) { image.startAnimatingWithImagesInRange(NSRange(1..<11), duration: 0.5, repeatCount: 1) } let localizedAnnouncement: String switch color { case .Red: localizedAnnouncement = NSLocalizedString("Red", comment: "Accessibility announcement; red") redImage.setImageNamed("Red") animate(redImage) case .Green: localizedAnnouncement = NSLocalizedString("Green", comment: "Accessibility announcement; green") greenImage.setImageNamed("Green") animate(greenImage) case .Yellow: localizedAnnouncement = NSLocalizedString("Yellow", comment: "Accessibility announcement; yellow") yellowImage.setImageNamed("Yellow") animate(yellowImage) case .Blue: localizedAnnouncement = NSLocalizedString("Blue", comment: "Accessibility announcement; blue") blueImage.setImageNamed("Blue") animate(blueImage) } UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, argument: localizedAnnouncement) WKInterfaceDevice.currentDevice().playHaptic(.Click) } func disableAllButtons() { for button in [redButton, greenButton, yellowButton, blueButton] { button.setEnabled(false) } } func playHistory() { disableAllButtons() for (i, color) in game.history.enumerate() { let when = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(i) * NSEC_PER_SEC)) dispatch_after(when, dispatch_get_main_queue()) { self.flashImage(color) } } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(game.history.count - 1) * NSEC_PER_SEC + NSEC_PER_SEC / 2)) dispatch_after(when, dispatch_get_main_queue(), enableAllButtons) } // MARK: - Life Cycle override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) if let gameHistory = userDefaults.arrayForKey(GameHistoryKey) as? [Int] { game = Game(history: gameHistory.flatMap(Color.init)) } updatePoints(game.history.count) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue(), playHistory) } override func willActivate() { super.willActivate() if didTapMenuItem { didTapMenuItem = false return } if game.history.count == 0 { game.addRound() } } override func didDeactivate() { super.didDeactivate() if didTapMenuItem { didTapMenuItem = false return } let object = game.history.map { $0.rawValue } userDefaults.setObject(object, forKey: GameHistoryKey) userDefaults.synchronize() } }
mit
a8318b383a559292de18a4451ef3ace9
30.856481
191
0.629269
4.873229
false
false
false
false
readium/r2-streamer-swift
r2-streamer-swift/Toolkit/Streams/ZIPInputStream.swift
1
3534
// // RDUnzipStream.swift // r2-streamer-swift // // Created by Olivier Körner on 11/01/2017. // // Copyright 2018 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license which is detailed // in the LICENSE file present in the project repository where this source code is maintained. // import UIKit import Minizip import R2Shared extension ZipInputStream: Loggable {} /// Create a InputStream related to ONE file in the ZipArchive. class ZipInputStream: SeekableInputStream { var zipArchive: ZipArchive var fileInZipPath: String private var _streamError: Error? override var streamError: Error? { get { return _streamError } } private var _streamStatus: Stream.Status = .notOpen override var streamStatus: Stream.Status { get { return _streamStatus } } private var _length: UInt64 override var length: UInt64 { return _length } override var offset: UInt64 { return UInt64(zipArchive.currentFileOffset) } override var hasBytesAvailable: Bool { get { return offset < _length } } init?(zipFilePath: String, path: String) { // New ZipArchive for archive at `zipFilePath`. guard let zipArchive = ZipArchive(url: URL(fileURLWithPath: zipFilePath)) else { return nil } self.zipArchive = zipArchive fileInZipPath = path // Check if the file exists in the archive. guard zipArchive.locateFile(path: fileInZipPath), let fileInfo = try? zipArchive.informationsOfCurrentFile() else { return nil } _length = fileInfo.length super.init() } init?(zipArchive: ZipArchive, path: String) { self.zipArchive = zipArchive fileInZipPath = path // Check if the file exists in the archive. guard zipArchive.locateFile(path: fileInZipPath), let fileInfo = try? zipArchive.informationsOfCurrentFile() else { return nil } _length = fileInfo.length super.init() } override func open() { do { try zipArchive.openCurrentFile() _streamStatus = .open } catch { log(.error, "Could not ZipArchive.openCurrentFile()") _streamStatus = .error _streamError = error } } override func getBuffer(_ buffer: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>, length len: UnsafeMutablePointer<Int>) -> Bool { return false } override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int { let bytesRead = zipArchive.readDataFromCurrentFile(buffer, maxLength: UInt64(maxLength)) if Int(bytesRead) < maxLength { _streamStatus = .atEnd } return Int(bytesRead) } override func close() { zipArchive.closeCurrentFile() _streamStatus = .closed } override func seek(offset: Int64, whence: SeekWhence) throws { assert(whence == .startOfFile, "Only seek from start of stream is supported for now.") assert(offset >= 0, "Since only seek from start of stream if supported, offset must be >= 0") do { try zipArchive.seek(Int(offset)) } catch { _streamStatus = .error _streamError = error } } }
bsd-3-clause
b8c92e280b9ca5899e945157efc7f807
27.264
101
0.606284
4.873103
false
false
false
false
inamiy/VTree
VTreePlayground.playground/Pages/Simple Counter (Flexbox).xcplaygroundpage/Contents.swift
1
3465
import UIKit import PlaygroundSupport import VTree import Flexbox import DemoFramework struct Model { let rootSize = CGSize(width: 320, height: 480) let count: Int } func update(_ model: Model, _ msg: Msg) -> Model? { switch msg { case .increment: return Model(count: model.count + 1) case .decrement: return Model(count: model.count - 1) } } func view(model: Model) -> VView<Msg> { let rootWidth = model.rootSize.width let rootHeight = model.rootSize.height let space: CGFloat = 20 let buttonWidth = (rootWidth - space*3)/2 func rootView(_ children: [AnyVTree<Msg>] = []) -> VView<Msg> { return VView( styles: .init { $0.backgroundColor = .white $0.flexbox = Flexbox.Node( size: model.rootSize, flexDirection: .column, justifyContent: .center, alignItems: .center, padding: Edges(uniform: space) ) }, children: children ) } func label(_ count: Int) -> VLabel<Msg> { return VLabel( text: .text("\(count)"), styles: .init { $0.backgroundColor = .clear $0.textAlignment = .center $0.font = .systemFont(ofSize: 48) $0.flexbox = Flexbox.Node( maxSize: CGSize(width: rootWidth - space*2, height: CGFloat.nan), padding: Edges(left: 50, right: 50) ) } ) } func buttons(_ children: [AnyVTree<Msg>]) -> VView<Msg> { return VView( styles: .init { $0.flexbox = Flexbox.Node( size: CGSize(width: CGFloat.nan, height: 70), flexDirection: .row, justifyContent: .spaceBetween, alignSelf: .stretch ) return }, children: children ) } func incrementButton() -> VButton<Msg> { return VButton( title: "+", styles: .init { $0.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) $0.font = .systemFont(ofSize: 24) $0.flexbox = Flexbox.Node( flexGrow: 1, margin: Edges(uniform: 10) ) }, handlers: [.touchUpInside: .increment] ) } func decrementButton() -> VButton<Msg> { return VButton( title: "-", styles: .init { $0.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1) $0.font = .systemFont(ofSize: 24) $0.flexbox = Flexbox.Node( flexGrow: 1, margin: Edges(uniform: 10) ) }, handlers: [.touchUpInside: .decrement] ) } let count = model.count return rootView([ *label(count), *buttons([ *decrementButton(), *incrementButton() ]) ]) } // MARK: Main let initial = Model(count: 0) let program = Program(model: initial, update: update, view: view) PlaygroundPage.current.liveView = program.rootView
mit
7b681fa27ee24b8c4233cd6d6608339e
26.070313
120
0.486003
4.347553
false
false
false
false
AthensWorks/OBWapp-iOS
Brew Week/Brew Week/Model Classes/EstablishmentExtension.swift
1
4202
// // Establishment.swift // Brew Week // // Created by Ben Lachman on 3/19/15. // Copyright (c) 2015 Ohio Brew Week. All rights reserved. // import UIKit import CoreData extension Establishment { class func establishmentsFromJSON(jsonDict: [String: AnyObject]) { guard let jsonEstablishmentsArray = jsonDict["establishments"] as? [[String: AnyObject]] else { return } let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate if jsonEstablishmentsArray.count == 0 { return } var establishmentIDs = [Int]() for establishmentJSON in jsonEstablishmentsArray { guard let intIdentifier = establishmentJSON["id"] as? Int else { continue } let identifier = Int32(intIdentifier) var establishment = establishmentForIdentifier(identifier, inContext: appDelegate.managedObjectContext) if establishment == nil { establishment = NSEntityDescription.insertNewObjectForEntityForName("Establishment", inManagedObjectContext: appDelegate.managedObjectContext) as? Establishment print("Adding new establishment: " + (establishmentJSON["name"] as? String ?? "No name") + "\n") } if let 🏬 = establishment { 🏬.identifier = identifier 🏬.address = establishmentJSON["address"] as? String ?? "No Address" 🏬.name = establishmentJSON["name"] as? String ?? "No Name" 🏬.lat = establishmentJSON["lat"] as? Float ?? 0 🏬.lon = establishmentJSON["lon"]as? Float ?? 0 if let statuses = establishmentJSON["beer_statuses"] as? [[String: AnyObject]] { for statusJSON in statuses { 🏬.updateOrCreateStatusFromJSON(statusJSON) } } } establishmentIDs.append(Int(identifier)) } let fetchRemovedEstablishments = NSFetchRequest(entityName: "Establishment") fetchRemovedEstablishments.predicate = NSPredicate(format: "NOT (identifier IN %@)", establishmentIDs) if let array = try? appDelegate.managedObjectContext.executeFetchRequest(fetchRemovedEstablishments), results = array as? [NSManagedObject] { if results.count > 0 { print("Removing \(results.count) establishments") for establishment in results { appDelegate.managedObjectContext.deleteObject(establishment) } } } appDelegate.saveContext() } class func establishmentForIdentifier(identifier: Int32, inContext context: NSManagedObjectContext) -> Establishment? { let request = NSFetchRequest(entityName: "Establishment") request.predicate = NSPredicate(format: "identifier == %d", identifier) request.fetchLimit = 1 if let result = (try? context.executeFetchRequest(request)) as? [Establishment] { if result.count > 0 { return result[0] } } return nil } func updateOrCreateStatusFromJSON(statusJSON: [String: AnyObject]) { guard let intIdentifier = statusJSON["id"] as? Int else { return } let beerIdentifier = Int32(intIdentifier) let status = statusJSON["status"] as? String ?? "No Status" if let 🍺 = Beer.beerForIdentifier(beerIdentifier, inContext: managedObjectContext!) { var statusExists = false for item in beerStatuses { if let beerStatus = item as? BeerStatus { if beerStatus.beer == 🍺 { statusExists = true beerStatus.status = status } } } if statusExists == false { if let newStatus = NSEntityDescription.insertNewObjectForEntityForName("BeerStatus", inManagedObjectContext: managedObjectContext!) as? BeerStatus { newStatus.beer = 🍺 newStatus.establishment = self newStatus.status = status } } } } }
apache-2.0
23f2b5e6bb61d379f5ac5001e05da852
33.196721
176
0.603308
5.176179
false
false
false
false
UW-AppDEV/AUXWave
AUXWave/ViewController.swift
1
8000
// // ViewController.swift // AUXWave // // Created by Nico Cvitak on 2015-02-28. // Copyright (c) 2015 UW-AppDEV. All rights reserved. // import UIKit import AVFoundation import MediaPlayer import MultipeerConnectivity class ViewController: UIViewController, MPMediaPickerControllerDelegate, UIActionSheetDelegate, UITableViewDataSource, UITableViewDelegate, PlaylistPlayerDelegate, DJServiceDelegate { private let mediaPicker = MPMediaPickerController(mediaTypes: .Music) private var clearPlaylistActionSheet: UIActionSheet? private var player: PlaylistPlayer? private var toolbarIdleItems: [UIBarButtonItem]? private var toolbarEditItems: [UIBarButtonItem]? @IBOutlet private var blurAlbumArtworkImageView: UIImageView? @IBOutlet private var toolbar: UIToolbar? @IBOutlet private var tableView: UITableView? @IBOutlet private var controlBar: PlayerControlBar? @IBOutlet private var volumeView: MPVolumeView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mediaPicker.allowsPickingMultipleItems = true mediaPicker.showsCloudItems = false mediaPicker.delegate = self clearPlaylistActionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Clear") clearPlaylistActionSheet?.tintColor = self.view.tintColor toolbarIdleItems = [ UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editPlaylist"), UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: "clearPlaylist") ] toolbarEditItems = [ UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneEditingPlaylist"), UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: "shufflePlaylist"), UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addItemsToPlaylist") ] toolbar?.items = toolbarIdleItems player = PlaylistPlayer() player?.delegate = self tableView?.dataSource = self tableView?.delegate = self controlBar?.player = player volumeView?.showsVolumeSlider = true volumeView?.showsRouteButton = false volumeView?.sizeToFit() DJService.localService().delegate = self } override func viewWillAppear(animated: Bool) { //self.navigationController?.navigationBarHidden = true } override func viewWillDisappear(animated: Bool) { //self.navigationController?.navigationBarHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func editPlaylist() { tableView?.setEditing(true, animated: true) toolbar?.setItems(toolbarEditItems, animated: false) } func clearPlaylist() { clearPlaylistActionSheet?.showInView(self.view) } func doneEditingPlaylist() { tableView?.setEditing(false, animated: true) toolbar?.setItems(toolbarIdleItems, animated: false) } func addItemsToPlaylist() { self.presentViewController(mediaPicker, animated: true, completion: nil) } func shufflePlaylist() { player?.shuffle() tableView?.reloadData() } func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) { let items: [PlaylistItem] = map(mediaItemCollection.items, {($0 as MPMediaItem).asPlaylistItem() }) player?.playlist.extend(items) mediaPicker.dismissViewControllerAnimated(true, completion: nil) } func mediaPickerDidCancel(mediaPicker: MPMediaPickerController!) { mediaPicker.dismissViewControllerAnimated(true, completion: nil) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if actionSheet == clearPlaylistActionSheet && buttonIndex == 0 { player?.playlist.removeAll(keepCapacity: false) tableView?.reloadData() } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PlaylistTableViewCell") as PlaylistTableViewCell let item = player?.playlist[indexPath.row] cell.albumArtworkImageView?.image = player?.playlist[indexPath.row].artwork cell.titleLabel?.text = item?.title if item?.artist != nil && item?.albumName != nil { cell.artistAndAlbumNameLabel?.text = "\(item!.artist!) | \(item!.albumName!)" } if player?.currentItem == item { cell.titleLabel?.textColor = kAUXWaveTintColor cell.artistAndAlbumNameLabel?.textColor = kAUXWaveTintColor } else { cell.titleLabel?.textColor = UIColor.whiteColor() cell.artistAndAlbumNameLabel?.textColor = UIColor.whiteColor() } return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let player = self.player { return player.playlist.count } else { return 0 } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { player?.playlist.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if let item = player?.playlist[sourceIndexPath.row] { player?.playlist.removeAtIndex(sourceIndexPath.row) player?.playlist.insert(item, atIndex: destinationIndexPath.row) } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { player?.setCurrentItemFromIndex(indexPath.row) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = UIColor.clearColor() } func player(playlistPlayer: PlaylistPlayer, didChangeCurrentPlaylistItem playlistItem: PlaylistItem?) { blurAlbumArtworkImageView?.image = playlistItem?.artwork tableView?.reloadData() } func service(service: DJService, didReceivePlaylistItem item: PlaylistItem, fromPeer peerID: MCPeerID) { tableView?.beginUpdates() if let player = player { player.playlist.append(item) if let index = find(player.playlist, item) { tableView?.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade) } } tableView?.endUpdates() } }
gpl-2.0
0d164ade8bd0ae139858db23b12775de
36.914692
183
0.672375
5.710207
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Tests/EurofurenceModelTests/Days/DayAssertion.swift
1
1023
import EurofurenceModel import TestUtilities class DayAssertion: Assertion { func assertDays(_ days: [Day], characterisedBy characteristics: [ConferenceDayCharacteristics]) { guard days.count == characteristics.count else { fail(message: "Differing amount of expected/actual days") return } let orderedCharacteristics = characteristics.sorted { (first, second) -> Bool in return first.date < second.date } for (idx, day) in days.enumerated() { let characteristic = orderedCharacteristics[idx] assertDay(day, characterisedBy: characteristic) } } func assertDay(_ day: Day?, characterisedBy characteristic: ConferenceDayCharacteristics) { guard let day = day else { fail(message: "Expected day: \(characteristic)") return } assert(day.date, isEqualTo: characteristic.date) assert(day.identifier, isEqualTo: characteristic.identifier) } }
mit
5d719ed1f58108b687a3a174607797b6
30.96875
101
0.645161
5.192893
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/News/Widgets/Events/Model/FilteredScheduleWidgetDataSourceTests.swift
1
2773
import Combine import EurofurenceApplication import EurofurenceModel import XCTest import XCTEurofurenceModel class FilteredScheduleWidgetDataSourceTests: XCTestCase { func testFiltersEventsToSpecification() throws { let (first, second, third) = (FakeEvent.random, FakeEvent.random, FakeEvent.random) let specification = FilterSpecificEventSpecification(satisactoryEvent: second) let repository = FakeScheduleRepository() repository.allEvents = [first, second, third] let dataSource = FilteredScheduleWidgetDataSource(repository: repository, specification: specification) var actual = [Event]() let cancellable = dataSource .events .sink { (events) in actual = events } let expected: [Event] = [second] let elementsEqual = expected.elementsEqual(actual, by: { $0.identifier == $1.identifier }) XCTAssertTrue(elementsEqual, "Data source should be using the output of the filtered schedule") cancellable.cancel() } func testCorrectlyRetainsScheduleForFutureUpdates_BUG() { let event = FakeEvent.random var dataSource: FilteredScheduleWidgetDataSource<FilterSpecificEventSpecification>! weak var weakSchedule: FakeEventsSchedule? autoreleasepool { let specification = FilterSpecificEventSpecification(satisactoryEvent: event) let repository = FakeScheduleRepository() dataSource = FilteredScheduleWidgetDataSource(repository: repository, specification: specification) weakSchedule = repository.lastProducedSchedule } weakSchedule?.simulateEventsChanged([event]) var actual = [Event]() let cancellable = dataSource .events .sink { (events) in actual = events } let expected: [Event] = [event] let elementsEqual = expected.elementsEqual(actual, by: { $0.identifier == $1.identifier }) XCTAssertTrue(elementsEqual, "Data source should retain schedule for future updates") cancellable.cancel() } private struct FilterSpecificEventSpecification: Specification { static func == (lhs: FilterSpecificEventSpecification, rhs: FilterSpecificEventSpecification) -> Bool { lhs.satisactoryEvent.identifier == rhs.satisactoryEvent.identifier } typealias Element = Event var satisactoryEvent: Event func isSatisfied(by element: Element) -> Bool { element.identifier == satisactoryEvent.identifier } } }
mit
671039f4c72febcfb22ad53941984cad
35.486842
111
0.643707
6.189732
false
true
false
false
sviatoslav/EndpointProcedure
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/DispatchQueue+ProcedureKit.swift
2
4270
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Foundation import Dispatch // MARK: - Queue public extension DispatchQueue { static var isMainDispatchQueue: Bool { return mainQueueScheduler.isOnScheduledQueue } var isMainDispatchQueue: Bool { return mainQueueScheduler.isScheduledQueue(self) } static var `default`: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.default) } static var initiated: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated) } static var interactive: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive) } static var utility: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.utility) } static var background: DispatchQueue { return DispatchQueue.global(qos: DispatchQoS.QoSClass.background) } static func concurrent(label: String, qos: DispatchQoS = .default, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil) -> DispatchQueue { return DispatchQueue(label: label, qos: qos, attributes: [.concurrent], autoreleaseFrequency: autoreleaseFrequency, target: target) } static func onMain<T>(execute work: () throws -> T) rethrows -> T { guard isMainDispatchQueue else { return try DispatchQueue.main.sync(execute: work) } return try work() } static var currentQoSClass: DispatchQoS.QoSClass { return DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? .unspecified } } internal extension QualityOfService { var qos: DispatchQoS { switch self { case .userInitiated: return DispatchQoS.userInitiated case .userInteractive: return DispatchQoS.userInteractive case .utility: return DispatchQoS.utility case .background: return DispatchQoS.background case .default: return DispatchQoS.default } } var qosClass: DispatchQoS.QoSClass { switch self { case .userInitiated: return .userInitiated case .userInteractive: return .userInteractive case .utility: return .utility case .background: return .background case .default: return .default } } } extension DispatchQoS.QoSClass: Comparable { public static func < (lhs: DispatchQoS.QoSClass, rhs: DispatchQoS.QoSClass) -> Bool { // swiftlint:disable:this cyclomatic_complexity switch lhs { case .unspecified: return rhs != .unspecified case .background: switch rhs { case .unspecified, lhs: return false default: return true } case .utility: switch rhs { case .default, .userInitiated, .userInteractive: return true default: return false } case .default: switch rhs { case .userInitiated, .userInteractive: return true default: return false } case .userInitiated: return rhs == .userInteractive case .userInteractive: return false } } } extension DispatchQoS: Comparable { public static func < (lhs: DispatchQoS, rhs: DispatchQoS) -> Bool { if lhs.qosClass < rhs.qosClass { return true } else if lhs.qosClass > rhs.qosClass { return false } else { // qosClass are equal return lhs.relativePriority < rhs.relativePriority } } } internal final class Scheduler { var key: DispatchSpecificKey<UInt8> var value: UInt8 = 1 init(queue: DispatchQueue) { key = DispatchSpecificKey() queue.setSpecific(key: key, value: value) } var isOnScheduledQueue: Bool { guard let retrieved = DispatchQueue.getSpecific(key: key) else { return false } return value == retrieved } func isScheduledQueue(_ queue: DispatchQueue) -> Bool { guard let retrieved = queue.getSpecific(key: key) else { return false } return value == retrieved } } internal let mainQueueScheduler = Scheduler(queue: DispatchQueue.main)
mit
9c0d1c42fed17c98342c86676ce41531
29.276596
188
0.652612
5.106459
false
false
false
false
baiyidjp/SwiftWB
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/SwiftExtension/String+Extensions.swift
1
963
// // String+Extensions.swift // SwiftWeibo // // Created by tztddong on 2016/12/7. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import Foundation extension String { /// 返回值可以是多个 swift中的元组 在OC中可以使用字典 func jp_hrefSource() -> (link: String,text: String)? { //1- 匹配方案 let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>" //2- 创建正则表达式 guard let regular = try? NSRegularExpression(pattern: pattern, options: []), let result = regular.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.characters.count)) else { return nil } //3- 获取结果 let link = (self as NSString).substring(with: result.rangeAt(1)) let text = (self as NSString).substring(with: result.rangeAt(2)) return(link,text) } }
mit
9959d6d688329bb541f7f0bf9de2bbdd
25.969697
128
0.55618
3.869565
false
false
false
false
jhliberty/GitLabKit
GitLabKit/Logger.swift
1
1644
// // Logger.swift // GitLabKit // // Copyright (c) 2015 orih. 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 class Logger{ class func log(message: AnyObject?, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) { var filename = file if let match = filename.rangeOfString("[^/]*$", options: .RegularExpressionSearch) { filename = filename.substringWithRange(match) } println("Log:\(filename):L\(line):\(function) \"\(message)\"") } }
mit
a60324c28caf2786a1bcf956ac96364c
42.289474
96
0.690998
4.431267
false
false
false
false
chengxxxxwang/buttonPopView
SwiftCircleButton/SwiftCircleButton/ViewController.swift
1
2447
// // ViewController.swift // SwiftCircleButton // // Created by chenxingwang on 2017/3/14. // Copyright © 2017年 chenxingwang. All rights reserved. // import UIKit let kScreenHeight = UIScreen.main.bounds.size.height let kScreenWidth = UIScreen.main.bounds.size.width class ViewController: UIViewController { @IBOutlet weak var showViewAction: circleButton! var popView = UIView() var isShow:Bool = false override func viewDidLoad() { super.viewDidLoad() showViewAction.layer.cornerRadius = 4 showViewAction.layer.masksToBounds = true // Do any additional setup after loading the view, typically from a nib. } @IBAction func showView(_ sender: Any) { if self.isShow == false{ if self.popView.frame.size.width != 0 { self.popView.removeFromSuperview() } setUpPopView() showPopView() self.isShow = !isShow }else{ dismissPopView() self.isShow = !isShow } } fileprivate func setUpPopView(){ self.popView = UIView(frame:CGRect(x:60,y:300,width:kScreenWidth - 120,height:kScreenWidth/20)) self.popView.backgroundColor = UIColor.cyan self.popView.layer.cornerRadius = 5 self.popView.layer.masksToBounds = true self.view.addSubview(self.popView) } fileprivate func showPopView(){ UIView.animate(withDuration: 0.25, delay: 0.05, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in self.popView.frame = CGRect.init(origin: CGPoint.init(x: 60, y: 100), size: CGSize.init(width: kScreenWidth - 120, height: kScreenWidth/3*2)) }) { (Bool) in } } fileprivate func dismissPopView(){ print("dismiss") UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in self.popView.frame = CGRect.init(origin: CGPoint.init(x: 60, y: 300), size: CGSize.init(width: kScreenWidth - 120, height: kScreenWidth/20)) }) { (Bool) in self.popView.removeFromSuperview() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
834fb774ea295a88b06c0c9b546abba3
30.74026
153
0.610884
4.628788
false
false
false
false
jakerockland/Swisp
Sources/SwispFramework/Environment/Library.swift
1
4755
// // Library.swift // SwispFramework // // MIT License // // Copyright (c) 2018 Jake Rockland (http://jakerockland.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 /** Provides the following basic library operations as static functions: - `abs` - `append` // // "apply": apply, // [TODO](https://www.drivenbycode.com/the-missing-apply-function-in-swift/) // "begin": { $0[-1] }, - `car` - `cdr` // "cons": { [$0] + $1 }, // "eq?": { $0 === $1 }, // "equal?": { $0 == $1 }, // "length": { $0.count }, // "list": { List($0) }, // "list?": { $0 is List }, // // "map": map, // [TODO](https://www.weheartswift.com/higher-order-functions-map-filter-reduce-and-more/) // "max": max, // "min": min, - `not` // "null?": { $0 == nil }, // "number?": { $0 is Number }, // "procedure?": { String(type(of: $0)).containsString("->") }, // "round": round, // "symbol?": { $0 is Symbol } */ internal struct Library { /** Static function for `abs` operation */ static func abs(_ args: [Any]) throws -> Any? { guard args.count == 1 else { throw SwispError.SyntaxError(message: "invalid procedure input") } switch (args[safe: 0]) { case let (val as Int): return Swift.abs(val) case let (val as Double): return Swift.abs(val) default: throw SwispError.SyntaxError(message: "invalid procedure input") } } /** Static function for `append` operation */ static func append(_ args: [Any]) throws -> Any? { guard args.count == 2 else { throw SwispError.SyntaxError(message: "invalid procedure input") } guard let lis1 = args[safe: 0] as? [Any], let lis2 = args[safe: 1] as? [Any] else { throw SwispError.SyntaxError(message: "invalid procedure input") } return lis1 + lis2 } /** Static function for `car` operation */ static func car(_ args: [Any]) throws -> Any? { guard args.count == 1 else { throw SwispError.SyntaxError(message: "invalid procedure input") } guard let lis = args[safe: 0] as? [Any] else { throw SwispError.SyntaxError(message: "invalid procedure input") } return lis.first } /** Static function for `cdr` operation */ static func cdr(_ args: [Any]) throws -> Any? { guard args.count == 1 else { throw SwispError.SyntaxError(message: "invalid procedure input") } guard let lis = args[safe: 0] as? [Any] else { throw SwispError.SyntaxError(message: "invalid procedure input") } return Array(lis.dropFirst()) } /** Static function for `not` operation */ static func not(_ args: [Any]) throws -> Any? { guard args.count == 1 else { throw SwispError.SyntaxError(message: "invalid procedure input") } switch (args[safe: 0]) { case let (val as Bool): return !val case let (val as NSNumber): return !Bool(truncating: val) case let (val as String): if let bool = Bool(val) { return !bool } else { throw SwispError.SyntaxError(message: "invalid procedure input") } default: throw SwispError.SyntaxError(message: "invalid procedure input") } } }
mit
3ca27da70072d920122903c4da2c2bc4
34.75188
124
0.565089
4.13119
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Graphics/CNBitmapData.swift
1
2941
/* * @file CNBitmapData.swift * @brief Define CNBitmapData class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ import Foundation public class CNBitmapData { private var mWidth: Int private var mHeight: Int private var mData: Array<Array<CNColor>> public var width: Int { get { return mWidth }} public var height: Int { get { return mHeight }} public init(width w: Int, height h: Int) { mWidth = w mHeight = h mData = [] for _ in 0..<h { let row = Array(repeating: CNColor.clear, count: w) mData.append(row) } } public init(colorData cdata: Array<Array<CNColor>>) { mHeight = cdata.count mWidth = cdata[0].count mData = cdata } public func resize(width wid: Int, height hgt: Int) { /* If the size is not changed, do nothing */ if mWidth == wid && mHeight == hgt { return } /* Allocate new empty data */ var newdata: Array<Array<CNColor>> = [] for _ in 0..<wid { let row = Array(repeating: CNColor.clear, count: hgt) newdata.append(row) } /* copy contents */ let mwid = min(wid, mWidth) let mhgt = min(hgt, mHeight) for y in 0..<mhgt { for x in 0..<mwid { newdata[y][x] = mData[y][x] } } /* Replace */ mWidth = wid mHeight = hgt mData = newdata } public func set(x posx: Int, y posy: Int, color col: CNColor) { if 0<=posx && posx<mWidth { if 0<=posy && posy<mHeight { mData[posy][posx] = col } } } public func set(x posx: Int, y posy: Int, bitmap bm: CNBitmapData){ let height = bm.mData.count for y in 0..<height { let line = bm.mData[y] let width = line.count for x in 0..<width { set(x: posx + x, y: posy + y, color: line[x]) } } } public func clean() { for y in 0..<mHeight { for x in 0..<mWidth { mData[y][x] = CNColor.clear } } } public func get(x posx: Int, y posy: Int) -> CNColor? { if 0<=posx && posx<mWidth { if 0<=posy && posy<mHeight { return mData[posy][posx] } } return nil } public func toText() -> CNText { let result = CNTextSection() result.header = "BitmapContents: {" ; result.footer = "}" result.add(text: CNTextLine(string: "width: \(width)")) result.add(text: CNTextLine(string: "height: \(height)")) let data = CNTextSection() data.header = "data: {" ; data.footer = "}" for line in mData { data.add(text: lineToText(line: line)) } result.add(text: data) return result } private func lineToText(line ln: Array<CNColor>) -> CNTextLine { var result = "" for col in ln { if col.alphaComponent == 0.0 { result += "-" } else { switch col.escapeCode() { case 0: result += "k" case 1: result += "r" case 2: result += "g" case 3: result += "y" case 4: result += "b" case 5: result += "m" case 6: result += "c" case 7: result += "w" default: result += "?" } } } return CNTextLine(string: result + "\n") } }
lgpl-2.1
01c8848141bdd7759e91bedfb706f124
20.947761
68
0.590955
2.748598
false
false
false
false
svanimpe/around-the-table
Tests/AroundTheTableTests/Persistence/GameRepositoryTests.swift
1
4898
import BSON import XCTest @testable import AroundTheTable /** Run these tests against the **aroundthetable-test** database. Import it from **Tests/AroundTheTable/Fixtures/dump**. */ class GameRepositoryTests: XCTestCase { static var allTests: [(String, (GameRepositoryTests) -> () throws -> Void)] { return [ ("testQueryExact", testQueryExact), ("testQueryNotExact", testQueryNotExact), ("testQueryNoResults", testQueryNoResults), ("testGamesCached", testGamesCached), ("testGamesNew", testGamesNew), ("testGameCached", testGameCached), ("testGameNew", testGameNew) ] } let persistence = try! Persistence() func testQueryExact() { let resultsReceived = expectation(description: "results received") persistence.games(forQuery: "Small World", exactMatchesOnly: true) { ids in XCTAssert(ids == [40692]) resultsReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } } func testQueryNotExact() { let resultsReceived = expectation(description: "results received") persistence.games(forQuery: "Small World", exactMatchesOnly: false) { ids in XCTAssert(ids.count > 1) resultsReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } } func testQueryNoResults() { let resultsReceived = expectation(description: "results received") persistence.games(forQuery: "definitely_no_results", exactMatchesOnly: false) { ids in XCTAssert(ids.isEmpty) resultsReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } } func testGamesCached() throws { let ids = [1323, 27092, 192457] // The cache contains only these three games. XCTAssert(try persistence.games.count() == 3) XCTAssert(try persistence.games.count(["_id": ["$in": ids]]) == 3) // Now try to fetch them. let resultsReceived = expectation(description: "results received") try persistence.games(forIDs: ids) { games in XCTAssert(games.count == 3) resultsReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } // There should be no additional games in the cache as a result of this operation. XCTAssert(try persistence.games.count() == 3) } func testGamesNew() throws { let id = 40692 // The game shouldn't be in the cache. XCTAssertNil(try persistence.games.findOne(["_id": id])) // Now fetch it. let resultsReceived = expectation(description: "results received") try persistence.games(forIDs: [id]) { games in XCTAssert(games.count == 1) resultsReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } // The game should now be in the cache. XCTAssertNotNil(try persistence.games.findOne(["_id": id])) // Clean-up try persistence.games.remove(["_id": id]) } func testGameCached() throws { let id = 192457 // The game should be in the cache. XCTAssertNotNil(try persistence.games.findOne(["_id": id])) XCTAssert(try persistence.games.count() == 3) // Now fetch it. let resultReceived = expectation(description: "result received") try persistence.game(forID: id) { game in XCTAssertNotNil(game) resultReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } // There should be no additional games in the cache as a result of this operation. XCTAssert(try persistence.games.count() == 3) } func testGameNew() throws { let id = 40692 // The game shouldn't be in the cache. XCTAssertNil(try persistence.games.findOne(["_id": id])) // Now fetch it. let resultReceived = expectation(description: "result received") try persistence.game(forID: id) { game in XCTAssertNotNil(game) resultReceived.fulfill() } waitForExpectations(timeout: 2) { error in XCTAssertNil(error) } // The game should now be in the cache. XCTAssertNotNil(try persistence.games.findOne(["_id": id])) // Clean-up try persistence.games.remove(["_id": id]) } }
bsd-2-clause
5aa15d8808d8648654c0ff15b48391b9
32.77931
90
0.576358
4.917671
false
true
false
false
fgulan/letter-ml
project/LetterML/Frameworks/framework/Source/Operations/AverageLuminanceExtractor.swift
3
2293
#if os(Linux) #if GLES import COpenGLES.gles2 #else import COpenGL #endif #else #if GLES import OpenGLES #else import OpenGL.GL3 #endif #endif public class AverageLuminanceExtractor: BasicOperation { public var extractedLuminanceCallback:((Float) -> ())? public init() { super.init(vertexShader:AverageColorVertexShader, fragmentShader:AverageLuminanceFragmentShader) } override func renderFrame() { // Reduce to luminance before passing into the downsampling // TODO: Combine this with the first stage of the downsampling by doing reduction here let luminancePassShader = crashOnShaderCompileFailure("AverageLuminance"){try sharedImageProcessingContext.programForVertexShader(defaultVertexShaderForInputs(1), fragmentShader:LuminanceFragmentShader)} let luminancePassFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation:inputFramebuffers[0]!.orientation, size:inputFramebuffers[0]!.size) luminancePassFramebuffer.activateFramebufferForRendering() renderQuadWithShader(luminancePassShader, vertexBufferObject:sharedImageProcessingContext.standardImageVBO, inputTextures:[inputFramebuffers[0]!.texturePropertiesForTargetOrientation(luminancePassFramebuffer.orientation)]) averageColorBySequentialReduction(inputFramebuffer:luminancePassFramebuffer, shader:shader, extractAverageOperation:extractAverageLuminanceFromFramebuffer) releaseIncomingFramebuffers() } func extractAverageLuminanceFromFramebuffer(_ framebuffer:Framebuffer) { var data = [UInt8](repeating:0, count:Int(framebuffer.size.width * framebuffer.size.height * 4)) glReadPixels(0, 0, framebuffer.size.width, framebuffer.size.height, GLenum(GL_BGRA), GLenum(GL_UNSIGNED_BYTE), &data) renderFramebuffer = framebuffer framebuffer.resetRetainCount() let totalNumberOfPixels = Int(framebuffer.size.width * framebuffer.size.height) var redTotal = 0 for currentPixel in 0..<totalNumberOfPixels { redTotal += Int(data[currentPixel * 4]) } extractedLuminanceCallback?(Float(redTotal) / Float(totalNumberOfPixels) / 255.0) } }
mit
b0f496da93d674f5528f48c3a32848d6
45.795918
230
0.748801
5.211364
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/check-if-a-string-contains-all-binary-codes-of-size-k.swift
2
579
/** * https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ * * */ // Date: Fri Mar 12 11:25:30 PST 2021 class Solution { func hasAllCodes(_ s: String, _ k: Int) -> Bool { var list: Set<String> = [] var cand: [Character] = [] for c in s { cand.append(c) if cand.count == k { list.insert(String(cand)) cand.removeFirst() } } var expected = 1 for _ in 0 ..< k { expected *= 2 } return list.count == expected } }
mit
578f00d964513675872c3d8a7f0bef3c
25.363636
87
0.488774
3.552147
false
false
false
false
ozpopolam/DoctorBeaver
DoctorBeaver/TaskMenuViewController.swift
1
37656
// // TaskMenuViewController.swift // DoctorBeaver // // Created by Anastasia Stepanova-Kolupakhina on 18.02.16. // Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved. // import UIKit import CoreData protocol TaskMenuViewControllerDelegate: class { func taskMenuViewController(viewController: TaskMenuViewController, didAddTask task: Task) func taskMenuViewController(viewController: TaskMenuViewController, didDeleteTask task: Task) func taskMenuViewController(viewController: TaskMenuViewController, didSlightlyEditScheduleOfTask task: Task) func taskMenuViewController(viewController: TaskMenuViewController, didFullyEditScheduleOfTask task: Task) } enum TaskMenuMode { case Add case Edit case Show } class TaskMenuViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var decoratedNavigationBar: DecoratedNavigationBarView! weak var delegate: TaskMenuViewControllerDelegate? var petsRepository: PetsRepository! var task: Task! // task to show or edit var taskWithInitialSettings: Task? // needed to store initial (first) values var taskWithPreviousSettings: Task? // needed to store second, third... version of values var menu = TaskMenuConfiguration() var menuMode: TaskMenuMode! var initialMenuMode: TaskMenuMode! // types of cells in table let headerId = "headerView" let menuTextFieldCellId = "menuTextFieldCell" let menuTitleValueCellId = "menuTitleValueCell" let menuTitleSegmentCellId = "menuTitleSegmentCell" let menuDataPickerCellId = "menuDataPickerCell" let menuDatePickerCellId = "menuDatePickerCell" let menuComplexPickerCellId = "menuComplexPickerCell" // heights of cells let headerHeight: CGFloat = 22.0 let regularCellHeight: CGFloat = 44.0 let pickerCellHeight: CGFloat = 216.0 let complexCellHeight: CGFloat = 260.0 var keyboardHeight: CGFloat! let minutesDoseMenuSegueId = "minutesDoseMenuSegue" // segue to sub-menu var unwindSegueId: String? // id of a possible unwind segue let animationDuration: NSTimeInterval = 0.5 // to animate change of button's icon var taskWasEdited = false // task was edited var scheduleWasChanged = false // time-related parts of settings were changed override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidLoad() { super.viewDidLoad() decoratedNavigationBar.titleLabel.font = VisualConfiguration.navigationBarFont decoratedNavigationBar.titleLabel.text = task.typeItem.name.uppercaseString // button "Delete" (will be hiden or shown depending on menuMode) decoratedNavigationBar.setButtonImage("trash", forButton: .CenterRight, withTintColor: UIColor.fogColor(), withAnimationDuration: animationDuration) decoratedNavigationBar.centerRightButton.addTarget(self, action: #selector(trash(_:)), forControlEvents: .TouchUpInside) let tableSectionHeaderNib = UINib(nibName: "TableSectionHeaderView", bundle: nil) tableView.registerNib(tableSectionHeaderNib, forHeaderFooterViewReuseIdentifier: headerId) if menuMode == .Add { // controller has been loaded in add-mode -> need to save initial values saveInitialSettings() savePreviousSettings() } initialMenuMode = menuMode configureForMenuMode() tableView.tableFooterView = UIView(frame: .zero) // hide footer reloadTaskMenuTable() } // configuring user's possibility of interaction, selection style of cells, showing or hiding necessary buttons func configureForMenuMode(withAnimationDuration animationDuration: NSTimeInterval = 0) { if menuMode == .Add || menuMode == .Edit { // adding or editing task // button "Cancel" decoratedNavigationBar.setButtonImage("cancel", forButton: .Left, withTintColor: UIColor.fogColor(), withAnimationDuration: animationDuration) decoratedNavigationBar.leftButton.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside) decoratedNavigationBar.leftButton.addTarget(self, action: #selector(cancel(_:)), forControlEvents: .TouchUpInside) decoratedNavigationBar.hideButton(.CenterRight) // hide Delete-button // button "Done" decoratedNavigationBar.setButtonImage("done", forButton: .Right, withTintColor: UIColor.fogColor(), withAnimationDuration: animationDuration) decoratedNavigationBar.rightButton.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside) decoratedNavigationBar.rightButton.addTarget(self, action: #selector(done(_:)), forControlEvents: .TouchUpInside) } else { // browsing settings of task or deleting it // button "Back" decoratedNavigationBar.setButtonImage("back", forButton: .Left, withTintColor: UIColor.fogColor(), withAnimationDuration: animationDuration) decoratedNavigationBar.leftButton.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside) decoratedNavigationBar.leftButton.addTarget(self, action: #selector(back(_:)), forControlEvents: .TouchUpInside) decoratedNavigationBar.showButton(.CenterRight, withAnimationDuration: animationDuration) // show Delete-button // button "Edit" decoratedNavigationBar.setButtonImage("edit", forButton: .Right, withTintColor: UIColor.fogColor(), withAnimationDuration: animationDuration) decoratedNavigationBar.rightButton.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside) decoratedNavigationBar.rightButton.addTarget(self, action: #selector(edit(_:)), forControlEvents: .TouchUpInside) } configureUserInteractionForMenuMode() configureCellsSelectionStyleForMenuMode() } // fully reload table with data of task func reloadTaskMenuTable() { menu.configure(withTask: task) tableView.reloadData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = true // start observing notifications from keyboard to update height of table let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if keyboardHeight == nil { // update height of keyboard if let userInfo = notification.userInfo { if let keyboardSizeNSValue = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue { keyboardHeight = keyboardSizeNSValue.CGRectValue().height } } } // move lower edge of table to show keyboard let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardHeight, 0.0) tableView.contentInset = contentInsets tableView.scrollIndicatorInsets = contentInsets } func keyboardWillHide(notification: NSNotification) { // move lower edge of table back tableView.contentInset = UIEdgeInsetsZero tableView.scrollIndicatorInsets = UIEdgeInsetsZero } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // stop observing notifications from keyboard let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } // MARK: Actions for buttons // Back-button func back(sender: UIButton) { deleteTemporarySettingsStorage() if initialMenuMode == .Add { delegate?.taskMenuViewController(self, didAddTask: task) } else if taskWasEdited { // task was edited if scheduleWasChanged { // time frame of task changed task.countEndDate() delegate?.taskMenuViewController(self, didFullyEditScheduleOfTask: task) } else { delegate?.taskMenuViewController(self, didSlightlyEditScheduleOfTask: task) } } popTaskMenuViewController() } func deleteTemporarySettingsStorage() { // if task for storing initial setting was created, need to delete it if let taskWithInitialSettings = taskWithInitialSettings { taskWasEdited = taskIsDifferent(fromTask: taskWithInitialSettings) // task was edited scheduleWasChanged = taskScheduleIsDifferent(fromTask: taskWithInitialSettings) // schedule was edited in that or some previous iteration petsRepository.deleteObject(taskWithInitialSettings) } // if task for storing version of setting was created, need to delete it if let taskWithPreviousSettings = taskWithPreviousSettings { petsRepository.deleteObject(taskWithPreviousSettings) } petsRepository.saveOrRollback() } func popTaskMenuViewController() { if let unwindSegueId = unwindSegueId { // we have id for unwind segue -> use it performSegueWithIdentifier(unwindSegueId, sender: self) } else { navigationController?.popViewControllerAnimated(true) // just close VC } } // Delete-button func trash(sender: UIButton) { let deleteController = UIAlertController(title: "Удалить задание?", message: nil, preferredStyle: .ActionSheet) let confirmAction = UIAlertAction(title: "Да, давайте удалим", style: .Destructive) { (action) -> Void in self.delegate?.taskMenuViewController(self, didDeleteTask: self.task) self.navigationController?.popViewControllerAnimated(true) } let cancelAction = UIAlertAction(title: "Нет, я передумал", style: .Cancel) { (action) -> Void in } deleteController.addAction(confirmAction) deleteController.addAction(cancelAction) presentViewController(deleteController, animated: true, completion: nil) } // Edit-button func edit(sender: UIButton) { menuMode = .Edit saveInitialSettings() savePreviousSettings() configureForMenuMode(withAnimationDuration: animationDuration) } // save initial settings of task func saveInitialSettings() { if taskWithInitialSettings == nil { taskWithInitialSettings = petsRepository.insertTask() if let taskWithInitialSettings = taskWithInitialSettings { taskWithInitialSettings.copySettings(fromTask: task, withPet: true) } } } // save another version of settings func savePreviousSettings() { if taskWithPreviousSettings == nil { taskWithPreviousSettings = petsRepository.insertTask() } if let taskWithPreviousSettings = taskWithPreviousSettings { taskWithPreviousSettings.copySettings(fromTask: task, withPet: true) } } // Cancel-button func cancel(sender: UIButton) { if menuMode == .Add { // user press cancel-button immediately -> user doesn't want to add new task deleteTemporarySettingsStorage() // delete newly created task petsRepository.deleteObject(task) petsRepository.saveOrRollback() popTaskMenuViewController() return } else { menuMode = .Show // stop editing task deactivateAllActiveTextFields() // close all text fields if taskIsDifferent(fromTask: taskWithPreviousSettings) { // settings were changed in that iteration - need to restore them loadPreviousSettings() reloadTaskMenuTable() } else { closePickerCellsForShowState() // close all open picker cells } configureForMenuMode(withAnimationDuration: animationDuration) } } // check whether some settings of task did change func taskIsDifferent(fromTask taskWithOldSettings: Task?) -> Bool { // compare new settings to the other version if let taskWithOldSettings = taskWithOldSettings { return !task.allSettingsAreEqual(toTask: taskWithOldSettings) } else { return false } } // check whether some schedule settings of task did change func taskScheduleIsDifferent(fromTask taskWithOldSettings: Task?) -> Bool { // compare new settings to the other version if let taskWithOldSettings = taskWithOldSettings { return !task.scheduleSettingsAreEqual(toTask: taskWithOldSettings) } else { return false } } // restore previous settings of task func loadPreviousSettings() { if let taskWithPreviousSettings = taskWithPreviousSettings { task.copySettings(fromTask: taskWithPreviousSettings) } } // Done-button func done(sender: UIButton) { menuMode = .Show closePickerCellsForShowState() deactivateAllActiveTextFields() configureForMenuMode(withAnimationDuration: animationDuration) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == minutesDoseMenuSegueId { if let destinationViewController = segue.destinationViewController as? MinutesDoseMenuViewController { if let cell = sender as? MenuTitleValueCell { destinationViewController.task = task //destinationViewController.delegate = self destinationViewController.menuType = menu.getMinutesDoseMenuType(ofTag: cell.tag) destinationViewController.menuMode = menuMode == .Show ? .Show : .Edit if menuMode == .Show { // need to make snapshot of task' settings explicitly as TaskMenuViewController does it only in Edit-mode saveInitialSettings() savePreviousSettings() } } } } } } // MARK: UITableViewDataSource extension TaskMenuViewController: UITableViewDataSource { // user's possibility to select segmented control in a cell func configureUserInteractionForMenuMode() { for s in 0..<menu.cellsTagTypeState.count { for r in 0..<menu.cellsTagTypeState[s].count { let cellTagTypeState = menu.cellsTagTypeState[s][r] if cellTagTypeState.type == .TitleSegmentCell && cellTagTypeState.state != .Hidden { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: r, inSection: s)) as? MenuTitleSegmentCell { cell.hideShowSgCtrl.userInteractionEnabled = menuMode == .Add || menuMode == .Edit } } } } } // selection style for all cells func configureCellsSelectionStyleForMenuMode() { for s in 0..<menu.cellsTagTypeState.count { for r in 0..<menu.cellsTagTypeState[s].count { let indexPath = NSIndexPath(forRow: r, inSection: s) if let cell = tableView.cellForRowAtIndexPath(indexPath) { configureCellSelectionStyleForMenuMode(cell, atIndexPath: indexPath) } } } } // selection style of a cell depending on menuMode func configureCellSelectionStyleForMenuMode(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let cellType = menu.cellsTagTypeState[indexPath.section][indexPath.row].type let cellState = menu.cellsTagTypeState[indexPath.section][indexPath.row].state if (menuMode != .Show && cellType != .ComplexPickerCell) || cellState == .Accessory { cell.selectionStyle = VisualConfiguration.graySelection } else { cell.selectionStyle = .None } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return menu.sectionTitles.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menu.cellsTagTypeState[section].count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellType = menu.cellsTagTypeState[indexPath.section][indexPath.row].type var generalCell: UITableViewCell! switch cellType { case .TextFieldCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuTextFieldCellId) as? MenuTextFieldCell { configureTextFieldCell(cell, forRowAtIndexPath: indexPath) generalCell = cell } case .TitleValueCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuTitleValueCellId) as? MenuTitleValueCell { configureTitleValueCell(cell, forRowAtIndexPath: indexPath) generalCell = cell } case .TitleSegmentCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuTitleSegmentCellId) as? MenuTitleSegmentCell { configureTitleSegmentCell(cell, forRowAtIndexPath: indexPath) generalCell = cell } case .DataPickerCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuDataPickerCellId) as? MenuDataPickerCell { configureDataPickerCell(cell, forRowAtIndexPath: indexPath) generalCell = cell } case .TimePickerCell, .DateTimePickerCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuDatePickerCellId) as? MenuDatePickerCell { configureDatePickerCell(cell, ofType: cellType, forRowAtIndexPath: indexPath) generalCell = cell } case .ComplexPickerCell: if let cell = tableView.dequeueReusableCellWithIdentifier(menuComplexPickerCellId) as? MenuComplexPickerCell { configureComplexPickerCell(cell, forRowAtIndexPath: indexPath) generalCell = cell } default: return UITableViewCell() } configureCellSelectionStyleForMenuMode(generalCell, atIndexPath: indexPath) return generalCell } // MARK: Configuration of cells of different types func configureTextFieldCell(cell: MenuTextFieldCell, forRowAtIndexPath indexPath: NSIndexPath) { let tag = menu.tagForIndexPath(indexPath) let textField = cell.textField textField.tag = tag textField.delegate = self textField.autocapitalizationType = .Words textField.keyboardAppearance = .Dark textField.keyboardType = .Default textField.returnKeyType = .Done textField.placeholder = menu.textFieldPlaceholders[tag] textField.text = menu.titleValueValues[cell.textField.tag] textField.textColorResponder = VisualConfiguration.blackColor textField.textColorNonResponder = VisualConfiguration.lightGrayColor let cellState = menu.cellsTagTypeState[indexPath.section][indexPath.row].state cellState == TaskMenuCellState.Visible ? textField.resignFirstResponder() : textField.becomeFirstResponder() } func configureTitleValueCell(cell: MenuTitleValueCell, forRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section let row = indexPath.row cell.tag = menu.tagForIndexPath(indexPath) cell.titleLabel.text = menu.titleValueTitles[cell.tag] let state = menu.cellsTagTypeState[section][row].state if state == .Accessory { cell.accessoryType = .DisclosureIndicator cell.valueLabel.text = "" } else { cell.accessoryType = .None cell.valueLabel.text = menu.titleValueValues[cell.tag] } // text color of valueLabel depends on state of underlying cell, which is used to set text of valueLabel of this cell if menu.cellsTagTypeState[section][row + 1].state == TaskMenuCellState.Hidden { cell.valueLabel.textColor = VisualConfiguration.textGrayColor } else { cell.valueLabel.textColor = VisualConfiguration.textOrangeColor } } func configureTitleSegmentCell(cell: MenuTitleSegmentCell, forRowAtIndexPath indexPath: NSIndexPath) { // cell with segmented control with two options: 1 - no value, 2 - some values let tag = menu.tagForIndexPath(indexPath) cell.hideShowSgCtrl.tag = tag cell.delegate = self cell.hideShowSgCtrl.userInteractionEnabled = menuMode == .Add || menuMode == .Edit cell.titleLabel.text = menu.titleValueTitles[tag] var frequencySegmentTitles = menu.frequencySegmentTitles() let segmentTitle = menu.frequencySegmentTitle() if segmentTitle.isVoid { // no value option cell.configure(withValues: frequencySegmentTitles, andSelectedSegment: 0) } else { // option with some values frequencySegmentTitles[1] = segmentTitle cell.configure(withValues: frequencySegmentTitles, andSelectedSegment: 1) } } func configureDataPickerCell(cell: MenuDataPickerCell, forRowAtIndexPath indexPath: NSIndexPath) { // this cell always lay below MenuTitleValueCell and is used to set its value let section = indexPath.section let row = indexPath.row // need to configure it only if it's visible if menu.cellsTagTypeState[section][row].state != .Hidden { let tag = menu.tagForIndexPath(indexPath) cell.dataPickerView.tag = tag if let options = menu.pickerOptions[tag] { // all possible values for picker cell.dataPickerView.font = VisualConfiguration.pickerFont cell.dataPickerView.textColor = VisualConfiguration.textBlackColor let initialValues = menu.initialDataPickerValues(withTag: tag) // initial values to select on picker cell.dataPickerView.configure(withOptions: options, andInitialValues: initialValues, andDelegate: self) } } } func configureDatePickerCell(cell: MenuDatePickerCell, ofType cellType: TaskMenuCellType, forRowAtIndexPath indexPath: NSIndexPath) { let section = indexPath.section let row = indexPath.row if menu.cellsTagTypeState[section][row].state != .Hidden { let tag = menu.tagForIndexPath(indexPath) cell.datePicker.tag = tag switch cellType { case .TimePickerCell: let minutes = menu.initialDateTimePickerTime(withTag: tag) cell.datePicker.configure(withDelegate: self, selectedMinutes: minutes) case .DateTimePickerCell: let dates = menu.initialDateTimePickerDate(withTag: tag) // initial and minimum possible dates cell.datePicker.configure(withDelegate: self, selectedDate: dates.initialDate, andMinimumDate: dates.minimumDate) default: break } } } func configureComplexPickerCell(cell: MenuComplexPickerCell, forRowAtIndexPath indexPath: NSIndexPath) { // cell with segmentd control, which switch between 3 pickers: 2 data-picker and 1 date-picker // choice of picker depends on endType: picker for end-times, end-days and end-date let section = indexPath.section let row = indexPath.row if menu.cellsTagTypeState[section][row].state != .Hidden { var tags = [Int]() // tags for cell and three pickers tags.append(menu.tagForIndexPath(indexPath)) // cell's tag // tags for pickers tags.append(menu.tagForEndType(Task.EndType.EndDays)) tags.append(menu.tagForEndType(Task.EndType.EndTimes)) tags.append(menu.tagForEndType(Task.EndType.EndDate)) cell.configure(withTags: tags, andDelegate: self) let endSegmentTitles = menu.endSegmentTitles() cell.configure(withSegmentValues: endSegmentTitles, andSelectedSegment: task.endType.rawValue) let pickerTag = menu.tagForEndType(task.endType) if task.endType == .EndDate { // configure date-picker let dates = menu.initialDateTimePickerDate(withTag: pickerTag) cell.configure(withDelegate: self, selectedDate: dates.initialDate, andMinimumDate: dates.minimumDate) } else { // configure data-picker let endOptions = menu.endOptions() let initialValues = menu.initialDataPickerValues(withTag: pickerTag) cell.configure(withTitles: [endOptions], andWithInitialValues: initialValues, andDelegate: self) } } } } // MARK: UITableViewDelegate extension TaskMenuViewController: UITableViewDelegate { func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if menu.sectionTitles[section].isVoid { // don't need header for section without title return nil } else { if let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(headerId) as? TableSectionHeaderView { header.titleLabel.text = menu.sectionTitles[section].lowercaseString header.view.backgroundColor = VisualConfiguration.lightOrangeColor return header } else { return nil } } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if menu.sectionTitles[section].isVoid { // height of header for section without title is ~ 0 return CGFloat.min } else { return headerHeight } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height: CGFloat = CGFloat.min if menu.cellsTagTypeState[indexPath.section][indexPath.row].state == TaskMenuCellState.Hidden { // if cell is hidden, it's height = ~ 0 return height } else { // in other cases cell's height depends on its type let cellType = menu.cellsTagTypeState[indexPath.section][indexPath.row].type switch cellType { case .TextFieldCell, .TitleValueCell, .TitleSegmentCell: height = regularCellHeight case .DataPickerCell, .TimePickerCell, .DateTimePickerCell: height = pickerCellHeight case .ComplexPickerCell: height = complexCellHeight default: break } return height } } func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if let cell = tableView.cellForRowAtIndexPath(indexPath) { return cell.selectionStyle == VisualConfiguration.graySelection ? indexPath : nil } else { return nil } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // TextFieldCell, TitleValueCell, TitleSegmentCell or Accessory-cell was selected // tapping on the first three leads to opening/closing underlying cells with picker view for value selectio let section = indexPath.section let row = indexPath.row let cellType = menu.cellsTagTypeState[section][row].type let cellState = menu.cellsTagTypeState[section][row].state if cellState == .Accessory { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MenuTitleValueCell { // prepare to edit minutes or doses of task performSegueWithIdentifier(minutesDoseMenuSegueId, sender: cell) } } deactivateAllActiveTextFields() var rowsToReload: [NSIndexPath] = [] // after opening new picker cell or starting typing in text field, the old picker cell must be closed var indexPathToScroll = indexPath switch cellType { case .TextFieldCell: if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MenuTextFieldCell { activateVisibleTextField(cell.textField) rowsToReload = closeAllOpenPickerCells() indexPathToScroll = indexPath } // after tapping on these cell, cell with picker must be revealed or hidden case .TitleSegmentCell, .TitleValueCell: let pickerCellRow = row + 1 // picker lies under tapped cell let pickerCellState = menu.cellsTagTypeState[section][pickerCellRow].state let pickerCellIndPth = NSIndexPath(forRow: pickerCellRow, inSection: section) if cellType == .TitleSegmentCell { if menu.frequencySegmentFirstOption() { // segmented control with first option selected rowsToReload = closeAllOpenPickerCells() } else { // segmented control with second option selected if pickerCellState == .Hidden { // underlying picker was hidden and about to be revealed rowsToReload = closeAllOpenPickerCells() } menu.toggleCellTagTypeState(atIndexPath: pickerCellIndPth) rowsToReload.append(pickerCellIndPth) } } else if cellType == .TitleValueCell { if pickerCellState == .Hidden { rowsToReload = closeAllOpenPickerCells() } if cellState != .Accessory { if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MenuTitleValueCell { if pickerCellState == .Hidden { // if cell with picker is about to be revealed, text color of selected cell will become orange (active) cell.valueLabel.textColor = VisualConfiguration.textOrangeColor } else { // if cell with picker is about to be hidden, text color of selected cell will become grey (inactive) cell.valueLabel.textColor = VisualConfiguration.textGrayColor } } menu.toggleCellTagTypeState(atIndexPath: pickerCellIndPth) // change state of picker cell from hidden to open or vice versa rowsToReload.append(pickerCellIndPth) indexPathToScroll = pickerCellIndPth // cell to be focused on } } default: break } // reload cells, which state or appearance were modified tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(rowsToReload, withRowAnimation: .Automatic) tableView.endUpdates() tableView.deselectRowAtIndexPath(indexPath, animated: false) // focus on selected cell tableView.scrollToRowAtIndexPath(indexPathToScroll, atScrollPosition: .Middle, animated: true) } // change state of open picker cells and return its index paths func closeAllOpenPickerCells() -> [NSIndexPath] { var rowsToReload: [NSIndexPath] = [] for s in 0..<menu.cellsTagTypeState.count { for r in 0..<menu.cellsTagTypeState[s].count { let cell = menu.cellsTagTypeState[s][r] if (cell.type == .DataPickerCell || cell.type == .TimePickerCell || cell.type == .DateTimePickerCell || cell.type == .ComplexPickerCell) && cell.state != .Hidden { // if cell contains picker and is not hidden menu.cellsTagTypeState[s][r].state = .Hidden // change state to hidden rowsToReload.append(NSIndexPath(forRow: r, inSection: s)) if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: r - 1, inSection: s)) as? MenuTitleValueCell { // deactive text color of overlying MenuTitleValueCell cell.valueLabel.textColor = VisualConfiguration.textGrayColor } } } } return rowsToReload } // close all open picker cells after finishing with editing func closePickerCellsForShowState() { let rowsToReload = closeAllOpenPickerCells() tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(rowsToReload, withRowAnimation: .Automatic) tableView.endUpdates() } // cells with given tags need to be reloaded func updateCells(withTags tags: [Int]) { var indexPaths: [NSIndexPath] = [] for tag in tags { menu.updateTitleValueValues(ofTag: tag) if let indexPath = menu.indexPathForTag(tag) { indexPaths.append(indexPath) } } tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: .None) tableView.endUpdates() } } // MARK: UITextFieldDelegate extension TaskMenuViewController: UITextFieldDelegate { // start text inputing func activateVisibleTextField(textField: UITextField) { if let indexPath = menu.indexPathForTag(textField.tag) { menu.cellsTagTypeState[indexPath.section][indexPath.row].state = .Active } textField.becomeFirstResponder() } func textFieldShouldReturn(textField: UITextField) -> Bool { if let indexPath = menu.indexPathForTag(textField.tag) { menu.cellsTagTypeState[indexPath.section][indexPath.row].state = .Visible } textField.resignFirstResponder() return true } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let oldText = textField.text { let newText = (oldText as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString // some text was typed - need to save new text in task menu.updateTask(byTextFieldWithTag: textField.tag, byString: newText as String) menu.updateTitleValueValues(ofTag: textField.tag) } return true } // deactivate all text fields func deactivateAllActiveTextFields() { for s in 0..<menu.cellsTagTypeState.count { for r in 0..<menu.cellsTagTypeState[s].count { let cellTTS = menu.cellsTagTypeState[s][r] if cellTTS.type == .TextFieldCell && cellTTS.state == .Active { let indexPath = NSIndexPath(forRow: r, inSection: s) if let cell = tableView.cellForRowAtIndexPath(indexPath) as? MenuTextFieldCell { textFieldShouldReturn(cell.textField) } else { menu.cellsTagTypeState[s][r].state = .Visible UIApplication.sharedApplication().sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, forEvent: nil) } } } } } } // MARK: DataPickerViewDelegate extension TaskMenuViewController: DataPickerViewDelegate { func dataPicker(picker: DataPickerView, didPickValues values: [String]) { // picker picked some values - need to update cell, which is assigned to show it let tagsToUpdate = menu.updateTask(byPickerViewWithTag: picker.tag, byStrings: values) updateCells(withTags: tagsToUpdate) } func dataStillNeeded(fromPicker picker: DataPickerView) -> Bool { // when picker chooses some values, after having been hidden - no data is needed from it if let cellIndexPath = menu.indexPathForTag(picker.tag) { if menu.cellsTagTypeState[cellIndexPath.section][cellIndexPath.row].type == .ComplexPickerCell { if let cell = tableView.cellForRowAtIndexPath(cellIndexPath) as? MenuComplexPickerCell { let pickerIsHidden = cell.hidden(forTag: picker.tag) if pickerIsHidden { } return !cell.hidden(forTag: picker.tag) } } else if menu.cellsTagTypeState[cellIndexPath.section][cellIndexPath.row].state != .Hidden { return true } } return false } } // MARK: DatePickerDelegate extension TaskMenuViewController: DatePickerDelegate { func datePicker(picker: UIDatePicker, didPickDate date: NSDate) { let tagsToUpdate = menu.updateTask(byPickerViewWithTag: picker.tag, byDateTimeValue: date) updateCells(withTags: tagsToUpdate) } func datePicker(picker: UIDatePicker, didPickMinutes minutes: Int) { let tagsToUpdate = menu.updateTask(byPickerViewWithTag: picker.tag, byMinutes: minutes) updateCells(withTags: tagsToUpdate) } func dateStillNeeded(fromPicker picker: UIDatePicker) -> Bool { if let cellIndexPath = menu.indexPathForTag(picker.tag) { if menu.cellsTagTypeState[cellIndexPath.section][cellIndexPath.row].type == .ComplexPickerCell { if let cell = tableView.cellForRowAtIndexPath(cellIndexPath) as? MenuComplexPickerCell { return !cell.hidden(forTag: picker.tag) } } else if menu.cellsTagTypeState[cellIndexPath.section][cellIndexPath.row].state != .Hidden { return true } } return false } } // MARK: DoubleOptionSegmControlDelegate extension TaskMenuViewController: DoubleOptionSegmControlDelegate { func segmControl(sgCtrl: UISegmentedControl, didSelectSegment segment: Int) { // first or second option was chosen let tagsToUpdate = menu.updateTask(bySegmentedControlWithTag: sgCtrl.tag, andSegment: segment) updateCells(withTags: tagsToUpdate) if let indexPath = menu.indexPathForTag(sgCtrl.tag) { tableView(tableView, didSelectRowAtIndexPath: indexPath) } } } // MARK: MenuComplexPickerCellDelegate extension TaskMenuViewController: MenuComplexPickerCellDelegate { func getPickerOptionsAndInitialValues(bySelectedSegment index: Int, andByTag tag: Int) -> (options: [[String]], initialValues: [String], delegate: DataPickerViewDelegate) { // get options and initial values for a picker, corresponding for specific end type (end-days or end-times) let et = Task.EndType(rawValue: index) let endOptions = menu.endOptions(byNewEndType: et) let initialValues = menu.initialDataPickerValues(withTag: tag, andNewEndType: et) return ([endOptions], initialValues, self) } func getPickerInitialValues(bySelectedSegment index: Int, andByTag tag: Int) -> [String] { // get initial values for a picker, corresponding for specific end type (end-days or end-times) let et = Task.EndType(rawValue: index) let initialValues = menu.initialDataPickerValues(withTag: tag, andNewEndType: et) return initialValues } func getPickerInitialDate(bySelectedSegment index: Int, andByTag tag: Int) -> (iDate: NSDate, mDate: NSDate, delegate: DatePickerDelegate) { // get initial and minimum dates for picker for end-date let dates = menu.initialDateTimePickerDate(withTag: tag) return (dates.initialDate, dates.minimumDate, self) } func getPickerInitialDate(bySelectedSegment index: Int, andByTag tag: Int) -> NSDate { // get initial date for picker for end-date let dates = menu.initialDateTimePickerDate(withTag: tag) return dates.initialDate } }
mit
6ef72198ac06a52e441b435939759419
38.098753
174
0.713184
5.305078
false
true
false
false
davidahouse/chute
chute/Output/DifferenceReport/DifferenceReportDetailCodeCoverage.swift
1
2519
// // DifferenceReportDetailCodeCoverage.swift // chute // // Created by David House on 11/16/17. // Copyright © 2017 David House. All rights reserved. // import Foundation struct DifferenceReportDetailCodeCoverage: ChuteOutputDifferenceRenderable { enum Constants { static let Template = """ <div class="jumbotron"> <h3>Code Coverage Details</h3> <div class="table-responsive"> <table class="table"> <thead> <th>Target</th> <th>File</th> <th>Coverage</th> </thead> <tbody> {{details}} </tbody> </table> </div> </div> """ static let CoverageTemplate = """ <tr class="{{row_class}}"> <td>{{target}}</td> <td>{{file}}</td> <td>{{coverage}}% <span class="badge {{change_badge}}">{{change}}%</span></td> </tr> """ } func render(difference: DataCaptureDifference) -> String { let parameters: [String: CustomStringConvertible] = [ "details": reportDetails(difference: difference) ] return Constants.Template.render(parameters: parameters) } private func reportDetails(difference: DataCaptureDifference) -> String { var output = "" for coverage in difference.codeCoverageDifference.codeCoverageChanges { let trClass: String = { if coverage.1.lineCoverage <= 0.70 { return "table-danger" } else if coverage.1.lineCoverage >= 0.90 { return "table-success" } else { return "table-warning" } }() let changeBadge: String = { if coverage.2 <= 0.0 { return "badge-danger" } else { return "badge-success" } }() let parameters: [String: CustomStringConvertible] = [ "row_class": trClass, "target": coverage.0, "file": coverage.1.name, "coverage": Int(round(coverage.1.lineCoverage * 100)), "change_badge": changeBadge, "change": Int(round(coverage.2 * 100)) ] output += Constants.CoverageTemplate.render(parameters: parameters) } return output } }
mit
5a6a5975302016b5443c4b07556285f5
29.337349
90
0.492454
4.680297
false
false
false
false
icetime17/CSSwiftExtension
Sources/UIKit+CSExtension/UIImage+Gif.swift
1
5981
// // Thanks to https://github.com/bahlo/SwiftGif for gif support // // // Gif.swift // SwiftGif // // Created by Arne Bahlo on 07.06.14. // Copyright (c) 2014 Arne Bahlo. All rights reserved. // import UIKit import ImageIO public extension UIImageView { func loadGif(name: String) { DispatchQueue.global().async { let image = UIImage.gif(name: name) DispatchQueue.main.async { self.image = image } } } } public extension UIImage { class func gif(data: Data) -> UIImage? { // Create source from data guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { CS_Print("SwiftGif: Source for the image does not exist") return nil } return UIImage.animatedImageWithSource(source) } class func gif(url: String) -> UIImage? { // Validate URL guard let bundleURL = URL(string: url) else { CS_Print("SwiftGif: This image named \"\(url)\" does not exist") return nil } // Validate data guard let imageData = try? Data(contentsOf: bundleURL) else { CS_Print("SwiftGif: Cannot turn image named \"\(url)\" into NSData") return nil } return gif(data: imageData) } class func gif(name: String) -> UIImage? { // Check for existance of gif guard let bundleURL = Bundle.main .url(forResource: name, withExtension: "gif") else { CS_Print("SwiftGif: This image named \"\(name)\" does not exist") return nil } // Validate data guard let imageData = try? Data(contentsOf: bundleURL) else { CS_Print("SwiftGif: Cannot turn image named \"\(name)\" into NSData") return nil } return gif(data: imageData) } internal class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double { var delay = 0.1 // Get dictionaries let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0) if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false { return delay } let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self) // Get delay time var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if delayObject.doubleValue == 0 { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } delay = delayObject as? Double ?? 0 if delay < 0.1 { delay = 0.1 // Make sure they're not too fast } return delay } internal class func gcdForPair(_ a: Int?, _ b: Int?) -> Int { var a = a var b = b // Check if one of them is nil if b == nil || a == nil { if b != nil { return b! } else if a != nil { return a! } else { return 0 } } // Swap for modulo if a! < b! { let c = a a = b b = c } // Get greatest common divisor var rest: Int while true { rest = a! % b! if rest == 0 { return b! // Found it } else { a = b b = rest } } } internal class func gcdForArray(_ array: Array<Int>) -> Int { if array.isEmpty { return 1 } var gcd = array[0] for val in array { gcd = UIImage.gcdForPair(val, gcd) } return gcd } internal class func animatedImageWithSource(_ source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images = [CGImage]() var delays = [Int]() // Fill arrays for i in 0..<count { // Add image if let image = CGImageSourceCreateImageAtIndex(source, i, nil) { images.append(image) } // At it's delay in cs let delaySeconds = UIImage.delayForImageAtIndex(Int(i), source: source) delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms } // Calculate full duration let duration: Int = { var sum = 0 for val: Int in delays { sum += val } return sum }() // Get frames let gcd = gcdForArray(delays) var frames = [UIImage]() var frame: UIImage var frameCount: Int for i in 0..<count { frame = UIImage(cgImage: images[Int(i)]) frameCount = Int(delays[Int(i)] / gcd) for _ in 0..<frameCount { frames.append(frame) } } // Heyhey let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0) return animation } }
mit
c8c83b9dfc6bd8f935550ea1fe91e689
28.318627
155
0.497408
5.20087
false
false
false
false
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document13.playgroundchapter/Pages/Challenge1.playgroundpage/Contents.swift
1
1236
//#-hidden-code // // Contents.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // //#-end-hidden-code /*: **Challenge:** Add blocks to bridge all the gaps. For this challenge, practice modifying the puzzle world. You'll need to add multiple blocks to reach the gems. You can create a stack by placing one block on top of another. Be sure to use [loops](glossary://loop), and factor your code into functions so you don't have to write the same lines of code more than once. */ //#-code-completion(everything, hide) //#-code-completion(currentmodule, show) //#-code-completion(identifier, show, isOnOpenSwitch, if, func, for, while, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, Expert, Character, Block, (, ), (), turnLockUp(), turnLockDown(), isOnClosedSwitch, var, let, ., =, <, >, ==, !=, +, -, isBlocked, move(distance:), jump(), true, false, turnLock(up:numberOfTimes:), world, place(_:facing:atColumn:row:), place(_:atColumn:row:), isBlockedLeft, &&, ||, !, isBlockedRight) //#-hidden-code playgroundPrologue() typealias Character = Actor //#-end-hidden-code //#-editable-code Tap to enter code //#-end-editable-code //#-hidden-code playgroundEpilogue() //#-end-hidden-code
mit
fcd02aec19175d8191c4f826e8e40a78
43.142857
456
0.700647
4
false
false
false
false
SaberVicky/LoveStory
LoveStory/Feature/Reply/LSReplyModel.swift
1
887
// // LSReplyModel.swift // LoveStory // // Created by songlong on 2017/2/6. // Copyright © 2017年 com.Saber. All rights reserved. // import UIKit class LSReplyModel: NSObject { var time: String? var avator_url: String? var content: String? var account: String? init(dict: [String: AnyObject]) { super.init() time = dict["time"] as? String content = dict["content"] as? String let timeString = Double(time!) let date = Date(timeIntervalSince1970: timeString!) let formatter = DateFormatter() formatter.dateFormat = "yyyy年MM月dd日 HH:mm" time = formatter.string(from: date) // avator_url = dict["avator"] as? String avator_url = "http://ojae83ylm.bkt.clouddn.com/19343a60e16c11e69e6a5254005b67a6.png" account = dict["account"] as? String } }
mit
c6001a74065a402813e3354618a13cf0
26.4375
92
0.616173
3.540323
false
false
false
false
ozpopolam/TrivialAsia
TrivialAsia/TriviaRepositoryService.swift
1
954
// // TriviaRepositoryService.swift // TrivialAsia // // Created by Anastasia Stepanova-Kolupakhina on 25.05.17. // Copyright © 2017 Anastasia Kolupakhina. All rights reserved. // import Foundation import RealmSwift class TriviaRepositoryService { func getTriviaToken() -> TriviaToken? { let realm = try! Realm() return realm.objects(TriviaToken.self).first } func setTriviaToken(_ token: TriviaToken) { let realm = try! Realm() try! realm.write { realm.add(token, update: true) } } func getAnsweredTrivia() -> [Trivia] { let realm = try! Realm() let trivia = realm.objects(Trivia.self).filter { $0.isAnswered } return Array(trivia) } func setAnswered(_ trivia: Trivia) { let realm = try! Realm() trivia.isAnswered = true try! realm.write { realm.add(trivia, update: true) } } }
mit
7f704db73a593c3dd597e71250ffcd02
23.435897
72
0.60021
4.161572
false
false
false
false
LubosPlavucha/DateMyDate
classes/DateUtil.swift
1
12100
// // DateUtil.swift // HomeBudgetSoft // // Created by lubos plavucha on 08/12/14. // Copyright (c) 2014 Acepricot. All rights reserved. // import Foundation open class DateUtil { // as of now, swift doesn't have static variables for class -> make use of struct for this struct Attributes { fileprivate static let flags: NSCalendar.Unit = [.year, .month, .day, .hour, .minute, .second] } // INFO: when testing and checking the dates in console, be aware that NSDate is logged in UTC /** get day X months before specified day - time is set to the first second of the day */ open class func getXMonthsAgo(_ date: Date, monthCount: Int) -> Date { let cal = Calendar.current var dateComp = (cal as NSCalendar).components(Attributes.flags, from: date) dateComp.month = dateComp.month! - monthCount dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** Add number of days to the date */ open class func addDays(_ date: Date, daysCount: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.day = daysCount return (cal as NSCalendar).date(byAdding: dateComp, to: date, options: [])! } /** Add number of weeks to the date */ open class func addWeeks(_ date: Date, weeksCount: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.weekOfYear = weeksCount return (cal as NSCalendar).date(byAdding: dateComp, to: date, options: [])! } /** Add number of months to the date */ open class func addMonths(_ date: Date, monthsCount: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.month = monthsCount return (cal as NSCalendar).date(byAdding: dateComp, to: date, options: [])! } /** Add number of years to the date */ open class func addYears(_ date: Date, yearCount: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.year = yearCount return (cal as NSCalendar).date(byAdding: dateComp, to: date, options: [])! } /** get today - time is set to the first second of the day */ open class func getBeginningOfDay(_ date: Date) -> Date { let cal = Calendar.current var dateComp = (cal as NSCalendar).components(Attributes.flags, from: date) dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** get today - time is set to the last second of the day */ open class func getEndOfDay(_ date: Date) -> Date { let cal = Calendar.current var dateComp = (cal as NSCalendar).components(Attributes.flags, from: date) dateComp.hour = (cal as NSCalendar).range(of: .hour, in: .day, for: date).length - 1 dateComp.minute = (cal as NSCalendar).range(of: .minute, in: .hour, for: date).length - 1 dateComp.second = (cal as NSCalendar).range(of: .second, in: .minute, for: date).length - 1 return cal.date(from: dateComp)! } /** get first day of the month - time is set to the first second of the day */ open class func getFirstDayOfMonth(_ date: Date) -> Date { let cal = Calendar.current var dateComp = (cal as NSCalendar).components(Attributes.flags, from: date) dateComp.day = 1 dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** get last day of the month - time is set to the last second of the day */ open class func getLastDayOfMonth(_ date: Date) -> Date { let cal = Calendar.current var dateComp = (cal as NSCalendar).components(Attributes.flags, from: date) dateComp.day = (cal as NSCalendar).range(of: .day, in: .month, for: date).length dateComp.hour = (cal as NSCalendar).range(of: .hour, in: .day, for: date).length - 1 dateComp.minute = (cal as NSCalendar).range(of: .minute, in: .hour, for: date).length - 1 dateComp.second = (cal as NSCalendar).range(of: .second, in: .minute, for: date).length - 1 return cal.date(from: dateComp)! } /** get first day of the week - time is set to the first second of the day */ open class func getFirstDayOfWeek(_ date: Date, locale: Locale) -> Date { var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.locale = locale // locale needs to be used here, because the first day of week depends on it (e.g. Sunday vs. Monday) var dateComp = (cal as NSCalendar).components(Attributes.flags.union(.weekday), from: date) dateComp.day = dateComp.day! - dateComp.weekday! + 1 // workaround, because setting directly weekdays is not working dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** get last day of the week - time is set to the last second of the day */ open class func getLastDayOfWeek(_ date: Date, locale: Locale) -> Date { var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.locale = locale var dateComp = (cal as NSCalendar).components(Attributes.flags.union(.weekday), from: date) let weekdayCount = cal.weekdaySymbols.count dateComp.day = dateComp.day! + (weekdayCount - dateComp.weekday!) // workaround, because setting directly weekdays is not working dateComp.hour = (cal as NSCalendar).range(of: .hour, in: .day, for: date).length - 1 dateComp.minute = (cal as NSCalendar).range(of: .minute, in: .hour, for: date).length - 1 dateComp.second = (cal as NSCalendar).range(of: .second, in: .minute, for: date).length - 1 return cal.date(from: dateComp)! } /** Get next weekday counting from the specified date, e.g. get next Friday from today. If today is the specified weekday, it returns today. */ open class func getWeekday(_ date: Date, weekdayIndex: Int, locale: Locale) -> Date { var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.locale = locale var dateComp = (cal as NSCalendar).components([.year, .month, .day, .weekday], from: date) if weekdayIndex >= dateComp.weekday! { dateComp.day = dateComp.day! + (weekdayIndex - dateComp.weekday!) return cal.date(from: dateComp)! } else { // next weekday is in the next week let weekdayCount = cal.weekdaySymbols.count dateComp.day = dateComp.day! - (dateComp.weekday! - weekdayIndex) + weekdayCount return cal.date(from: dateComp)! } } /** get first day of the year - time is set to the first second of the day */ open class func getFirstDayOfYear(_ year: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.year = year dateComp.month = 1 dateComp.day = 1 dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** get last day of the year - time is set to the last second of the day */ open class func getLastDayOfYear(_ year: Int) -> Date { let cal = Calendar.current var dateComp = DateComponents() dateComp.year = year dateComp.month = (cal as NSCalendar).range(of: .month, in: .year, for: cal.date(from: dateComp)!).length dateComp.day = (cal as NSCalendar).range(of: .day, in: .month, for: cal.date(from: dateComp)!).length dateComp.hour = (cal as NSCalendar).range(of: .hour, in: .day, for: cal.date(from: dateComp)!).length - 1 dateComp.minute = (cal as NSCalendar).range(of: .minute, in: .hour, for: cal.date(from: dateComp)!).length - 1 dateComp.second = (cal as NSCalendar).range(of: .second, in: .minute, for: cal.date(from: dateComp)!).length - 1 return cal.date(from: dateComp)! } /** get tomorrow - time is set to the first second of the day */ open class func getTomorrow() -> Date { let cal = Calendar.current let today = Date() var dateComp = (cal as NSCalendar).components(Attributes.flags, from: today) dateComp.day = dateComp.day! + 1 dateComp.hour = 0 dateComp.minute = 0 dateComp.second = 0 return cal.date(from: dateComp)! } /** Comparing if first date is before second date ignoring time */ open class func isBeforeDate(_ firstDate: Date, secondDate: Date) -> Bool { let firstDateDayBeginning = getBeginningOfDay(firstDate) let secondDateDayBeginning = getBeginningOfDay(secondDate) let result = firstDateDayBeginning.compare(secondDateDayBeginning) if result == .orderedAscending { return true } return false } /** Comparing if first date is before second date or it is same date ignoring time */ open class func isBeforeOrSameDate(_ firstDate: Date, secondDate: Date) -> Bool { let firstDateDayBeginning = getBeginningOfDay(firstDate) let secondDateDayBeginning = getBeginningOfDay(secondDate) let result = firstDateDayBeginning.compare(secondDateDayBeginning) if result == .orderedAscending || result == .orderedSame { return true } return false } /** Comparing if first date is after second date ignoring time */ open class func isAfterDate(_ firstDate: Date, secondDate: Date) -> Bool { let firstDateDayBeginning = getBeginningOfDay(firstDate) let secondDateDayBeginning = getBeginningOfDay(secondDate) let result = firstDateDayBeginning.compare(secondDateDayBeginning) if result == .orderedDescending { return true } return false } /** Comparing if first date is after second date or it is same date ignoring time */ open class func isAfterOrSameDate(_ firstDate: Date, secondDate: Date) -> Bool { let firstDateDayBeginning = getBeginningOfDay(firstDate) let secondDateDayBeginning = getBeginningOfDay(secondDate) let result = firstDateDayBeginning.compare(secondDateDayBeginning) if result == .orderedDescending || result == .orderedSame { return true } return false } /** Comparing if first date is same day as second date ignoring time */ open class func isSameDay(_ firstDate: Date, secondDate: Date) -> Bool { let firstDateDayBeginning = getBeginningOfDay(firstDate) let secondDateDayBeginning = getBeginningOfDay(secondDate) let result = firstDateDayBeginning.compare(secondDateDayBeginning) if result == .orderedSame { return true } return false } /** Comparing if first date is within given month ignoring time */ open class func isSameMonth(_ firstDate: Date, month: Date) -> Bool { let cal = Calendar.current let firsDateComp = (cal as NSCalendar).components([.year, .month], from: firstDate) let monthDateComp = (cal as NSCalendar).components([.year, .month], from: month) return firsDateComp.year == monthDateComp.year && firsDateComp.month == monthDateComp.month } /** Returns localized month name for given date */ open class func getMonthName(_ date: Date, locale: Locale) -> String { let dateFormatter = DateFormatter() dateFormatter.locale = locale let cal = Calendar(identifier: Calendar.Identifier.gregorian) let monthIndex = (cal as NSCalendar).components(.month, from: date).month return dateFormatter.monthSymbols[monthIndex! - 1] } }
mit
19b6ba5b9ddfb5a7762804128404104e
40.868512
147
0.630331
4.559156
false
false
false
false
wanliming11/MurlocAlgorithms
Last/LeetCode/String/38._Count_and_Say/38. Count and Say/main.swift
1
1892
// // main.swift // 38. Count and Say // // Created by FlyingPuPu on 09/02/2017. // Copyright (c) 2017 FPP. All rights reserved. // import Foundation /* 38. Count and Say The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. */ /* Thinking: 遍历数字,得到Count, Number(用栈结构,每次取出上一个数字,相同则计数,不同则Append ) 计算完后展平,得到新的数字, 然后重复 */ func countAndSay(_ n: Int ) -> String { //计算出 (count, Number) guard n > 0 else { return "0" } let nStr = String(1) var stackArray: [(Int, Character)] = [(Int, Character)]() func pushStack(_ c: Character) { if let last = stackArray.last { if (last.1 == c) { let count = last.0 + 1 stackArray[stackArray.count - 1] = (count, last.1) } else { stackArray.append((1, c)) } } else { stackArray.append((1, c)) } } func emptyStack() { stackArray.removeAll() } func stackToString() -> String { var strArray: [String] = [String]() for value in stackArray { strArray.append(String(value.0)) strArray.append(String(value.1)) } emptyStack() return strArray.joined() } func calc(_ nStr: String) -> String { for c in nStr.characters { pushStack(c) } return stackToString() } var newString = nStr for _ in (0 ..< n-1) { newString = calc(newString) } return newString } //print(countAndSay(0)) //print(countAndSay(1)) print(countAndSay(3))
mit
6d6ae66c626a030d31ba4c3d8ef777a1
20.011765
76
0.555431
3.474708
false
false
false
false
joerocca/GitHawk
Classes/Issues/Managing/IssueManagingActionCell.swift
1
2155
// // IssueManagingActionCell.swift // Freetime // // Created by Ryan Nystrom on 11/13/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit import SnapKit final class IssueManagingActionCell: UICollectionViewCell, ListBindable { private let label = UILabel() private let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) accessibilityTraits |= UIAccessibilityTraitButton isAccessibilityElement = true let tint = Styles.Colors.Blue.medium.color imageView.tintColor = tint imageView.contentMode = .center contentView.addSubview(imageView) imageView.snp.makeConstraints { make in make.size.equalTo(Styles.Sizes.buttonIcon) make.centerX.equalTo(contentView) make.top.equalTo(contentView) } label.textColor = tint label.font = Styles.Fonts.secondary contentView.addSubview(label) label.snp.makeConstraints { make in make.centerX.equalTo(imageView) make.top.equalTo(imageView.snp.bottom) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var isSelected: Bool { didSet { highlight(isSelected) } } override var isHighlighted: Bool { didSet { highlight(isHighlighted) } } // MARK: Private API func highlight(_ highlight: Bool) { let alpha: CGFloat = highlight ? 0.5 : 1 label.alpha = alpha imageView.alpha = alpha } // MARK: ListBindable func bindViewModel(_ viewModel: Any) { guard let viewModel = viewModel as? IssueManagingActionModel else { return } label.text = viewModel.label imageView.image = UIImage(named: viewModel.imageName)?.withRenderingMode(.alwaysTemplate) } // MARK: Accessibility override var accessibilityLabel: String? { get { return AccessibilityHelper.generatedLabel(forCell: self) } set { } } }
mit
58bcd2981b69d00ae60118c51f9757b7
25.268293
97
0.632312
4.873303
false
false
false
false
odigeoteam/TableViewKit
TableViewKit/TableViewKitDataSource.swift
1
2279
import UIKit open class TableViewKitDataSource: NSObject, UITableViewDataSource { open unowned var manager: TableViewManager private var sections: ObservableArray<TableSection> { return manager.sections } public required init(manager: TableViewManager) { self.manager = manager } /// Implementation of UITableViewDataSource open func numberOfSections(in tableView: UITableView) -> Int { return sections.count } /// Implementation of UITableViewDataSource open func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int { let section = sections[sectionIndex] return section.items.count } /// Implementation of UITableViewDataSource open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let currentItem = manager.item(at: indexPath) let drawer = type(of: currentItem).drawer let cell = drawer.cell(in: manager, with: currentItem, for: indexPath) drawer.draw(cell, with: currentItem) return cell } /// Implementation of UITableViewDataSource open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return title(for: { $0.header }, inSection: section) } /// Implementation of UITableViewDataSource open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return title(for: { $0.footer }, inSection: section) } /// Implementation of UITableViewDataSource // swiftlint:disable:next line_length open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } /// Implementation of UITableViewDataSource open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return manager.item(at: indexPath) is Editable } fileprivate func title(for key: (TableSection) -> HeaderFooterView, inSection section: Int) -> String? { if case .title(let value) = key(sections[section]) { return value } return nil } }
mit
a07ac1f8254c606430db32d105697041
35.758065
133
0.698552
5.452153
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InstantPageWebEmbedItem.swift
1
1840
// // InstantPageWebEmbedItem.swift // Telegram // // Created by keepcoder on 10/08/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCore final class InstantPageWebEmbedItem: InstantPageItem { var frame: CGRect let hasLinks: Bool = false let wantsView: Bool = true let medias: [InstantPageMedia] = [] let url: String? let html: String? let enableScrolling: Bool let separatesTiles: Bool = false let isInteractive: Bool = false init(frame: CGRect, url: String?, html: String?, enableScrolling: Bool) { self.frame = frame self.url = url self.html = html self.enableScrolling = enableScrolling } func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? { return InstantPageWebEmbedView(frame: self.frame, url: self.url, html: self.html, enableScrolling: self.enableScrolling, updateWebEmbedHeight: { height in arguments.updateWebEmbedHeight(height) }) } func matchesAnchor(_ anchor: String) -> Bool { return false } func matchesView(_ node: InstantPageView) -> Bool { if let node = node as? InstantPageWebEmbedView { return self.url == node.url && self.html == node.html } else { return false } } func distanceThresholdGroup() -> Int? { return 3 } func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat { if count > 3 { return 1000.0 } else { return CGFloat.greatestFiniteMagnitude } } func linkSelectionViews() -> [InstantPageLinkSelectionView] { return [] } func drawInTile(context: CGContext) { } }
gpl-2.0
a3520aadd4509592e9aafbc787d073ba
25.271429
162
0.616639
4.563275
false
false
false
false
paraskakis/polls-app
Polls/ViewControllers/QuestionDetailViewController.swift
1
3263
// // QuestionDetailViewController.swift // Polls // // Created by Kyle Fuller on 01/04/2015. // Copyright (c) 2015 Apiary. All rights reserved. // import UIKit import SVProgressHUD /// A view controller for showing specific questions class QuestionDetailViewController : UITableViewController { /// The view model backing this view controller var viewModel:QuestionDetailViewModel? { didSet { if isViewLoaded() { updateState() } } } // MARK: View life-cycle override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("QUESTION_DETAIL_TITLE", comment: "") updateState() } // MARK: UITableViewDelegate override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if viewModel == nil { return 0 } return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } return viewModel?.numberOfChoices() ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("QuestionCell") as! UITableViewCell cell.textLabel?.text = viewModel?.question cell.detailTextLabel?.text = nil cell.accessoryType = .None return cell } let cell = tableView.dequeueReusableCellWithIdentifier("ChoiceCell") as! UITableViewCell cell.textLabel?.text = viewModel?.choice(indexPath.row) cell.detailTextLabel?.text = viewModel?.votes(indexPath.row).description if viewModel!.canVote(indexPath.row) { cell.accessoryType = .DisclosureIndicator } else { cell.accessoryType = .None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 && viewModel!.canVote(indexPath.row) { // Vote on the question vote(indexPath.row) } else { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return NSLocalizedString("QUESTION_DETAIL_QUESTION_TITLE", comment: "") } return NSLocalizedString("QUESTION_DETAIL_CHOICE_LIST_TITLE", comment: "") } /// Vote on the given choice private func vote(index:Int) { SVProgressHUD.showWithStatus(NSLocalizedString("QUESTION_DETAIL_CHOICE_VOTING", comment: ""), maskType: .Gradient) viewModel?.vote(index) { voted in SVProgressHUD.dismiss() self.tableView.reloadData() } } func updateState() { if viewModel?.canReload ?? false { if refreshControl == nil { refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action:Selector("reload"), forControlEvents:.ValueChanged) } } else { refreshControl = nil } tableView?.reloadData() } func reload() { if let viewModel = viewModel { viewModel.reload { result in self.refreshControl?.endRefreshing() self.updateState() } } else { refreshControl?.endRefreshing() } } }
mit
0358b200fb3a1657c40a56cfff62ebec
25.966942
118
0.679436
4.877429
false
false
false
false
5calls/ios
FiveCalls/FiveCalls/IssueActivityItemSource.swift
1
2542
// // IssueActivityItemSource.swift // FiveCalls // // Created by Alex on 2/4/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit class IssueActivityItemSource: NSObject, UIActivityItemSource { let issue: Issue init(issue: Issue) { self.issue = issue } func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return issue.name } func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { return R.string.localizable.iJustCalledMyRep(issue.name, issue.slug) } func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String { return issue.name } func activityViewController(_ activityViewController: UIActivityViewController, thumbnailImageForActivityType activityType: UIActivity.ActivityType?, suggestedSize size: CGSize) -> UIImage? { return nil } } protocol IssueShareable: AnyObject { var issue: Issue! { get } func shareIssue(from: Any?) } extension IssueShareable where Self: UIViewController { func shareIssue(from: Any?) { guard let issue = issue else { return assertionFailure("There was no issue to share") } AnalyticsManager.shared.trackEvent(withName: "Action: Share Issue", andProperties: ["issue_id": String(issue.id)]) let activityViewController = UIActivityViewController(activityItems: [IssueActivityItemSource(issue: issue)], applicationActivities: nil) activityViewController.excludedActivityTypes = [.addToReadingList, .airDrop, .assignToContact, .openInIBooks, .print, .saveToCameraRoll] if UIDevice.current.userInterfaceIdiom == .pad { if let button = from as? UIButton { activityViewController.modalPresentationStyle = .popover activityViewController.popoverPresentationController?.sourceView = button activityViewController.popoverPresentationController?.sourceRect = button.bounds } else if let item = from as? UIBarButtonItem { activityViewController.modalPresentationStyle = .popover activityViewController.popoverPresentationController?.barButtonItem = item } } present(activityViewController, animated: true, completion: nil) } }
mit
e1deb2a187b976f047bfa131755e56fb
38.703125
195
0.708383
5.814645
false
false
false
false
psharanda/Atributika
Demo/IBViewController.swift
1
2706
// // IBViewController.swift // Demo // // Created by Pavel Sharanda on 12/17/19. // Copyright © 2019 Atributika. All rights reserved. // import UIKit import Atributika class IBViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let font: UIFont if #available(iOS 11.0, *) { font = UIFont.preferredFont(forTextStyle: .body) } else { font = UIFont.systemFont(ofSize: 16) } let button = Style("button") .underlineStyle(.styleSingle) .font(font) .foregroundColor(.black, .normal) .foregroundColor(.red, .highlighted) if #available(iOS 10.0, *) { attributedLabel.adjustsFontForContentSizeCategory = true } attributedLabel.attributedText = "Hello! <button>Need to register?</button>".style(tags: button).styleAll(.font(.systemFont(ofSize: 12))) setupTopLabels() } private func setupTopLabels() { let message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <button>Need to register?</button> Cras eu auctor est. Vestibulum ornare dui ut orci congue placerat. Nunc et tortor vulputate, elementum quam at, tristique nibh. Cras a mollis mauris. Cras non mauris nisi. Ut turpis tellus, pretium sed erat eu, consectetur volutpat nisl. Praesent at bibendum ante. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque ut mauris eu felis venenatis condimentum finibus ac nisi. Nulla id turpis libero. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nullam pulvinar lorem eu metus scelerisque, non lacinia ligula molestie. Vivamus vestibulum sem sit amet pellentesque tristique. Aenean hendrerit mi turpis. Mauris tempus viverra mauris, non accumsan leo aliquet nec. Suspendisse in ipsum ut arcu mollis bibendum." let button = Style("button") .underlineStyle(.styleSingle) .font(.systemFont(ofSize: 30)) .foregroundColor(.black, .normal) .foregroundColor(.red, .highlighted) issue103Label.numberOfLines = 0 issue103Label.attributedText = message .style(tags: button) .styleAll(.font(.systemFont(ofSize: 30))) issue103Label.onClick = { label, detection in print(detection) } pinkLabel.attributedText = "Lorem ipsum dolor sit amet".styleAll(Style()) } @IBOutlet private var attributedLabel: AttributedLabel! @IBOutlet private var issue103Label: AttributedLabel! @IBOutlet private var pinkLabel: AttributedLabel! }
mit
bd10b4d600bc3da8f91ec41886382e97
41.936508
889
0.669501
4.882671
false
false
false
false
KyoheiG3/Keynode
KeynodeExample/KeynodeExample/RespondButton.swift
1
1900
// // RespondButton.swift // KeynodeExample // // Created by Kyohei Ito on 2015/01/30. // Copyright (c) 2015年 kyohei_ito. All rights reserved. // import UIKit class RespondButton: UIButton { let contents = [1, 2, 3, 4, 5] lazy fileprivate var pickerView: UIPickerView = { let picker = UIPickerView() picker.backgroundColor = UIColor.white picker.delegate = self picker.dataSource = self return picker }() lazy fileprivate var accessoryToolbar: UIView = { let toolbar = UIToolbar() toolbar.barStyle = .default toolbar.sizeToFit() toolbar.frame.size.height = 44 let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(RespondButton.buttonAction(_:))) let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) toolbar.items = [spacer, button] return toolbar }() @objc func buttonAction(_ sender: AnyObject) { self.resignFirstResponder() } override var inputView: UIView? { return pickerView } override var inputAccessoryView: UIView? { return accessoryToolbar } override var canBecomeFirstResponder : Bool { return true } override func becomeFirstResponder() -> Bool { return super.becomeFirstResponder() } } extension RespondButton: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return contents.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(contents[row]) } }
mit
e6e424ecdacc18a5c63fb52bd44f8aa6
26.911765
129
0.641728
5.088472
false
false
false
false
pyromobile/nubomedia-ouatclient-src
ios/LiveTales-smartphones/uoat/ProfileViewController.swift
1
8111
// // ProfileViewController.swift // uoat // // Created by Pyro User on 13/5/16. // Copyright © 2016 Zed. All rights reserved. // import UIKit class ProfileViewController: UIViewController { weak var user:User! weak var delegate:ProfileDelegate? required init?(coder aDecoder: NSCoder) { self.preparedKeyboard = false self.adjustedKeyboard = false super.init(coder: aDecoder) } deinit { self.user = nil self.delegate = nil NSNotificationCenter.defaultCenter().removeObserver( self ) print("ProfileViewController - deInit....OK") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.translucent = true //load resources. //.:Back button let leftArrowActiveImage:UIImage = Utils.flipImage( named: "btn_next_available", orientation: .Down ) self.leftArrowImage.image = leftArrowActiveImage //Head title. let headAttrString = NSMutableAttributedString(string: self.headerLabel.text!, attributes: [NSStrokeWidthAttributeName: -7.0, NSFontAttributeName: UIFont(name: "ArialRoundedMTBold", size: 22)!, NSStrokeColorAttributeName: UIColor.whiteColor(), NSForegroundColorAttributeName: self.headerLabel.textColor ]) self.headerLabel.attributedText! = headAttrString //Add blur efect to hide the last view. let blurEffectView:UIVisualEffectView = Utils.blurEffectView( self.view, radius: 10 ) self.view.addSubview( blurEffectView ) self.view.sendSubviewToBack( blurEffectView ) userNickNameLabel.text = self.user.nick uniqueCodeLabel.text = self.user.secretCode //Utils.md5(string: "(\(self.user.name)\(self.user.password)\(self.user.id)") //Keyboard self.userNickNameLabel.addTarget(self, action: #selector(ProfileViewController.prepareKeyboard(_:)), forControlEvents: UIControlEvents.TouchDown ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prefersStatusBarHidden() -> Bool { return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func prepareKeyboard( sender:UITextField ) { if( !self.preparedKeyboard ) { self.preparedKeyboard = true //Keyboard. NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(ProfileViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(ProfileViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil ) } } func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) { guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return } let keyboardFrame = value.CGRectValue() let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 0) * (show ? -1 : 1) self.view.frame.offsetInPlace(dx: 0, dy: adjustmentHeight ) } func keyboardWillShow(notification: NSNotification) { if(!self.adjustedKeyboard) { self.adjustedKeyboard = true adjustInsetForKeyboardShow(true, notification: notification) } } func keyboardWillHide(notification: NSNotification) { self.adjustedKeyboard = false adjustInsetForKeyboardShow(false, notification: notification) } /*=============================================================*/ /* UI Section */ /*=============================================================*/ @IBOutlet weak var leftArrowImage: UIImageView! @IBOutlet weak var headerLabel: UILabel! @IBOutlet weak var uniqueCodeLabel: UITextField! @IBOutlet weak var userNickNameLabel: UITextField! //@IBOutlet weak var userPasswordLabel: UITextField! @IBAction func back() { //Hide keyboard. self.view.endEditing( true ) self.dismissViewControllerAnimated(true, completion: {}) } @IBAction func copyUniqueUserId() { let pasteboard = UIPasteboard.generalPasteboard() pasteboard.string = "\(uniqueCodeLabel.text!)" Utils.alertMessage( self, title:Utils.localize("notice.title"), message:Utils.localize("notice.profileCopyUniqueCode"), onAlertClose: nil ) } @IBAction func changeNick() { if( userNickNameLabel.text?.isEmpty == false ) { self.user.nick = userNickNameLabel.text! UserModel.updateNick(self.user.id, nick: self.user.nick, uniqueCode: self.uniqueCodeLabel.text!, onUpdateNick: { [weak self](isOK) in if( isOK ) { Utils.alertMessage( self!, title:Utils.localize("notice.title"), message:Utils.localize("notice.profileNickNameChanged"), onAlertClose: nil ) } else { Utils.alertMessage( self!, title:Utils.localize("error.title"), message:Utils.localize("error.profileNickNameChanged"), onAlertClose: nil ) } }) } else { Utils.alertMessage( self, title:Utils.localize("attention.title"), message:Utils.localize("attention.profileNeedField"), onAlertClose: nil ) } } @IBAction func logout(sender: UIButton) { UserModel.logout() //self.user.setProfile( "", name:"", password:"", secretCode: "" ) self.user.reset() //Hide keyboard. self.view.endEditing( true ); self.dismissViewControllerAnimated(true, completion:{ [unowned self] in self.delegate?.onProfileReady() }) } @IBAction func changePassword() { /* if( userPasswordLabel.text?.isEmpty == false ) { let userKuasars = KuasarsUser(internalToken: Utils.md5(string: self.user.password), andInternalIdentifier: self.user.name) userKuasars.changePassword(Utils.md5(string: userPasswordLabel.text!), oldPassword: Utils.md5(string: self.user.password)) { (response:KuasarsResponse!, error:KuasarsError!) -> Void in if( error != nil ) { print( "Error from kuasars \(error.description)" ) Utils.alertMessage( self, title: "Error", message: "Password wasn't changed!" ) } else { self.user.password = self.userPasswordLabel.text! self.userPasswordLabel.text = "" Utils.alertMessage( self, title: "Info", message: "Password was changed correctly!" ) } } } else { Utils.alertMessage( self, title:"Warning!", message:"You must fill this field." ) } */ } private var preparedKeyboard:Bool private var adjustedKeyboard:Bool }
apache-2.0
7ecdf74163d7c433b0752698e531a4ae
37.075117
196
0.598274
5.360212
false
false
false
false
4faramita/TweeBox
TweeBox/Entity.swift
1
1527
// // Entity.swift // TweeBox // // Created by 4faramita on 2017/8/5. // Copyright © 2017年 4faramita. All rights reserved. // import Foundation import SwiftyJSON struct Entity { typealias TweetSymbol = Hashtag public var hashtags: [Hashtag] public var urls: [TweetURL] public var userMentions: [Mention] public var symbols: [TweetSymbol] public var media: [TweetMedia]? public var realMedia: [TweetMedia]? public var mediaToShare: [TweetMedia]? public var thumbMedia: [TweetMedia]? init(with json: JSON, and extendedJson: JSON) { hashtags = json["hashtags"].arrayValue.map { Hashtag(with: $0) } urls = json["urls"].arrayValue.map { TweetURL(with: $0) } userMentions = json["user_mentions"].arrayValue.map { Mention(with: $0) } symbols = json["symbols"].arrayValue.map { TweetSymbol(with: $0) } if extendedJson.null == nil { // there exists extended_json media = extendedJson["media"].arrayValue.map { TweetMedia(with: $0, quality: MediaSize.small) } realMedia = extendedJson["media"].arrayValue.map { TweetMedia(with: $0, quality: Constants.picQuality) } mediaToShare = extendedJson["media"].arrayValue.map { TweetMedia(with: $0, quality: .nonNormal) } thumbMedia = extendedJson["media"].arrayValue.map { TweetMedia(with: $0, quality: MediaSize.thumb) } // media in extended_entities } } }
mit
5776f8bd41afe68b35e348018804010f
34.44186
116
0.624672
4.04244
false
false
false
false
maxkonovalov/MKRingProgressView
Example/ProgressRingExample/Icon.swift
1
1037
// // Icon.swift // ProgressRingExample // // Created by Max Konovalov on 22/10/2018. // Copyright © 2018 Max Konovalov. All rights reserved. // import MKRingProgressView import UIKit func generateAppIcon(scale: CGFloat = 1.0) -> UIImage { let size = CGSize(width: 512, height: 512) let rect = CGRect(origin: .zero, size: size) let icon = UIView(frame: rect) icon.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) let ring = RingProgressView(frame: icon.bounds.insetBy(dx: 66, dy: 66)) ring.ringWidth = 93 ring.startColor = #colorLiteral(red: 1, green: 0.07450980392, blue: 0.3254901961, alpha: 1) ring.endColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) ring.progress = 1.0 icon.addSubview(ring) UIGraphicsBeginImageContextWithOptions(size, true, scale) icon.drawHierarchy(in: rect, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image }
mit
f46d292dc4f144929c897ebf860bba3d
31.375
95
0.690154
3.726619
false
false
false
false
tjw/swift
stdlib/public/core/SmallString.swift
1
22844
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// internal typealias _SmallUTF16StringBuffer = _FixedArray16<UInt16> // // NOTE: Small string is not available on 32-bit platforms (not enough bits!), // but we don't want to #if-def all use sites (at least for now). So, provide a // minimal unavailable interface. // #if arch(i386) || arch(arm) // Helper method for declaring something as not supported in 32-bit. Use inside // a function body inside a #if block so that callers don't have to be // conditional. @_transparent @inlinable func unsupportedOn32bit() -> Never { _conditionallyUnreachable() } // Trivial type declaration for type checking. Never present at runtime. @_fixed_layout public struct _SmallUTF8String {} #else @_fixed_layout public // @testable struct _SmallUTF8String { typealias _RawBitPattern = (low: UInt, high: UInt) // // TODO: pretty ASCII art. // // TODO: endianess awareness day // // The low byte of the first word stores the first code unit. There is up to // 15 such code units encodable, with the second-highest byte of the second // word being the final code unit. The high byte of the final word stores the // count. // @usableFromInline var _storage: _RawBitPattern = (0,0) @inlinable @inline(__always) init() { self._storage = (0,0) } } #endif // 64-bit // // Small string creation interface // extension _SmallUTF8String { @inlinable public // @testable static var capacity: Int { return 15 } #if _runtime(_ObjC) public // @testable init?(_cocoaString cocoa: _CocoaString) { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else self.init() let len = self._withAllUnsafeMutableBytes { bufPtr -> Int? in guard let len = _bridgeASCIICocoaString(cocoa, intoUTF8: bufPtr), len <= _SmallUTF8String.capacity else { return nil } return len } guard let count = len else { return nil } _sanityCheck(self.count == 0, "overwrote count early?") self.count = count _invariantCheck() #endif } #endif // _runtime(_ObjC) @inlinable public // @testable init?<C: RandomAccessCollection>(_ codeUnits: C) where C.Element == UInt16 { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else guard codeUnits.count <= _SmallUTF8String.capacity else { return nil } // TODO(TODO: JIRA): Just implement this directly self.init() var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: codeUnits.makeIterator(), parser: Unicode.UTF16.ForwardParser() ) { guard let transcoded = Unicode.UTF8.transcode( encodedScalar, from: Unicode.UTF16.self ) else { // FIXME: can this fail with unpaired surrogates? _sanityCheckFailure("UTF-16 should be transcodable to UTF-8") return nil } _sanityCheck(transcoded.count <= 4, "how?") guard bufferIdx + transcoded.count <= _SmallUTF8String.capacity else { return nil } for i in transcoded.indices { self._uncheckedSetCodeUnit(at: bufferIdx, to: transcoded[i]) bufferIdx += 1 } } _sanityCheck(self.count == 0, "overwrote count early?") self.count = bufferIdx // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } @inlinable public // @testable init?<C: RandomAccessCollection>(_ codeUnits: C) where C.Element == UInt8 { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else let count = codeUnits.count guard count <= _SmallUTF8String.capacity else { return nil } self.init() self._withAllUnsafeMutableBytes { rawBufPtr in let bufPtr = UnsafeMutableBufferPointer( start: rawBufPtr.baseAddress.unsafelyUnwrapped.assumingMemoryBound( to: UInt8.self), count: rawBufPtr.count) var (itr, written) = codeUnits._copyContents(initializing: bufPtr) _sanityCheck(itr.next() == nil) _sanityCheck(count == written) } _sanityCheck(self.count == 0, "overwrote count early?") self.count = count // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } } // // Small string read interface // extension _SmallUTF8String { @inlinable @inline(__always) func withUTF8CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return try _withAllUnsafeBytes { bufPtr in let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try body(UnsafeBufferPointer(start: ptr, count: self.count)) } #endif } @inlinable @inline(__always) public // @testable func withTranscodedUTF16CodeUnits<Result>( _ body: (UnsafeBufferPointer<UInt16>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else var (transcoded, transcodedCount) = self.transcoded return try Swift.withUnsafeBytes(of: &transcoded.storage) { bufPtr -> Result in let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt16.self) return try body(UnsafeBufferPointer(start: ptr, count: transcodedCount)) } #endif } @inlinable @inline(__always) func withUnmanagedUTF16<Result>( _ body: (_UnmanagedString<UInt16>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return try withTranscodedUTF16CodeUnits { return try body(_UnmanagedString($0)) } #endif } @inlinable @inline(__always) func withUnmanagedASCII<Result>( _ body: (_UnmanagedString<UInt8>) throws -> Result ) rethrows -> Result { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(self.isASCII) return try withUTF8CodeUnits { return try body(_UnmanagedString($0)) } #endif } } extension _SmallUTF8String { @inlinable public // @testable // FIXME: internal(set) var count: Int { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else return Int(bitPattern: UInt(self._uncheckedCodeUnit(at: 15))) #endif } @inline(__always) set { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(newValue <= _SmallUTF8String.capacity, "out of bounds") self._uncheckedSetCodeUnit( at: 15, to: UInt8(truncatingIfNeeded: UInt(bitPattern: newValue))) #endif } } @inlinable public // @testable var capacity: Int { @inline(__always) get { return 15 } } @inlinable public // @testable var unusedCapacity: Int { @inline(__always) get { return capacity - count } } @inlinable public // @testable var isASCII: Bool { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else // TODO (TODO: JIRA): Consider using our last bit for this _sanityCheck(_uncheckedCodeUnit(at: 15) & 0xF0 == 0) let topBitMask: UInt = 0x8080_8080_8080_8080 return (_storage.low | _storage.high) & topBitMask == 0 #endif } } @inlinable func _invariantCheck() { #if arch(i386) || arch(arm) unsupportedOn32bit() #else #if INTERNAL_CHECKS_ENABLED _sanityCheck(count <= _SmallUTF8String.capacity) _sanityCheck(self.isASCII, "UTF-8 currently unsupported") #endif // INTERNAL_CHECKS_ENABLED #endif } internal func _dump() { #if arch(i386) || arch(arm) unsupportedOn32bit() #else #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.dropLast() ) """) #endif // INTERNAL_CHECKS_ENABLED #endif } @inlinable // FIXME(sil-serialize-all) internal func _copy<TargetCodeUnit>( into target: UnsafeMutableBufferPointer<TargetCodeUnit> ) where TargetCodeUnit : FixedWidthInteger & UnsignedInteger { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(target.count >= self.count) guard count > 0 else { return } if _fastPath(TargetCodeUnit.bitWidth == 8) { _sanityCheck(TargetCodeUnit.self == UInt8.self) let target = _castBufPtr(target, to: UInt8.self) // TODO: Inspect generated code. Consider checking count for alignment so // we can just copy our UInts directly when possible. var ptr = target.baseAddress._unsafelyUnwrappedUnchecked for cu in self { ptr[0] = cu ptr += 1 } return } _sanityCheck(TargetCodeUnit.self == UInt16.self) self.transcode(_uncheckedInto: _castBufPtr(target, to: UInt16.self)) #endif } } extension _SmallUTF8String: RandomAccessCollection { public // @testable typealias Index = Int public // @testable typealias Element = UInt8 public // @testable typealias SubSequence = _SmallUTF8String @inlinable public // @testable var startIndex: Int { @inline(__always) get { return 0 } } @inlinable public // @testable var endIndex: Int { @inline(__always) get { return count } } @inlinable public // @testable subscript(_ idx: Int) -> UInt8 { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(idx >= 0 && idx <= count) return _uncheckedCodeUnit(at: idx) #endif } @inline(__always) set { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(idx >= 0 && idx <= count) _uncheckedSetCodeUnit(at: idx, to: newValue) #endif } } @inlinable public // @testable subscript(_ bounds: Range<Index>) -> SubSequence { @inline(__always) get { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(bounds.lowerBound >= 0 && bounds.upperBound <= count) return self._uncheckedClamp( lowerBound: bounds.lowerBound, upperBound: bounds.upperBound) #endif } } } extension _SmallUTF8String { @inlinable public // @testable func _repeated(_ n: Int) -> _SmallUTF8String? { #if arch(i386) || arch(arm) unsupportedOn32bit() #else _sanityCheck(n > 1) let finalCount = self.count * n guard finalCount <= 15 else { return nil } var ret = self for _ in 0..<(n &- 1) { ret = ret._appending(self)._unsafelyUnwrappedUnchecked } return ret #endif } @inlinable public // @testable func _appending<C: RandomAccessCollection>(_ other: C) -> _SmallUTF8String? where C.Element == UInt8 { #if arch(i386) || arch(arm) unsupportedOn32bit() #else guard other.count <= self.unusedCapacity else { return nil } // TODO: as _copyContents var result = self result._withMutableExcessCapacityBytes { rawBufPtr in var i = 0 for cu in other { rawBufPtr[i] = cu i += 1 } } result.count = self.count &+ other.count return result #endif } @inlinable func _appending<C: RandomAccessCollection>(_ other: C) -> _SmallUTF8String? where C.Element == UInt16 { #if arch(i386) || arch(arm) unsupportedOn32bit() #else guard other.count <= self.unusedCapacity else { return nil } // TODO: as _copyContents var result = self let success = result._withMutableExcessCapacityBytes { rawBufPtr -> Bool in var i = 0 for cu in other { guard cu <= 0x7F else { // TODO: transcode and communicate count back return false } rawBufPtr[i] = UInt8(truncatingIfNeeded: cu) i += 1 } return true } guard success else { return nil } result.count = self.count &+ other.count return result #endif } // NOTE: This exists to facilitate _fromCodeUnits, which is awful for this use // case. Please don't call this from anywhere else. @usableFromInline @inline(never) // @outlined // @_specialize(where Encoding == UTF16) // @_specialize(where Encoding == UTF8) init?<S: Sequence, Encoding: Unicode.Encoding>( _fromCodeUnits codeUnits: S, utf16Length: Int, isASCII: Bool, _: Encoding.Type = Encoding.self ) where S.Element == Encoding.CodeUnit { #if arch(i386) || arch(arm) return nil // Never form small strings on 32-bit #else guard utf16Length <= 15 else { return nil } // TODO: transcode guard isASCII else { return nil } self.init() var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: codeUnits.makeIterator(), parser: Encoding.ForwardParser() ) { guard let transcoded = Unicode.UTF8.transcode( encodedScalar, from: Encoding.self ) else { fatalError("Somehow un-transcodable?") } _sanityCheck(transcoded.count <= 4, "how?") guard bufferIdx + transcoded.count <= 15 else { return nil } for i in transcoded.indices { self._uncheckedSetCodeUnit(at: bufferIdx, to: transcoded[i]) bufferIdx += 1 } } _sanityCheck(self.count == 0, "overwrote count early?") self.count = bufferIdx // FIXME: support transcoding if !self.isASCII { return nil } _invariantCheck() #endif } } extension _SmallUTF8String { #if arch(i386) || arch(arm) @_fixed_layout @usableFromInline struct UnicodeScalarIterator { @inlinable @inline(__always) func next() -> Unicode.Scalar? { unsupportedOn32bit() } } @inlinable @inline(__always) func makeUnicodeScalarIterator() -> UnicodeScalarIterator { unsupportedOn32bit() } #else // FIXME (TODO: JIRA): Just make a real decoding iterator @_fixed_layout @usableFromInline // FIXME(sil-serialize-all) struct UnicodeScalarIterator { @usableFromInline // FIXME(sil-serialize-all) var buffer: _SmallUTF16StringBuffer @usableFromInline // FIXME(sil-serialize-all) var count: Int @usableFromInline // FIXME(sil-serialize-all) var _offset: Int @inlinable // FIXME(sil-serialize-all) init(_ base: _SmallUTF8String) { (self.buffer, self.count) = base.transcoded self._offset = 0 } @inlinable // FIXME(sil-serialize-all) mutating func next() -> Unicode.Scalar? { if _slowPath(_offset == count) { return nil } let u0 = buffer[_offset] if _fastPath(UTF16._isScalar(u0)) { _offset += 1 return Unicode.Scalar(u0) } if UTF16.isLeadSurrogate(u0) && _offset + 1 < count { let u1 = buffer[_offset + 1] if UTF16.isTrailSurrogate(u1) { _offset += 2 return UTF16._decodeSurrogates(u0, u1) } } _offset += 1 return Unicode.Scalar._replacementCharacter } } @inlinable func makeUnicodeScalarIterator() -> UnicodeScalarIterator { return UnicodeScalarIterator(self) } #endif // 64-bit } #if arch(i386) || arch(arm) #else extension _SmallUTF8String { @inlinable @inline(__always) init(_rawBits: _RawBitPattern) { self._storage.low = _rawBits.low self._storage.high = _rawBits.high _invariantCheck() } @inlinable @inline(__always) init(low: UInt, high: UInt, count: Int) { self.init() self._storage.low = low self._storage.high = high self.count = count _invariantCheck() } @inlinable internal var _rawBits: _RawBitPattern { @inline(__always) get { return _storage } } @inlinable internal var lowUnpackedBits: UInt { @inline(__always) get { return _storage.low } } @inlinable internal var highUnpackedBits: UInt { @inline(__always) get { return _storage.high & 0x00FF_FFFF_FFFF_FFFF } } @inlinable internal var unpackedBits: (low: UInt, high: UInt, count: Int) { @inline(__always) get { return (lowUnpackedBits, highUnpackedBits, count) } } } extension _SmallUTF8String { // Operate with a pointer to the entire struct, including unused capacity // and inline count. You should almost never call this directly. @inlinable @inline(__always) mutating func _withAllUnsafeMutableBytes<Result>( _ body: (UnsafeMutableRawBufferPointer) throws -> Result ) rethrows -> Result { var copy = self defer { self = copy } return try Swift.withUnsafeMutableBytes(of: &copy._storage) { try body($0) } } @inlinable @inline(__always) func _withAllUnsafeBytes<Result>( _ body: (UnsafeRawBufferPointer) throws -> Result ) rethrows -> Result { var copy = self return try Swift.withUnsafeBytes(of: &copy._storage) { try body($0) } } @inlinable @inline(__always) mutating func _withMutableExcessCapacityBytes<Result>( _ body: (UnsafeMutableRawBufferPointer) throws -> Result ) rethrows -> Result { let unusedCapacity = self.unusedCapacity let count = self.count return try self._withAllUnsafeMutableBytes { allBufPtr in let ptr = allBufPtr.baseAddress._unsafelyUnwrappedUnchecked + count return try body( UnsafeMutableRawBufferPointer(start: ptr, count: unusedCapacity)) } } } extension _SmallUTF8String { @inlinable @inline(__always) func _uncheckedCodeUnit(at i: Int) -> UInt8 { _sanityCheck(i >= 0 && i <= 15) if i < 8 { return _storage.low._uncheckedGetByte(at: i) } else { return _storage.high._uncheckedGetByte(at: i &- 8) } } @inlinable @inline(__always) mutating func _uncheckedSetCodeUnit(at i: Int, to: UInt8) { // TODO(TODO: JIRA): in-register operation instead self._withAllUnsafeMutableBytes { $0[i] = to } } } extension _SmallUTF8String { @inlinable @inline(__always) internal func _uncheckedClamp(upperBound: Int) -> _SmallUTF8String { _sanityCheck(upperBound <= self.count) guard upperBound >= 8 else { var low = self.lowUnpackedBits let shift = upperBound &* 8 let mask: UInt = (1 &<< shift) &- 1 low &= mask return _SmallUTF8String(low: low, high: 0, count: upperBound) } let shift = (upperBound &- 8) &* 8 _sanityCheck(shift % 8 == 0) var high = self.highUnpackedBits high &= (1 &<< shift) &- 1 return _SmallUTF8String( low: self.lowUnpackedBits, high: high, count: upperBound) } @inlinable @inline(__always) internal func _uncheckedClamp(lowerBound: Int) -> _SmallUTF8String { _sanityCheck(lowerBound < self.count) let low: UInt let high: UInt if lowerBound < 8 { let shift: UInt = UInt(bitPattern: lowerBound) &* 8 let newLowHigh: UInt = self.highUnpackedBits & ((1 &<< shift) &- 1) low = (self.lowUnpackedBits &>> shift) | (newLowHigh &<< (64 &- shift)) high = self.highUnpackedBits &>> shift } else { high = 0 low = self.highUnpackedBits &>> ((lowerBound &- 8) &* 8) } return _SmallUTF8String( low: low, high: high, count: self.count &- lowerBound) } @inlinable @inline(__always) internal func _uncheckedClamp( lowerBound: Int, upperBound: Int ) -> _SmallUTF8String { // TODO: More efficient to skip the intermediary shifts and just mask up // front. _sanityCheck(upperBound >= lowerBound) if lowerBound == upperBound { return _SmallUTF8String() } let dropTop = self._uncheckedClamp(upperBound: upperBound) return dropTop._uncheckedClamp(lowerBound: lowerBound) } } extension _SmallUTF8String {//}: _StringVariant { typealias TranscodedBuffer = _SmallUTF16StringBuffer @inlinable @discardableResult func transcode( _uncheckedInto buffer: UnsafeMutableBufferPointer<UInt16> ) -> Int { if _fastPath(isASCII) { _sanityCheck(buffer.count >= self.count) var bufferIdx = 0 for cu in self { buffer[bufferIdx] = UInt16(cu) bufferIdx += 1 } return bufferIdx } let length = _transcodeNonASCII(_uncheckedInto: buffer) _sanityCheck(length <= buffer.count) // TODO: assert ahead-of-time return length } @inlinable @inline(__always) func transcode(into buffer: UnsafeMutablePointer<TranscodedBuffer>) -> Int { let ptr = UnsafeMutableRawPointer(buffer).assumingMemoryBound( to: UInt16.self) return transcode( _uncheckedInto: UnsafeMutableBufferPointer(start: ptr, count: count)) } @inlinable var transcoded: (TranscodedBuffer, count: Int) { @inline(__always) get { // TODO: in-register zero-extension for ascii var buffer = TranscodedBuffer(allZeros:()) let count = transcode(into: &buffer) return (buffer, count: count) } } @usableFromInline @inline(never) // @outlined func _transcodeNonASCII( _uncheckedInto buffer: UnsafeMutableBufferPointer<UInt16> ) -> Int { _sanityCheck(!isASCII) // TODO(TODO: JIRA): Just implement this directly var bufferIdx = 0 for encodedScalar in Unicode._ParsingIterator( codeUnits: self.makeIterator(), parser: Unicode.UTF8.ForwardParser() ) { guard let transcoded = Unicode.UTF16.transcode( encodedScalar, from: Unicode.UTF8.self ) else { fatalError("Somehow un-transcodable?") } switch transcoded.count { case 1: buffer[bufferIdx] = transcoded.first! bufferIdx += 1 case 2: buffer[bufferIdx] = transcoded.first! buffer[bufferIdx+1] = transcoded.dropFirst().first! bufferIdx += 2 case _: fatalError("Somehow, not transcoded or more than 2?") } } _sanityCheck(bufferIdx <= buffer.count) // TODO: assert earlier return bufferIdx } } @inlinable @inline(__always) internal func _castBufPtr<A, B>( _ bufPtr: UnsafeMutableBufferPointer<A>, to: B.Type = B.self ) -> UnsafeMutableBufferPointer<B> { let numBytes = bufPtr.count &* MemoryLayout<A>.stride _sanityCheck(numBytes % MemoryLayout<B>.stride == 0) let ptr = UnsafeMutableRawPointer( bufPtr.baseAddress._unsafelyUnwrappedUnchecked ).assumingMemoryBound(to: B.self) let count = numBytes / MemoryLayout<B>.stride return UnsafeMutableBufferPointer(start: ptr, count: count) } #endif // 64-bit extension UInt { // Fetches the `i`th byte, from least-significant to most-significant // // TODO: endianess awareness day @inlinable @inline(__always) func _uncheckedGetByte(at i: Int) -> UInt8 { _sanityCheck(i >= 0 && i < MemoryLayout<UInt>.stride) let shift = UInt(bitPattern: i) &* 8 return UInt8(truncatingIfNeeded: (self &>> shift)) } }
apache-2.0
25e7ead4b881dd925dc9e922957343b2
26.995098
80
0.650893
4.09244
false
false
false
false