repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
darwin/textyourmom
refs/heads/master
TextYourMom/Brain.swift
mit
1
import UIKit protocol BrainDelegate { func remindCallMomFromAirport(city:String, _ airportName:String) } class Brain { var delegate: BrainDelegate? var state = AirportsVisitorState() init() { } func reportAirportVisit(airportId: AirportId) { if let airport = masterController.airportsProvider.lookupAirport(airportId) { model.lastReportedAirport = airport.name delegate?.remindCallMomFromAirport(airport.city, airport.name) } else { log("unable to lookup airport #\(airportId)") } } } // MARK: AirportsWatcherDelegate extension Brain : AirportsWatcherDelegate { func visitorPotentialChangeInState(newState: AirportsVisitorState) { let diff = AirportsVisitorStateDiff(oldState:state, newState:newState) if diff.empty { return } log("brain: state changed \(diff)") state = newState // new state should be stored in the model model.visitorState = state.serialize() if supressNextStateChangeReport { log("supressNextStateChangeReport active => bail out") supressNextStateChangeReport = false return } // we are only interested in airports where user was suddenly teleported in // in other words: the airport state changed from .None to .Inner var candidates = [AirportId]() for (id, change) in diff.diff { if change.before == .None && change.after == .Inner { candidates.append(id) } } if candidates.count == 0 { log(" no teleportations detected => bail out") return } // in case we got multiple simultaneous teleportations // report only airport with lowest id candidates.sort({$0 < $1}) log(" got candidates \(candidates), reporting the first one") reportAirportVisit(candidates[0]) } }
350193d814dfe4a176bc113680458493
28.542857
85
0.59381
false
false
false
false
ParsePlatform/Parse-SDK-iOS-OSX
refs/heads/master
ParseUI/ParseUIDemo/Swift/CustomViewControllers/QueryCollectionViewController/DeletionCollectionViewController.swift
bsd-3-clause
1
// // DeletionCollectionViewController.swift // ParseUIDemo // // Created by Richard Ross III on 5/14/15. // Copyright (c) 2015 Parse Inc. All rights reserved. // import UIKit import Parse import ParseUI import Bolts.BFTask class DeletionCollectionViewController: PFQueryCollectionViewController, UIAlertViewDelegate { convenience init(className: String?) { let layout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsetsMake(0.0, 10.0, 0.0, 10.0) layout.minimumInteritemSpacing = 5.0 self.init(collectionViewLayout: layout, className: className) title = "Deletion Collection" pullToRefreshEnabled = true objectsPerPage = 10 paginationEnabled = true collectionView?.allowsMultipleSelection = true navigationItem.rightBarButtonItems = [ editButtonItem, UIBarButtonItem(barButtonSystemItem: .add, target: self, action:#selector(addTodo)) ] } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let layout = collectionViewLayout as? UICollectionViewFlowLayout { let bounds = UIEdgeInsetsInsetRect(view.bounds, layout.sectionInset) let sideLength = min(bounds.width, bounds.height) / 2.0 - layout.minimumInteritemSpacing layout.itemSize = CGSize(width: sideLength, height: sideLength) } } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) if (editing) { navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .trash, target: self, action: #selector(deleteSelectedItems) ) } else { navigationItem.leftBarButtonItem = navigationItem.backBarButtonItem } } @objc func addTodo() { if #available(iOS 8.0, *) { let alertDialog = UIAlertController(title: "Add Todo", message: nil, preferredStyle: .alert) var titleTextField : UITextField? = nil alertDialog.addTextField(configurationHandler: { titleTextField = $0 }) alertDialog.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertDialog.addAction(UIAlertAction(title: "Save", style: .default) { action in if let title = titleTextField?.text { let object = PFObject(className: self.parseClassName!, dictionary: [ "title": title ]) object.saveEventually().continueOnSuccessWith { _ -> AnyObject! in return self.loadObjects() } } }) present(alertDialog, animated: true, completion: nil) } else { let alertView = UIAlertView( title: "Add Todo", message: "", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Save" ) alertView.alertViewStyle = .plainTextInput alertView.textField(at: 0)?.placeholder = "Name" alertView.show() } } @objc func deleteSelectedItems() { guard let paths = collectionView?.indexPathsForSelectedItems else { return } removeObjects(at: paths) } // MARK - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath, object: PFObject?) -> PFCollectionViewCell? { let cell = super.collectionView(collectionView, cellForItemAt: indexPath, object: object) cell?.textLabel.textAlignment = .center cell?.textLabel.text = object?["title"] as? String cell?.contentView.layer.borderWidth = 1.0 cell?.contentView.layer.borderColor = UIColor.lightGray.cgColor return cell } // MARK - UIAlertViewDelegate @objc func alertView(_ alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) { if (buttonIndex == alertView.cancelButtonIndex) { return } if let title = alertView.textField(at: 0)?.text { let object = PFObject( className: self.parseClassName!, dictionary: [ "title": title ] ) object.saveEventually().continueOnSuccessWith { _ -> AnyObject! in return self.loadObjects() } } } }
1e6d7ea20297c66462bcf18867958f37
32.588235
150
0.610552
false
false
false
false
Ben21hao/edx-app-ios-new
refs/heads/master
Source/DiscussionNewPostViewController.swift
apache-2.0
1
// // DiscussionNewPostViewController.swift // edX // // Created by Tang, Jeff on 6/1/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct DiscussionNewThread { let courseID: String let topicID: String let type: DiscussionThreadType let title: String let rawBody: String } protocol DiscussionNewPostViewControllerDelegate : class { func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread) } public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding { public typealias Environment = protocol<DataManagerProvider, NetworkManagerProvider, OEXRouterProvider, OEXAnalyticsProvider> private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text private let environment: Environment private let growingTextController = GrowingTextViewController() private let insetsController = ContentInsetsController() @IBOutlet private var scrollView: UIScrollView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var contentTextView: OEXPlaceholderTextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl! @IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var topicButton: UIButton! @IBOutlet private var postButton: SpinnerButton! @IBOutlet weak var contentTitleLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! private let loadController = LoadStateViewController() private let courseID: String private let topics = BackedStream<[DiscussionTopic]>() private var selectedTopic: DiscussionTopic? private var optionsViewController: MenuOptionsViewController? weak var delegate: DiscussionNewPostViewControllerDelegate? private let tapButton = UIButton() var titleTextStyle : OEXTextStyle{ return OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) } private var selectedThreadType: DiscussionThreadType = .Discussion { didSet { switch selectedThreadType { case .Discussion: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.courseDashboardDiscussion), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion) contentTextView.accessibilityLabel = Strings.courseDashboardDiscussion case .Question: self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.question), titleTextStyle.attributedStringWithText(Strings.asteric)]) postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: Strings.postQuestion) contentTextView.accessibilityLabel = Strings.question } } } public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) { self.environment = environment self.courseID = courseID super.init(nibName: "DiscussionNewPostViewController", bundle: nil) let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) self.selectedTopic = selectedTopic } private var firstSelectableTopic : DiscussionTopic? { let selectablePredicate = { (topic : DiscussionTopic) -> Bool in topic.isSelectable } guard let topics = self.topics.value, selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else { return nil } return topics[selectableTopicIndex] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func postTapped(sender: AnyObject) { postButton.enabled = false postButton.showProgress = true // create new thread (post) if let topic = selectedTopic, topicID = topic.id { let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text ?? "", rawBody: contentTextView.text) let apiRequest = DiscussionAPI.createNewThread(newThread) environment.networkManager.taskForRequest(apiRequest) {[weak self] result in self?.postButton.enabled = true self?.postButton.showProgress = false if let post = result.data { self?.delegate?.newPostController(self!, addedPost: post) self?.dismissViewControllerAnimated(true, completion: nil) } else { DiscussionHelper.showErrorMessage(self, error: result.error) } } } } override public func viewDidLoad() { super.viewDidLoad() self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "OpenSans", size: 18.0)!] self.navigationItem.title = Strings.post let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil) cancelItem.oex_setAction { [weak self]() -> Void in self?.dismissViewControllerAnimated(true, completion: nil) } self.navigationItem.leftBarButtonItem = cancelItem contentTitleLabel.isAccessibilityElement = false titleLabel.isAccessibilityElement = false titleLabel.attributedText = NSAttributedString.joinInNaturalLayout([titleTextStyle.attributedStringWithText(Strings.title), titleTextStyle.attributedStringWithText(Strings.asteric)]) contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight() contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) contentTextView.delegate = self titleTextField.accessibilityLabel = Strings.title self.view.backgroundColor = OEXStyles.sharedStyles().baseColor5() configureSegmentControl() titleTextField.defaultTextAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes setTopicsButtonTitle() let insets = OEXStyles.sharedStyles().standardTextViewInsets topicButton.titleEdgeInsets = UIEdgeInsetsMake(0, insets.left, 0, insets.right) topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint topicButton.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) topicButton.localizedHorizontalContentAlignment = .Leading let dropdownLabel = UILabel() dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(titleTextStyle) topicButton.addSubview(dropdownLabel) dropdownLabel.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(topicButton).offset(-insets.right) make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0) } topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in self?.showTopicPicker() }, forEvents: UIControlEvents.TouchUpInside) postButton.enabled = false titleTextField.oex_addAction({[weak self] _ in self?.validatePostButton() }, forEvents: .EditingChanged) self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: postButton) self.insetsController.setupInController(self, scrollView: scrollView) // Force setting it to call didSet which is only called out of initialization context self.selectedThreadType = .Question loadController.setupInController(self, contentView: self.scrollView) topics.listen(self, success : {[weak self]_ in self?.loadedData() }, failure : {[weak self] error in self?.loadController.state = LoadState.failed(error) }) backgroundView.addSubview(tapButton) backgroundView.sendSubviewToBack(tapButton) tapButton.backgroundColor = UIColor.clearColor() tapButton.frame = CGRectMake(0, 0, backgroundView.frame.size.width, backgroundView.frame.size.height) tapButton.isAccessibilityElement = false tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard tapButton.oex_addAction({[weak self] (sender) in self?.view.endEditing(true) }, forEvents: .TouchUpInside) } private func configureSegmentControl() { discussionQuestionSegmentedControl.removeAllSegments() let questionIcon = Icon.Question.attributedTextWithStyle(titleTextStyle) let questionTitle = NSAttributedString.joinInNaturalLayout([questionIcon, titleTextStyle.attributedStringWithText(Strings.question)]) let discussionIcon = Icon.Comments.attributedTextWithStyle(titleTextStyle) let discussionTitle = NSAttributedString.joinInNaturalLayout([discussionIcon, titleTextStyle.attributedStringWithText(Strings.discussion)]) let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [ (title : questionTitle, value : .Question), (title : discussionTitle, value : .Discussion), ] for i in 0..<segmentOptions.count { discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(segmentOptions[i].title, index: i, animated: false) discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string } discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in if let segmentedControl = control as? UISegmentedControl { let index = segmentedControl.selectedSegmentIndex let threadType = segmentOptions[index].value self?.selectedThreadType = threadType self?.updateSelectedTabColor() } else { assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum") } }, forEvents: UIControlEvents.ValueChanged) discussionQuestionSegmentedControl.tintColor = OEXStyles.sharedStyles().neutralDark() discussionQuestionSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName: OEXStyles.sharedStyles().neutralWhite()], forState: UIControlState.Selected) discussionQuestionSegmentedControl.selectedSegmentIndex = 0 updateSelectedTabColor() } private func updateSelectedTabColor() { // //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour let subViews:NSArray = discussionQuestionSegmentedControl.subviews for i in 0..<subViews.count { if subViews.objectAtIndex(i).isSelected ?? false { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().primaryBaseColor() } else { let view = subViews.objectAtIndex(i) as! UIView view.tintColor = OEXStyles.sharedStyles().neutralDark() } } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.environment.analytics.trackDiscussionScreenWithName(OEXAnalyticsScreenCreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil) } override public func shouldAutorotate() -> Bool { return true } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } private func loadedData() { loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded if selectedTopic == nil { selectedTopic = firstSelectableTopic } setTopicsButtonTitle() } private func setTopicsButtonTitle() { if let topic = selectedTopic, name = topic.name { let title = Strings.topic(topic: name) topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal) } } func showTopicPicker() { if self.optionsViewController != nil { return } view.endEditing(true) self.optionsViewController = MenuOptionsViewController() self.optionsViewController?.delegate = self guard let courseTopics = topics.value else { //Don't need to configure an empty state here because it's handled in viewDidLoad() return } self.optionsViewController?.options = courseTopics.map { return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "") } self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex() self.view.addSubview(self.optionsViewController!.view) self.optionsViewController!.view.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.topicButton) make.leading.equalTo(self.topicButton) make.top.equalTo(self.topicButton.snp_bottom).offset(-3) // make.bottom.equalTo(self.view.snp_bottom) make.height.equalTo((self.optionsViewController?.options.count)! * 30) } self.optionsViewController?.view.alpha = 0.0 UIView.animateWithDuration(0.3) { self.optionsViewController?.view.alpha = 1.0 } } private func selectedTopicIndex() -> Int? { guard let selected = selectedTopic else { return 0 } return self.topics.value?.firstIndexMatching { return $0.id == selected.id } } public func textViewDidChange(textView: UITextView) { validatePostButton() growingTextController.handleTextChange() } public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool { return self.topics.value?[index].isSelectable ?? false } private func validatePostButton() { self.postButton.enabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil } func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) { selectedTopic = self.topics.value?[index] if let topic = selectedTopic where topic.id != nil { setTopicsButtonTitle() UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, titleTextField); UIView.animateWithDuration(0.3, animations: { self.optionsViewController?.view.alpha = 0.0 }, completion: {[weak self](finished: Bool) in self?.optionsViewController?.view.removeFromSuperview() self?.optionsViewController = nil }) } } public override func viewDidLayoutSubviews() { self.insetsController.updateInsets() growingTextController.scrollToVisible() } func textFieldDidBeginEditing(textField: UITextField) { tapButton.isAccessibilityElement = true } func textFieldDidEndEditing(textField: UITextField) { tapButton.isAccessibilityElement = false } public func textViewDidBeginEditing(textView: UITextView) { tapButton.isAccessibilityElement = true } public func textViewDidEndEditing(textView: UITextView) { tapButton.isAccessibilityElement = false } } extension UISegmentedControl { //UIsegmentControl didn't support attributedTitle by default func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) { let segmentLabel = UILabel() segmentLabel.backgroundColor = UIColor.clearColor() segmentLabel.textAlignment = .Center segmentLabel.attributedText = title segmentLabel.sizeToFit() self.insertSegmentWithImage(segmentLabel.toImage(), atIndex: 1, animated: false) } } extension UILabel { func toImage()-> UIImage? { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image; } } // For use in testing only extension DiscussionNewPostViewController { public func t_topicsLoaded() -> Stream<[DiscussionTopic]> { return topics } }
0341bcdd4e372b498ba0495a7e4b2cf9
43.102439
230
0.681506
false
false
false
false
optimizely/swift-sdk
refs/heads/master
Sources/Optimizely/OptimizelyError.swift
apache-2.0
1
// // Copyright 2019-2021, Optimizely, Inc. and contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public enum OptimizelyError: Error { case generic // MARK: - Decision errors case sdkNotReady case featureKeyInvalid(_ key: String) case variableValueInvalid(_ key: String) case invalidJSONVariable // MARK: - Experiment case experimentKeyInvalid(_ key: String) case experimentIdInvalid(_ id: String) case experimentHasNoTrafficAllocation(_ key: String) case variationKeyInvalid(_ expKey: String, _ varKey: String) case variationIdInvalid(_ expKey: String, _ varKey: String) case variationUnknown(_ userId: String, _ key: String) case variableKeyInvalid(_ varKey: String, _ feature: String) case eventKeyInvalid(_ key: String) case eventBuildFailure(_ key: String) case eventTagsFormatInvalid case attributesKeyInvalid(_ key: String) case attributeValueInvalid(_ key: String) case attributeFormatInvalid case groupIdInvalid(_ id: String) case groupHasNoTrafficAllocation(_ key: String) case rolloutIdInvalid(_ id: String, _ feature: String) // MARK: - Audience Evaluation case conditionNoMatchingAudience(_ id: String) case conditionInvalidFormat(_ hint: String) case conditionCannotBeEvaluated(_ hint: String) case evaluateAttributeInvalidCondition(_ condition: String) case evaluateAttributeInvalidType(_ condition: String, _ value: Any, _ key: String) case evaluateAttributeValueOutOfRange(_ condition: String, _ key: String) case evaluateAttributeInvalidFormat(_ hint: String) case userAttributeInvalidType(_ condition: String) case userAttributeInvalidMatch(_ condition: String) case userAttributeNilValue(_ condition: String) case userAttributeInvalidName(_ condition: String) case nilAttributeValue(_ condition: String, _ key: String) case missingAttributeValue(_ condition: String, _ key: String) // MARK: - Bucketing case userIdInvalid case bucketingIdInvalid(_ id: UInt64) case userProfileInvalid // MARK: - Datafile Errors case datafileDownloadFailed(_ hint: String) case dataFileInvalid case dataFileVersionInvalid(_ version: String) case datafileSavingFailed(_ hint: String) case datafileLoadingFailed(_ hint: String) // MARK: - EventDispatcher Errors case eventDispatchFailed(_ reason: String) case eventDispatcherConfigError(_ reason: String) // MARK: - AudienceSegements Errors case invalidSegmentIdentifier case fetchSegmentsFailed(_ hint: String) case odpEventFailed(_ hint: String, _ canRetry: Bool) case odpNotIntegrated case odpNotEnabled case odpInvalidData } // MARK: - CustomStringConvertible extension OptimizelyError: CustomStringConvertible, ReasonProtocol { public var description: String { return "[Optimizely][Error] " + self.reason } public var localizedDescription: String { return description } var reason: String { var message: String switch self { case .generic: message = "Unknown reason." // DO NOT CHANGE these critical error messages - FSC will validate exact-wordings of these messages. case .sdkNotReady: message = "Optimizely SDK not configured properly yet." case .featureKeyInvalid(let key): message = "No flag was found for key \"\(key)\"." case .variableValueInvalid(let key): message = "Variable value for key \"\(key)\" is invalid or wrong type." case .invalidJSONVariable: message = "Invalid variables for OptimizelyJSON." // These error messages not validated by FSC case .experimentKeyInvalid(let key): message = "Experiment key (\(key)) is not in datafile. It is either invalid, paused, or archived." case .experimentIdInvalid(let id): message = "Experiment ID (\(id)) is not in datafile." case .experimentHasNoTrafficAllocation(let key): message = "No traffic allocation rules are defined for experiment (\(key))." case .variationKeyInvalid(let expKey, let varKey): message = "No variation key (\(varKey)) defined in datafile for experiment (\(expKey))." case .variationIdInvalid(let expKey, let varId): message = "No variation ID (\(varId)) defined in datafile for experiment (\(expKey))." case .variationUnknown(let userId, let key): message = "User (\(userId)) does not meet conditions to be in experiment/feature (\(key))." case .variableKeyInvalid(let varKey, let feature): message = "Variable with key (\(varKey)) associated with feature with key (\(feature)) is not in datafile." case .eventKeyInvalid(let key): message = "Event key (\(key)) is not in datafile." case .eventBuildFailure(let key): message = "Failed to create a dispatch event (\(key))" case .eventTagsFormatInvalid: message = "Provided event tags are in an invalid format." case .attributesKeyInvalid(let key): message = "Attribute key (\(key)) is not in datafile." case .attributeValueInvalid(let key): message = "Attribute value for (\(key)) is invalid." case .attributeFormatInvalid: message = "Provided attributes are in an invalid format." case .groupIdInvalid(let id): message = "Group ID (\(id)) is not in datafile." case .groupHasNoTrafficAllocation(let id): message = "No traffic allocation rules are defined for group (\(id))." case .rolloutIdInvalid(let id, let feature): message = "Invalid rollout ID (\(id)) attached to feature (\(feature))." case .conditionNoMatchingAudience(let id): message = "Audience (\(id)) is not in datafile." case .conditionInvalidFormat(let hint): message = "Condition has an invalid format (\(hint))." case .conditionCannotBeEvaluated(let hint): message = "Condition cannot be evaluated (\(hint))." case .evaluateAttributeInvalidCondition(let condition): message = "Audience condition (\(condition)) has an unsupported condition value. You may need to upgrade to a newer release of the Optimizely SDK." case .evaluateAttributeInvalidType(let condition, let value, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a value of type (\(value)) was passed for user attribute (\(key))." case .evaluateAttributeValueOutOfRange(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because the number value for user attribute (\(key)) is not in the range [-2^53, +2^53]." case .evaluateAttributeInvalidFormat(let hint): message = "Evaluation attribute has an invalid format (\(hint))." case .userAttributeInvalidType(let condition): message = "Audience condition (\(condition)) uses an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK." case .userAttributeInvalidMatch(let condition): message = "Audience condition (\(condition)) uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK." case .userAttributeNilValue(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of null value." case .userAttributeInvalidName(let condition): message = "Audience condition (\(condition)) evaluated to UNKNOWN because of invalid attribute name." case .nilAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because a null value was passed for user attribute (\(key))." case .missingAttributeValue(let condition, let key): message = "Audience condition (\(condition)) evaluated to UNKNOWN because no value was passed for user attribute (\(key))." case .userIdInvalid: message = "Provided user ID is in an invalid format." case .bucketingIdInvalid(let id): message = "Invalid bucketing ID (\(id))." case .userProfileInvalid: message = "Provided user profile object is invalid." case .datafileDownloadFailed(let hint): message = "Datafile download failed (\(hint))." case .dataFileInvalid: message = "Provided datafile is in an invalid format." case .dataFileVersionInvalid(let version): message = "Provided datafile version (\(version)) is not supported." case .datafileSavingFailed(let hint): message = "Datafile save failed (\(hint))." case .datafileLoadingFailed(let hint): message = "Datafile load failed (\(hint))." case .eventDispatchFailed(let hint): message = "Event dispatch failed (\(hint))." case .eventDispatcherConfigError(let hint): message = "EventDispatcher config error (\(hint))." case .invalidSegmentIdentifier: message = "Audience segments fetch failed (invalid identifier)" case .fetchSegmentsFailed(let hint): message = "Audience segments fetch failed (\(hint))." case .odpEventFailed(let hint, _): message = "ODP event send failed (\(hint))." case .odpNotIntegrated: message = "ODP is not integrated." case .odpNotEnabled: message = "ODP is not enabled." case .odpInvalidData: message = "ODP data is not valid." } return message } } // MARK: - LocalizedError (ObjC NSError) extension OptimizelyError: LocalizedError { public var errorDescription: String? { return self.reason } }
91db27c2c871e8655a1b1ccca69eeab7
59.207865
229
0.65606
false
false
false
false
jdkelley/Udacity-OnTheMap-ExampleApps
refs/heads/master
TheMovieManager-v1/TheMovieManager/TMDBAuthViewController.swift
mit
1
// // TMDBAuthViewController.swift // TheMovieManager // // Created by Jarrod Parkes on 2/11/15. // Copyright (c) 2015 Jarrod Parkes. All rights reserved. // import UIKit // MARK: - TMDBAuthViewController: UIViewController class TMDBAuthViewController: UIViewController { // MARK: Properties var urlRequest: NSURLRequest? = nil var requestToken: String? = nil var completionHandlerForView: ((success: Bool, errorString: String?) -> Void)? = nil // MARK: Outlets @IBOutlet weak var webView: UIWebView! // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() webView.delegate = self navigationItem.title = "TheMovieDB Auth" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: #selector(cancelAuth)) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) auth() } func auth() { if let urlRequest = urlRequest { webView.loadRequest(urlRequest) } } // MARK: Cancel Auth Flow func cancelAuth() { dismissViewControllerAnimated(true, completion: nil) } } // MARK: - TMDBAuthViewController: UIWebViewDelegate extension TMDBAuthViewController: UIWebViewDelegate { func webViewDidFinishLoad(webView: UIWebView) { if webView.request?.URL!.absoluteString == "\(TMDBClient.Constants.AuthorizationURL)\(requestToken!)\(TMDBClient.Methods.Allow)" { print("Authorized") dismissViewControllerAnimated(true) { self.completionHandlerForView?(success: true, errorString: nil) } } if webView.request!.URL!.absoluteString.containsString("https://www.themoviedb.org/account/") { auth() } } }
4e344089d1540536df3dd444573ad653
26.128571
138
0.634879
false
false
false
false
VicFrolov/Markit
refs/heads/master
iOS/Markit/Markit/NewListingTableViewController.swift
apache-2.0
1
// // NewListingTableViewController.swift // Markit // // Created by Victor Frolov on 9/25/16. // Copyright © 2016 Victor Frolov. All rights reserved. // import UIKit import Firebase class NewListingTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let imagePicker: UIImagePickerController! = UIImagePickerController() var priceSelected = false var titleSelected = false var photoSelected = false var tagSelected = false var hubSelected = false var descriptionSelected = false var databaseRef: FIRDatabaseReference! var tagRef: FIRDatabaseReference! var hubRef: FIRDatabaseReference! var tagList: [String] = [String]() var hubList: [String] = [String]() @IBOutlet weak var price: UIButton! @IBOutlet weak var itemImage: UIImageView! @IBOutlet weak var itemTitle: UIButton! @IBOutlet weak var itemDescription: UIButton! @IBOutlet weak var tags: UIButton! @IBOutlet weak var hubs: UIButton! @IBOutlet weak var postButton: UIButton! @IBAction func takePicture(sender: UIButton) { if (UIImagePickerController.isSourceTypeAvailable(.camera)) { if (UIImagePickerController.isCameraDeviceAvailable(.rear)) { imagePicker.sourceType = .camera imagePicker.cameraCaptureMode = .photo present(imagePicker, animated: true, completion: {}) } } else { imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil) photoSelected = true } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var selectedImageFromPicker: UIImage? if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage { selectedImageFromPicker = editedImage } else if let originalImage: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage { selectedImageFromPicker = originalImage } if let selectedImage = selectedImageFromPicker { itemImage.contentMode = .scaleAspectFill itemImage.image = selectedImage itemImage.layer.zPosition = 1 photoSelected = true if (!priceSelected) { price.layer.zPosition = 2 } } imagePicker.dismiss(animated: true, completion: {}) if photoSelected && priceSelected { price.layer.zPosition = 2 itemImage.layer.zPosition = 1 } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func getTags () { tagRef.observe(.childAdded, with: { (snapshot) -> Void in if snapshot.value is Int { if (snapshot.value as! Int?)! > 7 { self.tagList.append(snapshot.key.trim()) } } }) } func getHubs () { hubRef.observe(.childAdded, with: { (snapshot) -> Void in if snapshot.value! is Int { self.hubList.append(snapshot.key.trim()) } }) } @IBAction func unwindPrice(segue: UIStoryboardSegue) { let priceVC = segue.source as? AddPriceViewController var userPrice = (priceVC?.priceLabel.text)! if (userPrice != "...") { userPrice = "$" + userPrice let blingedOutUserPrice = NSMutableAttributedString(string: userPrice as String) blingedOutUserPrice.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 255, green: 218, blue: 0, alpha: 0.7), range: NSRange(location:0,length:1)) price.setAttributedTitle(blingedOutUserPrice, for: .normal) price.backgroundColor = UIColor(red: 100/255, green: 100/255, blue: 100/255, alpha: 0.5) priceSelected = true } } @IBAction func unwindAddTitle(segue: UIStoryboardSegue) { let titleVC = segue.source as? AddTitleViewController let userTitle = titleVC?.itemTitle.text! if userTitle != "" { itemTitle.setAttributedTitle(NSMutableAttributedString(string: userTitle! as String), for: .normal) titleSelected = true } print("it's running! and here's the title: \(userTitle!)") } @IBAction func unwindDescription(segue: UIStoryboardSegue) { let descVC = segue.source as? AddDescriptionViewController let userDescription = descVC?.itemDescription.text if userDescription != "" { itemDescription.setAttributedTitle(NSMutableAttributedString(string: userDescription! as String), for: .normal) descriptionSelected = true } print("description accepted: \(userDescription!)") } @IBAction func unwindTag(segue: UIStoryboardSegue) { let tagVC = segue.source as? AddTagsViewController let userTags = tagVC?.tagsField.text?.lowercased() if userTags != "" { tags.setAttributedTitle(NSMutableAttributedString(string: userTags! as String), for: .normal) tagSelected = true } print("tags accepted: \(userTags!)") } @IBAction func unwindAddHubs(segue: UIStoryboardSegue) { let hubVC = segue.source as? AddHubViewController let userHubs = hubVC?.hubsField.text if userHubs != "" { hubs.setAttributedTitle(NSMutableAttributedString(string: userHubs! as String), for: .normal) hubSelected = true } print("hubs accepted: \(userHubs!)") } override func viewDidLoad() { super.viewDidLoad() imagePicker.delegate = self postButton.isUserInteractionEnabled = false postButton.alpha = 0.1 postButton.layer.cornerRadius = 10 databaseRef = FIRDatabase.database().reference() tagRef = databaseRef.child("tags") hubRef = databaseRef.child("hubs") getTags() getHubs() } override func viewDidAppear(_ animated: Bool) { if priceSelected && titleSelected && photoSelected && tagSelected && hubSelected && descriptionSelected { postButton.isUserInteractionEnabled = true postButton.alpha = 1.0 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addTagSegue" { let addTagVC = segue.destination as! AddTagsViewController addTagVC.tagList = self.tagList } else if segue.identifier == "addHubSegue" { let addHubVC = segue.destination as! AddHubViewController addHubVC.hubList = self.hubList } } @IBAction func cancelToNewListings(segue: UIStoryboardSegue) {} }
896c6c1bb41abac3340f3b5e676f87e3
34.728155
172
0.61087
false
false
false
false
JaySonGD/SwiftDayToDay
refs/heads/master
Swift - 闭包/Swift - 闭包/ViewController.swift
mit
1
// // ViewController.swift // Swift - 闭包 // // Created by czljcb on 16/2/26. // Copyright © 2016年 czljcb. All rights reserved. // import UIKit class ViewController: UIViewController { var tool : HTTPTool? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let tool = HTTPTool() self.tool = tool // MARK: - 闭包格式 (参数类型) -> (返回值类型) // var myBlock : ( (String) -> () )? // MARK: - 常用写法 // tool.load { (data : String) -> () in // // print(data) // } // // MARK: - 方式2 // tool.load ({ (data : String) -> () in // // print("888\(data)") // }) // MARK: - 方式3 // tool.load (){ (data : String) -> () in // print("9999\(data)") // self.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 最直接方式 // weak var weakSelf : ViewController? = self // // // tool.load (){ (data : String) -> () in // print("9999\(data)") // weakSelf!.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 最直接方式(简写) // tool.load (){[weak self] (data : String) -> () in // print("9999\(data)") // self!.view.backgroundColor = UIColor.orangeColor() // } // MARK: - 不安全方式(viewController delloc 时 指针不清空,永远指着那一块地址) tool.load (){[unowned self] (data : String) -> () in print("9999\(data)") self.view.backgroundColor = UIColor.orangeColor() } } // MARK: - 相当于OC delloc deinit{ print("delloc") } }
ff86a25a782c53f232d1e472ded11acf
23.682353
80
0.396568
false
false
false
false
iOS-mamu/SS
refs/heads/master
P/PotatsoModel/Rule.swift
mit
1
// // Rule.swift // Potatso // // Created by LEI on 4/6/16. // Copyright © 2016 TouchingApp. All rights reserved. // import RealmSwift import PotatsoBase private let ruleValueKey = "value"; private let ruleActionKey = "action"; public enum RuleType: String { case URLMatch = "URL-MATCH" case URL = "URL" case Domain = "DOMAIN" case DomainMatch = "DOMAIN-MATCH" case DomainSuffix = "DOMAIN-SUFFIX" case GeoIP = "GEOIP" case IPCIDR = "IP-CIDR" } extension RuleType { public static func fromInt(_ intValue: Int) -> RuleType? { switch intValue { case 1: return .Domain case 2: return .DomainSuffix case 3: return .DomainMatch case 4: return .URL case 5: return .URLMatch case 6: return .GeoIP case 7: return .IPCIDR default: return nil } } } extension RuleType: CustomStringConvertible { public var description: String { return rawValue } } public enum RuleAction: String { case Direct = "DIRECT" case Reject = "REJECT" case Proxy = "PROXY" } extension RuleAction { public static func fromInt(_ intValue: Int) -> RuleAction? { switch intValue { case 1: return .Direct case 2: return .Reject case 3: return .Proxy default: return nil } } } extension RuleAction: CustomStringConvertible { public var description: String { return rawValue } } public enum RuleError: Error { case invalidRule(String) } //extension RuleError: CustomStringConvertible { // // public var description: String { // switch self { // case .InvalidRule(let rule): // return "Invalid rule - \(rule)" // } // } // //} // //public final class Rule: BaseModel { // // public dynamic var typeRaw = "" // public dynamic var content = "" // public dynamic var order = 0 // public let rulesets = LinkingObjects(fromType: RuleSet.self, property: "rules") // //} // //extension Rule { // // public var type : RuleType { // get { // return RuleType(rawValue: typeRaw) ?? .DomainSuffix // } // set(v) { // typeRaw = v.rawValue // } // } // // public var action : RuleAction { // let json = content.jsonDictionary() // if let raw = json?[ruleActionKey] as? String { // return RuleAction(rawValue: raw) ?? .Proxy // } // return .Proxy // } // // public var value : String { // let json = content.jsonDictionary() // return json?[ruleValueKey] as? String ?? "" // } // //} // public final class Rule { public var type: RuleType public var value: String public var action: RuleAction public convenience init(str: String) throws { var ruleStr = str.replacingOccurrences(of: "\t", with: "") ruleStr = ruleStr.replacingOccurrences(of: " ", with: "") let parts = ruleStr.components(separatedBy: ",") guard parts.count >= 3 else { throw RuleError.invalidRule(str) } let actionStr = parts[2].uppercased() let typeStr = parts[0].uppercased() let value = parts[1] guard let type = RuleType(rawValue: typeStr), let action = RuleAction(rawValue: actionStr), value.characters.count > 0 else { throw RuleError.invalidRule(str) } self.init(type: type, action: action, value: value) } public init(type: RuleType, action: RuleAction, value: String) { self.type = type self.value = value self.action = action } public convenience init?(json: [String: AnyObject]) { guard let typeRaw = json["type"] as? String, let type = RuleType(rawValue: typeRaw) else { return nil } guard let actionRaw = json["action"] as? String, let action = RuleAction(rawValue: actionRaw) else { return nil } guard let value = json["value"] as? String else { return nil } self.init(type: type, action: action, value: value) } public var description: String { return "\(type), \(value), \(action)" } public var json: [String: AnyObject] { return ["type": type.rawValue as AnyObject, "value": value as AnyObject, "action": action.rawValue as AnyObject] } } // // //public func ==(lhs: Rule, rhs: Rule) -> Bool { // return lhs.uuid == rhs.uuid //}
6898005a5f50f4f4e877c64c80f181a4
23.375
133
0.563248
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/Category.swift
apache-2.0
1
// // Category.swift // Webretail // // Created by Gerardo Grisolini on 17/02/17. // // import Foundation import StORM import mwsWebretail class Category: PostgresSqlORM, Codable { public var categoryId : Int = 0 public var categoryIsPrimary : Bool = false public var categoryName : String = "" public var categoryDescription: [Translation] = [Translation]() public var categoryMedia: Media = Media() public var categorySeo : Seo = Seo() public var categoryCreated : Int = Int.now() public var categoryUpdated : Int = Int.now() private enum CodingKeys: String, CodingKey { case categoryId case categoryIsPrimary case categoryName case categoryDescription = "translations" case categoryMedia = "media" case categorySeo = "seo" } open override func table() -> String { return "categories" } open override func tableIndexes() -> [String] { return ["categoryName"] } open override func to(_ this: StORMRow) { categoryId = this.data["categoryid"] as? Int ?? 0 categoryIsPrimary = this.data["categoryisprimary"] as? Bool ?? true categoryName = this.data["categoryname"] as? String ?? "" let decoder = JSONDecoder() var jsonData: Data if let translates = this.data["categorydescription"] { jsonData = try! JSONSerialization.data(withJSONObject: translates, options: []) categoryDescription = try! decoder.decode([Translation].self, from: jsonData) } if let media = this.data["categorymedia"] { jsonData = try! JSONSerialization.data(withJSONObject: media, options: []) categoryMedia = try! decoder.decode(Media.self, from: jsonData) } if let seo = this.data["categoryseo"] { jsonData = try! JSONSerialization.data(withJSONObject: seo, options: []) categorySeo = try! decoder.decode(Seo.self, from: jsonData) } categoryCreated = this.data["categorycreated"] as? Int ?? 0 categoryUpdated = this.data["categoryupdated"] as? Int ?? 0 } func rows() -> [Category] { var rows = [Category]() for i in 0..<self.results.rows.count { let row = Category() row.to(self.results.rows[i]) rows.append(row) } return rows } override init() { super.init() } required init(from decoder: Decoder) throws { super.init() let container = try decoder.container(keyedBy: CodingKeys.self) categoryId = try container.decode(Int.self, forKey: .categoryId) categoryIsPrimary = try container.decode(Bool.self, forKey: .categoryIsPrimary) categoryName = try container.decode(String.self, forKey: .categoryName) categoryDescription = try container.decodeIfPresent([Translation].self, forKey: .categoryDescription) ?? [Translation]() categoryMedia = try container.decodeIfPresent(Media.self, forKey: .categoryMedia) ?? Media() categorySeo = try container.decodeIfPresent(Seo.self, forKey: .categorySeo) ?? Seo() } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(categoryId, forKey: .categoryId) try container.encode(categoryIsPrimary, forKey: .categoryIsPrimary) try container.encode(categoryName, forKey: .categoryName) try container.encode(categoryDescription, forKey: .categoryDescription) try container.encode(categoryMedia, forKey: .categoryMedia) try container.encode(categorySeo, forKey: .categorySeo) } fileprivate func addCategory(name: String, description: String, isPrimary: Bool) throws { let translation = Translation() translation.country = "EN" translation.value = description let item = Category() item.categoryName = name item.categoryIsPrimary = isPrimary item.categoryDescription.append(translation) item.categorySeo.permalink = item.categoryName.permalink() item.categoryCreated = Int.now() item.categoryUpdated = Int.now() try item.save() } func setupMarketplace() throws { try query(cursor: StORMCursor(limit: 1, offset: 0)) if results.rows.count == 0 { for item in ClothingType.cases() { if item != .jewelry { try addCategory(name: item.rawValue, description: "Clothing: \(item.rawValue)", isPrimary: true) } } } } }
44d02e640aed389fb97d0cd16932442f
37.363636
128
0.636148
false
false
false
false
Fitbit/thrift
refs/heads/master
lib/swift/Sources/TProtocolError.swift
apache-2.0
21
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Foundation public struct TProtocolError : TError { public init() { } public enum Code : TErrorCode { case unknown case invalidData case negativeSize case sizeLimit(limit: Int, got: Int) case badVersion(expected: String, got: String) case notImplemented case depthLimit public var thriftErrorCode: Int { switch self { case .unknown: return 0 case .invalidData: return 1 case .negativeSize: return 2 case .sizeLimit: return 3 case .badVersion: return 4 case .notImplemented: return 5 case .depthLimit: return 6 } } public var description: String { switch self { case .unknown: return "Unknown TProtocolError" case .invalidData: return "Invalid Data" case .negativeSize: return "Negative Size" case .sizeLimit(let limit, let got): return "Message exceeds size limit of \(limit) (received: \(got)" case .badVersion(let expected, let got): return "Bad Version. (Expected: \(expected), Got: \(got)" case .notImplemented: return "Not Implemented" case .depthLimit: return "Depth Limit" } } } public enum ExtendedErrorCode : TErrorCode { case unknown case missingRequiredField(fieldName: String) case unexpectedType(type: TType) case mismatchedProtocol(expected: String, got: String) public var thriftErrorCode: Int { switch self { case .unknown: return 1000 case .missingRequiredField: return 1001 case .unexpectedType: return 1002 case .mismatchedProtocol: return 1003 } } public var description: String { switch self { case .unknown: return "Unknown TProtocolExtendedError" case .missingRequiredField(let fieldName): return "Missing Required Field: \(fieldName)" case .unexpectedType(let type): return "Unexpected Type \(type.self)" case .mismatchedProtocol(let expected, let got): return "Mismatched Protocol. (Expected: \(expected), got \(got))" } } } public var extendedError: ExtendedErrorCode? = nil public init(error: Code = .unknown, message: String? = nil, extendedError: ExtendedErrorCode? = nil) { self.error = error self.message = message self.extendedError = extendedError } /// Mark: TError public var error: Code = .unknown public var message: String? = nil public static var defaultCase: Code { return .unknown } public var description: String { var out = "\(TProtocolError.self): (\(error.thriftErrorCode) \(error.description)\n" if let extendedError = extendedError { out += "TProtocolExtendedError (\(extendedError.thriftErrorCode)): \(extendedError.description)" } if let message = message { out += "Message: \(message)" } return out } } /// Wrapper for Transport errors in Protocols. Inspired by Thrift-Cocoa PROTOCOL_TRANSPORT_ERROR /// macro. Modified to be more Swift-y. Catches any TError thrown within the block and /// rethrows a given TProtocolError, the original error's description is appended to the new /// TProtocolError's message. sourceFile, sourceLine, sourceMethod are auto-populated and should /// be ignored when calling. /// /// - parameter error: TProtocolError to throw if the block throws /// - parameter sourceFile: throwing file, autopopulated /// - parameter sourceLine: throwing line, autopopulated /// - parameter sourceMethod: throwing method, autopopulated /// - parameter block: throwing block /// /// - throws: TProtocolError Default is TProtocolError.ErrorCode.unknown. Underlying /// error's description appended to TProtocolError.message func ProtocolTransportTry(error: TProtocolError = TProtocolError(), sourceFile: String = #file, sourceLine: Int = #line, sourceMethod: String = #function, block: () throws -> ()) throws { // Need mutable copy var error = error do { try block() } catch let err as TError { var message = error.message ?? "" message += "\nFile: \(sourceFile)\n" message += "Line: \(sourceLine)\n" message += "Method: \(sourceMethod)" message += "\nOriginal Error:\n" + err.description error.message = message throw error } }
340c58a2a2a3ded1b359228177ebbe07
35.287671
122
0.65855
false
false
false
false
scotteg/LayerPlayer
refs/heads/master
LayerPlayer/TrackBall.swift
mit
1
// // TrackBall.swift // LayerPlayer // // Created by Scott Gardner on 11/20/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit postfix operator ** postfix func ** (value: CGFloat) -> CGFloat { return value * value } class TrackBall { let tolerance = 0.001 var baseTransform = CATransform3DIdentity let trackBallRadius: CGFloat let trackBallCenter: CGPoint var trackBallStartPoint = (x: CGFloat(0.0), y: CGFloat(0.0), z: CGFloat(0.0)) init(location: CGPoint, inRect bounds: CGRect) { if bounds.width > bounds.height { trackBallRadius = bounds.height * 0.5 } else { trackBallRadius = bounds.width * 0.5 } trackBallCenter = CGPoint(x: bounds.midX, y: bounds.midY) setStartPointFromLocation(location) } func setStartPointFromLocation(_ location: CGPoint) { trackBallStartPoint.x = location.x - trackBallCenter.x trackBallStartPoint.y = location.y - trackBallCenter.y let distance = trackBallStartPoint.x** + trackBallStartPoint.y** trackBallStartPoint.z = distance > trackBallRadius** ? CGFloat(0.0) : sqrt(trackBallRadius** - distance) } func finalizeTrackBallForLocation(_ location: CGPoint) { baseTransform = rotationTransformForLocation(location) } func rotationTransformForLocation(_ location: CGPoint) -> CATransform3D { var trackBallCurrentPoint = (x: location.x - trackBallCenter.x, y: location.y - trackBallCenter.y, z: CGFloat(0.0)) let withinTolerance = fabs(Double(trackBallCurrentPoint.x - trackBallStartPoint.x)) < tolerance && fabs(Double(trackBallCurrentPoint.y - trackBallStartPoint.y)) < tolerance if withinTolerance { return CATransform3DIdentity } let distance = trackBallCurrentPoint.x** + trackBallCurrentPoint.y** if distance > trackBallRadius** { trackBallCurrentPoint.z = 0.0 } else { trackBallCurrentPoint.z = sqrt(trackBallRadius** - distance) } let startPoint = trackBallStartPoint let currentPoint = trackBallCurrentPoint let x = startPoint.y * currentPoint.z - startPoint.z * currentPoint.y let y = -startPoint.x * currentPoint.z + trackBallStartPoint.z * currentPoint.x let z = startPoint.x * currentPoint.y - startPoint.y * currentPoint.x var rotationVector = (x: x, y: y, z: z) let startLength = sqrt(Double(startPoint.x** + startPoint.y** + startPoint.z**)) let currentLength = sqrt(Double(currentPoint.x** + currentPoint.y** + currentPoint.z**)) let startDotCurrent = Double(startPoint.x * currentPoint.x + startPoint.y + currentPoint.y + startPoint.z + currentPoint.z) let rotationLength = sqrt(Double(rotationVector.x** + rotationVector.y** + rotationVector.z**)) let angle = CGFloat(atan2(rotationLength / (startLength * currentLength), startDotCurrent / (startLength * currentLength))) let normalizer = CGFloat(rotationLength) rotationVector.x /= normalizer rotationVector.y /= normalizer rotationVector.z /= normalizer let rotationTransform = CATransform3DMakeRotation(angle, rotationVector.x, rotationVector.y, rotationVector.z) return CATransform3DConcat(baseTransform, rotationTransform) } }
bbb9278f5033ff6ebf07835dc026e93d
36.941176
176
0.709147
false
false
false
false
dduan/swift
refs/heads/master
benchmark/single-source/ArrayAppend.swift
apache-2.0
2
//===--- ArrayAppend.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks the performance of appending to an array. import TestsUtils @inline(never) public func run_ArrayAppend(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40000 { nums.append(1) } } } } @inline(never) public func run_ArrayAppendReserved(N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() nums.reserveCapacity(40000) for _ in 0..<40000 { nums.append(1) } } } }
475d74f17185f9fa9e7d6bdb054f4a96
24.75
80
0.532039
false
false
false
false
easyui/Alamofire
refs/heads/master
Source/Protected.swift
mit
1
// // Protected.swift // // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation private protocol Lock { func lock() func unlock() } extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to run. /// /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure() } /// Execute a closure while acquiring the lock. /// /// - Parameter closure: The closure to run. func around(_ closure: () -> Void) { lock(); defer { unlock() } closure() } } #if os(Linux) || os(Windows) extension NSLock: Lock {} #endif #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) /// An `os_unfair_lock` wrapper. final class UnfairLock: Lock { private let unfairLock: os_unfair_lock_t init() { unfairLock = .allocate(capacity: 1) unfairLock.initialize(to: os_unfair_lock()) } deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } fileprivate func lock() { os_unfair_lock_lock(unfairLock) } fileprivate func unlock() { os_unfair_lock_unlock(unfairLock) } } #endif /// A thread-safe wrapper around a value. @propertyWrapper @dynamicMemberLookup final class Protected<T> { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) private let lock = UnfairLock() #elseif os(Linux) || os(Windows) private let lock = NSLock() #endif private var value: T init(_ value: T) { self.value = value } /// The contained value. Unsafe for anything more than direct read or write. var wrappedValue: T { get { lock.around { value } } set { lock.around { value = newValue } } } var projectedValue: Protected<T> { self } init(wrappedValue: T) { value = wrappedValue } /// Synchronously read or transform the contained value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The return value of the closure passed. func read<U>(_ closure: (T) -> U) -> U { lock.around { closure(self.value) } } /// Synchronously modify the protected value. /// /// - Parameter closure: The closure to execute. /// /// - Returns: The modified value. @discardableResult func write<U>(_ closure: (inout T) -> U) -> U { lock.around { closure(&self.value) } } subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property { get { lock.around { value[keyPath: keyPath] } } set { lock.around { value[keyPath: keyPath] = newValue } } } } extension Protected where T: RangeReplaceableCollection { /// Adds a new element to the end of this protected collection. /// /// - Parameter newElement: The `Element` to append. func append(_ newElement: T.Element) { write { (ward: inout T) in ward.append(newElement) } } /// Adds the elements of a sequence to the end of this protected collection. /// /// - Parameter newElements: The `Sequence` to append. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } /// Add the elements of a collection to the end of the protected collection. /// /// - Parameter newElements: The `Collection` to append. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element { write { (ward: inout T) in ward.append(contentsOf: newElements) } } } extension Protected where T == Data? { /// Adds the contents of a `Data` value to the end of the protected `Data`. /// /// - Parameter data: The `Data` to be appended. func append(_ data: Data) { write { (ward: inout T) in ward?.append(data) } } } extension Protected where T == Request.MutableState { /// Attempts to transition to the passed `State`. /// /// - Parameter state: The `State` to attempt transition to. /// /// - Returns: Whether the transition occurred. func attemptToTransitionTo(_ state: Request.State) -> Bool { lock.around { guard value.state.canTransitionTo(state) else { return false } value.state = state return true } } /// Perform a closure while locked with the provided `Request.State`. /// /// - Parameter perform: The closure to perform while locked. func withState(perform: (Request.State) -> Void) { lock.around { perform(value.state) } } }
2f6fa727fbb3ad17131da5c679e27532
29.213198
90
0.624328
false
false
false
false
calkinssean/woodshopBMX
refs/heads/master
WoodshopBMX/WoodshopBMX/ItemDetailViewController.swift
apache-2.0
1
// // ItemDetailViewController.swift // M3rch // // Created by Sean Calkins on 4/4/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit import Charts class ItemDetailViewController: UIViewController, ChartViewDelegate { //MARK: - Outlets @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var itemPriceLabel: UILabel! @IBOutlet weak var itemQuantityLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet var sizeButtons: [UIButton]! @IBOutlet weak var currentSizeLabel: UILabel! @IBOutlet weak var currentColorView: UIView! @IBOutlet weak var pickColorLabel: UILabel! @IBOutlet weak var whiteLabel: UILabel! //MARK: - Properties var currentEvent: Event? var currentItem: Item? var currentSubItem: SubItem? var currentColor: String? var currentSize: String? var formatter = NSDateFormatter() var timeInterval: Double = 3600 var arrayOfSubItems = [SubItem]() var sizeStrings = [String]() var numFormatter = NSNumberFormatter() //MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = self.currentItem?.name numFormatter.minimumFractionDigits = 2 numFormatter.maximumFractionDigits = 2 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit Item", style: .Plain, target: self, action: #selector(self.editItemTapped)) formatter.dateFormat = "h:mm a" formatter.AMSymbol = "AM" formatter.PMSymbol = "PM" } override func viewWillAppear(animated: Bool) { if let event = self.currentEvent { if event.name == "WoodShop" { self.backgroundImageView.image = UIImage(named: "wood copy") } } //Grab subitems for current item from data store let fetchedSubItems = DataController.sharedInstance.fetchSubItems() self.arrayOfSubItems.removeAll() for subItem in fetchedSubItems { if subItem.item == self.currentItem { self.arrayOfSubItems.append(subItem) } } self.updateUI() self.changeSizeButtonTitles() self.updateColorButtons() self.updateSizeButtons() } //MARK: - Color button tapped @IBAction func colorButtons(sender: UIButton) { var stock: Int = 0 if let color = sender.backgroundColor { //Changed current color on tap to button's background color self.currentColor = "\(color)" if self.currentColor == "UIDeviceRGBColorSpace 1 1 1 1" { self.whiteLabel.hidden = false } else { self.whiteLabel.hidden = true } self.currentColorView.backgroundColor = color self.pickColorLabel.text = "Pick a Size" } for item in arrayOfSubItems { //If sub item with current color exists, update quantity label and show sizes for that color if item.color == self.currentColor { if let quan = item.quantity { stock = stock + Int(quan) } } } self.itemQuantityLabel.text = "\(stock) left" self.updateSizeButtons() } //MARK: - Size button tapped @IBAction func sizeButtons(sender: UIButton) { //Changes current size on button tap var quantityTotal: Int = 0 if let size = sender.titleLabel?.text { self.currentSize = size self.currentSizeLabel.text = size self.pickColorLabel.text = "" } for item in arrayOfSubItems { //If sub item with selected color and size exists, update current quantity label if item.color == self.currentColor && item.size == self.currentSize { if let quantity = item.quantity { quantityTotal = quantityTotal + Int(quantity) if Int(quantity) > 0 { self.currentSubItem = item } } } } self.itemQuantityLabel.text = "\(quantityTotal) left" } //MARK: - Sell item tapped @IBAction func sellItemTapped() { if self.currentColor != nil && self.currentSize != nil { if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { self.saleTypeAlert() } else { self.presentAlert("Item is sold out") } } else { self.presentAlert("Please select a size and color") } } else { self.presentAlert("Please select a size and color") } } //Alert if item is sold out func presentAlert(message: String) { let alert = UIAlertController(title: "\(message)", message: nil, preferredStyle: .Alert) let ok = UIAlertAction(title: "Ok", style: .Default, handler: nil) alert.addAction(ok) presentViewController(alert, animated: true, completion: nil) self.updateColorButtons() self.updateSizeButtons() } //Choose type of sale func saleTypeAlert() { let alert = UIAlertController(title: "Sell Item", message: "Choose Type Of Sale", preferredStyle: .Alert) //If cash sale, create sale object with "Cash" as type let cashAction = UIAlertAction(title: "Cash", style: .Default) { (action: UIAlertAction) -> Void in if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { var newAmount = Double(quan) newAmount = newAmount - Double(1) //update quantity on sale self.currentSubItem?.setValue(newAmount, forKey: "quantity") dataControllerSave() let date = NSDate() if let price = self.currentItem?.price { let priceDouble = Double(price) if let event = self.currentItem?.event { if let item = self.currentItem { if let currentSubItem = self.currentSubItem { if let initialCost = self.currentItem?.purchasedPrice { DataController.sharedInstance.seedSale(date, type: "Cash", amount: priceDouble, initialCost: Double(initialCost), event: event, item: item, subItem: currentSubItem) self.updateColorButtons() self.updateSizeButtons() self.updateUI() } } } } } } else { self.presentAlert("Item is sold out") } } } //If cash sale, create sale object with "Card" as type let cardAction = UIAlertAction(title: "Card", style: .Default) { (action: UIAlertAction) -> Void in if let quan = self.currentSubItem?.quantity { if Double(quan) > 0 { var newAmount = Double(quan) newAmount = newAmount - Double(1) //update quantity on sale self.currentSubItem?.setValue(newAmount, forKey: "quantity") dataControllerSave() let date = NSDate() if let price = self.currentItem?.price { let priceDouble = Double(price) if let event = self.currentItem?.event { if let item = self.currentItem { if let currentSubItem = self.currentSubItem { if let initialCost = self.currentItem?.purchasedPrice { DataController.sharedInstance.seedSale(date, type: "Card", amount: priceDouble, initialCost: Double(initialCost), event: event, item: item, subItem: currentSubItem) self.updateColorButtons() self.updateSizeButtons() self.updateUI() } } } } } } else { self.presentAlert("Item is sold out") } } self.updateUI() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addAction(cashAction) alert.addAction(cardAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } //MARK: - Helper Methods func updateUI() { if let price = self.currentItem?.price { if let formattedString = numFormatter.stringFromNumber(price) { self.itemPriceLabel.text = "$\(formattedString)" } } let qty = Int(self.getCurrentStock(self.currentItem!)) self.itemQuantityLabel.text = "\(qty) left" if let imageName = currentItem?.imageName { if let image = loadImageFromUrl(imageName) { self.imageView.image = image } } self.currentSize = nil self.currentColor = nil self.currentSizeLabel.text = "" self.currentColorView.backgroundColor = UIColor.clearColor() self.pickColorLabel.text = "Pick a Color" } //MARK: - Change size button titles func changeSizeButtonTitles() { self.sizeStrings = [] for item in arrayOfSubItems { if !self.sizeStrings.contains(item.size!) { self.sizeStrings.append(item.size!) } } //loop through buttons array and change button titles to size strings as needed then unhide the button for (index, size) in self.sizeStrings.enumerate() { let button = self.sizeButtons[index] button.setTitle(size, forState: .Normal) button.hidden = false } } //MARK: - Edit Item Tapped func editItemTapped() { performSegueWithIdentifier("editItemSegue", sender: self) } //MARK: - Prepare for segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "editItemSegue" { let controller = segue.destinationViewController as! ColorsAndSizesViewController controller.currentItem = self.currentItem controller.currentEvent = self.currentEvent } } //MARK: - Update Color Buttons func updateColorButtons() { for button in colorButtons { button.hidden = true } for sItem in arrayOfSubItems { if let quan = sItem.quantity { if Double(quan) > 0 { for button in colorButtons { //Unhides the color button if the current item has a sub item of that color if let color = button.backgroundColor { if "\(color)" == sItem.color { button.hidden = false } } } } } } } //MARK: - Update size buttons func updateSizeButtons() { for button in sizeButtons { button.hidden = true } for sItem in arrayOfSubItems { if let quan = sItem.quantity { if Double(quan) > 0 { for button in sizeButtons { if let color = sItem.color { if let size = button.titleLabel!.text { //Unhides size button if current item has sub item of that size and current color if size == sItem.size && color == self.currentColor { button.hidden = false } } } } } } } } //MARK: - Unwind Segue @IBAction func unwindSegue (segue: UIStoryboardSegue) {} //Add the quantities of all sub items to get a quantity of current item func getCurrentStock(item: Item) -> Double { let fetchedSubItems = DataController.sharedInstance.fetchSubItems() var stockTotal: Double = 0 for subItem in fetchedSubItems { if subItem.item == item { if let quantity = subItem.quantity { stockTotal = stockTotal + Double(quantity) } } } return stockTotal } }
1fb9c85b2893c1b2f7399394a45fe1d3
31.786448
204
0.440158
false
false
false
false
dathtcheapgo/Jira-Demo
refs/heads/master
Driver/Extension/UIViewExtension.swift
mit
1
// // UIViewExtension.swift // drivers // // Created by Đinh Anh Huy on 10/10/16. // Copyright © 2016 Đinh Anh Huy. All rights reserved. // import UIKit extension UIView { //MARK: Layer func makeRoundedConner(radius: CGFloat = 10) { self.layer.cornerRadius = radius self.clipsToBounds = true } func copyView() -> UIView { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! UIView } } //MARK: Indicator extension UIView { func showIndicator(indicatorStyle: UIActivityIndicatorViewStyle, blockColor: UIColor, alpha: CGFloat) { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = blockColor viewBlock.alpha = alpha viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) let indicator = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) indicator.startAnimating() } } func showIndicator() { OperationQueue.main.addOperation { for currentView in self.subviews { if currentView.tag == 9999 { return } } let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.black viewBlock.alpha = 0.3 viewBlock.layer.cornerRadius = self.layer.cornerRadius let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white) viewBlock.translatesAutoresizingMaskIntoConstraints = false self.addSubview(viewBlock) _ = viewBlock.addConstraintFillInView(view: self, commenParrentView: self) indicator.translatesAutoresizingMaskIntoConstraints = false viewBlock.addSubview(indicator) _ = indicator.addConstraintCenterXToView(view: self, commonParrentView: self) _ = indicator.addConstraintCenterYToView(view: self, commonParrentView: self) indicator.startAnimating() } } func showIndicator(frame: CGRect, blackStyle: Bool = false) { let viewBlock = UIView() viewBlock.tag = 9999 viewBlock.backgroundColor = UIColor.white viewBlock.frame = frame let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicator.frame = CGRect( x: self.frame.width/2-25, y: self.frame.height/2-25, width: 50, height: 50) viewBlock.addSubview(indicator) self.addSubview(viewBlock) indicator.startAnimating() } func hideIndicator() { let indicatorView = self.viewWithTag(9999) indicatorView?.removeFromSuperview() for currentView in self.subviews { if currentView.tag == 9999 { let _view = currentView OperationQueue.main.addOperation { _view.removeFromSuperview() } } } } } //MARK: Animation extension UIView { func moveToFrameWithAnimation(newFrame: CGRect, delay: TimeInterval, time: TimeInterval) { UIView.animate(withDuration: time, delay: delay, options: .curveEaseOut, animations: { self.frame = newFrame }, completion:nil) } func fadeOut(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 0.0 }, completion: { (finished: Bool) -> Void in if finished == true { self.isHidden = true } }) } func fadeIn(time: TimeInterval, delay: TimeInterval) { self.isUserInteractionEnabled = true self.alpha = 0 self.isHidden = false UIView.animate(withDuration: time, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: { self.alpha = 1.0 }, completion: { (finished: Bool) -> Void in if finished == true { } }) } } //MARK: Add constraint extension UIView { func leadingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func trailingMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopToBot(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotToTop(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintBotMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintTopMarginToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { // self.setTranslatesAutoresizingMaskIntoConstraints(false) let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintWidth(parrentView: UIView, width: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width) parrentView.addConstraint(constraint) return constraint } func addConstraintHeight(parrentView: UIView, height: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: height) parrentView.addConstraint(constraint) return constraint } func addConstraintLeftToRight(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintRightToLeft(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: margin) commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterYToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintCenterXToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualHeightToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintEqualWidthToView(view: UIView, commonParrentView: UIView, margin: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint (item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: margin) //hardcode commonParrentView.addConstraint(constraint) return constraint } func addConstraintFillInView(view: UIView, commenParrentView: UIView, margins: [CGFloat]? = nil) -> (top: NSLayoutConstraint, bot: NSLayoutConstraint, lead: NSLayoutConstraint, trail: NSLayoutConstraint) { var mutableMargins = margins if mutableMargins == nil { mutableMargins = [0, 0, 0, 0] } let top = addConstraintTopMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![0]) let trail = trailingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![1]) let bot = addConstraintBotMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![2]) let lead = leadingMarginToView(view: view, commonParrentView: commenParrentView, margin: mutableMargins![3]) return (top, bot, lead, trail) } } //MARK: Get constraint from superview extension UIView { func constraintTop() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTopConstraint() else { continue } return constraint } return nil } func constraintBot() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isBotConstraint() else { continue } return constraint } return nil } func constraintLead() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isLeadConstraint() else { continue } return constraint } return nil } func constraintTrail() -> NSLayoutConstraint? { guard let parrentView = superview else { return nil } for constraint in parrentView.constraints { guard constraint.isConstraintOfView(view: self) else { continue } guard constraint.isTrailConstraint() else { continue } return constraint } return nil } }
94da2428a15f7e7af789cf06c87d5419
41.064599
123
0.532834
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Graphic Equalizer.xcplaygroundpage/Contents.swift
mit
1
//: ## Graphic Equalizer //: This playground builds a graphic equalizer from a set of equalizer filters import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let filterBand2 = AKEqualizerFilter(player, centerFrequency: 32, bandwidth: 44.7, gain: 1.0) let filterBand3 = AKEqualizerFilter(filterBand2, centerFrequency: 64, bandwidth: 70.8, gain: 1.0) let filterBand4 = AKEqualizerFilter(filterBand3, centerFrequency: 125, bandwidth: 141, gain: 1.0) let filterBand5 = AKEqualizerFilter(filterBand4, centerFrequency: 250, bandwidth: 282, gain: 1.0) let filterBand6 = AKEqualizerFilter(filterBand5, centerFrequency: 500, bandwidth: 562, gain: 1.0) let filterBand7 = AKEqualizerFilter(filterBand6, centerFrequency: 1_000, bandwidth: 1_112, gain: 1.0) AudioKit.output = filterBand7 AudioKit.start() player.play() //: User Interface Set up import AudioKitUI class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Graphic Equalizer") addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles)) addLabel("Equalizer Gains") addView(AKSlider(property: "32Hz", value: filterBand2.gain, range: 0 ... 2) { sliderValue in filterBand2.gain = sliderValue }) addView(AKSlider(property: "64Hz", value: filterBand3.gain, range: 0 ... 2) { sliderValue in filterBand3.gain = sliderValue }) addView(AKSlider(property: "125Hz", value: filterBand4.gain, range: 0 ... 2) { sliderValue in filterBand4.gain = sliderValue }) addView(AKSlider(property: "250Hz", value: filterBand5.gain, range: 0 ... 2) { sliderValue in filterBand5.gain = sliderValue }) addView(AKSlider(property: "500Hz", value: filterBand6.gain, range: 0 ... 2) { sliderValue in filterBand6.gain = sliderValue }) addView(AKSlider(property: "1000Hz", value: filterBand7.gain, range: 0 ... 2) { sliderValue in filterBand7.gain = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
ed3fc124d408f52a4a2d110f54bd9977
36.064516
102
0.704526
false
false
false
false
seuzl/iHerald
refs/heads/master
Herald/AcademicViewController.swift
mit
1
// // AcademicViewController.swift // 先声 // // Created by Wangshuo on 14-9-2. // Copyright (c) 2014年 WangShuo. All rights reserved. // import UIKit class AcademicViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,APIGetter { @IBOutlet var upSegmentControl: UISegmentedControl! @IBOutlet var downSegmentControl: UISegmentedControl! @IBOutlet var tableView: UITableView! var allInfoList:NSMutableArray = []//All information in a list with all JWC info.Should be initialized before use var contentDictionary:NSDictionary?//All information in a dictionary with 5 type of JWC info var currentList:NSMutableArray = [] var segmentedControlLastPressedIndex:NSNumber = 0 var firstLoad = true var API = HeraldAPI() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "教务信息" self.view.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) self.tableView.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) self.upSegmentControl.addTarget(self, action: Selector("upSegmentedControlPressed"), forControlEvents: UIControlEvents.ValueChanged) self.downSegmentControl.addTarget(self, action: Selector("downSegmentedControlPressed"), forControlEvents: UIControlEvents.ValueChanged) //设置默认选择项索引 self.upSegmentControl.selectedSegmentIndex = 0 self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment //设置表格刷新 self.tableView.addFooterWithTarget(self, action: Selector("footerRefreshing")) let initResult = Tool.initNavigationAPI(self) if initResult{ Tool.showProgressHUD("正在查询教务信息") self.API.delegate = self API.sendAPI("jwc") } } override func viewWillDisappear(animated: Bool) { Tool.dismissHUD() API.cancelAllRequest() } func getResult(APIName: String, results: JSON) { Tool.showSuccessHUD("获取成功") contentDictionary = results["content"].dictionaryObject getAllInformation() if firstLoad{ upSegmentedControlPressed() firstLoad = false } } func getError(APIName: String, statusCode: Int) { Tool.showErrorHUD("获取数据失败") } func upSegmentedControlPressed() { let selectedIndex = self.upSegmentControl.selectedSegmentIndex if contentDictionary == nil{ Tool.showErrorHUD("没有数据哦") return } switch selectedIndex { case 0: if allInfoList.count != 0{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = allInfoList self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 1: if let segmentedContent:NSMutableArray = contentDictionary!["最新动态"] as? NSMutableArray{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 2: if let segmentedContent:NSMutableArray = contentDictionary!["教务信息"] as? NSMutableArray{ self.downSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } default: break } } func downSegmentedControlPressed() { let selectedIndex = self.downSegmentControl.selectedSegmentIndex switch selectedIndex { case 0: if let segmentedContent:NSMutableArray = contentDictionary!["合作办学"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 1: if let segmentedContent:NSMutableArray = contentDictionary!["学籍管理"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } case 2: if let segmentedContent:NSMutableArray = contentDictionary!["实践教学"] as? NSMutableArray{ self.upSegmentControl.selectedSegmentIndex = UISegmentedControlNoSegment self.currentList = segmentedContent self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } default: break } } //获取教务信息中的全部信息,而非某个信息,供第一个SegmentedControl显示 func getAllInformation(){ allInfoList = []//清空 if let allContent = contentDictionary{ for (_,infoArray) in allContent{ allInfoList.addObjectsFromArray(infoArray as! Array<AnyObject>) } } } func footerRefreshing() { Tool.showProgressHUD("正在加载更多数据") API.sendAPI("jwc") self.tableView.footerEndRefreshing() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 110 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.currentList.count == 0 { return 0 } else { return self.currentList.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier:String = "AcademicTableViewCell" var cell: AcademicTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? AcademicTableViewCell if nil == cell { let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("AcademicTableViewCell", owner: self, options: nil) cell = nibArray.objectAtIndex(0) as? AcademicTableViewCell } cell?.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) let row = indexPath.row cell?.headLineLabel.text = self.currentList[row]["title"] as? String cell?.dateLabel.text = self.currentList[row]["date"] as? String cell?.headLineLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping cell?.headLineLabel.numberOfLines = 0 cell?.dateLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping cell?.dateLabel.numberOfLines = 0 return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) let row = indexPath.row self.tableView.deselectRowAtIndexPath(indexPath, animated: true) let academicDetailVC = AcademicDetailViewController() academicDetailVC.initWebView(self.currentList[row]["href"] as! NSString as String) self.navigationController!.pushViewController(academicDetailVC, animated: true) } //现在API只返回网页形式的教务信息,没有文字信息 }
0fa5cc5b5b484bf46c897659b88367cf
34.877273
144
0.643988
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/MailPagePresenter.swift
lgpl-2.1
2
// // MailPagePresenter.swift // Neocom // // Created by Artem Shimanski on 11/2/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import EVEAPI class MailPagePresenter: TreePresenter { typealias View = MailPageViewController typealias Interactor = MailPageInteractor typealias Presentation = [Tree.Item.DateSection<Tree.Item.MailRow>] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? var lastMailID: Int64? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.MailCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { guard let input = view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))} guard !content.value.headers.isEmpty else {return .init(.failure(NCError.noResults))} guard let characterID = Services.storage.viewContext.currentAccount?.characterID else {return .init(.failure(NCError.authenticationRequired))} let treeController = view?.treeController let old = self.presentation ?? [] let api = interactor.api return DispatchQueue.global(qos: .utility).async { () -> (Presentation, Int?) in let calendar = Calendar(identifier: .gregorian) let headers = content.value.headers.filter{$0.mailID != nil && $0.timestamp != nil}.sorted{$0.mailID! > $1.mailID!}.map { header -> Tree.Item.MailRow in var ids = Set(header.recipients?.map{Int64($0.recipientID)} ?? []) if let from = header.from { ids.insert(Int64(from)) } return Tree.Item.MailRow(header, contacts: content.value.contacts.filter {ids.contains($0.key)}, label: input, characterID: characterID, api: api) } let sections = Dictionary(grouping: headers, by: { (i) -> Date in let components = calendar.dateComponents([.year, .month, .day], from: i.content.timestamp!) return calendar.date(from: components) ?? i.content.timestamp! }).sorted {$0.key > $1.key} .map{Tree.Item.DateSection(date: $0.key, diffIdentifier: $0.key, treeController: treeController, children: $0.value)} return (sections, headers.last?.content.mailID) }.then(on: .main) { [weak self] (new, lastMailID) -> Presentation in self?.lastMailID = lastMailID.map{Int64($0)} var result = old for i in new { if let j = old.upperBound(where: {$0.date <= i.date}).first, j.date == i.date { let mailIDs = Set(j.children?.compactMap {$0.content.mailID} ?? []) j.children?.append(contentsOf: i.children?.filter {$0.content.mailID != nil && !mailIDs.contains($0.content.mailID!)} ?? []) } else { result.append(i) } } return result } } func prepareForReload() { self.presentation = nil self.lastMailID = nil self.isEndReached = false } private var isEndReached = false @discardableResult func fetchIfNeeded() -> Future<Presentation> { guard !isEndReached else {return .init(.failure(NCError.isEndReached))} guard let lastMailID = lastMailID, self.loading == nil else {return .init(.failure(NCError.reloadInProgress))} view?.activityIndicator.startAnimating() let loading = interactor.load(from: lastMailID, cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self] content -> Future<Presentation> in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} return strongSelf.presentation(for: content).then(on: .main) { [weak self] presentation -> Presentation in self?.presentation = presentation self?.view?.present(presentation, animated: false) self?.loading = nil return presentation } }.catch(on: .main) { [weak self] error in self?.loading = nil self?.isEndReached = true }.finally(on: .main) { [weak self] in self?.view?.activityIndicator.stopAnimating() } if case .pending = loading.state { self.loading = loading } return loading } func canEdit<T: TreeItem>(_ item: T) -> Bool { return item is Tree.Item.MailRow } func editingStyle<T: TreeItem>(for item: T) -> UITableViewCell.EditingStyle { return item is Tree.Item.MailRow ? .delete : .none } func editActions<T: TreeItem>(for item: T) -> [UITableViewRowAction]? { guard let item = item as? Tree.Item.MailRow else {return nil} return [UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: "")) { [weak self] (_, _) in self?.interactor.delete(item.content).then(on: .main) { guard let bound = self?.presentation?.upperBound(where: {$0.date <= item.content.timestamp!}) else {return} guard let section = bound.first else {return} guard let i = section.children?.firstIndex(of: item) else {return} section.children?.remove(at: i) if section.children?.isEmpty == true { self?.presentation?.remove(at: bound.indices.first!) if let presentation = self?.presentation { _ = self?.view?.treeController.reloadData(presentation, with: .fade) } } else { self?.view?.treeController.update(contentsOf: section, with: .fade) } if let n = self?.view?.input?.unreadCount, item.content.isRead != true && n > 0 { self?.view?.input?.unreadCount = n - 1 self?.view?.updateTitle() } }.catch(on: .main) { [weak self] error in self?.view?.present(UIAlertController(error: error), animated: true, completion: nil) } }] } func didSelect<T: TreeItem>(item: T) -> Void { guard let view = view else {return} guard let item = item as? Tree.Item.MailRow else {return} if item.content.isRead != true { item.content.isRead = true interactor.markRead(item.content) if let n = view.input?.unreadCount, n > 0 { view.input?.unreadCount = n - 1 view.updateTitle() } if let cell = view.treeController.cell(for: item) { item.configure(cell: cell, treeController: view.treeController) } else { view.treeController.reloadRow(for: item, with: .none) } } Router.Mail.mailBody(item.content).perform(from: view) } } extension Tree.Item { class DateSection<Element: TreeItem>: Section<Tree.Content.Section, Element> { let date: Date init<T: Hashable>(date: Date, doesRelativeDateFormatting: Bool = true, diffIdentifier: T, expandIdentifier: CustomStringConvertible? = nil, treeController: TreeController?, children: [Element]? = nil) { self.date = date let formatter = DateFormatter() formatter.doesRelativeDateFormatting = doesRelativeDateFormatting formatter.timeStyle = .none formatter.dateStyle = .medium let title = formatter.string(from: date).uppercased() super.init(Tree.Content.Section(prototype: Prototype.TreeSectionCell.default, title: title), isExpanded: true, diffIdentifier: diffIdentifier, expandIdentifier: expandIdentifier, treeController: treeController, children: children) } } }
b9c06ffc1a5657254b3794c67817b486
34.688679
204
0.690986
false
false
false
false
FsThatOne/FSOAuth2.0Test
refs/heads/master
FSOAuth2.0Test/FSOAuth2.0Test/NetworkTools.swift
mit
1
// // NetworkTools.swift // // // Created by FS小一 on 15/11/22. // // import UIKit import AFNetworking /// HTTP 请求方法枚举 enum FSRequestMethod: String { case GET = "GET" case POST = "POST" } // MARK: - 网络工具 class NetworkTools: AFHTTPSessionManager { private let testOAuthLoginUrl = "https://api.weibo.com/oauth2/authorize?client_id=3353833785&redirect_uri=https://github.com/FsThatOne" // 单例 static let sharedTools: NetworkTools = { let tools = NetworkTools(baseURL: nil) // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set tools.responseSerializer.acceptableContentTypes?.insert("text/html") return tools }() } extension NetworkTools{ func oauthUrl() -> NSURL { let url = NSURL(string: testOAuthLoginUrl) return url! } } // MARK: - 封装 AFN 网络方法 extension NetworkTools { /// 网络请求 /// /// - parameter method: GET / POST /// - parameter URLString: URLString /// - parameter parameters: 参数字典 /// - parameter finished: 完成回调 func request(method: FSRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?, error: NSError?)->()) { // 定义成功回调 let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in finished(result: result, error: nil) } // 定义失败回调 let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in // 在开发网络应用的时候,错误不要提示给用户,但是错误一定要输出! print(error) finished(result: nil, error: error) } if method == FSRequestMethod.GET { GET(URLString, parameters: parameters, success: success, failure: failure) } else { POST(URLString, parameters: parameters, success: success, failure: failure) } } }
09a8d773f6c3ed1b169b3268a78a9be3
24.90411
149
0.59651
false
false
false
false
thomashocking/SimpleGeo
refs/heads/master
Constants.swift
gpl-3.0
1
// // Constants.swift // LSGeo // // Created by Thomas Hocking on 11/18/16. // Copyright © 2016 Thomas Hocking. All rights reserved. // import Foundation let NamesResultsKey : String = "NamesResultsKey" let TotalResultsCountKey : String = "TotalResultsCountKey" let AdminCode1Key : String = "AdminCode1Key" let AdminCode2Key : String = "AdminCode2Key" let AdminCode3Key : String = "AdminCode3Key" let AdminName1Key : String = "AdminName1Key" let AdminName2Key : String = "AdminName2Key" let AdminName3Key : String = "AdminName3Key" let AdminName4Key : String = "AdminName4Key" let NameKey : String = "NameKey" let ToponymNameKey : String = "ToponymNameKey" let ContinentCodeKey : String = "ContinentCodeKey" let CountryCodeKey : String = "CountryCodeKey" let CountryNameKey : String = "CountryNameKey" let PopulationKey : String = "PopulationKey" //used for wikipedia requests. let WikiTitleKey : String = "WikiTitleKey" let WikiSummaryKey : String = "WikiSummaryKey" let WikiURLKey : String = "WikiURLKey" let WikiFeatureKey : String = "WikiFeatureKey" let AlternateNamesKey : String = "AlternateNamesKey" let AlternateNameKey : String = "AlternateNameKey" let AlternateLanguageKey : String = "AlternateLanguageKey" let IDKey : String = "IDKey" let FeatureClassKey : String = "FeatureClassKey" let FeatureCodeKey : String = "FeatureCodeKey" let FeatureClassNameKey : String = "FeatureClassNameKey" let FeatureNameKey : String = "FeatureNameKey" let NamesScoreKey : String = "NamesScoreKey" let LatitudeKey : String = "LatitudeKey" let LongitudeKey : String = "LongitudeKey" let DistanceKey : String = "DistanceKey" let ElevationKey : String = "ElevationKey" let LanguageKey : String = "LanguageKey" //Wiki let RankKey : String = "RankKey" //Wiki let TimeZoneInfoKey : String = "TimeZoneInfoKey" let TimeZoneDSTOffsetKey : String = "TimeZoneDSTOffsetKey" let TimeZoneGMTOffsetKey : String = "TimeZoneGMTOffsetKey" let TimeZoneIDKey : String = "TimeZoneIDKey" let ErrorResponseKey : String = "ErrorResponseKey" let ErrorMessageKey : String = "ErrorMessageKey" let ErrorCodeKey : String = "ErrorCodeKey"
38a33950c986ae8c0375d0add92bf373
30.235294
58
0.768832
false
false
false
false
iadmir/Signal-iOS
refs/heads/master
Signal/src/call/CallAudioService.swift
gpl-3.0
1
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import AVFoundation public let CallAudioServiceSessionChanged = Notification.Name("CallAudioServiceSessionChanged") struct AudioSource: Hashable { let image: UIImage let localizedName: String let portDescription: AVAudioSessionPortDescription? // The built-in loud speaker / aka speakerphone let isBuiltInSpeaker: Bool // The built-in quiet speaker, aka the normal phone handset receiver earpiece let isBuiltInEarPiece: Bool init(localizedName: String, image: UIImage, isBuiltInSpeaker: Bool, isBuiltInEarPiece: Bool, portDescription: AVAudioSessionPortDescription? = nil) { self.localizedName = localizedName self.image = image self.isBuiltInSpeaker = isBuiltInSpeaker self.isBuiltInEarPiece = isBuiltInEarPiece self.portDescription = portDescription } init(portDescription: AVAudioSessionPortDescription) { let isBuiltInEarPiece = portDescription.portType == AVAudioSessionPortBuiltInMic // portDescription.portName works well for BT linked devices, but if we are using // the built in mic, we have "iPhone Microphone" which is a little awkward. // In that case, instead we prefer just the model name e.g. "iPhone" or "iPad" let localizedName = isBuiltInEarPiece ? UIDevice.current.localizedModel : portDescription.portName self.init(localizedName: localizedName, image:#imageLiteral(resourceName: "button_phone_white"), // TODO isBuiltInSpeaker: false, isBuiltInEarPiece: isBuiltInEarPiece, portDescription: portDescription) } // Speakerphone is handled separately from the other audio routes as it doesn't appear as an "input" static var builtInSpeaker: AudioSource { return self.init(localizedName: NSLocalizedString("AUDIO_ROUTE_BUILT_IN_SPEAKER", comment: "action sheet button title to enable built in speaker during a call"), image: #imageLiteral(resourceName: "button_phone_white"), //TODO isBuiltInSpeaker: true, isBuiltInEarPiece: false) } // MARK: Hashable static func ==(lhs: AudioSource, rhs: AudioSource) -> Bool { // Simply comparing the `portDescription` vs the `portDescription.uid` // caused multiple instances of the built in mic to turn up in a set. if lhs.isBuiltInSpeaker && rhs.isBuiltInSpeaker { return true } if lhs.isBuiltInSpeaker || rhs.isBuiltInSpeaker { return false } guard let lhsPortDescription = lhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } guard let rhsPortDescription = rhs.portDescription else { owsFail("only the built in speaker should lack a port description") return false } return lhsPortDescription.uid == rhsPortDescription.uid } var hashValue: Int { guard let portDescription = self.portDescription else { assert(self.isBuiltInSpeaker) return "Built In Speaker".hashValue } return portDescription.uid.hash } } @objc class CallAudioService: NSObject, CallObserver { private let TAG = "[CallAudioService]" private var vibrateTimer: Timer? private let audioPlayer = AVAudioPlayer() private let handleRinging: Bool class Sound { let TAG = "[Sound]" static let incomingRing = Sound(filePath: "r", fileExtension: "caf", loop: true) static let outgoingRing = Sound(filePath: "outring", fileExtension: "mp3", loop: true) static let dialing = Sound(filePath: "sonarping", fileExtension: "mp3", loop: true) static let busy = Sound(filePath: "busy", fileExtension: "mp3", loop: false) static let failure = Sound(filePath: "failure", fileExtension: "mp3", loop: false) let filePath: String let fileExtension: String let url: URL let loop: Bool init(filePath: String, fileExtension: String, loop: Bool) { self.filePath = filePath self.fileExtension = fileExtension self.url = Bundle.main.url(forResource: self.filePath, withExtension: self.fileExtension)! self.loop = loop } lazy var player: AVAudioPlayer? = { let newPlayer: AVAudioPlayer? do { try newPlayer = AVAudioPlayer(contentsOf: self.url, fileTypeHint: nil) if self.loop { newPlayer?.numberOfLoops = -1 } } catch { owsFail("\(self.TAG) failed to build audio player with error: \(error)") newPlayer = nil } return newPlayer }() } // MARK: Vibration config private let vibrateRepeatDuration = 1.6 // Our ring buzz is a pair of vibrations. // `pulseDuration` is the small pause between the two vibrations in the pair. private let pulseDuration = 0.2 // MARK: - Initializers init(handleRinging: Bool) { self.handleRinging = handleRinging } // MARK: - CallObserver internal func stateDidChange(call: SignalCall, state: CallState) { AssertIsOnMainThread() self.handleState(call:call) } internal func muteDidChange(call: SignalCall, isMuted: Bool) { AssertIsOnMainThread() Logger.verbose("\(TAG) in \(#function) is no-op") } internal func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) { AssertIsOnMainThread() ensureProperAudioSession(call: call) } private func ensureProperAudioSession(call: SignalCall?) { AssertIsOnMainThread() guard let call = call else { setAudioSession(category: AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault) return } // Disallow bluetooth while (and only while) the user has explicitly chosen the built in receiver. // // NOTE: I'm actually not sure why this is required - it seems like we should just be able // to setPreferredInput to call.audioSource.portDescription in this case, // but in practice I'm seeing the call revert to the bluetooth headset. // Presumably something else (in WebRTC?) is touching our shared AudioSession. - mjk let options: AVAudioSessionCategoryOptions = call.audioSource?.isBuiltInEarPiece == true ? [] : [.allowBluetooth] if call.state == .localRinging { // SoloAmbient plays through speaker, but respects silent switch setAudioSession(category: AVAudioSessionCategorySoloAmbient, mode: AVAudioSessionModeDefault) } else if call.hasLocalVideo { // Apple Docs say that setting mode to AVAudioSessionModeVideoChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVideoChat, options: options) } else { // Apple Docs say that setting mode to AVAudioSessionModeVoiceChat has the // side effect of setting options: .allowBluetooth, when I remove the (seemingly unnecessary) // option, and inspect AVAudioSession.sharedInstance.categoryOptions == 0. And availableInputs // does not include my linked bluetooth device setAudioSession(category: AVAudioSessionCategoryPlayAndRecord, mode: AVAudioSessionModeVoiceChat, options: options) } let session = AVAudioSession.sharedInstance() do { // It's important to set preferred input *after* ensuring properAudioSession // because some sources are only valid for certain category/option combinations. let existingPreferredInput = session.preferredInput if existingPreferredInput != call.audioSource?.portDescription { Logger.info("\(TAG) changing preferred input: \(String(describing: existingPreferredInput)) -> \(String(describing: call.audioSource?.portDescription))") try session.setPreferredInput(call.audioSource?.portDescription) } if call.isSpeakerphoneEnabled { try session.overrideOutputAudioPort(.speaker) } else { try session.overrideOutputAudioPort(.none) } } catch { owsFail("\(TAG) failed setting audio source with error: \(error) isSpeakerPhoneEnabled: \(call.isSpeakerphoneEnabled)") } } // MARK: - Service action handlers public func didUpdateVideoTracks(call: SignalCall?) { Logger.verbose("\(TAG) in \(#function)") self.ensureProperAudioSession(call: call) } public func handleState(call: SignalCall) { assert(Thread.isMainThread) Logger.verbose("\(TAG) in \(#function) new state: \(call.state)") // Stop playing sounds while switching audio session so we don't // get any blips across a temporary unintended route. stopPlayingAnySounds() self.ensureProperAudioSession(call: call) switch call.state { case .idle: handleIdle(call: call) case .dialing: handleDialing(call: call) case .answering: handleAnswering(call: call) case .remoteRinging: handleRemoteRinging(call: call) case .localRinging: handleLocalRinging(call: call) case .connected: handleConnected(call: call) case .localFailure: handleLocalFailure(call: call) case .localHangup: handleLocalHangup(call: call) case .remoteHangup: handleRemoteHangup(call: call) case .remoteBusy: handleBusy(call: call) } } private func handleIdle(call: SignalCall) { Logger.debug("\(TAG) \(#function)") } private func handleDialing(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // HACK: Without this async, dialing sound only plays once. I don't really understand why. Does the audioSession // need some time to settle? Is somethign else interrupting our session? DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { self.play(sound: Sound.dialing) } } private func handleAnswering(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() } private func handleRemoteRinging(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // FIXME if you toggled speakerphone before this point, the outgoing ring does not play through speaker. Why? self.play(sound: Sound.outgoingRing) } private func handleLocalRinging(call: SignalCall) { Logger.debug("\(TAG) in \(#function)") AssertIsOnMainThread() startRinging(call: call) } private func handleConnected(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() } private func handleLocalFailure(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() play(sound: Sound.failure) } private func handleLocalHangup(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() handleCallEnded(call: call) } private func handleRemoteHangup(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() vibrate() handleCallEnded(call:call) } private func handleBusy(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() play(sound: Sound.busy) // Let the busy sound play for 4 seconds. The full file is longer than necessary DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4.0) { self.handleCallEnded(call: call) } } private func handleCallEnded(call: SignalCall) { Logger.debug("\(TAG) \(#function)") AssertIsOnMainThread() // Stop solo audio, revert to default. setAudioSession(category: AVAudioSessionCategoryAmbient) } // MARK: Playing Sounds var currentPlayer: AVAudioPlayer? private func stopPlayingAnySounds() { currentPlayer?.stop() stopAnyRingingVibration() } private func play(sound: Sound) { guard let newPlayer = sound.player else { owsFail("\(self.TAG) unable to build player") return } Logger.info("\(self.TAG) playing sound: \(sound.filePath)") // It's important to stop the current player **before** starting the new player. In the case that // we're playing the same sound, since the player is memoized on the sound instance, we'd otherwise // stop the sound we just started. self.currentPlayer?.stop() newPlayer.play() self.currentPlayer = newPlayer } // MARK: - Ringing private func startRinging(call: SignalCall) { guard handleRinging else { Logger.debug("\(TAG) ignoring \(#function) since CallKit handles it's own ringing state") return } vibrateTimer = WeakTimer.scheduledTimer(timeInterval: vibrateRepeatDuration, target: self, userInfo: nil, repeats: true) {[weak self] _ in self?.ringVibration() } vibrateTimer?.fire() play(sound: Sound.incomingRing) } private func stopAnyRingingVibration() { guard handleRinging else { Logger.debug("\(TAG) ignoring \(#function) since CallKit handles it's own ringing state") return } Logger.debug("\(TAG) in \(#function)") // Stop vibrating vibrateTimer?.invalidate() vibrateTimer = nil } // public so it can be called by timer via selector public func ringVibration() { // Since a call notification is more urgent than a message notifaction, we // vibrate twice, like a pulse, to differentiate from a normal notification vibration. vibrate() DispatchQueue.default.asyncAfter(deadline: DispatchTime.now() + pulseDuration) { self.vibrate() } } func vibrate() { // TODO implement HapticAdapter for iPhone7 and up AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) } // MARK - AudioSession MGMT // TODO move this to CallAudioSession? // Note this method is sensitive to the current audio session configuration. // Specifically if you call it while speakerphone is enabled you won't see // any connected bluetooth routes. var availableInputs: [AudioSource] { let session = AVAudioSession.sharedInstance() guard let availableInputs = session.availableInputs else { // I'm not sure why this would happen, but it may indicate an error. // In practice, I haven't seen it on iOS9+. // // I *have* seen it on iOS8, but it doesn't seem to cause any problems, // so we do *not* trigger the assert on that platform. if #available(iOS 9.0, *) { owsFail("No available inputs or inputs not ready") } return [AudioSource.builtInSpeaker] } Logger.info("\(TAG) in \(#function) availableInputs: \(availableInputs)") return [AudioSource.builtInSpeaker] + availableInputs.map { portDescription in return AudioSource(portDescription: portDescription) } } func currentAudioSource(call: SignalCall) -> AudioSource? { if let audioSource = call.audioSource { return audioSource } // Before the user has specified an audio source on the call, we rely on the existing // system state to determine the current audio source. // If a bluetooth is connected, this will be bluetooth, otherwise // this will be the receiver. let session = AVAudioSession.sharedInstance() guard let portDescription = session.currentRoute.inputs.first else { return nil } return AudioSource(portDescription: portDescription) } private func setAudioSession(category: String, mode: String? = nil, options: AVAudioSessionCategoryOptions = AVAudioSessionCategoryOptions(rawValue: 0)) { AssertIsOnMainThread() let session = AVAudioSession.sharedInstance() var audioSessionChanged = false do { if #available(iOS 10.0, *), let mode = mode { let oldCategory = session.category let oldMode = session.mode let oldOptions = session.categoryOptions guard oldCategory != category || oldMode != mode || oldOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.TAG) audio session changed category: \(oldCategory) -> \(category) ") } if oldMode != mode { Logger.debug("\(self.TAG) audio session changed mode: \(oldMode) -> \(mode) ") } if oldOptions != options { Logger.debug("\(self.TAG) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, mode: mode, options: options) } else { let oldCategory = session.category let oldOptions = session.categoryOptions guard session.category != category || session.categoryOptions != options else { return } audioSessionChanged = true if oldCategory != category { Logger.debug("\(self.TAG) audio session changed category: \(oldCategory) -> \(category) ") } if oldOptions != options { Logger.debug("\(self.TAG) audio session changed options: \(oldOptions) -> \(options) ") } try session.setCategory(category, with: options) } } catch { let message = "\(self.TAG) in \(#function) failed to set category: \(category) mode: \(String(describing: mode)), options: \(options) with error: \(error)" owsFail(message) } if audioSessionChanged { Logger.info("\(TAG) in \(#function)") // Update call view synchronously; already on main thread. NotificationCenter.default.post(name:CallAudioServiceSessionChanged, object: nil) } } }
be5c605eed0735817af02505309e0674
37.040777
169
0.625236
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Shepard Tab/Settings/Game Row/GameRow.swift
mit
1
// // GameRow.swift // MEGameTracker // // Created by Emily Ivie on 8/12/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit final class GameRow: UITableViewCell { // MARK: Types // MARK: Constants private let dateMessage = "Last Played: %@" // MARK: Outlets @IBOutlet private weak var photoImageView: UIImageView? @IBOutlet private weak var nameLabel: UILabel? @IBOutlet private weak var titleLabel: UILabel? @IBOutlet private weak var dateLabel: UILabel? // MARK: Properties internal fileprivate(set) var shepard: Shepard? // MARK: Change Listeners And Change Status Flags private var isDefined = false // MARK: Lifecycle Events public override func layoutSubviews() { if !isDefined { clearRow() } super.layoutSubviews() } // MARK: Initialization /// Sets up the row - expects to be in main/UI dispatch queue. /// Also, table layout needs to wait for this, /// so don't run it asynchronously or the layout will be wrong. public func define(shepard: Shepard?) { isDefined = true self.shepard = shepard setup() } // MARK: Populate Data private func setup() { guard photoImageView != nil else { return } if !UIWindow.isInterfaceBuilder { Photo.addPhoto(from: shepard, toView: photoImageView, placeholder: UIImage.placeholder()) } nameLabel?.text = shepard?.fullName ?? "" titleLabel?.text = shepard?.title dateLabel?.text = String(format: dateMessage, shepard?.modifiedDate.format(.typical) ?? "") } /// Resets all text in the cases where row UI loads before data/setup. /// (I prefer to use sample UI data in nib, so I need it to disappear before UI displays.) private func clearRow() { photoImageView?.image = nil nameLabel?.text = "" titleLabel?.text = "" dateLabel?.text = "" } }
a1d4b766bf2fa705125c1aaf106c2675
25.924242
93
0.705684
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Card/Controller/CardTableViewController.swift
mit
2
// // CardTableViewController.swift // DereGuide // // Created by zzk on 16/6/5. // Copyright © 2016 zzk. All rights reserved. // import UIKit class CardTableViewController: BaseCardTableViewController { override func viewDidLoad() { super.viewDidLoad() print(NSHomeDirectory()) print(Locale.preferredLanguages.first ?? "") if UserDefaults.standard.value(forKey: "DownloadAtStart") as? Bool ?? true { check(.all) } registerForPreviewing(with: self, sourceView: view) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { searchBar.resignFirstResponder() let card = cardList[indexPath.row] let vc = CDTabViewController(card: card) vc.hidesBottomBarWhenPushed = true navigationController?.pushViewController(vc, animated: true) } } @available(iOS 9.0, *) extension CardTableViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { viewControllerToCommit.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewControllerToCommit, animated: true) } func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location), let cell = tableView.cellForRow(at: indexPath) else { return nil } let card = cardList[indexPath.row] let vc = CDTabViewController(card: card) vc.preferredContentSize = CGSize(width: view.shortSide, height: CGSSGlobal.spreadImageHeight * view.shortSide / CGSSGlobal.spreadImageWidth + 68) previewingContext.sourceRect = cell.frame return vc } }
fca204f87c086389b9b705e8614bc31a
33.649123
153
0.687089
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
refs/heads/master
source/Core/Classes/Audio/RSAudioPlayer.swift
apache-2.0
1
// // RSAudioPlayer.swift // ResearchSuiteExtensions // // Created by James Kizer on 4/4/18. // import UIKit import AVFoundation open class RSAudioPlayer: UIStackView, AVAudioPlayerDelegate { public enum RSAudioPlayerError: Error { case NotSupported } var audioPlayer: AVAudioPlayer! var audioInterruptedObserver: NSObjectProtocol! var playPauseButton: RSLabelButton! var resetButton: RSLabelButton! var isReset: Bool { return self.audioPlayer.currentTime == 0.0 } var isPlaying: Bool { return self.audioPlayer.isPlaying } private func setupAudioSession() throws { if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: [.defaultToSpeaker]) self.audioInterruptedObserver = NotificationCenter.default.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: nil, using: { [weak self](notification) in self?.audioPlayer.pause() }) } else { throw RSAudioPlayerError.NotSupported } } public convenience init?(fileURL: URL) { guard let audioPlayer = try? AVAudioPlayer(contentsOf: fileURL) else { return nil } self.init(arrangedSubviews: []) self.axis = .horizontal self.distribution = .fillEqually self.spacing = 16.0 self.audioPlayer = audioPlayer self.audioPlayer.delegate = self if self.audioPlayer.prepareToPlay() == false { return nil } do { try self.setupAudioSession() } catch { return nil } self.playPauseButton = RSLabelButton(frame: CGRect()) self.playPauseButton.addTarget(self, action: #selector(playPauseButtonTapped), for: .touchUpInside) self.playPauseButton.configuredColor = self.tintColor self.addArrangedSubview(self.playPauseButton) self.resetButton = RSLabelButton(frame: CGRect()) self.resetButton.addTarget(self, action: #selector(resetButtonTapped), for: .touchUpInside) self.resetButton.configuredColor = self.tintColor self.addArrangedSubview(self.resetButton) self.updateUI() } deinit { NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil) } private func reset() { self.audioPlayer.stop() self.audioPlayer.currentTime = 0.0 self.audioPlayer.prepareToPlay() self.updateUI() } @objc func playPauseButtonTapped() { if self.isPlaying { self.audioPlayer.pause() } else { self.audioPlayer.play() } self.updateUI() } @objc func resetButtonTapped() { self.reset() } public func updateUI() { self.playPauseButton.setTitle(self.isPlaying ? "Pause Audio" : "Play Audio", for: .normal) self.resetButton.setTitle("Reset Audio", for: .normal) self.resetButton.isEnabled = !self.isReset } public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if flag { self.reset() } } public func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) { // debugPrint(player) // debugPrint(error) } }
4992838c08447e70c9e0280f28779b91
25.791367
195
0.594791
false
false
false
false
cuappdev/DiningStack
refs/heads/master
DiningStack/DataManager.swift
mit
1
// // DataManager.swift // Eatery // // Created by Eric Appel on 10/8/14. // Copyright (c) 2014 CUAppDev. All rights reserved. // import Foundation import Alamofire import SwiftyJSON let separator = ":------------------------------------------" /** Router Endpoints enum */ internal enum Router: URLConvertible { /// Returns a URL that conforms to RFC 2396 or throws an `Error`. /// /// - throws: An `Error` if the type cannot be converted to a `URL`. /// /// - returns: A URL or throws an `Error`. public func asURL() throws -> URL { let path: String = { switch self { case .root: return "/" case .eateries: return "/eateries.json" } }() if let url = URL(string: Router.baseURLString + path) { return url } else { throw AFError.invalidURL(url: self) } } static let baseURLString = "https://now.dining.cornell.edu/api/1.0/dining" case root case eateries } /** Keys for Cornell API These will be in the response dictionary */ public enum APIKey : String { // Top Level case status = "status" case data = "data" case meta = "meta" case message = "message" // Data case eateries = "eateries" // Eatery case identifier = "id" case slug = "slug" case name = "name" case nameShort = "nameshort" case eateryTypes = "eateryTypes" case aboutShort = "aboutshort" case latitude = "latitude" case longitude = "longitude" case hours = "operatingHours" case payment = "payMethods" case phoneNumber = "contactPhone" case campusArea = "campusArea" case address = "location" case diningItems = "diningItems" // Hours case date = "date" case events = "events" // Events case startTime = "startTimestamp" case endTime = "endTimestamp" case startFormat = "start" case endFormat = "end" case menu = "menu" case summary = "calSummary" // Events/Payment/CampusArea/EateryTypes case description = "descr" case shortDescription = "descrshort" // Menu case items = "items" case category = "category" case item = "item" case healthy = "healthy" // Meta case copyright = "copyright" case timestamp = "responseDttm" // External case weekday = "weekday" case external = "external" } /** Enumerated Server Response - Success: String for the status if the request was a success. */ enum Status: String { case success = "success" } /** Error Types - ServerError: An error arose from the server-side of things */ enum DataError: Error { case serverError } public enum DayOfTheWeek: Int { case sunday = 1 case monday case tuesday case wednesday case thursday case friday case saturday init?(string: String) { switch string.lowercased() { case "sunday": self = .sunday case "monday": self = .monday case "tuesday": self = .tuesday case "wednesday": self = .wednesday case "thursday": self = .thursday case "friday": self = .friday case "saturday": self = .saturday default: return nil } } static func ofDateSpan(_ string: String) -> [DayOfTheWeek]? { let partition = string.lowercased().split { $0 == "-" } .map(String.init) switch partition.count { case 2: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } guard let end = DayOfTheWeek(string: partition[1]) else { return nil } var result: [DayOfTheWeek] = [] let endValue = start.rawValue <= end.rawValue ? end.rawValue : end.rawValue + 7 for dayValue in start.rawValue...endValue { guard let day = DayOfTheWeek(rawValue: dayValue % 7) else { return nil } result.append(day) } return result case 1: guard let start = DayOfTheWeek(string: partition[0]) else { return nil } return [start] default: return nil } } func getDate() -> Date { let startOfToday = Calendar.current.startOfDay(for: Date()) let weekDay = Calendar.current.component(.weekday, from: Date()) let daysAway = (rawValue - weekDay + 7) % 7 let endDate = Calendar.current.date(byAdding: .weekday, value: daysAway, to: startOfToday) ?? Date() return endDate } func getDateString() -> String { let date = getDate() let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: date) } func getTimeStamp(_ timeString: String) -> Date { let endDate = getDate() let formatter = DateFormatter() formatter.dateFormat = "h:mma" let timeIntoEndDate = formatter.date(from: timeString) ?? Date() let components = Calendar.current.dateComponents([.hour, .minute], from: timeIntoEndDate) return Calendar.current.date(byAdding: components, to: endDate) ?? Date() } } /// Top-level class to communicate with Cornell Dining public class DataManager: NSObject { /// Gives a shared instance of `DataManager` public static let sharedInstance = DataManager() /// List of all the Dining Locations with parsed events and menus private (set) public var eateries: [Eatery] = [] /** Sends a GET request to the Cornell API to get the events for all eateries and stores them in user documents. - parameter force: Boolean indicating that the data should be refreshed even if the cache is invalid. - parameter completion: Completion block called upon successful receipt and parsing of the data or with an error if there was one. Use `-eateries` to get the parsed response. */ public func fetchEateries(_ force: Bool, completion: ((Error?) -> Void)?) { if eateries.count > 0 && !force { completion?(nil) return } let req = Alamofire.request(Router.eateries) func processData (_ data: Data) { let json = JSON(data) if (json[APIKey.status.rawValue].stringValue != Status.success.rawValue) { completion?(DataError.serverError) // do something is message return } let eateryList = json["data"]["eateries"] self.eateries = eateryList.map { Eatery(json: $0.1) } let externalEateryList = kExternalEateries["eateries"]! let externalEateries = externalEateryList.map { Eatery(json: $0.1) } //don't add duplicate external eateries //Uncomment after CU Dining Pushes Eatery with marketing for external in externalEateries { if !eateries.contains(where: { $0.slug == external.slug }) { eateries.append(external) } } completion?(nil) } if let request = req.request, !force { let cached = URLCache.shared.cachedResponse(for: request) if let info = cached?.userInfo { // This is hacky because the server doesn't support caching really // and even if it did it is too slow to respond to make it worthwhile // so I'm going to try to screw with the cache policy depending // upon the age of the entry in the cache if let date = info["date"] as? Double { let maxAge: Double = 24 * 60 * 60 let now = Date().timeIntervalSince1970 if now - date <= maxAge { processData(cached!.data) return } } } } req.responseData { (resp) -> Void in let data = resp.result let request = resp.request let response = resp.response if let data = data.value, let response = response, let request = request { let cached = CachedURLResponse(response: response, data: data, userInfo: ["date": NSDate().timeIntervalSince1970], storagePolicy: .allowed) URLCache.shared.storeCachedResponse(cached, for: request) } if let jsonData = data.value { processData(jsonData) } else { completion?(data.error) } } } }
5584e5f8d55a0d0c2b4904523a75c483
29.230508
159
0.559879
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Reader/Select Interests/ReaderInterestsStyleGuide.swift
gpl-2.0
2
import Foundation import WordPressShared class ReaderInterestsStyleGuide { // MARK: - View Styles public class func applyTitleLabelStyles(label: UILabel) { label.font = WPStyleGuide.serifFontForTextStyle(.largeTitle, fontWeight: .medium) label.textColor = .text } public class func applySubtitleLabelStyles(label: UILabel) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = .text } // MARK: - Collection View Cell Styles public class var cellLabelTitleFont: UIFont { return WPStyleGuide.fontForTextStyle(.body) } public class func applyCellLabelStyle(label: UILabel, isSelected: Bool) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = isSelected ? .white : .text label.backgroundColor = isSelected ? .muriel(color: .primary, .shade40) : .quaternaryBackground } // MARK: - Compact Collection View Cell Styles public class var compactCellLabelTitleFont: UIFont { return WPStyleGuide.fontForTextStyle(.footnote) } public class func applyCompactCellLabelStyle(label: UILabel) { label.font = Self.compactCellLabelTitleFont label.textColor = .text label.backgroundColor = .quaternaryBackground } // MARK: - Next Button public class var buttonContainerViewBackgroundColor: UIColor { if #available(iOS 13, *) { return .tertiarySystemBackground } return .white } public class func applyNextButtonStyle(button: FancyButton) { let disabledBackgroundColor: UIColor let titleColor: UIColor disabledBackgroundColor = UIColor(light: .systemGray4, dark: .systemGray3) titleColor = .textTertiary button.disabledTitleColor = titleColor button.disabledBorderColor = disabledBackgroundColor button.disabledBackgroundColor = disabledBackgroundColor } // MARK: - Loading public class func applyLoadingLabelStyles(label: UILabel) { label.font = WPStyleGuide.fontForTextStyle(.body) label.textColor = .textSubtle } public class func applyActivityIndicatorStyles(indicator: UIActivityIndicatorView) { indicator.color = UIColor(light: .black, dark: .white) } } class ReaderSuggestedTopicsStyleGuide { /// The array of colors from the designs /// Note: I am explictly using the MurielColor names instead of using the semantic ones /// since these are explicit and not semantic colors. static let colors: [TopicStyle] = [ // Green .init(textColor: .init(colorName: .green, section: .text), backgroundColor: .init(colorName: .green, section: .background), borderColor: .init(colorName: .green, section: .border)), // Purple .init(textColor: .init(colorName: .purple, section: .text), backgroundColor: .init(colorName: .purple, section: .background), borderColor: .init(colorName: .purple, section: .border)), // Yellow .init(textColor: .init(colorName: .yellow, section: .text), backgroundColor: .init(colorName: .yellow, section: .background), borderColor: .init(colorName: .yellow, section: .border)), // Orange .init(textColor: .init(colorName: .orange, section: .text), backgroundColor: .init(colorName: .orange, section: .background), borderColor: .init(colorName: .orange, section: .border)), ] private class func topicStyle(for index: Int) -> TopicStyle { let colorCount = Self.colors.count // Safety feature if for some reason the count of returned topics ever increases past 4 we will // loop through the list colors again. return Self.colors[index % colorCount] } public static var topicFont: UIFont = WPStyleGuide.fontForTextStyle(.footnote) public class func applySuggestedTopicStyle(label: UILabel, with index: Int) { let style = Self.topicStyle(for: index) label.font = Self.topicFont label.textColor = style.textColor.color() label.layer.borderColor = style.borderColor.color().cgColor label.layer.borderWidth = .hairlineBorderWidth label.layer.backgroundColor = style.backgroundColor.color().cgColor } // MARK: - Color Representation struct TopicStyle { let textColor: TopicColor let backgroundColor: TopicColor let borderColor: TopicColor struct TopicColor { enum StyleSection { case text, background, border } let colorName: MurielColorName let section: StyleSection func color() -> UIColor { let lightShade: MurielColorShade let darkShade: MurielColorShade switch section { case .text: lightShade = .shade50 darkShade = .shade40 case .border: lightShade = .shade5 darkShade = .shade100 case .background: lightShade = .shade0 darkShade = .shade90 } return UIColor(light: .muriel(color: MurielColor(name: colorName, shade: lightShade)), dark: .muriel(color: MurielColor(name: colorName, shade: darkShade))) } } } }
19f447b6ab3328ed6a871f8eeab2f36d
34.767742
103
0.630051
false
false
false
false
fcanas/Compass
refs/heads/master
Compass/ChevronPathRenderer.swift
mit
1
// // ChevronPathRenderer.swift // Compass // // Created by Fabian Canas on 5/27/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import MapKit #if os(OSX) public typealias CMPSColor = NSColor #else public typealias CMPSColor = UIColor #endif public class ChevronPathRenderer: MKOverlayRenderer { public var color: CMPSColor = CMPSColor(red: 0xff/255.0, green: 0x85/255.0, blue: 0x1b/255.0, alpha: 1) public var chevronColor: CMPSColor = CMPSColor(red: 0xff/255.0, green: 0x41/255.0, blue: 0x36/255.0, alpha: 1) public let polyline: MKPolyline public var lineWidth: CGFloat = 12 public init(polyline: MKPolyline) { self.polyline = polyline super.init(overlay: polyline) setNeedsDisplayInMapRect(polyline.boundingMapRect) } public override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext!) { if !MKMapRectIntersectsRect(mapRect, MKMapRectInset(polyline.boundingMapRect, -20, -20)) { return } let path = CGPathCreateMutable() let chevronPath = CGPathCreateMutable() let firstPoint = pointForMapPoint(polyline.points()[0]) let ctxLineWidth = CGContextConvertSizeToUserSpace(context, CGSizeMake(lineWidth, lineWidth)).width * contentScaleFactor let ctxPixelWidth = CGContextConvertSizeToUserSpace(context, CGSizeMake(1, 1)).width * contentScaleFactor CGPathMoveToPoint(path, nil, firstPoint.x, firstPoint.y) CGPathMoveToPoint(chevronPath, nil, firstPoint.x, firstPoint.y) var offset: CGFloat = 0.0 for idx in 1...(polyline.pointCount - 1) { let nextPoint = pointForMapPoint(polyline.points()[idx]) CGPathAddLineToPoint(path, nil, nextPoint.x, nextPoint.y) let lastPoint = CGPathGetCurrentPoint(path) offset = chevronToPoint(chevronPath, point: nextPoint, size: ctxLineWidth, offset: offset) } CGContextSetLineJoin(context, kCGLineJoinRound) CGContextSetLineCap(context, kCGLineCapRound) CGContextAddPath(context, path) CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, ctxLineWidth) CGContextStrokePath(context) CGContextSetLineJoin(context, kCGLineJoinMiter) CGContextSetLineCap(context, kCGLineCapSquare) CGContextAddPath(context, chevronPath) CGContextSetFillColorWithColor(context, chevronColor.CGColor) CGContextSetLineWidth(context, ctxPixelWidth) CGContextFillPath(context) } private func pointDist(point1: CGPoint!, point2: CGPoint!) -> CGFloat { return sqrt(pow(point1.x - point2.x, 2.0) + pow(point1.y - point2.y, 2.0)) } private func chevronToPoint(path: CGMutablePathRef!, point: CGPoint, size: CGFloat!, offset: CGFloat) -> CGFloat { let startingPoint = CGPathGetCurrentPoint(path) let dx = point.x - startingPoint.x let dy = point.y - startingPoint.y let w: CGFloat = size / 2 let h: CGFloat = size / 3 let count = Int( (pointDist(startingPoint, point2: point) - offset) / (2.0 * h) ) * 2 / 3 // Create Transform for Chevron var t = CGAffineTransformMakeTranslation(startingPoint.x, startingPoint.y) t = CGAffineTransformRotate(t, -atan2(dx, dy)) t = CGAffineTransformTranslate(t, 0, offset) var overshoot = offset while overshoot < pointDist(startingPoint, point2: point) { CGPathMoveToPoint (path, &t, 0, 0) CGPathAddLineToPoint(path, &t, w, -h) CGPathAddLineToPoint(path, &t, w, 0) CGPathAddLineToPoint(path, &t, 0, h) CGPathAddLineToPoint(path, &t, -w, 0) CGPathAddLineToPoint(path, &t, -w, -h) CGPathAddLineToPoint(path, &t, 0, 0) t = CGAffineTransformTranslate(t, 0, 3 * h) overshoot += 3 * h } overshoot -= pointDist(startingPoint, point2: point) CGPathMoveToPoint(path, nil, point.x, point.y) return overshoot } }
249d3dbfd81e4c0f6cb27dca94737ab3
38.2
128
0.639295
false
false
false
false
Scorocode/scorocode-SDK-swift
refs/heads/master
todolist/SCLib/Model/SCScript.swift
mit
1
// // SCScript.swift // SC // // Created by Alexey Kuznetsov on 27/12/2016. // Copyright © 2016 Prof-IT Group OOO. All rights reserved. // import Foundation public enum ScriptJobType : String { case custom = "custom" case daily = "daily" case monthly = "monthly" case once = "once" } public struct RepeatTimer { fileprivate let kRepeatTimerCustomName = "custom" fileprivate let kRepeatTimerDailyName = "daily" fileprivate let kRepeatTimerMonthlyName = "monthly" public var custom = _custom() public var daily = _daily() public var monthly = _monthly() public struct _custom { public var days = 0 public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["days": self.days, "hours": self.hours, "minutes": self.minutes] } } public struct _daily { public var on = [Int]() public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["on": self.on, "hours": self.hours, "minutes": self.minutes] } } public struct _monthly { public var on = [Int]() public var days = [Int]() public var lastDate = false public var hours = 0 public var minutes = 0 func toDict() -> [String: Any] { return ["on": self.on, "days": self.days, "lastDate": self.lastDate, "hours": self.hours, "minutes": self.minutes] } } public func toDict() -> [String: Any] { var dict = [String: Any]() dict.updateValue(self.custom.toDict(), forKey: kRepeatTimerCustomName) dict.updateValue(self.daily.toDict(), forKey: kRepeatTimerDailyName) dict.updateValue(self.monthly.toDict(), forKey: kRepeatTimerMonthlyName) return dict } } public class SCScript { public var id: String? public var path: String? public var name = "" public var description = "" public var code = "" public var jobStartAt = SCDate(Date()) public var isActiveJob = false public var jobType = ScriptJobType.once public var ACL = [String]() public var repeatTimer = RepeatTimer() public init(id: String) { self.id = id } public init(path: String) { self.path = path } // Запуск скрипта public func run(pool: [String: Any], debug: Bool, callback: @escaping (Bool, SCError?) -> Void) { guard self.id != nil || self.path != nil else { callback(false, SCError.system("Укажите id скрипта или путь к скрипту.")) return } SCAPI.sharedInstance.runScript(scriptId: self.id, scriptPath: self.path, pool: pool, debug: debug, callback: callback) } // Получение скрипта public func load(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.getScript(scriptId: self.id!) { (success, error, result, script) in if script != nil { self.path = script?.path ?? "" self.name = script?.name ?? "" self.description = script?.description ?? "" self.code = script?.code ?? "" self.jobStartAt = script?.jobStartAt ?? SCDate(Date()) self.isActiveJob = script?.isActiveJob ?? false self.jobType = script?.jobType ?? ScriptJobType.once self.ACL = script?.ACL ?? [String]() self.repeatTimer = script?.repeatTimer ?? RepeatTimer() } callback(success, error, result) } } // Создание нового скрипта public func create(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.path != nil else { callback(false, SCError.system("путь скрипта не задан."), nil) return } SCAPI.sharedInstance.createScript(script: self, callback: callback) } // Изменение скрипта public func save(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.saveScript(script: self, callback: callback) } // Удаление скрипта public func delete(callback: @escaping (Bool, SCError?, [String: Any]?) -> Void) { guard self.id != nil else { callback(false, SCError.system("id скрипта не задан."), nil) return } SCAPI.sharedInstance.deleteScript(scriptId: self.id!, callback: callback) } }
b3b5d15776b674e83d15739df53cd381
31.635135
126
0.574327
false
false
false
false
aatalyk/swift-algorithm-club
refs/heads/master
Radix Sort/radixSort.swift
mit
2
/* Sorting Algorithm that sorts an input array of integers digit by digit. */ // NOTE: This implementation does not handle negative numbers func radixSort(_ array: inout [Int] ) { let radix = 10 //Here we define our radix to be 10 var done = false var index: Int var digit = 1 //Which digit are we on? while !done { //While our sorting is not completed done = true //Assume it is done for now var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets for _ in 1...radix { buckets.append([]) } for number in array { index = number / digit //Which bucket will we access? buckets[index % radix].append(number) if done && index > 0 { //If we arent done, continue to finish, otherwise we are done done = false } } var i = 0 for j in 0..<radix { let bucket = buckets[j] for number in bucket { array[i] = number i += 1 } } digit *= radix //Move to the next digit } }
eed4948fc94e7cef1fb62431847bc66b
22.5
103
0.579093
false
false
false
false
rain2540/RGAppTools
refs/heads/master
Sources/Extensions/Basic/Int+RGAppTools.swift
mpl-2.0
1
// // Int+RGAppTools.swift // RGAppTools // // Created by RAIN on 16/2/2. // Copyright © 2016-2017 Smartech. All rights reserved. // import UIKit extension Int { public var rat: IntExtension { return IntExtension(int: self) } public static var rat: IntExtension.Type { return IntExtension.self } } // MARK: - public struct IntExtension { private var int: Int fileprivate init(int: Int) { self.int = int } } // MARK: - Farmatted Output extension IntExtension { /// 格式化输出字符串 /// - Parameter format: 以字符串形式表示的输出格式 /// - Returns: 格式化输出结果 public func string(format: String) -> String { return String(format: "%\(format)d", int) } /// 格式化输出 /// - Parameter fmt: 以字符串形式表示的输出格式 /// - Returns: 格式化输出结果 @available(*, deprecated, renamed: "string(format:)") public func format(_ fmt: String) -> String { return String(format: "%\(fmt)d", int) } } // MARK: - Transfer extension IntExtension { /// 转换为对应的 CGFloat 值 public var cgFloatValue: CGFloat { return CGFloat(int) } } // MARK: - Random Number extension IntExtension { /// 创建 lower - upper 之间的一个随机数 /// - Parameter lower: 范围下限,默认为 0 /// - Parameter upper: 范围上限,默认为 UInt32.max /// - Returns: 获取到的随机数 public static func randomNumber( lower: Int = 0, upper: Int = Int(UInt32.max)) -> Int { return lower + Int(arc4random_uniform(UInt32(upper - lower))) } /// 创建 range 范围内的一个随机数 /// - Parameter range: 产生随机数的范围 /// - Returns: 获取到的随机数 public static func randomNumber(range: Range<Int>) -> Int { return randomNumber(lower: range.lowerBound, upper: range.upperBound) } /// 创建 lower - upper 之间的若干个随机数 /// - Parameters: /// - lower: 范围下限,默认为 0 /// - upper: 范围上限,默认为 UInt32.max /// - size: 随机数个数。默认为 10 /// - Returns: 获取到的随机数数组 public static func randomNumbers( lower: Int = 0, upper: Int = Int(UInt32.max), size: Int = 10) -> [Int] { var res: [Int] = [] for _ in 0 ..< size { res.append(randomNumber(lower: lower, upper: upper)) } return res } /// 创建 range 范围内的若干个随机数 /// - Parameters: /// - range: 产生随机数的范围 /// - size: 随机数个数,默认为 10 /// - Returns: 获取到的随机数数组 public static func randomNumbers( range: Range<Int>, size: Int = 10) -> [Int] { var res: [Int] = [] for _ in 0 ..< size { res.append(randomNumber(range: range)) } return res } }
2f6d0d03043b9ecb2d33a4ea17182f61
18.03937
73
0.609595
false
false
false
false
yasuoza/graphPON
refs/heads/master
graphPON iOS/ViewControllers/DailyChartViewController.swift
mit
1
import UIKit import GraphPONDataKit import JBChartFramework class DailyChartViewController: BaseChartViewController, JBBarChartViewDelegate, JBBarChartViewDataSource, HddServiceListTableViewControllerDelegate, DisplayPacketLogsSelectTableViewControllerDelegate { @IBOutlet weak var chartViewContainerView: ChartViewContainerView! let mode: Mode = .Daily private var chartData: [CGFloat]? private var chartHorizontalData: [String]? private var hdoService: HdoService? { didSet { self.serviceCode = hdoService?.hdoServiceCode } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = self.mode.backgroundColor() self.chartViewContainerView.chartView.delegate = self self.chartViewContainerView.chartView.dataSource = self self.chartViewContainerView.chartView.headerPadding = kJBAreaChartViewControllerChartHeaderPadding self.chartViewContainerView.chartView.footerPadding = kJBAreaChartViewControllerChartFooterPadding self.chartViewContainerView.chartView.backgroundColor = self.mode.backgroundColor() let footerView = LineChartFooterView(frame: CGRectMake( self.chartViewContainerView.chartView.frame.origin.x, ceil(self.view.bounds.size.height * 0.5) - ceil(kJBLineChartViewControllerChartFooterHeight * 0.5), self.chartViewContainerView.chartView.bounds.width, kJBLineChartViewControllerChartFooterHeight + kJBLineChartViewControllerChartPadding )) footerView.backgroundColor = UIColor.clearColor() footerView.leftLabel.textColor = UIColor.whiteColor() footerView.rightLabel.textColor = UIColor.whiteColor() self.chartViewContainerView.chartView.footerView = footerView self.chartInformationView.setHidden(true, animated: false) if self.serviceCode == nil { if let hdoService = PacketInfoManager.sharedManager.hddServices.first?.hdoServices?.first { self.hdoService = hdoService } } self.reBuildChartData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.reloadChartView(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserverForName( PacketInfoManager.LatestPacketLogsDidFetchNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { _ in self.reBuildChartData() self.reloadChartView(true) }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - Actions override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "HddServiceListFromDailyChartSegue" { let navigationController = segue.destinationViewController as! UINavigationController let hddServiceListViewController = navigationController.topViewController as! HddServiceListTableViewController hddServiceListViewController.delegate = self hddServiceListViewController.mode = .Daily hddServiceListViewController.selectedService = self.hdoService?.number ?? "" } else if segue.identifier == "DisplayPacketLogsSelectFromSummaryChartSegue" { let navigationController = segue.destinationViewController as! UINavigationController let displayPacketLogSelectViewController = navigationController.topViewController as! DisplayPacketLogsSelectTableViewController displayPacketLogSelectViewController.delegate = self displayPacketLogSelectViewController.selectedFilteringSegment = self.chartDataFilteringSegment } } @IBAction func chartSegmentedControlValueDidChanged(segmentedControl: UISegmentedControl) { self.chartDurationSegment = HdoService.Duration(rawValue: segmentedControl.selectedSegmentIndex)! self.reBuildChartData() self.reloadChartView(false) } func reloadChartView(animated: Bool) { if let hdoService = self.hdoService { self.navigationItem.title = "\(hdoService.nickName) (\(self.chartDataFilteringSegment.text()))" } if let chartData = self.chartData where chartData.count > 0 { self.chartViewContainerView.chartView.minimumValue = 0 self.chartViewContainerView.chartView.maximumValue = maxElement(chartData) } if let footerView = self.chartViewContainerView.chartView.footerView as? LineChartFooterView { footerView.leftLabel.text = self.hdoService?.packetLogs.first?.dateText() footerView.rightLabel.text = self.hdoService?.packetLogs.last?.dateText() footerView.sectionCount = self.chartData?.count ?? 0 footerView.hidden = footerView.sectionCount == 0 } self.displayLatestTotalChartInformation() self.chartViewContainerView.reloadChartData() self.chartViewContainerView.chartView.setState(JBChartViewState.Expanded, animated: animated) } func displayLatestTotalChartInformation() { if let packetLog = self.hdoService?.packetLogs.last { self.chartInformationView.setTitleText( String(format: NSLocalizedString("Used in %@", comment: "Chart information title text in daily chart"), packetLog.dateText()) ) self.chartInformationView.setHidden(false, animated: true) } else { self.chartInformationView.setHidden(true, animated: false) self.informationValueLabelSeparatorView.alpha = 0.0 self.valueLabel.alpha = 0.0 return } UIView.animateWithDuration(NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.informationValueLabelSeparatorView.alpha = 1.0 self.valueLabel.text = PacketLog.stringForValue(self.chartData?.last) self.valueLabel.alpha = 1.0 }, completion: nil ) } // MARK: - Private methods func reBuildChartData() { if let hdoService = PacketInfoManager.sharedManager.hdoServiceForServiceCode(self.serviceCode) ?? PacketInfoManager.sharedManager.hddServices.first?.hdoServices?.first { self.hdoService = hdoService } else { return } self.chartData = self.hdoService?.summarizeServiceUsageInDuration( self.chartDurationSegment, couponSwitch: self.chartDataFilteringSegment ) self.chartHorizontalData = self.hdoService?.packetLogs.map { $0.dateText() } } // MARK: - JBLineChartViewDataSource func numberOfBarsInBarChartView(barChartView: JBBarChartView!) -> UInt { return UInt(self.chartData?.count ?? 0) } // MARK: - JBLineChartViewDelegate func barChartView(barChartView: JBBarChartView!, heightForBarViewAtIndex index: UInt) -> CGFloat { return self.chartData?[Int(index)] ?? 0.0 } func barChartView(barChartView: JBBarChartView!, didSelectBarAtIndex index: UInt, touchPoint: CGPoint) { let dateText = self.chartHorizontalData?[Int(index)] ?? "" self.chartInformationView.setTitleText( String(format: NSLocalizedString("Used in %@", comment: "Chart information title text in daily chart"), dateText) ) self.chartInformationView.setHidden(false, animated: true) UIView.animateWithDuration( NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.valueLabel.text = PacketLog.stringForValue(self.chartData?[Int(index)]) self.valueLabel.alpha = 1.0 }, completion: nil ) } func didDeselectBarChartView(barChartView: JBBarChartView!) { self.chartInformationView.setHidden(true, animated: true) UIView.animateWithDuration( NSTimeInterval(kJBChartViewDefaultAnimationDuration) * 0.5, delay: 0.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.valueLabel.alpha = 0.0 }, completion: { [unowned self] finish in if finish { self.displayLatestTotalChartInformation() } } ) } func barChartView(barChartView: JBBarChartView!, colorForBarViewAtIndex index: UInt) -> UIColor! { return UIColor.whiteColor() } func barSelectionColorForBarChartView(barChartView: JBBarChartView!) -> UIColor! { return UIColor(red:0.392, green:0.392, blue:0.559, alpha:1.0) } // MARK: - HddServiceListTableViewControllerDelegate func serviceDidSelectedSection(section: Int, row: Int) { self.hdoService = PacketInfoManager.sharedManager.hddServices[section].hdoServices?[row] self.reBuildChartData() if self.traitCollection.horizontalSizeClass == .Regular { self.reloadChartView(true) } } // MARK: - DisplayPacketLogsSelectTableViewControllerDelegate func displayPacketLogSegmentDidSelected(segment: Int) { self.chartDataFilteringSegment = Coupon.Switch(rawValue: segment)! self.reBuildChartData() if self.traitCollection.horizontalSizeClass == .Regular { self.reloadChartView(true) } } }
c83757ef5a9da6f6f8de02c2733e8778
39.63786
202
0.680506
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
refs/heads/master
Libraries/SwiftyJSON/Source/SwiftyJSON.swift
apache-2.0
3
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let error1 as NSError { error.memory = error1 self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case _ as NSString: _type = .String case _ as NSNull: _type = .Null case _ as NSArray: _type = .Array case _ as NSDictionary: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return self.arrayValue.count case .Dictionary: return self.dictionaryValue.count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator<(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return AnyGenerator { if let element_: AnyObject = generate_.next() { let result = ("\(index_)", JSON(element_)) index_ += 1 return result } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return AnyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return AnyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! NSDictionary if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in Array(path.reverse()) { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number.flatMap{ Int($0) } } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return Int(self.numberValue.unsignedIntegerValue) } } }
8fd7afdf0229164a5de37989de5a93b4
25.476718
264
0.526505
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/TextBarButtonItem.swift
mit
1
import UIKit /// A Themeable UIBarButtonItem with title text only class TextBarButtonItem: UIBarButtonItem, Themeable { // MARK: - Properties private var theme: Theme? override var isEnabled: Bool { get { return super.isEnabled } set { super.isEnabled = newValue if let theme = theme { apply(theme: theme) } } } // MARK: - Lifecycle @objc convenience init(title: String, target: Any?, action: Selector?) { self.init(title: title, style: .plain, target: target, action: action) } // MARK: - Themeable public func apply(theme: Theme) { self.theme = theme if let customView = customView as? UIButton { customView.tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } else { tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink } } }
af171da741078e091049b7bf60ccacee
23.794872
92
0.585315
false
false
false
false
NoManTeam/Hole
refs/heads/master
CryptoFramework/Crypto/Algorithm/AES_256_ECB/NSAESString.swift
unlicense
1
// // NSAESString.swift // 密语输入法 // // Created by macsjh on 15/10/17. // Copyright © 2015年 macsjh. All rights reserved. // import Foundation class NSAESString:NSObject { internal static func aes256_encrypt(PlainText:NSString, Key:NSString) -> NSString? { let cstr:UnsafePointer<Int8> = PlainText.cStringUsingEncoding(NSUTF8StringEncoding) let data = NSData(bytes: cstr, length:PlainText.length) //对数据进行加密 let result = data.aes256_encrypt(Key) if (result != nil && result!.length > 0 ) { return result!.toHexString() } return nil } internal static func aes256_decrypt(CipherText:String, key:NSString) -> NSString? { //转换为2进制Data guard let data = CipherText.hexStringToData() else {return nil} //对数据进行解密 let result = data.aes256_decrypt(key) if (result != nil && result!.length > 0) { return NSString(data:result!, encoding:NSUTF8StringEncoding) } return nil } }
8ce00b9b0062e786e1f1b0c07c7dc88f
24.942857
85
0.708931
false
false
false
false
aksskas/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DYZB // // Created by aksskas on 2017/9/19. // Copyright © 2017年 aksskas. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView,progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let contentCellID = "contentCell" class PageContentView: UIView { //MARK:- 定义属性 private var childVcs: [UIViewController] private var startOffsetX: CGFloat = 0 weak var delegate: PageContentViewDelegate? private weak var parentViewController: UIViewController? //MARK:- 懒加载属性 private lazy var collectionView: UICollectionView = { [weak self] in let layout = UICollectionViewFlowLayout().then { $0.itemSize = self!.bounds.size $0.minimumLineSpacing = 0 $0.minimumInteritemSpacing = 0 $0.scrollDirection = .horizontal } let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then { $0.showsVerticalScrollIndicator = false $0.isPagingEnabled = true $0.bounces = false } //设置数据源相关 collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) collectionView.dataSource = self collectionView.delegate = self return collectionView }() //MARK:- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 设置UI extension PageContentView { private func setupUI() { for childVc in childVcs { parentViewController?.addChildViewController(childVc) childVc.view.frame = bounds } addSubview(collectionView) collectionView.frame = bounds } } //MARK:- CollectionView 数据源 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() } cell.contentView.addSubview(childVcs[indexPath.item].view!) return cell } } //MARK:- Delegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { var progress: CGFloat = 0 var targetIndex: Int = 0 var sourceIndex: Int = 0 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { //左滑 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { //右滑 progress = 1 - currentOffsetX / scrollViewW + floor(currentOffsetX / scrollViewW) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } } delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK:- 对外暴露设置的方法 extension PageContentView { func setCurrentIndex(currentIndex index: Int) { let offsetX = CGFloat(index) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
3b75fdc8af65b4fbbd4a6646c95c01c7
30.386207
124
0.640299
false
false
false
false
toddkramer/Archiver
refs/heads/master
Sources/Archivable.swift
mit
1
// // Archivable.swift // // Copyright (c) 2016 Todd Kramer (http://www.tekramer.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public typealias Archive = [String: Any] public protocol Archivable: ArchiveRepresentable, UniquelyIdentifiable { static var archiver: Archiver { get } static var directoryName: String { get } init?(resourceID: String) func storeArchive() func deleteArchive() } extension Archivable { public static var archiver: Archiver { return .default } public static var directoryName: String { return String(describing: self) } static var directoryURL: URL? { return archiver.archiveDirectoryURL?.appendingPathComponent(directoryName) } var fileURL: URL? { return Self.directoryURL?.appendingPathComponent("\(id).plist") } public init?(resourceID: String) { let url = Self.directoryURL?.appendingPathComponent("\(resourceID).plist") guard let path = url?.path else { return nil } guard let archive = Self.archiver.archive(atPath: path) else { return nil } self.init(archive: archive) } public func storeArchive() { guard let directoryPath = Self.directoryURL?.path else { return } Self.archiver.createDirectoryIfNeeded(atPath: directoryPath) guard let path = fileURL?.path else { return } Self.archiver.store(archive: archiveValue, atPath: path) } public func deleteArchive() { guard let path = fileURL?.path else { return } Self.archiver.deleteArchive(atPath: path) } } extension Archivable { public static func unarchivedCollection(withIdentifiers identifiers: [String]) -> [Self] { return identifiers.flatMap { Self(resourceID: $0) } } } extension Array where Element: Archivable { public func storeArchives() { forEach { $0.storeArchive() } } }
88f79d7dd69f6c29b4f499d7558718e0
32.314607
94
0.703879
false
false
false
false
raulriera/Bike-Compass
refs/heads/master
App/Carthage/Checkouts/Alamofire/Source/ParameterEncoding.swift
mit
2
// // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case url case urlEncodedInURL case json case propertyList(PropertyListSerialization.PropertyListFormat, PropertyListSerialization.WriteOptions) case custom((URLRequestConvertible, [String: AnyObject]?) -> (URLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied. - parameter parameters: The parameters to apply. - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( _ URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (Foundation.URLRequest, NSError?) { var urlRequest = URLRequest.urlRequest guard let parameters = parameters else { return (urlRequest, nil) } var encodingError: NSError? = nil switch self { case .url, .urlEncodedInURL: func query(_ parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(isOrderedBefore: <) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joined(separator: "&") } func encodesParametersInURL(_ method: Method) -> Bool { switch self { case .urlEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: urlRequest.httpMethod!) where encodesParametersInURL(method) { if var URLComponents = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false) where !parameters.isEmpty { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = URLComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } urlRequest.httpBody = query(parameters).data( using: String.Encoding.utf8, allowLossyConversion: false ) } case .json: do { let options = JSONSerialization.WritingOptions() let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { encodingError = error as NSError } case .propertyList(let format, let options): do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { encodingError = error as NSError } case .custom(let closure): (urlRequest, encodingError) = closure(urlRequest, parameters) } return (urlRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(_ key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" // rdar://26850776 // Crash in Xcode 8 Seed 1 when trying to mutate a CharacterSet with remove var allowedCharacterSet = NSMutableCharacterSet.urlQueryAllowed() allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, OSX 10.10, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) let range = startIndex..<(endIndex ?? string.endIndex) let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring index = endIndex ?? string.endIndex } } return escaped } }
9a2a36e025c593c3416ff76a7e58ee6d
42.288973
124
0.58173
false
false
false
false
JiriTrecak/Warp
refs/heads/master
Source/WRPObject.swift
mit
1
// // WRPObject.swift // // Copyright (c) 2016 Jiri Trecak (http://jiritrecak.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. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Imports import Foundation // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Definitions // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extension // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Protocols // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Implementation open class WRPObject: NSObject { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Setup override public init() { super.init() // No initialization required - nothing to fill object with } convenience public init(fromJSON: String) { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? self.init(parameters: jsonObject as! NSDictionary) } catch let error as NSError { self.init(parameters: [:]) print ("Error while parsing a json object: \(error.domain)") } } else { self.init(parameters: NSDictionary()) } } convenience public init(fromDictionary: NSDictionary) { self.init(parameters: fromDictionary) } required public init(parameters: NSDictionary) { super.init() self.preInit() if self.debugInstantiate() { NSLog("Object type %@\nParsing using %@", self.self, parameters) } self.fillValues(parameters) self.processClosestRelationships(parameters) self.postInit() } required public init(parameters: NSDictionary, parentObject: WRPObject?) { super.init() self.preInit() if self.debugInstantiate() { NSLog("Object type %@\nParsing using %@", self.self, parameters) } self.fillValues(parameters) self.processClosestRelationships(parameters, parentObject: parentObject) self.postInit() } open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String) -> [T] { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { var buffer: [T] = [] let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? for jsonDictionary in jsonObject as! NSArray { let object = T(parameters: jsonDictionary as! NSDictionary) buffer.append(object) } return buffer } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") return [] } } else { return [] } } open static func fromArray<T: WRPObject>(_ object: NSArray) -> [T] { var buffer: [T] = [] for jsonDictionary in object { let object = T(parameters: jsonDictionary as! NSDictionary) buffer.append(object) } return buffer } open static func fromArrayInJson<T: WRPObject>(_ fromJSON: String, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] { if let jsonData: Data = fromJSON.data(using: String.Encoding.utf8, allowLossyConversion: true) { do { var buffer: [WRPObject] = [] let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? for object: Any in jsonObject as! NSArray { if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String { let type = modelClassTransformer(key) if let type = type { let object = type.init(parameters: jsonDictionary) buffer.append(object) } } } return buffer as! [T] } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") return [] } } else { return [] } } open static func fromArray<T: WRPObject>(_ object: NSArray, modelClassTypeKey : String, modelClassTransformer : ((String) -> WRPObject.Type?)) -> [T] { var buffer: [WRPObject] = [] for object: Any in object { if let jsonDictionary = object as? NSDictionary, let key = jsonDictionary[modelClassTypeKey] as? String { let type = modelClassTransformer(key) if let type = type { let object = type.init(parameters: jsonDictionary) buffer.append(object) } } } return buffer as! [T] } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - User overrides for data mapping open func propertyMap() -> [WRPProperty] { return [] } open func relationMap() -> [WRPRelation] { return [] } open func preInit() { } open func postInit() { } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Private fileprivate func fillValues(_ parameters: NSDictionary) { for element: WRPProperty in self.propertyMap() { // Dot convention self.assignValueForElement(element, parameters: parameters) } } fileprivate func processClosestRelationships(_ parameters: NSDictionary) { self.processClosestRelationships(parameters, parentObject: nil) } fileprivate func processClosestRelationships(_ parameters: NSDictionary, parentObject: WRPObject?) { for element in self.relationMap() { self.assignDataObjectForElement(element, parameters: parameters, parentObject: parentObject) } } fileprivate func assignValueForElement(_ element: WRPProperty, parameters: NSDictionary) { switch element.elementDataType { // Handle string data type case .string: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.stringFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle boolean data type case .bool: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.boolFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle double data type case .double: for elementRemoteName in element.remoteNames { if (self.setValue(.double, value: self.doubleFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle float data type case .float: for elementRemoteName in element.remoteNames { if (self.setValue(.float, value: self.floatFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle int data type case .int: for elementRemoteName in element.remoteNames { if (self.setValue(.int, value: self.intFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle int data type case .number: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.numberFromParameters(parameters, key: elementRemoteName), forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle date data type case .date: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.dateFromParameters(parameters, key: elementRemoteName, format: element.format) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle array data type case .array: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.arrayFromParameters(parameters, key: elementRemoteName) as AnyObject?, forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } // Handle dictionary data type case .dictionary: for elementRemoteName in element.remoteNames { if (self.setValue(.any, value: self.dictionaryFromParameters(parameters, key: elementRemoteName), forKey: element.localName, optional: element.optional, temporaryOptional: element.remoteNames.count > 1)) { break } } } } @discardableResult fileprivate func assignDataObjectForElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? { switch element.relationshipType { case .toOne: return self.handleToOneRelationshipWithElement(element, parameters: parameters, parentObject: parentObject) case .toMany: self.handleToManyRelationshipWithElement(element, parameters: parameters, parentObject: parentObject) } return nil } fileprivate func handleToOneRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) -> WRPObject? { if let objectData: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? { if objectData is NSDictionary { guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else { return nil } // Create object let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject) // Set child object to self.property self.setValue(.any, value: dataObject, forKey: element.localName, optional: element.optional, temporaryOptional: false) // Set inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else if inverseRelationshipType == .toMany { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } return dataObject } else if objectData is NSNull { // Set empty object to self.property self.setValue(.any, value: nil, forKey: element.localName, optional: element.optional, temporaryOptional: false) return nil } } return nil } fileprivate func handleToManyRelationshipWithElement(_ element: WRPRelation, parameters: NSDictionary, parentObject: WRPObject?) { if let objectDataPack: AnyObject? = parameters.value(forKeyPath: element.remoteName) as AnyObject?? { // While the relationship is .ToMany, we can actually add it from single entry if objectDataPack is NSDictionary { // Always override local property, there is no inserting allowed var objects: [WRPObject]? = [WRPObject]() self.setValue(objects, forKey: element.localName) guard let classType = self.elementClassType(objectDataPack as! NSDictionary, relationDescriptor: element) else { return } // Create object let dataObject = self.dataObjectFromParameters(objectDataPack as! NSDictionary, objectType: classType, parentObject: parentObject) // Set inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else if inverseRelationshipType == .toMany { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } // Append new data object to array objects!.append(dataObject) // Write new objects back self.setValue(objects, forKey: element.localName) // More objects in the same entry } else if objectDataPack is NSArray { // Always override local property, there is no inserting allowed var objects: [WRPObject]? = [WRPObject]() self.setValue(objects, forKey: element.localName) // Fill that property with data for objectData in (objectDataPack as! NSArray) { // Skip generation of this object, if the class does not exist guard let classType = self.elementClassType(objectData as! NSDictionary, relationDescriptor: element) else { continue } // Create object let dataObject = self.dataObjectFromParameters(objectData as! NSDictionary, objectType: classType, parentObject: parentObject) // Assign inverse relationship if let inverseRelationshipType = element.inverseRelationshipType, let inverseKey = element.inverseName { if inverseRelationshipType == .toOne { dataObject.setValue(.any, value: self, forKey: inverseKey, optional: true, temporaryOptional: true) // If the relationship is to .ToMany, then create data pack for that } else { var objects: [WRPObject]? = [WRPObject]() objects?.append(self) dataObject.setValue(.any, value: objects as AnyObject?, forKey: inverseKey, optional: true, temporaryOptional: true) } } // Append new data objects!.append(dataObject) } // Write new objects back self.setValue(objects, forKey: element.localName) // Null encountered, null the output } else if objectDataPack is NSNull { self.setValue(nil, forKey: element.localName) } } } fileprivate func elementClassType(_ element: NSDictionary, relationDescriptor: WRPRelation) -> WRPObject.Type? { // If there is only one class to pick from (no transform function), return the type if let type = relationDescriptor.modelClassType { return type // Otherwise use transformation function to get object type from string key } else if let transformer = relationDescriptor.modelClassTypeTransformer, let key = relationDescriptor.modelClassTypeKey { return transformer(element.object(forKey: key) as! String) } // Transformation failed // TODO: Better error handling return WRPObject.self } @discardableResult fileprivate func setValue(_ type: WRPPropertyAssignement, value: AnyObject?, forKey key: String, optional: Bool, temporaryOptional: Bool) -> Bool { if ((optional || temporaryOptional) && value == nil) { return false } if type == .any { self.setValue(value, forKey: key) } else if type == .double { if value is Double { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(value?.doubleValue, forKey: key) } else { self.setValue(nil, forKey: key) } } else if type == .int { if value is Int { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(Int32(value as! NSNumber), forKey: key) } else { self.setValue(nil, forKey: key) } } else if type == .float { if value is Float { self.setValue(value as! NSNumber, forKey: key) } else if value is NSNumber { self.setValue(value?.floatValue, forKey: key) } else { self.setValue(nil, forKey: key) } } return true } fileprivate func setDictionary(_ value: Dictionary<AnyKey, AnyKey>?, forKey: String, optional: Bool, temporaryOptional: Bool) -> Bool { if ((optional || temporaryOptional) && value == nil) { return false } self.setValue((value as AnyObject), forKey: forKey) return true } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Variable creation fileprivate func stringFromParameters(_ parameters: NSDictionary, key: String) -> String? { if let value: NSString = parameters.value(forKeyPath: key) as? NSString { return value as String } return nil } fileprivate func numberFromParameters(_ parameters: NSDictionary, key: String) -> NSNumber? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return value as NSNumber } return nil } fileprivate func intFromParameters(_ parameters: NSDictionary, key: String) -> Int? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Int(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Int(wrappedValue) { return value } return nil } fileprivate func doubleFromParameters(_ parameters: NSDictionary, key: String) -> Double? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Double(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Double(wrappedValue) { return value } return nil } fileprivate func floatFromParameters(_ parameters: NSDictionary, key: String) -> Float? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Float(value) } else if wrappedValue = parameters.value(forKeyPath: key) as? String, let value = Float(wrappedValue) { return value } return nil } fileprivate func boolFromParameters(_ parameters: NSDictionary, key: String) -> Bool? { if let value: NSNumber = parameters.value(forKeyPath: key) as? NSNumber { return Bool(value) } return nil } fileprivate func dateFromParameters(_ parameters: NSDictionary, key: String, format: String?) -> Date? { if let value: String = parameters.value(forKeyPath: key) as? String { // Create date formatter let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: value) } return nil } fileprivate func arrayFromParameters(_ parameters: NSDictionary, key: String) -> Array<AnyObject>? { if let value: Array = parameters.value(forKeyPath: key) as? Array<AnyObject> { return value } return nil } fileprivate func dictionaryFromParameters(_ parameters: NSDictionary, key: String) -> NSDictionary? { if let value: NSDictionary = parameters.value(forKeyPath: key) as? NSDictionary { return value } return nil } fileprivate func dataObjectFromParameters(_ parameters: NSDictionary, objectType: WRPObject.Type, parentObject: WRPObject?) -> WRPObject { let dataObject: WRPObject = objectType.init(parameters: parameters, parentObject: parentObject) return dataObject } fileprivate func valueForKey(_ key: String, optional: Bool) -> AnyObject? { return nil } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Object serialization open func toDictionary() -> NSDictionary { return self.toDictionaryWithSerializationOption(.none, without: []) } open func toDictionaryWithout(_ exclude: [String]) -> NSDictionary { return self.toDictionaryWithSerializationOption(.none, without: exclude) } open func toDictionaryWithOnly(_ include: [String]) -> NSDictionary { print("toDictionaryWithOnly(:) is not yet supported. Expected version: 0.2") return NSDictionary() // return self.toDictionaryWithSerializationOption(.None, with: include) } open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption) -> NSDictionary { return self.toDictionaryWithSerializationOption(option, without: []) } open func toDictionaryWithSerializationOption(_ option: WRPSerializationOption, without: [String]) -> NSDictionary { // Create output let outputParams: NSMutableDictionary = NSMutableDictionary() // Get mapping parameters, go through all of them and serialize them into output for element: WRPProperty in self.propertyMap() { // Skip element if it should be excluded if self.keyPathShouldBeExcluded(element.masterRemoteName, exclusionArray: without) { continue } // Get actual value of property let actualValue: AnyObject? = self.value(forKey: element.localName) as AnyObject? // Check for nil, if it is nil, we add <NSNull> object instead of value if (actualValue == nil) { if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKeyPath: element.remoteNames.first!) } } else { // Otherwise add value itself outputParams.setObject(self.valueOfElement(element, value: actualValue!), forKeyPath: element.masterRemoteName) } } // Now get all relationships and call .toDictionary above all of them for element: WRPRelation in self.relationMap() { if self.keyPathShouldBeExcluded(element.remoteName, exclusionArray: without) { continue } if (element.relationshipType == .toMany) { // Get data pack if let actualValues = self.value(forKey: element.localName) as? [WRPObject] { // Create data pack if exists, get all values, serialize those, and assign all of them var outputArray = [NSDictionary]() for actualValue: WRPObject in actualValues { outputArray.append(actualValue.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without))) } // Add all intros back outputParams.setObject(outputArray as AnyObject!, forKeyPath: element.remoteName) } else { // Add null value for relationship if needed if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying) } } } else { // Get actual value of property let actualValue: WRPObject? = self.value(forKey: element.localName) as? WRPObject // Check for nil, if it is nil, we add <NSNull> object instead of value if (actualValue == nil) { if (option == WRPSerializationOption.includeNullProperties) { outputParams.setObject(NSNull(), forKey: element.remoteName as NSCopying) } } else { // Otherwise add value itself outputParams.setObject(actualValue!.toDictionaryWithSerializationOption(option, without: self.keyPathForChildWithElement(element, parentRules: without)), forKey: element.remoteName as NSCopying) } } } return outputParams } fileprivate func keyPathForChildWithElement(_ element: WRPRelation, parentRules: [String]) -> [String] { if (parentRules.count > 0) { var newExlusionRules = [String]() for parentRule: String in parentRules { let objcString: NSString = parentRule as NSString let range: NSRange = objcString.range(of: String(format: "%@.", element.remoteName)) if range.location != NSNotFound && range.location == 0 { let newPath = objcString.replacingCharacters(in: range, with: "") newExlusionRules.append(newPath as String) } } return newExlusionRules } else { return [] } } fileprivate func keyPathShouldBeExcluded(_ valueKeyPath: String, exclusionArray: [String]) -> Bool { let objcString: NSString = valueKeyPath as NSString for exclustionKeyPath: String in exclusionArray { let range: NSRange = objcString.range(of: exclustionKeyPath) if range.location != NSNotFound && range.location == 0 { return true } } return false } fileprivate func valueOfElement(_ element: WRPProperty, value: AnyObject) -> AnyObject { switch element.elementDataType { case .int: return NSNumber(value: value as! Int as Int) case .float: return NSNumber(value: value as! Float as Float) case .double: return NSNumber(value: value as! Double as Double) case .bool: return NSNumber(value: value as! Bool as Bool) case .date: let formatter: DateFormatter = DateFormatter() formatter.dateFormat = element.format! return formatter.string(from: value as! Date) as AnyObject default: return value } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Convenience open func updateWithJSONString(_ jsonString: String) -> Bool { // Try to parse json data if let jsonData: Data = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: true) { // If it worked, update data of current object (dictionary is expected on root level) do { let jsonObject: AnyObject? = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject? self.fillValues(jsonObject as! NSDictionary) self.processClosestRelationships(jsonObject as! NSDictionary) return true } catch let error as NSError { print ("Error while parsing a json object: \(error.domain)") } } // Could not process json string return false } open func updateWithDictionary(_ objectData: NSDictionary) -> Bool { // Update data of current object self.fillValues(objectData) self.processClosestRelationships(objectData) return true } open func excludeOnSerialization() -> [String] { return [] } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Debug open func debugInstantiate() -> Bool { return false } override open var debugDescription: String { return "Class: \(self.self)\nContent: \(self.toDictionary().debugDescription)" } }
9986641fc9c1b1080b3ea79f6f4269a1
38.365541
214
0.545527
false
false
false
false
codestergit/swift
refs/heads/master
test/SILGen/newtype.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-RAW // RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-CANONICAL // REQUIRES: objc_interop import Newtype // CHECK-CANONICAL-LABEL: sil hidden @_T07newtype17createErrorDomain{{[_0-9a-zA-Z]*}}F // CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String) func createErrorDomain(str: String) -> ErrorDomain { // CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]]) // CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString) return ErrorDomain(rawValue: str) } // CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainVABSS8rawValue_tcfC // CHECK-RAW: bb0([[STR:%[0-9]+]] : $String, // CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain }, var, name "self" // CHECK-RAW: [[SELF:%[0-9]+]] = project_box [[SELF_BOX]] // CHECK-RAW: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-RAW: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[BORROWED_STR]]) // CHECK-RAW: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[UNINIT_SELF]] // CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]] func getRawValue(ed: ErrorDomain) -> String { return ed.rawValue } // CHECK-RAW-LABEL: sil shared [serializable] @_T0SC11ErrorDomainV8rawValueSSfg // CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain): // CHECK-RAW: [[FORCE_BRIDGE:%[0-9]+]] = function_ref @_forceBridgeFromObjectiveC_bridgeable // CHECK-RAW: [[STRING_RESULT_ADDR:%[0-9]+]] = alloc_stack $String // CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue // CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]] // CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thick String.Type // CHECK-RAW: apply [[FORCE_BRIDGE]]<String>([[STRING_RESULT_ADDR]], [[STORED_VALUE_COPY]], [[STRING_META]]) // CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = load [take] [[STRING_RESULT_ADDR]] // CHECK-RAW: return [[STRING_RESULT]] class ObjCTest { // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> { @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { return ed } // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt { @objc func integerPassThrough(_ ed: MyInt) -> MyInt { return ed } }
ce0ed517500364c9de330ce022ff03a6
55.37931
207
0.679817
false
true
false
false
tinrobots/CoreDataPlus
refs/heads/master
Sources/NSManagedObjectContext+Utils.swift
mit
1
// CoreDataPlus import CoreData extension NSManagedObjectContext { /// The persistent stores associated with the receiver (if any). public final var persistentStores: [NSPersistentStore] { return persistentStoreCoordinator?.persistentStores ?? [] } /// Returns a dictionary that contains the metadata currently stored or to-be-stored in a given persistent store. public final func metaData(for store: NSPersistentStore) -> [String: Any] { guard let persistentStoreCoordinator = persistentStoreCoordinator else { preconditionFailure("\(self.description) doesn't have a Persistent Store Coordinator.") } return persistentStoreCoordinator.metadata(for: store) } /// Adds an `object` to the store's metadata and saves it **asynchronously**. /// /// - Parameters: /// - object: Object to be added to the medata dictionary. /// - key: Object key /// - store: NSPersistentStore where is stored the metadata. /// - handler: The completion handler called when the saving is completed. public final func setMetaDataObject(_ object: Any?, with key: String, for store: NSPersistentStore, completion handler: ( (Error?) -> Void )? = nil ) { performSave(after: { context in guard let persistentStoreCoordinator = context.persistentStoreCoordinator else { preconditionFailure("\(context.description) doesn't have a Persistent Store Coordinator.") } var metaData = persistentStoreCoordinator.metadata(for: store) metaData[key] = object persistentStoreCoordinator.setMetadata(metaData, for: store) }, completion: { error in handler?(error) }) } /// Returns the entity with the specified name (if any) from the managed object model associated with the specified managed object context’s persistent store coordinator. public final func entity(forEntityName name: String) -> NSEntityDescription? { guard let persistentStoreCoordinator = persistentStoreCoordinator else { preconditionFailure("\(self.description) doesn't have a Persistent Store Coordinator.") } let entity = persistentStoreCoordinator.managedObjectModel.entitiesByName[name] return entity } } // MARK: - Fetch extension NSManagedObjectContext { /// Returns an array of objects that meet the criteria specified by a given fetch request. /// - Note: When fetching data from Core Data, you don’t always know how many values you’ll be getting back. /// Core Data solves this problem by using a subclass of `NSArray` that will dynamically pull in data from the underlying store on demand. /// On the other hand, a Swift `Array` requires having every element in the array all at once, and bridging an `NSArray` to a Swift `Array` requires retrieving every single value. /// - Warning: **Batched requests** are supported only when returning a `NSArray`. /// - SeeAlso:https://developer.apple.com/forums/thread/651325) public final func fetchNSArray<T>(_ request: NSFetchRequest<T>) throws -> NSArray { // [...] Similarly for fetch requests with batching enabled, you do not want a Swift Array but instead an NSArray to avoid making an immediate copy of the future. // https://developer.apple.com/forums/thread/651325. // swiftlint:disable force_cast let protocolRequest = request as! NSFetchRequest<NSFetchRequestResult> let results = try fetch(protocolRequest) as NSArray return results } } // MARK: - Child Context extension NSManagedObjectContext { /// Returns a `new` background `NSManagedObjectContext`. /// - Parameters: /// - asChildContext: Specifies if this new context is a child context of the current context (default *false*). public final func newBackgroundContext(asChildContext isChildContext: Bool = false) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) if isChildContext { context.parent = self } else { context.persistentStoreCoordinator = persistentStoreCoordinator } return context } /// Returns a `new` child `NSManagedObjectContext`. /// - Parameters: /// - concurrencyType: Specifies the concurrency pattern used by this child context (defaults to the parent type). public final func newChildContext(concurrencyType: NSManagedObjectContextConcurrencyType? = nil) -> NSManagedObjectContext { let type = concurrencyType ?? self.concurrencyType let context = NSManagedObjectContext(concurrencyType: type) context.parent = self return context } } // MARK: - Save extension NSManagedObjectContext { /// Returns the number of uncommitted changes (transient changes are included). public var changesCount: Int { guard hasChanges else { return 0 } return insertedObjects.count + deletedObjects.count + updatedObjects.count } /// Checks whether there are actually changes that will change the persistent store. /// - Note: The `hasChanges` method would return `true` for transient changes as well which can lead to false positives. public var hasPersistentChanges: Bool { guard hasChanges else { return false } return !insertedObjects.isEmpty || !deletedObjects.isEmpty || updatedObjects.first(where: { $0.hasPersistentChangedValues }) != nil } /// Returns the number of changes that will change the persistent store (transient changes are ignored). public var persistentChangesCount: Int { guard hasChanges else { return 0 } return insertedObjects.count + deletedObjects.count + updatedObjects.filter({ $0.hasPersistentChangedValues }).count } /// Asynchronously performs changes and then saves them. /// /// - Parameters: /// - changes: Changes to be applied in the current context before the saving operation. If they fail throwing an execption, the context will be reset. /// - completion: Block executed (on the context’s queue.) at the end of the saving operation. public final func performSave(after changes: @escaping (NSManagedObjectContext) throws -> Void, completion: ( (NSError?) -> Void )? = nil ) { // https://stackoverflow.com/questions/37837979/using-weak-strong-self-usage-in-block-core-data-swift // `perform` executes the block and then releases it. // In Swift terms it is @noescape (and in the future it may be marked that way and you won't need to use self. in noescape closures). // Until the block executes, self cannot be deallocated, but after the block executes, the cycle is immediately broken. perform { var internalError: NSError? do { try changes(self) // TODO // add an option flag to decide whether or not a context can be saved if only transient properties are changed // in that case hasPersistentChanges should be used instead of hasChanges if self.hasChanges { try self.save() } } catch { internalError = error as NSError } completion?(internalError) } } /// Synchronously performs changes and then saves them: if the changes fail throwing an execption, the context will be reset. /// /// - Throws: It throws an error in cases of failure (while applying changes or saving). public final func performSaveAndWait(after changes: (NSManagedObjectContext) throws -> Void) throws { // swiftlint:disable:next identifier_name try withoutActuallyEscaping(changes) { _changes in var internalError: NSError? performAndWait { do { try _changes(self) if hasChanges { try save() } } catch { internalError = error as NSError } } if let error = internalError { throw error } } } /// Saves the `NSManagedObjectContext` if changes are present or **rollbacks** if any error occurs. /// - Note: The rollback removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values. public final func saveOrRollBack() throws { guard hasChanges else { return } do { try save() } catch { rollback() // rolls back the pending changes throw error } } /// Saves the `NSManagedObjectContext` up to the last parent `NSManagedObjectContext`. internal final func performSaveUpToTheLastParentContextAndWait() throws { var parentContext: NSManagedObjectContext? = self while parentContext != nil { var saveError: Error? parentContext!.performAndWait { guard parentContext!.hasChanges else { return } do { try parentContext!.save() } catch { saveError = error } } parentContext = parentContext!.parent if let error = saveError { throw error } } } } // MARK: - Better PerformAndWait extension NSManagedObjectContext { /// Synchronously performs a given block on the context’s queue and returns the final result. /// - Throws: It throws an error in cases of failure. public func performAndWaitResult<T>(_ block: (NSManagedObjectContext) throws -> T) rethrows -> T { return try _performAndWait(function: performAndWait, execute: block, rescue: { throw $0 }) } /// Synchronously performs a given block on the context’s queue. /// - Throws: It throws an error in cases of failure. public func performAndWait(_ block: (NSManagedObjectContext) throws -> Void) rethrows { try _performAndWait(function: performAndWait, execute: block, rescue: { throw $0 }) } /// Helper function for convincing the type checker that the rethrows invariant holds for performAndWait. /// /// Source: https://oleb.net/blog/2018/02/performandwait/ /// Source: https://github.com/apple/swift/blob/bb157a070ec6534e4b534456d208b03adc07704b/stdlib/public/SDK/Dispatch/Queue.swift#L228-L249 private func _performAndWait<T>(function: (() -> Void) -> Void, execute work: (NSManagedObjectContext) throws -> T, rescue: ((Error) throws -> (T))) rethrows -> T { var result: T? var error: Error? // swiftlint:disable:next identifier_name withoutActuallyEscaping(work) { _work in function { do { result = try _work(self) } catch let catchedError { error = catchedError } } } if let error = error { return try rescue(error) } else { return result! } } }
4b6b5eed04b2c76a8c1748479310be00
41.772727
181
0.707275
false
false
false
false
dtop/SwiftValidate
refs/heads/master
validate/Validators/ValidatorNumeric.swift
mit
1
// // ValidatorNumeric.swift // validator // // Created by Danilo Topalovic on 19.12.15. // Copyright © 2015 Danilo Topalovic. All rights reserved. // import Foundation public class ValidatorNumeric: BaseValidator, ValidatorProtocol { /// nil is allowed public var allowNil: Bool = true /// Holds if the number can be a string representation public var allowString: Bool = true /// Holds if we accept floating point numbers public var allowFloatingPoint = true /// error message not numeric public var errorMessageNotNumeric = NSLocalizedString("Please enter avalid number", comment: "error message not numeric") /** inits - returns: the instance */ required public init( _ initializer: (ValidatorNumeric) -> () = { _ in }) { super.init() initializer(self) } /** Validates the value - parameter value: the value - parameter context: the context (if any) - throws: validation errors - returns: true on success */ override public func validate<T: Any>(_ value: T?, context: [String: Any?]?) throws -> Bool { self.emptyErrors() if self.allowNil && nil == value { return true } if let strVal: String = value as? String { if !self.allowString { return self.returnError(error: self.errorMessageNotNumeric) } if self.canBeInt(number: strVal) || (self.allowFloatingPoint && self.canBeFloat(number: strVal)) { return true } return self.returnError(error: self.errorMessageNotNumeric) } if let _ = value as? Int { return true } if self.allowFloatingPoint { if let _ = value as? Double { return true } } return self.returnError(error: self.errorMessageNotNumeric) } /** Tests if the number could be an int - parameter number: the number as string - returns: true if possible */ private func canBeInt(number: String) -> Bool { guard let _ = Int(number) else { return false } return true } /** Tests if the number could be a double - parameter number: the number as string - returns: true if possible */ private func canBeFloat(number: String) -> Bool { guard let _ = Double(number) else { return false } return true } }
7c8569c6a08a1abbcd7545de7a97507f
23.433628
125
0.534951
false
false
false
false
charmaex/poke-deck
refs/heads/master
PokeDeck/MainVC.swift
gpl-3.0
1
// // ViewController.swift // PokeDeck // // Created by Jan Dammshäuser on 24.02.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit class MainVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate { @IBOutlet weak var appView: AppView! @IBOutlet weak var collView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() collView.dataSource = self collView.delegate = self searchBar.delegate = self searchBar.returnKeyType = .Done NSNotificationCenter.defaultCenter().addObserver(self, selector: "showApp:", name: "introDone", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData", name: "reloadCollView", object: nil) } func reloadData() { collView.reloadData() } func showApp(notif: NSNotification) { appView.show() } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return PokemonService.inst.dataList.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collView.dequeueReusableCellWithReuseIdentifier("PokemonCell", forIndexPath: indexPath) as! PokemonCell cell.initializeCell(PokemonService.inst.dataList[indexPath.row]) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let pokemon = PokemonService.inst.dataList[indexPath.row] performSegueWithIdentifier("DetailVC", sender: pokemon) } func searchBarSearchButtonClicked(searchBar: UISearchBar) { view.endEditing(true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { PokemonService.inst.updateFilter(searchBar.text) if searchBar.text == nil || searchBar.text == "" { view.endEditing(false) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "DetailVC" { guard let vc = segue.destinationViewController as? DetailVC, let pokemon = sender as? Pokemon else { return } vc.pokemon = pokemon } } }
e8c6a2338300decd9068a59a70c086d4
30.879518
130
0.666289
false
false
false
false
lennet/bugreporter
refs/heads/master
Bugreporter/AppDelegate.swift
mit
1
// // AppDelegate.swift // Bugreporter // // Created by Leo Thomas on 12/07/16. // Copyright © 2016 Leonard Thomas. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var windowController: NSWindowController? let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) weak var menuController: MenuViewController? weak var menuPopover: NSPopover? override func awakeFromNib() { configureStatusItem() } func applicationDidFinishLaunching(_ aNotification: Notification) { UserPreferences.setup() DeviceObserver.shared.delegate = self NSUserNotificationCenter.default.delegate = self } func configureStatusItem() { guard let button = statusItem.button else { return } button.title = "Bugreporter" button.target = self button.action = #selector(statusItemClicked) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func statusItemClicked(sender: NSButton) { guard let menuController = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "MenuViewController") as? MenuViewController else { return } let popover = NSPopover() popover.behavior = .transient popover.contentViewController = menuController self.menuController = menuController popover.show(relativeTo: sender.frame, of: sender, preferredEdge: .minY) self.menuPopover = popover } func showDevice(name: String) { guard let selectedDevice = DeviceObserver.shared.device(withName: name) else { return } windowController = NSStoryboard(name: "Main", bundle: nil).instantiateController(withIdentifier: "DeviceWindowController") as? NSWindowController (windowController?.contentViewController as? RecordExternalDeviceViewController)?.device = selectedDevice windowController?.showWindow(self) } func showNotification(text: String) { let notification = NSUserNotification() notification.title = "Device detected" notification.informativeText = text notification.soundName = NSUserNotificationDefaultSoundName notification.hasActionButton = true NSUserNotificationCenter.default.deliver(notification) } } extension AppDelegate: DeviceObserverDelegate { func didRemoveDevice() { menuController?.reload() } func didAddDevice(name: String) { menuController?.reload() if UserPreferences.showNotifications { showNotification(text: name) } } } extension AppDelegate : NSUserNotificationCenterDelegate { func userNotificationCenter(_ center: NSUserNotificationCenter, didDeliver notification: NSUserNotification) { } func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) { guard let informativeText = notification.informativeText else { return } showDevice(name: informativeText) } }
46659b16806d0739bb03db6853daed75
31.346535
173
0.691154
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/ViewModels/ProjectEnvironmentalCommitmentCellViewModel.swift
apache-2.0
1
import KsApi import Prelude import ReactiveSwift public protocol ProjectEnvironmentalCommitmentCellViewModelInputs { /// Call to configure with a `ProjectEnvironmentalCommitment`. func configureWith(value: ProjectEnvironmentalCommitment) } public protocol ProjectEnvironmentalCommitmentCellViewModelOutputs { /// Emits a `String` of the category from the `ProjectEnvironmentalCommitment` object var categoryLabelText: Signal<String, Never> { get } /// Emits a `String` of the description from the `ProjectEnvironmentalCommitment` object var descriptionLabelText: Signal<String, Never> { get } } public protocol ProjectEnvironmentalCommitmentCellViewModelType { var inputs: ProjectEnvironmentalCommitmentCellViewModelInputs { get } var outputs: ProjectEnvironmentalCommitmentCellViewModelOutputs { get } } public final class ProjectEnvironmentalCommitmentCellViewModel: ProjectEnvironmentalCommitmentCellViewModelType, ProjectEnvironmentalCommitmentCellViewModelInputs, ProjectEnvironmentalCommitmentCellViewModelOutputs { public init() { let environmentalCommitment = self.configureWithProperty.signal .skipNil() self.categoryLabelText = environmentalCommitment .map(\.category) .map(internationalizedString) self.descriptionLabelText = environmentalCommitment.map(\.description) } fileprivate let configureWithProperty = MutableProperty<ProjectEnvironmentalCommitment?>(nil) public func configureWith(value: ProjectEnvironmentalCommitment) { self.configureWithProperty.value = value } public let categoryLabelText: Signal<String, Never> public let descriptionLabelText: Signal<String, Never> public var inputs: ProjectEnvironmentalCommitmentCellViewModelInputs { self } public var outputs: ProjectEnvironmentalCommitmentCellViewModelOutputs { self } } private func internationalizedString(for category: ProjectCommitmentCategory) -> String { switch category { case .longLastingDesign: return Strings.Long_lasting_design() case .sustainableMaterials: return Strings.Sustainable_materials() case .environmentallyFriendlyFactories: return Strings.Environmentally_friendly_factories() case .sustainableDistribution: return Strings.Sustainable_distribution() case .reusabilityAndRecyclability: return Strings.Reusability_and_recyclability() case .somethingElse: return Strings.Something_else() } }
e1535a6f2785b451befa0275ffafe9b5
36.765625
101
0.810509
false
true
false
false
lzpfmh/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers Support/AAViewController.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit import MobileCoreServices class AAViewController: UIViewController, UINavigationControllerDelegate { // MARK: - // MARK: Public vars var placeholder = BigPlaceholderView(topOffset: 0) var pendingPickClosure: ((image: UIImage) -> ())? var avatarHeight: CGFloat = DeviceType.IS_IPHONE_6P ? 336.0 : 256.0 var popover: UIPopoverController? // Content type for view tracking var content: ACPage? // Data for views var autoTrack: Bool = false { didSet { if self.autoTrack { if let u = self.uid { content = ACAllEvents_Profile_viewWithInt_(jint(u)) } if let g = self.gid { content = ACAllEvents_Group_viewWithInt_(jint(g)) } } } } var uid: Int! { didSet { if self.uid != nil { self.user = Actor.getUserWithUid(jint(self.uid)) self.isBot = user.isBot().boolValue } } } var user: ACUserVM! var isBot: Bool! var gid: Int! { didSet { if self.gid != nil { self.group = Actor.getGroupWithGid(jint(self.gid)) } } } var group: ACGroupVM! init() { super.init(nibName: nil, bundle: nil) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func showPlaceholderWithImage(image: UIImage?, title: String?, subtitle: String?) { placeholder.setImage(image, title: title, subtitle: subtitle) showPlaceholder() } func showPlaceholder() { if placeholder.superview == nil { placeholder.frame = view.bounds view.addSubview(placeholder) } } func hidePlaceholder() { if placeholder.superview != nil { placeholder.removeFromSuperview() } } func shakeView(view: UIView, originalX: CGFloat) { var r = view.frame r.origin.x = originalX let originalFrame = r var rFirst = r rFirst.origin.x = r.origin.x + 4 r.origin.x = r.origin.x - 4 UIView.animateWithDuration(0.05, delay: 0.0, options: .Autoreverse, animations: { () -> Void in view.frame = rFirst }) { (finished) -> Void in if (finished) { UIView.animateWithDuration(0.05, delay: 0.0, options: [.Repeat, .Autoreverse], animations: { () -> Void in UIView.setAnimationRepeatCount(3) view.frame = r }, completion: { (finished) -> Void in view.frame = originalFrame }) } else { view.frame = originalFrame } } } func applyScrollUi(tableView: UITableView, cell: UITableViewCell?) { let offset = min(tableView.contentOffset.y, avatarHeight) if let userCell = cell as? UserPhotoCell { userCell.userAvatarView.frame = CGRectMake(0, offset, tableView.frame.width, avatarHeight - offset) } else if let groupCell = cell as? GroupPhotoCell { groupCell.groupAvatarView.frame = CGRectMake(0, offset, tableView.frame.width, avatarHeight - offset) } var fraction: Double = 0 if (offset > 0) { if (offset > avatarHeight - 64) { fraction = 1 } else { fraction = Double(offset) / (Double(avatarHeight) - 64) } } navigationController?.navigationBar.lt_setBackgroundColor(MainAppTheme.navigation.barSolidColor.alpha(fraction)) } func applyScrollUi(tableView: UITableView) { applyScrollUi(tableView, indexPath: NSIndexPath(forRow: 0, inSection: 0)) } func applyScrollUi(tableView: UITableView, indexPath: NSIndexPath) { applyScrollUi(tableView, cell: tableView.cellForRowAtIndexPath(indexPath)) } func pickAvatar(takePhoto:Bool, closure: (image: UIImage) -> ()) { self.pendingPickClosure = closure let pickerController = AAImagePickerController() pickerController.sourceType = (takePhoto ? UIImagePickerControllerSourceType.Camera : UIImagePickerControllerSourceType.PhotoLibrary) pickerController.mediaTypes = [kUTTypeImage as String] pickerController.view.backgroundColor = MainAppTheme.list.bgColor pickerController.navigationBar.tintColor = MainAppTheme.navigation.barColor pickerController.delegate = self pickerController.navigationBar.tintColor = MainAppTheme.navigation.titleColor pickerController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MainAppTheme.navigation.titleColor] self.navigationController!.presentViewController(pickerController, animated: true, completion: nil) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() placeholder.frame = CGRectMake(0, 64, view.bounds.width, view.bounds.height - 64) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let c = content { Analytics.trackPageVisible(c) } if let u = uid { Actor.onProfileOpenWithUid(jint(u)) } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if let c = content { Analytics.trackPageHidden(c) } if let u = uid { Actor.onProfileClosedWithUid(jint(u)) } } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } func presentInNavigation(controller: UIViewController) { var navigation = AANavigationController() navigation.viewControllers = [controller] presentViewController(navigation, animated: true, completion: nil) } } extension AAViewController: UIImagePickerControllerDelegate, PECropViewControllerDelegate { func cropImage(image: UIImage) { let cropController = PECropViewController() cropController.cropAspectRatio = 1.0 cropController.keepingCropAspectRatio = true cropController.image = image cropController.delegate = self cropController.toolbarHidden = true navigationController!.presentViewController(UINavigationController(rootViewController: cropController), animated: true, completion: nil) } func cropViewController(controller: PECropViewController!, didFinishCroppingImage croppedImage: UIImage!) { if (pendingPickClosure != nil){ pendingPickClosure!(image: croppedImage) } pendingPickClosure = nil navigationController!.dismissViewControllerAnimated(true, completion: nil) } func cropViewControllerDidCancel(controller: PECropViewController!) { pendingPickClosure = nil navigationController!.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { MainAppTheme.navigation.applyStatusBar() navigationController!.dismissViewControllerAnimated(true, completion: { () -> Void in self.cropImage(image) }) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { MainAppTheme.navigation.applyStatusBar() let image = info[UIImagePickerControllerOriginalImage] as! UIImage navigationController!.dismissViewControllerAnimated(true, completion: { () -> Void in self.cropImage(image) }) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { pendingPickClosure = nil MainAppTheme.navigation.applyStatusBar() self.dismissViewControllerAnimated(true, completion: nil) } }
29a1140e517f55423b2f83c5415fa27e
33.818182
144
0.622772
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/AccessibilityAPI.swift
mit
1
import Foundation /// Indicates that the resource is compatible with the referenced accessibility API. public enum AccessibilityAPI: String, CaseIterable, Codable { case androidAccessibility = "AndroidAccessibility" case aria = "ARIA" case atk = "ATK" case atSPI = "AT-SPI" case blackberryAccessibility = "BlackberryAccessibility" case iAccessible2 = "iAccessible2" case iOSAccessibility = "iOSAccessibility" case javaAccessibility = "JavaAccessibility" case macOSXAccessibility = "MacOSXAccessibility" case msaa = "MSAA" case uiAutomation = "UIAutomation" public var displayValue: String { switch self { case .androidAccessibility: return "Android Accessibility" case .aria: return "Accessible Rich Internet Applications" case .atk: return "GNOME Accessibility Toolkit" case .atSPI: return "Assistive Technology Service Provider Interface" case .blackberryAccessibility: return "Blackberry Accessibility" case .iAccessible2: return "Microsoft Windows Accesibility" case .iOSAccessibility: return "iOS Accessibility" case .javaAccessibility: return "Java Accessibility" case .macOSXAccessibility: return "Mac OS Accessibiliy" case .msaa: return "Microsoft Active Accessibility" case .uiAutomation: return "UI Automation" } } }
1547b821f352ae5538cb119ba6b0fb26
42.40625
84
0.716343
false
false
false
false
citysite102/kapi-kaffeine
refs/heads/master
kapi-kaffeine/KPMenuUploadRequest.swift
mit
1
// // KPMenuUploadRequest.swift // kapi-kaffeine // // Created by MengHsiu Chang on 17/10/2017. // Copyright © 2017 kapi-kaffeine. All rights reserved. // import UIKit import PromiseKit import Alamofire class KPMenuUploadRequest: NetworkUploadRequest { typealias ResponseType = RawJsonResult private var cafeID: String! private var memberID: String! private var photoData: Data! var method: Alamofire.HTTPMethod { return .post } var endpoint: String { return "/menus" } var parameters: [String : Any]? { var parameters = [String : Any]() parameters["cafe_id"] = cafeID parameters["member_id"] = memberID return parameters } var fileData: Data? { return photoData } var fileKey: String? { return "menu1" } var fileName: String? { return "\(self.cafeID)-\(self.memberID)-\(arc4random_uniform(1000))" } var mimeType: String? { return "image/jpg" } var headers: [String : String] { return ["Content-Type":"multipart/form-data", "token":(KPUserManager.sharedManager.currentUser?.accessToken) ?? ""] } public func perform(_ cafeID: String, _ memberID: String?, _ photoData: Data!) -> Promise<(ResponseType)> { self.cafeID = cafeID self.memberID = memberID ?? KPUserManager.sharedManager.currentUser?.identifier self.photoData = photoData return networkClient.performUploadRequest(self).then(execute: responseHandler) } }
65512bfac29caed651a58adc8ab14622
25.015873
87
0.600976
false
false
false
false
artsy/eigen
refs/heads/main
ios/Artsy/View_Controllers/Live_Auctions/Views/AuctionLotMetadataStackScrollView.swift
mit
1
import UIKit import Interstellar class AuctionLotMetadataStackScrollView: ORStackScrollView { let aboveFoldStack = TextStack() fileprivate let toggle = AuctionLotMetadataStackScrollView.toggleSizeButton() var showAdditionalInformation: (() -> ())? var hideAdditionalInformation: (() -> ())? var aboveFoldHeightConstraint: NSLayoutConstraint! required init(viewModel: LiveAuctionLotViewModelType, salesPerson: LiveAuctionsSalesPersonType, sideMargin: String) { super.init(stackViewClass: TextStack.self) scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2) /// Anything addded to `stack` here will be hidden by default guard let stack = stackView as? TextStack else { return } /// Splits the essential lot metadata and the "lot info" button let aboveFoldStackWrapper = UIView() // Sets up the above the fold stack let name = aboveFoldStack.addArtistName("") let title = aboveFoldStack.addArtworkName("", date: nil) title.numberOfLines = 1 let estimate = aboveFoldStack.addBodyText("", topMargin: "4") let currentBid = aboveFoldStack.addBodyText("", topMargin: "4") // Want to make the wrapper hold the stack on the left aboveFoldStackWrapper.addSubview(aboveFoldStack) aboveFoldStack.alignTop("0", leading: "0", toView: aboveFoldStackWrapper) aboveFoldStack.alignBottomEdge(withView: aboveFoldStackWrapper, predicate: "0") // Then the button on the right aboveFoldStackWrapper.addSubview(toggle) toggle.alignTopEdge(withView: aboveFoldStackWrapper, predicate: "0") toggle.alignTrailingEdge(withView: aboveFoldStackWrapper, predicate: "0") toggle.addTarget(self, action: #selector(toggleTapped), for: .touchUpInside) // Then glue them together with 20px margin aboveFoldStack.constrainTrailingSpace(toView: toggle, predicate: "0") // Add the above the fold stack, to the stack stackView.addSubview(aboveFoldStackWrapper, withTopMargin: "0", sideMargin: sideMargin) // set a constraint to force it to be in small mode first aboveFoldHeightConstraint = constrainHeight(toView: aboveFoldStackWrapper, predicate: "0") // ----- Below the fold 👇 ----- // if let medium = viewModel.lotArtworkMedium { stack.addBodyText(medium, topMargin: "20", sideMargin: sideMargin) } if let dimensions = viewModel.lotArtworkDimensions { stack.addBodyText(dimensions, topMargin: "4", sideMargin: sideMargin) } if let editionInfo = viewModel.lotEditionInfo { stack.addBodyText(editionInfo, topMargin: "4", sideMargin: sideMargin) } let separatorMargin = String(Int(sideMargin) ?? 0 + 40) if let artworkdescription = viewModel.lotArtworkDescription, artworkdescription.isEmpty == false { stack.addSmallLineBreak(separatorMargin) stack.addSmallHeading("Description", sideMargin: sideMargin) stack.addBodyMarkdown(artworkdescription, sideMargin: sideMargin) } if let blurb = viewModel.lotArtistBlurb, blurb.isEmpty == false { stack.addThickLineBreak(separatorMargin) stack.addBigHeading("About the Artist", sideMargin: sideMargin) stack.addBodyMarkdown(blurb, sideMargin: sideMargin) } name.text = viewModel.lotArtist title.setTitle(viewModel.lotName, date: viewModel.lotArtworkCreationDate) estimate.text = "Estimate: \(viewModel.estimateString ?? "")" viewModel.currentBidSignal.subscribe { newCurrentBid in guard let state: LotState = viewModel.lotStateSignal.peek() else { currentBid.text = "" return } switch state { case .liveLot, .upcomingLot: if let reserve = newCurrentBid.reserve { currentBid.text = "\(newCurrentBid.bid) \(reserve)" currentBid.makeSubstringFaint(reserve) } else { currentBid.text = newCurrentBid.bid } case .closedLot: if viewModel.isBeingSold && viewModel.userIsBeingSoldTo, let winningLotValueString = salesPerson.winningLotValueString(viewModel) { currentBid.text = "Sold for: \(winningLotValueString)" } else { currentBid.text = "" } } } isScrollEnabled = false let views = stack.subviews + aboveFoldStack.subviews for label in views.filter({ $0.isKind(of: UILabel.self) || $0.isKind(of: UITextView.self) }) { label.backgroundColor = .clear } } @objc fileprivate func toggleTapped(_ button: UIButton) { if aboveFoldHeightConstraint.isActive { showAdditionalInformation?() } else { hideAdditionalInformation?() } } func setShowInfoButtonEnabled(_ enabled: Bool, animated: Bool = true) { if animated { UIView.transition(with: toggle, duration: ARAnimationQuickDuration, options: [.transitionCrossDissolve], animations: { self.toggle.isEnabled = enabled }, completion: nil) } else { toggle.isEnabled = enabled } } func showFullMetadata(_ animated: Bool) { isScrollEnabled = true toggle.setTitle("HIDE INFO", for: UIControl.State()) toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleDown), for: UIControl.State()) toggle.titleEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) toggle.imageTopConstraint?.constant = 15 aboveFoldHeightConstraint.isActive = false UIView.animateSpringIf(animated, duration: ARAnimationDuration, delay: 0, damping: 0.9, velocity: 3.5, { self.superview?.layoutIfNeeded() }) { _ in self.flashScrollIndicators() } } func hideFullMetadata(_ animated: Bool) { isScrollEnabled = false toggle.setTitle("LOT INFO", for: UIControl.State()) toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleUp), for: UIControl.State()) toggle.titleEdgeInsets = UIEdgeInsets.zero toggle.imageTopConstraint?.constant = 4 aboveFoldHeightConstraint.isActive = true UIView.animateSpringIf(animated, duration: ARAnimationDuration, delay: 0, damping: 0.9, velocity: 3.5) { self.contentOffset = CGPoint.zero self.superview?.layoutIfNeeded() } } /// A small class just to simplify changing the height constraint for the image view fileprivate class AuctionPushButton: UIButton { var imageTopConstraint: NSLayoutConstraint? } fileprivate class func toggleSizeButton() -> AuctionPushButton { let toggle = AuctionPushButton(type: .custom) // Adjusts where the text will be placed toggle.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 30, right: 17) toggle.titleLabel?.font = .sansSerifFont(withSize: 12) toggle.setTitle("LOT INFO", for: UIControl.State()) toggle.setTitleColor(.black, for: UIControl.State()) toggle.setTitleColor(.artsyGrayMedium(), for: .disabled) // Constrain the image to the left edge toggle.setImage(UIImage(asset: .LiveAuctionsDisclosureTriangleUp), for: UIControl.State()) toggle.imageView?.alignTrailingEdge(withView: toggle, predicate: "0") toggle.imageTopConstraint = toggle.imageView?.alignTopEdge(withView: toggle, predicate: "4") toggle.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal) toggle.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) // Extend its hit range, as it's like ~20px otherwise toggle.ar_extendHitTestSize(byWidth: 20, andHeight: 40) return toggle } override var intrinsicContentSize : CGSize { return aboveFoldStack.intrinsicContentSize } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
39ee8e10ac1a365a4c0672e0d1ff4b33
39.719807
130
0.654407
false
false
false
false
bolghuar/SlideMenuControllerSwift
refs/heads/master
Source/SlideMenuController.swift
mit
4
// // SlideMenuController.swift // // Created by Yuji Hato on 12/3/14. // import Foundation import UIKit public struct SlideMenuOptions { public static var leftViewWidth: CGFloat = 270.0 public static var leftBezelWidth: CGFloat = 16.0 public static var contentViewScale: CGFloat = 0.96 public static var contentViewOpacity: CGFloat = 0.5 public static var shadowOpacity: CGFloat = 0.0 public static var shadowRadius: CGFloat = 0.0 public static var shadowOffset: CGSize = CGSizeMake(0,0) public static var panFromBezel: Bool = true public static var animationDuration: CGFloat = 0.4 public static var rightViewWidth: CGFloat = 270.0 public static var rightBezelWidth: CGFloat = 16.0 public static var rightPanFromBezel: Bool = true public static var hideStatusBar: Bool = true public static var pointOfNoReturnWidth: CGFloat = 44.0 } public class SlideMenuController: UIViewController, UIGestureRecognizerDelegate { public enum SlideAction { case Open case Close } public enum TrackAction { case TapOpen case TapClose case FlickOpen case FlickClose } struct PanInfo { var action: SlideAction var shouldBounce: Bool var velocity: CGFloat } var opacityView = UIView() var mainContainerView = UIView() var leftContainerView = UIView() var rightContainerView = UIView() var mainViewController: UIViewController? var leftViewController: UIViewController? var leftPanGesture: UIPanGestureRecognizer? var leftTapGetsture: UITapGestureRecognizer? var rightViewController: UIViewController? var rightPanGesture: UIPanGestureRecognizer? var rightTapGesture: UITapGestureRecognizer? public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController initView() } public convenience init(mainViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController rightViewController = rightMenuViewController initView() } public convenience init(mainViewController: UIViewController, leftMenuViewController: UIViewController, rightMenuViewController: UIViewController) { self.init() self.mainViewController = mainViewController leftViewController = leftMenuViewController rightViewController = rightMenuViewController initView() } deinit { } func initView() { mainContainerView = UIView(frame: view.bounds) mainContainerView.backgroundColor = UIColor.clearColor() mainContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth view.insertSubview(mainContainerView, atIndex: 0) var opacityframe: CGRect = view.bounds var opacityOffset: CGFloat = 0 opacityframe.origin.y = opacityframe.origin.y + opacityOffset opacityframe.size.height = opacityframe.size.height - opacityOffset opacityView = UIView(frame: opacityframe) opacityView.backgroundColor = UIColor.blackColor() opacityView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth opacityView.layer.opacity = 0.0 view.insertSubview(opacityView, atIndex: 1) var leftFrame: CGRect = view.bounds leftFrame.size.width = SlideMenuOptions.leftViewWidth leftFrame.origin.x = leftMinOrigin(); var leftOffset: CGFloat = 0 leftFrame.origin.y = leftFrame.origin.y + leftOffset leftFrame.size.height = leftFrame.size.height - leftOffset leftContainerView = UIView(frame: leftFrame) leftContainerView.backgroundColor = UIColor.clearColor() leftContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(leftContainerView, atIndex: 2) var rightFrame: CGRect = view.bounds rightFrame.size.width = SlideMenuOptions.rightViewWidth rightFrame.origin.x = rightMinOrigin() var rightOffset: CGFloat = 0 rightFrame.origin.y = rightFrame.origin.y + rightOffset; rightFrame.size.height = rightFrame.size.height - rightOffset rightContainerView = UIView(frame: rightFrame) rightContainerView.backgroundColor = UIColor.clearColor() rightContainerView.autoresizingMask = UIViewAutoresizing.FlexibleHeight view.insertSubview(rightContainerView, atIndex: 3) addLeftGestures() addRightGestures() } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) leftContainerView.hidden = true rightContainerView.hidden = true coordinator.animateAlongsideTransition(nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.closeLeftNonAnimation() self.closeRightNonAnimation() self.leftContainerView.hidden = false self.rightContainerView.hidden = false self.removeLeftGestures() self.removeRightGestures() self.addLeftGestures() self.addRightGestures() }) } public override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge.None } public override func viewWillLayoutSubviews() { // topLayoutGuideの値が確定するこのタイミングで各種ViewControllerをセットする setUpViewController(mainContainerView, targetViewController: mainViewController) setUpViewController(leftContainerView, targetViewController: leftViewController) setUpViewController(rightContainerView, targetViewController: rightViewController) } public override func openLeft() { setOpenWindowLevel() //leftViewControllerのviewWillAppearを呼ぶため leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) openLeftWithVelocity(0.0) track(.TapOpen) } public override func openRight() { setOpenWindowLevel() //menuViewControllerのviewWillAppearを呼ぶため rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) openRightWithVelocity(0.0) } public override func closeLeft() { leftViewController?.beginAppearanceTransition(isLeftHidden(), animated: true) closeLeftWithVelocity(0.0) setCloseWindowLebel() } public override func closeRight() { rightViewController?.beginAppearanceTransition(isRightHidden(), animated: true) closeRightWithVelocity(0.0) setCloseWindowLebel() } public func addLeftGestures() { if (leftViewController != nil) { if leftPanGesture == nil { leftPanGesture = UIPanGestureRecognizer(target: self, action: "handleLeftPanGesture:") leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } if leftTapGetsture == nil { leftTapGetsture = UITapGestureRecognizer(target: self, action: "toggleLeft") leftTapGetsture!.delegate = self view.addGestureRecognizer(leftTapGetsture!) } } } public func addRightGestures() { if (rightViewController != nil) { if rightPanGesture == nil { rightPanGesture = UIPanGestureRecognizer(target: self, action: "handleRightPanGesture:") rightPanGesture!.delegate = self view.addGestureRecognizer(rightPanGesture!) } if rightTapGesture == nil { rightTapGesture = UITapGestureRecognizer(target: self, action: "toggleRight") rightTapGesture!.delegate = self view.addGestureRecognizer(rightTapGesture!) } } } public func removeLeftGestures() { if leftPanGesture != nil { view.removeGestureRecognizer(leftPanGesture!) leftPanGesture = nil } if leftTapGetsture != nil { view.removeGestureRecognizer(leftTapGetsture!) leftTapGetsture = nil } } public func removeRightGestures() { if rightPanGesture != nil { view.removeGestureRecognizer(rightPanGesture!) rightPanGesture = nil } if rightTapGesture != nil { view.removeGestureRecognizer(rightTapGesture!) rightTapGesture = nil } } public func isTagetViewController() -> Bool { // Function to determine the target ViewController // Please to override it if necessary return true } public func track(trackAction: TrackAction) { // function is for tracking // Please to override it if necessary } struct LeftPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false } func handleLeftPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isRightOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: LeftPanState.frameAtStartOfPan = leftContainerView.frame LeftPanState.startPointOfPan = panGesture.locationInView(view) LeftPanState.wasOpenAtStartOfPan = isLeftOpen() LeftPanState.wasHiddenAtStartOfPan = isLeftHidden() leftViewController?.beginAppearanceTransition(LeftPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(leftContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: var translation: CGPoint = panGesture.translationInView(panGesture.view!) leftContainerView.frame = applyLeftTranslation(translation, toFrame: LeftPanState.frameAtStartOfPan) applyLeftOpacity() applyLeftContentViewScale() case UIGestureRecognizerState.Ended: var velocity:CGPoint = panGesture.velocityInView(panGesture.view) var panInfo: PanInfo = panLeftResultInfoForVelocity(velocity) if panInfo.action == .Open { if !LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(true, animated: true) } openLeftWithVelocity(panInfo.velocity) track(.FlickOpen) } else { if LeftPanState.wasHiddenAtStartOfPan { leftViewController?.beginAppearanceTransition(false, animated: true) } closeLeftWithVelocity(panInfo.velocity) setCloseWindowLebel() track(.FlickClose) } default: break } } struct RightPanState { static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero static var wasOpenAtStartOfPan: Bool = false static var wasHiddenAtStartOfPan: Bool = false } func handleRightPanGesture(panGesture: UIPanGestureRecognizer) { if !isTagetViewController() { return } if isLeftOpen() { return } switch panGesture.state { case UIGestureRecognizerState.Began: RightPanState.frameAtStartOfPan = rightContainerView.frame RightPanState.startPointOfPan = panGesture.locationInView(view) RightPanState.wasOpenAtStartOfPan = isRightOpen() RightPanState.wasHiddenAtStartOfPan = isRightHidden() rightViewController?.beginAppearanceTransition(RightPanState.wasHiddenAtStartOfPan, animated: true) addShadowToView(rightContainerView) setOpenWindowLevel() case UIGestureRecognizerState.Changed: var translation: CGPoint = panGesture.translationInView(panGesture.view!) rightContainerView.frame = applyRightTranslation(translation, toFrame: RightPanState.frameAtStartOfPan) applyRightOpacity() applyRightContentViewScale() case UIGestureRecognizerState.Ended: var velocity: CGPoint = panGesture.velocityInView(panGesture.view) var panInfo: PanInfo = panRightResultInfoForVelocity(velocity) if panInfo.action == .Open { if !RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(true, animated: true) } openRightWithVelocity(panInfo.velocity) } else { if RightPanState.wasHiddenAtStartOfPan { rightViewController?.beginAppearanceTransition(false, animated: true) } closeRightWithVelocity(panInfo.velocity) setCloseWindowLebel() } default: break } } public func openLeftWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = leftContainerView.frame.origin.x var finalXOrigin: CGFloat = 0.0 var frame = leftContainerView.frame; frame.origin.x = finalXOrigin; var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(leftContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } } public func openRightWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = rightContainerView.frame.origin.x // CGFloat finalXOrigin = SlideMenuOptions.rightViewOverlapWidth; var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width var frame = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } addShadowToView(rightContainerView) UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(SlideMenuOptions.contentViewScale, SlideMenuOptions.contentViewScale) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.disableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() } } } public func closeLeftWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = leftContainerView.frame.origin.x var finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - finalXOrigin) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.leftContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.leftContainerView) strongSelf.enableContentInteraction() strongSelf.leftViewController?.endAppearanceTransition() } } } public func closeRightWithVelocity(velocity: CGFloat) { var xOrigin: CGFloat = rightContainerView.frame.origin.x var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin var duration: NSTimeInterval = Double(SlideMenuOptions.animationDuration) if velocity != 0.0 { duration = Double(fabs(xOrigin - CGRectGetWidth(view.bounds)) / velocity) duration = Double(fmax(0.1, fmin(1.0, duration))) } UIView.animateWithDuration(duration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { [weak self]() -> Void in if let strongSelf = self { strongSelf.rightContainerView.frame = frame strongSelf.opacityView.layer.opacity = 0.0 strongSelf.mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) } }) { [weak self](Bool) -> Void in if let strongSelf = self { strongSelf.removeShadow(strongSelf.rightContainerView) strongSelf.enableContentInteraction() strongSelf.rightViewController?.endAppearanceTransition() } } } public override func toggleLeft() { if isLeftOpen() { closeLeft() setCloseWindowLebel() // closeMenuはメニュータップ時にも呼ばれるため、closeタップのトラッキングはここに入れる track(.TapClose) } else { openLeft() } } public func isLeftOpen() -> Bool { return leftContainerView.frame.origin.x == 0.0 } public func isLeftHidden() -> Bool { return leftContainerView.frame.origin.x <= leftMinOrigin() } public override func toggleRight() { if isRightOpen() { closeRight() setCloseWindowLebel() } else { openRight() } } public func isRightOpen() -> Bool { return rightContainerView.frame.origin.x == CGRectGetWidth(view.bounds) - rightContainerView.frame.size.width } public func isRightHidden() -> Bool { return rightContainerView.frame.origin.x >= CGRectGetWidth(view.bounds) } public func changeMainViewController(mainViewController: UIViewController, close: Bool) { removeViewController(self.mainViewController) self.mainViewController = mainViewController setUpViewController(mainContainerView, targetViewController: mainViewController) if (close) { closeLeft() closeRight() } } public func changeLeftViewController(leftViewController: UIViewController, closeLeft:Bool) { removeViewController(self.leftViewController) self.leftViewController = leftViewController setUpViewController(leftContainerView, targetViewController: leftViewController) if closeLeft { self.closeLeft() } } public func changeRightViewController(rightViewController: UIViewController, closeRight:Bool) { removeViewController(self.rightViewController) self.rightViewController = rightViewController; setUpViewController(rightContainerView, targetViewController: rightViewController) if closeRight { self.closeRight() } } private func leftMinOrigin() -> CGFloat { return -SlideMenuOptions.leftViewWidth } private func rightMinOrigin() -> CGFloat { return CGRectGetWidth(view.bounds) } private func panLeftResultInfoForVelocity(velocity: CGPoint) -> PanInfo { var thresholdVelocity: CGFloat = 1000.0 var pointOfNoReturn: CGFloat = CGFloat(floor(leftMinOrigin())) + SlideMenuOptions.pointOfNoReturnWidth var leftOrigin: CGFloat = leftContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = leftOrigin <= pointOfNoReturn ? .Close : .Open; if velocity.x >= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if velocity.x <= (-1.0 * thresholdVelocity) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func panRightResultInfoForVelocity(velocity: CGPoint) -> PanInfo { var thresholdVelocity: CGFloat = -1000.0 var pointOfNoReturn: CGFloat = CGFloat(floor(CGRectGetWidth(view.bounds)) - SlideMenuOptions.pointOfNoReturnWidth) var rightOrigin: CGFloat = rightContainerView.frame.origin.x var panInfo: PanInfo = PanInfo(action: .Close, shouldBounce: false, velocity: 0.0) panInfo.action = rightOrigin >= pointOfNoReturn ? .Close : .Open if velocity.x <= thresholdVelocity { panInfo.action = .Open panInfo.velocity = velocity.x } else if (velocity.x >= (-1.0 * thresholdVelocity)) { panInfo.action = .Close panInfo.velocity = velocity.x } return panInfo } private func applyLeftTranslation(translation: CGPoint, toFrame:CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x var minOrigin: CGFloat = leftMinOrigin() var maxOrigin: CGFloat = 0.0 var newFrame: CGRect = toFrame if newOrigin < minOrigin { newOrigin = minOrigin } else if newOrigin > maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func applyRightTranslation(translation: CGPoint, toFrame: CGRect) -> CGRect { var newOrigin: CGFloat = toFrame.origin.x newOrigin += translation.x var minOrigin: CGFloat = rightMinOrigin() // var maxOrigin: CGFloat = SlideMenuOptions.rightViewOverlapWidth var maxOrigin: CGFloat = rightMinOrigin() - rightContainerView.frame.size.width var newFrame: CGRect = toFrame if newOrigin > minOrigin { newOrigin = minOrigin } else if newOrigin < maxOrigin { newOrigin = maxOrigin } newFrame.origin.x = newOrigin return newFrame } private func getOpenedLeftRatio() -> CGFloat { var width: CGFloat = leftContainerView.frame.size.width var currentPosition: CGFloat = leftContainerView.frame.origin.x - leftMinOrigin() return currentPosition / width } private func getOpenedRightRatio() -> CGFloat { var width: CGFloat = rightContainerView.frame.size.width var currentPosition: CGFloat = rightContainerView.frame.origin.x return -(currentPosition - CGRectGetWidth(view.bounds)) / width } private func applyLeftOpacity() { var openedLeftRatio: CGFloat = getOpenedLeftRatio() var opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedLeftRatio opacityView.layer.opacity = Float(opacity) } private func applyRightOpacity() { var openedRightRatio: CGFloat = getOpenedRightRatio() var opacity: CGFloat = SlideMenuOptions.contentViewOpacity * openedRightRatio opacityView.layer.opacity = Float(opacity) } private func applyLeftContentViewScale() { var openedLeftRatio: CGFloat = getOpenedLeftRatio() var scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedLeftRatio); mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func applyRightContentViewScale() { var openedRightRatio: CGFloat = getOpenedRightRatio() var scale: CGFloat = 1.0 - ((1.0 - SlideMenuOptions.contentViewScale) * openedRightRatio) mainContainerView.transform = CGAffineTransformMakeScale(scale, scale) } private func addShadowToView(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = false targetContainerView.layer.shadowOffset = SlideMenuOptions.shadowOffset targetContainerView.layer.shadowOpacity = Float(SlideMenuOptions.shadowOpacity) targetContainerView.layer.shadowRadius = SlideMenuOptions.shadowRadius targetContainerView.layer.shadowPath = UIBezierPath(rect: targetContainerView.bounds).CGPath } private func removeShadow(targetContainerView: UIView) { targetContainerView.layer.masksToBounds = true mainContainerView.layer.opacity = 1.0 } private func removeContentOpacity() { opacityView.layer.opacity = 0.0 } private func addContentOpacity() { opacityView.layer.opacity = Float(SlideMenuOptions.contentViewOpacity) } private func disableContentInteraction() { mainContainerView.userInteractionEnabled = false } private func enableContentInteraction() { mainContainerView.userInteractionEnabled = true } private func setOpenWindowLevel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelStatusBar + 1 } }) } } private func setCloseWindowLebel() { if (SlideMenuOptions.hideStatusBar) { dispatch_async(dispatch_get_main_queue(), { if let window = UIApplication.sharedApplication().keyWindow { window.windowLevel = UIWindowLevelNormal } }) } } private func setUpViewController(targetView: UIView, targetViewController: UIViewController?) { if let viewController = targetViewController { addChildViewController(viewController) viewController.view.frame = targetView.bounds targetView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } } private func removeViewController(viewController: UIViewController?) { if let _viewController = viewController { _viewController.willMoveToParentViewController(nil) _viewController.view.removeFromSuperview() _viewController.removeFromParentViewController() } } public func closeLeftNonAnimation(){ setCloseWindowLebel() var finalXOrigin: CGFloat = leftMinOrigin() var frame: CGRect = leftContainerView.frame; frame.origin.x = finalXOrigin leftContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(leftContainerView) enableContentInteraction() } public func closeRightNonAnimation(){ setCloseWindowLebel() var finalXOrigin: CGFloat = CGRectGetWidth(view.bounds) var frame: CGRect = rightContainerView.frame frame.origin.x = finalXOrigin rightContainerView.frame = frame opacityView.layer.opacity = 0.0 mainContainerView.transform = CGAffineTransformMakeScale(1.0, 1.0) removeShadow(rightContainerView) enableContentInteraction() } //pragma mark – UIGestureRecognizerDelegate public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { var point: CGPoint = touch.locationInView(view) if gestureRecognizer == leftPanGesture { return slideLeftForGestureRecognizer(gestureRecognizer, point: point) } else if gestureRecognizer == rightPanGesture { return slideRightViewForGestureRecognizer(gestureRecognizer, withTouchPoint: point) } else if gestureRecognizer == leftTapGetsture { return isLeftOpen() && !isPointContainedWithinLeftRect(point) } else if gestureRecognizer == rightTapGesture { return isRightOpen() && !isPointContainedWithinRightRect(point) } return true } private func slideLeftForGestureRecognizer( gesture: UIGestureRecognizer, point:CGPoint) -> Bool{ return isLeftOpen() || SlideMenuOptions.panFromBezel && isLeftPointContainedWithinBezelRect(point) } private func isLeftPointContainedWithinBezelRect(point: CGPoint) -> Bool{ var leftBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero var bezelWidth: CGFloat = SlideMenuOptions.leftBezelWidth CGRectDivide(view.bounds, &leftBezelRect, &tempRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(leftBezelRect, point) } private func isPointContainedWithinLeftRect(point: CGPoint) -> Bool { return CGRectContainsPoint(leftContainerView.frame, point) } private func slideRightViewForGestureRecognizer(gesture: UIGestureRecognizer, withTouchPoint point: CGPoint) -> Bool { return isRightOpen() || SlideMenuOptions.rightPanFromBezel && isRightPointContainedWithinBezelRect(point) } private func isRightPointContainedWithinBezelRect(point: CGPoint) -> Bool { var rightBezelRect: CGRect = CGRectZero var tempRect: CGRect = CGRectZero //CGFloat bezelWidth = rightContainerView.frame.size.width; var bezelWidth: CGFloat = CGRectGetWidth(view.bounds) - SlideMenuOptions.rightBezelWidth CGRectDivide(view.bounds, &tempRect, &rightBezelRect, bezelWidth, CGRectEdge.MinXEdge) return CGRectContainsPoint(rightBezelRect, point) } private func isPointContainedWithinRightRect(point: CGPoint) -> Bool { return CGRectContainsPoint(rightContainerView.frame, point) } } extension UIViewController { public func slideMenuController() -> SlideMenuController? { var viewController: UIViewController? = self while viewController != nil { if viewController is SlideMenuController { return viewController as? SlideMenuController } viewController = viewController?.parentViewController } return nil; } public func addLeftBarButtonWithImage(buttonImage: UIImage) { var leftButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleLeft") navigationItem.leftBarButtonItem = leftButton; } public func addRightBarButtonWithImage(buttonImage: UIImage) { var rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.Plain, target: self, action: "toggleRight") navigationItem.rightBarButtonItem = rightButton; } public func toggleLeft() { slideMenuController()?.toggleLeft() } public func toggleRight() { slideMenuController()?.toggleRight() } public func openLeft() { slideMenuController()?.openLeft() } public func openRight() { slideMenuController()?.openRight() } public func closeLeft() { slideMenuController()?.closeLeft() } public func closeRight() { slideMenuController()?.closeRight() } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { if let slideControlelr = slideMenuController() { let recognizers = slideControlelr.view.gestureRecognizers for recognizer in recognizers as! [UIGestureRecognizer] { if recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } } } }
72fc574f854888776bf062cd8c3ee620
37.318332
153
0.643921
false
false
false
false
carambalabs/UnsplashKit
refs/heads/master
UnsplashKit/Classes/UnsplashSource/Factories/Source/SourceRequestFactory.swift
mit
1
import Foundation import CarambaKit import CoreGraphics #if os(OSX) import AppKit #else import UIKit #endif open class SourceRequestFactory { // MARK: - Singleton open static var instance: SourceRequestFactory = SourceRequestFactory() // MARK: - Attributes let requestBuilder: UrlRequestBuilder // MARK: - Init internal init(requestBuilder: UrlRequestBuilder) { self.requestBuilder = requestBuilder } public convenience init() { self.init(requestBuilder: UrlRequestBuilder(baseUrl: "https://source.unsplash.com")) } // MARK: - Public internal func random(_ size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "random", size: size, filter: filter) } internal func search(_ terms: [String], size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "featured", size: size, filter: filter, search: terms) } internal func category(_ category: SourceCategory, size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "category/\(category.rawValue)", size: size, filter: filter) } internal func user(_ username: String, size: CGSize? = nil, filter: SourceRequestFilter? = .none) -> URLRequest { return self.get(path: "user/\(username)", size: size, filter: filter) } internal func userLikes(_ username: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "user/\(username)/likes", size: size) } internal func collection(_ collectionID: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "collection/\(collectionID)", size: size) } internal func photo(_ photoID: String, size: CGSize? = nil) -> URLRequest { return self.get(path: "/\(photoID)", size: size) } fileprivate func get(path: String, size: CGSize? = nil, filter: SourceRequestFilter? = .none, search: [String]? = nil) -> URLRequest { var fullPath = path if let size = size { fullPath += "/\(Int(size.width))x\(Int(size.height))" } if let filter = filter { fullPath += "/\(filter.rawValue)" } let request = self.requestBuilder.get(fullPath) if let terms = search { let requestWithParameters = request.with(parameters: ["search" : terms.joined(separator: ",") as AnyObject]) return requestWithParameters.build() as URLRequest } else { return request.build() as URLRequest } } } extension SourceRequestFactory { func searchParameterEncoding(_ request: NSURLRequest, params: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { let r = request as! NSMutableURLRequest if let params = params { if let searchTerms = params["search"] as? String { r.url = URL(string: "\(request.url!.absoluteString)?\(searchTerms)") } } return (request as! NSMutableURLRequest, nil) } }
5d7c616378de618e6315a7fea6ad91c7
33.03125
129
0.598714
false
false
false
false
zats/BrowserTV
refs/heads/master
BrowserTV/PreferencesViewController.swift
mit
1
// // PreferencesViewController.swift // BrowserTV // // Created by Sash Zats on 12/19/15. // Copyright © 2015 Sash Zats. All rights reserved. // import UIKit class PreferencesViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var URLs: [String] = [] private let service = CommunicationService() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) store.subscribe(self) service.start() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) store.unsubscribe(self) service.stop() } } // MARK: Gestures Handling extension PreferencesViewController { @IBAction func playPauseGestureAction(sender: AnyObject) { tableView.editing = !tableView.editing } @IBAction func menuAction(sender: AnyObject) { store.dispatch(Action(ActionKind.HidePreferences.rawValue)) } } extension PreferencesViewController: UITableViewDelegate { func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Delete } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { store.dispatch( Action( type: ActionKind.Remove.rawValue, payload:["index": indexPath.row] ) ) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { store.dispatch( Action( type: ActionKind.SelectedTab.rawValue, payload: ["index": indexPath.row] ) ) } } extension PreferencesViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return URLs.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let URLString = URLs[indexPath.row] cell.textLabel?.text = URLString return cell } } extension PreferencesViewController: StoreSubscriber { typealias StoreSubscriberStateType = AppState func newState(state: AppState) { let URLs = state.preferences.URLs.map{ String($0) } if self.URLs != URLs { self.URLs = URLs tableView.reloadData() } if let index = state.browser.selectedTabIndex { tableView.selectRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0), animated: true, scrollPosition: .Middle) } } }
ce8b8692e678cbcdadcdcb7365b20052
28.78
148
0.661182
false
false
false
false
SteveBarnegren/TweenKit
refs/heads/master
TweenKit/TweenKit/RepeatAction.swift
mit
1
// // RepeatAction.swift // TweenKit // // Created by Steve Barnegren on 19/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation /** Repeats an inner action a specified number of times */ public class RepeatAction: FiniteTimeAction { // MARK: - Public public var onBecomeActive: () -> () = {} public var onBecomeInactive: () -> () = {} /** Create with an action to repeat - Parameter action: The action to repeat - Parameter times: The number of repeats */ public init(action: FiniteTimeAction, times: Int) { self.action = action self.repeats = times self.duration = action.duration * Double(times) } // MARK: - Private Properties public var reverse: Bool = false { didSet{ action.reverse = reverse } } public internal(set) var duration: Double var action: FiniteTimeAction let repeats: Int var lastRepeatNumber = 0 // MARK: - Private Methods public func willBecomeActive() { lastRepeatNumber = 0 action.willBecomeActive() onBecomeActive() } public func didBecomeInactive() { action.didBecomeInactive() onBecomeInactive() } public func willBegin() { action.willBegin() } public func didFinish() { // We might have skipped over the action, so we still need to run the full cycle (lastRepeatNumber..<repeats-1).forEach{ _ in self.action.didFinish() self.action.willBegin() } action.didFinish() } public func update(t: CFTimeInterval) { let repeatNumber = Int( t * Double(repeats) ).constrained(max: repeats-1) (lastRepeatNumber..<repeatNumber).forEach{ _ in self.action.didFinish() self.action.willBegin() } let actionT = ( t * Double(repeats) ).fract // Avoid situation where fract is 0.0 because t is 1.0 if t > 0 && actionT == 0 { action.update(t: 1.0) } else{ action.update(t: actionT) } lastRepeatNumber = repeatNumber } } public extension FiniteTimeAction { func repeated(_ times: Int) -> RepeatAction { return RepeatAction(action: self, times: times) } }
17340fd6f3a665825c4d4af55214f7d6
23.32
88
0.57278
false
false
false
false
kperryua/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSString.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
7b3b2403f9fc1b3d6bc3286e00c90ba9
32.725191
97
0.659801
false
false
false
false
shajrawi/swift
refs/heads/master
test/Constraints/function.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift func f0(_ x: Float) -> Float {} func f1(_ x: Float) -> Float {} func f2(_ x: @autoclosure () -> Float) {} var f : Float _ = f0(f0(f)) _ = f0(1) _ = f1(f1(f)) f2(f) f2(1.0) func call_lvalue(_ rhs: @autoclosure () -> Bool) -> Bool { return rhs() } // Function returns func weirdCast<T, U>(_ x: T) -> U {} func ff() -> (Int) -> (Float) { return weirdCast } // Block <-> function conversions var funct: (Int) -> Int = { $0 } var block: @convention(block) (Int) -> Int = funct funct = block block = funct // Application of implicitly unwrapped optional functions var optFunc: ((String) -> String)! = { $0 } var s: String = optFunc("hi") // <rdar://problem/17652759> Default arguments cause crash with tuple permutation func testArgumentShuffle(_ first: Int = 7, third: Int = 9) { } testArgumentShuffle(third: 1, 2) // expected-error {{unnamed argument #2 must precede argument 'third'}} {{21-21=2, }} {{29-32=}} func rejectsAssertStringLiteral() { assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}} } // <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads func process(_ line: UInt = #line, _ fn: () -> Void) {} func process(_ line: UInt = #line) -> Int { return 0 } func dangerous() throws {} func test() { process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}} try dangerous() test() } } // <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic class A { func a(_ text:String) { } func a(_ text:String, something:Int?=nil) { } } A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}} // <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type func r22451001() -> AnyObject {} print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}} // SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler // SR-1028: Segmentation Fault: 11 when superclass init takes parameter of type 'Any' func sr590(_ x: Any) {} // expected-note {{'sr590' declared here}} sr590(3,4) // expected-error {{extra argument in call}} sr590() // expected-error {{missing argument for parameter #1 in call}} // Make sure calling with structural tuples still works. sr590(()) sr590((1, 2)) // SR-2657: Poor diagnostics when function arguments should be '@escaping'. private class SR2657BlockClass<T> { // expected-note 3 {{generic parameters are always considered '@escaping'}} let f: T init(f: T) { self.f = f } } func takesAny(_: Any) {} func foo(block: () -> (), other: () -> Int) { let _ = SR2657BlockClass(f: block) // expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}} let _ = SR2657BlockClass<()->()>(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} let _: SR2657BlockClass<()->()> = SR2657BlockClass(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} let _: SR2657BlockClass<()->()> = SR2657BlockClass<()->()>(f: block) // expected-error@-1 {{converting non-escaping parameter 'block' to generic parameter 'T' may allow it to escape}} _ = SR2657BlockClass<Any>(f: block) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} _ = SR2657BlockClass<Any>(f: other) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(block) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} takesAny(other) // expected-error {{converting non-escaping value to 'Any' may allow it to escape}} } struct S { init<T>(_ x: T, _ y: T) {} // expected-note {{generic parameters are always considered '@escaping'}} init(fn: () -> Int) { self.init({ 0 }, fn) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} } } protocol P { associatedtype U } func test_passing_noescape_function_to_dependent_member() { struct S<T : P> { // expected-note {{generic parameters are always considered '@escaping'}} func foo(_: T.U) {} } struct Q : P { typealias U = () -> Int } func test(_ s: S<Q>, fn: () -> Int) { s.foo(fn) // expected-error@-1 {{converting non-escaping parameter 'fn' to generic parameter 'Q.U' (aka '() -> Int') may allow it to escape}} } }
f60d41f929d66a03de23d2770821e44d
34.746269
152
0.663883
false
false
false
false
JGiola/swift
refs/heads/main
test/Interop/Cxx/reference/reference.swift
apache-2.0
8
// RUN: %empty-directory(%t) // RUN: %target-clangxx -c %S/Inputs/reference.cpp -I %S/Inputs -o %t/reference.o // RUN: %target-build-swift %s -I %S/Inputs -o %t/reference %t/reference.o -Xfrontend -enable-experimental-cxx-interop // RUN: %target-codesign %t/reference // RUN: %target-run %t/reference // // REQUIRES: executable_test import Reference import StdlibUnittest var ReferenceTestSuite = TestSuite("Reference") ReferenceTestSuite.test("read-lvalue-reference") { expectNotEqual(13, getStaticInt()) setStaticInt(13) expectEqual(13, getStaticIntRef().pointee) expectEqual(13, getConstStaticIntRef().pointee) } ReferenceTestSuite.test("read-rvalue-reference") { expectNotEqual(32, getStaticInt()) setStaticInt(32) expectEqual(32, getStaticIntRvalueRef().pointee) expectEqual(32, getConstStaticIntRvalueRef().pointee) } ReferenceTestSuite.test("write-lvalue-reference") { expectNotEqual(14, getStaticInt()) getStaticIntRef().pointee = 14 expectEqual(14, getStaticInt()) } ReferenceTestSuite.test("write-rvalue-reference") { expectNotEqual(41, getStaticInt()) getStaticIntRvalueRef().pointee = 41 expectEqual(41, getStaticInt()) } ReferenceTestSuite.test("pass-lvalue-reference") { expectNotEqual(21, getStaticInt()) var val: CInt = 21 setStaticIntRef(&val) expectEqual(21, getStaticInt()) } ReferenceTestSuite.test("pass-const-lvalue-reference") { expectNotEqual(22, getStaticInt()) let val: CInt = 22 setConstStaticIntRef(val) expectEqual(22, getStaticInt()) } ReferenceTestSuite.test("pass-rvalue-reference") { expectNotEqual(52, getStaticInt()) var val: CInt = 52 setStaticIntRvalueRef(&val) expectEqual(52, getStaticInt()) } ReferenceTestSuite.test("pass-const-rvalue-reference") { expectNotEqual(53, getStaticInt()) let val: CInt = 53 setConstStaticIntRvalueRef(val) expectEqual(53, getStaticInt()) } ReferenceTestSuite.test("func-reference") { let cxxF: @convention(c) () -> Int32 = getFuncRef() expectNotEqual(15, getStaticInt()) setStaticInt(15) expectEqual(15, cxxF()) } ReferenceTestSuite.test("func-rvalue-reference") { let cxxF: @convention(c) () -> Int32 = getFuncRvalueRef() expectNotEqual(61, getStaticInt()) setStaticInt(61) expectEqual(61, cxxF()) } ReferenceTestSuite.test("pod-struct-const-lvalue-reference") { expectNotEqual(getStaticInt(), 78) takeConstRef(78) expectEqual(getStaticInt(), 78) } ReferenceTestSuite.test("reference to template") { var val: CInt = 53 let ref = refToTemplate(&val) expectEqual(53, ref.pointee) ref.pointee = 42 expectEqual(42, val) } ReferenceTestSuite.test("const reference to template") { let val: CInt = 53 let ref = constRefToTemplate(val) expectEqual(53, ref.pointee) } runAllTests()
ba63e56db45acbac53811d68507d0a54
25.538462
118
0.737319
false
true
false
false
jpachecou/VIPER-Module-Generator
refs/heads/master
ViperModules/ViewController.swift
mit
1
// // ViewController.swift // ViperModules // // Created by Jonathan Pacheco on 29/12/15. // Copyright © 2015 Jonathan Pacheco. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var moduleNameCell: NSFormCell! @IBOutlet weak var projectNameCell: NSFormCell! @IBOutlet weak var developerNameCell: NSFormCell! @IBOutlet weak var organizationNameCell: NSFormCell! override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } @IBAction func generateModule(sender: AnyObject) { let model = ModuleModel().then { $0.moduleName = self.moduleNameCell.stringValue $0.projectName = self.projectNameCell.stringValue $0.developerName = self.developerNameCell.stringValue $0.organizationName = self.organizationNameCell.stringValue } let filesManager = FilesManager(moduleModel: model) filesManager.generateModule() } }
632727fe0de4d847498764aa593a7ecb
29.444444
75
0.642336
false
false
false
false
ZackKingS/Tasks
refs/heads/master
task/Classes/Main/Tools/UIViewController+ZBHUD.swift
apache-2.0
1
// // UIViewController+ZBHUD.swift // task // // Created by 柏超曾 on 2017/10/16. // Copyright © 2017年 柏超曾. All rights reserved. // import Foundation import UIKit import MBProgressHUD extension UIViewController{ func showHint(hint :String ){ //只显示文字 let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = MBProgressHUDMode.text hud.label.text = hint hud.margin = 10 hud.offset.y = 50 hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 3) } }
4d3a5170751aa40b5ccf969611a0c159
18.7
72
0.614213
false
false
false
false
10533176/TafelTaferelen
refs/heads/master
Tafel Taferelen/Extension.swift
mit
1
// // AlertFunctions.swift // Tafel Taferelen // // Created by Femke van Son on 31-01-17. // Copyright © 2017 Femke van Son. All rights reserved. // import Foundation import Firebase extension UIViewController { // MARK: functions to give alert massages for the user interface func signupErrorAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } func noGroupErrorAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: { action in let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "userVC") self.present(vc, animated: true, completion: nil) }) alert.addAction(action) present(alert, animated: true, completion: nil) } // MARK: getting the groupID of a user. WERKT NOG NIET, RETURNT VOORDAT DIE DE WAARDE HEEFT func hideKeyboardWhenTappedAroung(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard(){ view.endEditing(true) } }
9364a32f15627f688a66318468570f0b
34.711111
131
0.675793
false
false
false
false
RyanTech/SwinjectMVVMExample
refs/heads/master
ExampleViewModel/ImageSearchTableViewModel.swift
mit
1
// // ImageSearchTableViewModel.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/22/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import ReactiveCocoa import ExampleModel public final class ImageSearchTableViewModel: ImageSearchTableViewModeling { public var cellModels: PropertyOf<[ImageSearchTableViewCellModeling]> { return PropertyOf(_cellModels) } public var searching: PropertyOf<Bool> { return PropertyOf(_searching) } public var errorMessage: PropertyOf<String?> { return PropertyOf(_errorMessage) } private let _cellModels = MutableProperty<[ImageSearchTableViewCellModeling]>([]) private let _searching = MutableProperty<Bool>(false) private let _errorMessage = MutableProperty<String?>(nil) /// Accepts property injection. public var imageDetailViewModel: ImageDetailViewModelModifiable? public var loadNextPage: Action<(), (), NoError> { return Action(enabledIf: nextPageLoadable) { _ in return SignalProducer { observer, disposable in if let (_, observer) = self.nextPageTrigger.value { self._searching.value = true sendNext(observer, ()) } } } } private var nextPageLoadable: PropertyOf<Bool> { return PropertyOf( initialValue: false, producer: searching.producer.combineLatestWith(nextPageTrigger.producer).map { searching, trigger in !searching && trigger != nil }) } private let nextPageTrigger = MutableProperty<(SignalProducer<(), NoError>, Event<(), NoError> -> ())?>(nil) // SignalProducer buffer private let imageSearch: ImageSearching private let network: Networking private var foundImages = [ImageEntity]() public init(imageSearch: ImageSearching, network: Networking) { self.imageSearch = imageSearch self.network = network } public func startSearch() { func toCellModel(image: ImageEntity) -> ImageSearchTableViewCellModeling { return ImageSearchTableViewCellModel(image: image, network: self.network) as ImageSearchTableViewCellModeling } _searching.value = true nextPageTrigger.value = SignalProducer<(), NoError>.buffer() let (trigger, _) = nextPageTrigger.value! imageSearch.searchImages(nextPageTrigger: trigger) .map { response in (response.images, response.images.map { toCellModel($0) }) } .observeOn(UIScheduler()) .on(next: { images, cellModels in self.foundImages += images self._cellModels.value += cellModels self._searching.value = false }) .on(error: { error in self._errorMessage.value = error.description }) .on(event: { event in switch event { case .Completed, .Error, .Interrupted: self.nextPageTrigger.value = nil self._searching.value = false default: break } }) .start() } public func selectCellAtIndex(index: Int) { imageDetailViewModel?.update(foundImages, atIndex: index) } }
2b5fb2e11e64d94dc3fd553b3e9754a3
36.611111
137
0.615362
false
false
false
false
halo/LinkLiar
refs/heads/master
LinkLiarTests/PathsTests.swift
mit
1
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 XCTest @testable import LinkLiar class PathTests: XCTestCase { func testConfigDirectory() { let path = Paths.configDirectory XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar", path) } func testConfigDirectoryURL() { let url = Paths.configDirectoryURL XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar", url.path) } func testConfigFile() { let path = Paths.configFile XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar/config.json", path) } func testConfigFileURL() { let url = Paths.configFileURL XCTAssertEqual("/Library/Application Support/io.github.halo.LinkLiar/config.json", url.path) } func testHelperDirectory() { let path = Paths.helperDirectory XCTAssertEqual("/Library/PrivilegedHelperTools", path) } func testHelperDirectoryURL() { let url = Paths.helperDirectoryURL XCTAssertEqual("/Library/PrivilegedHelperTools", url.path) } func testHelperExecutable() { let path = Paths.helperExecutable XCTAssertEqual("/Library/PrivilegedHelperTools/io.github.halo.linkhelper", path) } func testHelperExecutableURL() { let url = Paths.helperExecutableURL XCTAssertEqual("/Library/PrivilegedHelperTools/io.github.halo.linkhelper", url.path) } func testDaemonsPlistDirectory() { let path = Paths.daemonsPlistDirectory XCTAssertEqual("/Library/LaunchDaemons", path) } func testDaemonsPlistDirectoryURL() { let url = Paths.daemonsPlistDirectoryURL XCTAssertEqual("/Library/LaunchDaemons", url.path) } func testDaemonPlistFile() { let path = Paths.daemonPlistFile XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkdaemon.plist", path) } func testDaemonPlistFileURL() { let url = Paths.daemonPlistFileURL XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkdaemon.plist", url.path) } func testHelperPlistFile() { let path = Paths.helperPlistFile XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkhelper.plist", path) } func testHelperPlistFileURL() { let url = Paths.helperPlistFileURL XCTAssertEqual("/Library/LaunchDaemons/io.github.halo.linkhelper.plist", url.path) } func testDaemonPristineExecutable() { let path = Paths.daemonPristineExecutablePath XCTAssertTrue(path.hasSuffix("/LinkLiar.app/Contents/Resources/linkdaemon")) } func testDaemonPristineExecutableURL() { let url = Paths.daemonPristineExecutableURL XCTAssertTrue(url.path.hasSuffix("/LinkLiar.app/Contents/Resources/linkdaemon")) } func testDaemonDirectory() { let path = Paths.daemonDirectory XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon", path) } func testDaemonDirectoryURL() { let url = Paths.daemonDirectoryURL XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon", url.path) } func testDaemonExecutable() { let path = Paths.daemonExecutable XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon/linkdaemon", path) } func testDaemonExecutableURL() { let url = Paths.daemonExecutableURL XCTAssertEqual("/Library/Application Support/io.github.halo.linkdaemon/linkdaemon", url.path) } }
4ac6c114923641767809915763bb32d9
35.02459
133
0.753129
false
true
false
false
darrarski/SwipeToReveal-iOS
refs/heads/master
ExampleTests/UI/TableExampleViewControllerSpec.swift
mit
1
import Quick import Nimble @testable import SwipeToRevealExample class TableExampleViewControllerSpec: QuickSpec { override func spec() { context("init with coder") { it("should throw asserion") { expect { () -> Void in _ = TableExampleViewController(coder: NSCoder()) }.to(throwAssertion()) } } context("init") { var sut: TableExampleViewController! beforeEach { sut = TableExampleViewController(assembly: Assembly()) } context("load view") { beforeEach { _ = sut.view sut.view.frame = CGRect(x: 0, y: 0, width: 320, height: 240) } describe("table view") { it("should have 1 section") { expect(sut.numberOfSections(in: sut.tableView)).to(equal(1)) } it("should have 100 rows in first section") { expect(sut.tableView(sut.tableView, numberOfRowsInSection: 0)).to(equal(100)) } it("should throw when asked for number of rows in second section") { expect { () -> Void in _ = sut.tableView(sut.tableView, numberOfRowsInSection: 1) }.to(throwAssertion()) } it("shuld not throw when asked for cell at valid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) }.notTo(throwAssertion()) } it("should return correct height for a row") { expect(sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 0))) .to(equal(88)) } it("should throw when asked for row height at invalid index path") { expect { () -> Void in _ = sut.tableView(sut.tableView, heightForRowAt: IndexPath(row: 0, section: 1)) }.to(throwAssertion()) } } } } } struct Assembly: TableExampleAssembly {} }
63d1b2253237460a3b65db84de915640
35.723077
110
0.466695
false
false
false
false
ijoshsmith/abandoned-strings
refs/heads/master
AbandonedStrings/main.swift
mit
1
#!/usr/bin/env xcrun swift // // main.swift // AbandonedStrings // // Created by Joshua Smith on 2/1/16. // Copyright © 2016 iJoshSmith. All rights reserved. // /* For overview and usage information refer to https://github.com/ijoshsmith/abandoned-strings */ import Foundation // MARK: - File processing let dispatchGroup = DispatchGroup.init() let serialWriterQueue = DispatchQueue.init(label: "writer") func findFilesIn(_ directories: [String], withExtensions extensions: [String]) -> [String] { let fileManager = FileManager.default var files = [String]() for directory in directories { guard let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: directory) else { print("Failed to create enumerator for directory: \(directory)") return [] } while let path = enumerator.nextObject() as? String { let fileExtension = (path as NSString).pathExtension.lowercased() if extensions.contains(fileExtension) { let fullPath = (directory as NSString).appendingPathComponent(path) files.append(fullPath) } } } return files } func contentsOfFile(_ filePath: String) -> String { do { return try String(contentsOfFile: filePath) } catch { print("cannot read file!!!") exit(1) } } func concatenateAllSourceCodeIn(_ directories: [String], withStoryboard: Bool) -> String { var extensions = ["h", "m", "swift", "jsbundle"] if withStoryboard { extensions.append("storyboard") } let sourceFiles = findFilesIn(directories, withExtensions: extensions) return sourceFiles.reduce("") { (accumulator, sourceFile) -> String in return accumulator + contentsOfFile(sourceFile) } } // MARK: - Identifier extraction let doubleQuote = "\"" func extractStringIdentifiersFrom(_ stringsFile: String) -> [String] { return contentsOfFile(stringsFile) .components(separatedBy: "\n") .map { $0.trimmingCharacters(in: CharacterSet.whitespaces) } .filter { $0.hasPrefix(doubleQuote) } .map { extractStringIdentifierFromTrimmedLine($0) } } func extractStringIdentifierFromTrimmedLine(_ line: String) -> String { let indexAfterFirstQuote = line.index(after: line.startIndex) let lineWithoutFirstQuote = line[indexAfterFirstQuote...] let endIndex = lineWithoutFirstQuote.index(of:"\"")! let identifier = lineWithoutFirstQuote[..<endIndex] return String(identifier) } // MARK: - Abandoned identifier detection func findStringIdentifiersIn(_ stringsFile: String, abandonedBySourceCode sourceCode: String) -> [String] { return extractStringIdentifiersFrom(stringsFile).filter { identifier in let quotedIdentifier = "\"\(identifier)\"" let quotedIdentifierForStoryboard = "\"@\(identifier)\"" let signalQuotedIdentifierForJs = "'\(identifier)'" let isAbandoned = (sourceCode.contains(quotedIdentifier) == false && sourceCode.contains(quotedIdentifierForStoryboard) == false && sourceCode.contains(signalQuotedIdentifierForJs) == false) return isAbandoned } } func stringsFile(_ stringsFile: String, without identifiers: [String]) -> String { return contentsOfFile(stringsFile) .components(separatedBy: "\n") .filter({ (line) in guard line.hasPrefix(doubleQuote) else { return true } // leave non-strings lines like comments in let lineIdentifier = extractStringIdentifierFromTrimmedLine(line.trimmingCharacters(in: CharacterSet.whitespaces)) return identifiers.contains(lineIdentifier) == false }) .joined(separator: "\n") } typealias StringsFileToAbandonedIdentifiersMap = [String: [String]] func findAbandonedIdentifiersIn(_ rootDirectories: [String], withStoryboard: Bool) -> StringsFileToAbandonedIdentifiersMap { var map = StringsFileToAbandonedIdentifiersMap() let sourceCode = concatenateAllSourceCodeIn(rootDirectories, withStoryboard: withStoryboard) let stringsFiles = findFilesIn(rootDirectories, withExtensions: ["strings"]) for stringsFile in stringsFiles { dispatchGroup.enter() DispatchQueue.global().async { let abandonedIdentifiers = findStringIdentifiersIn(stringsFile, abandonedBySourceCode: sourceCode) if abandonedIdentifiers.isEmpty == false { serialWriterQueue.async { map[stringsFile] = abandonedIdentifiers dispatchGroup.leave() } } else { NSLog("\(stringsFile) has no abandonedIdentifiers") dispatchGroup.leave() } } } dispatchGroup.wait() return map } // MARK: - Engine func getRootDirectories() -> [String]? { var c = [String]() for arg in CommandLine.arguments { c.append(arg) } c.remove(at: 0) if isOptionalParameterForStoryboardAvailable() { c.removeLast() } if isOptionaParameterForWritingAvailable() { c.remove(at: c.index(of: "write")!) } return c } func isOptionalParameterForStoryboardAvailable() -> Bool { return CommandLine.arguments.last == "storyboard" } func isOptionaParameterForWritingAvailable() -> Bool { return CommandLine.arguments.contains("write") } func displayAbandonedIdentifiersInMap(_ map: StringsFileToAbandonedIdentifiersMap) { for file in map.keys.sorted() { print("\(file)") for identifier in map[file]!.sorted() { print(" \(identifier)") } print("") } } if let rootDirectories = getRootDirectories() { print("Searching for abandoned resource strings…") let withStoryboard = isOptionalParameterForStoryboardAvailable() let map = findAbandonedIdentifiersIn(rootDirectories, withStoryboard: withStoryboard) if map.isEmpty { print("No abandoned resource strings were detected.") } else { print("Abandoned resource strings were detected:") displayAbandonedIdentifiersInMap(map) if isOptionaParameterForWritingAvailable() { map.keys.forEach { (stringsFilePath) in print("\n\nNow modifying \(stringsFilePath) ...") let updatedStringsFileContent = stringsFile(stringsFilePath, without: map[stringsFilePath]!) do { try updatedStringsFileContent.write(toFile: stringsFilePath, atomically: true, encoding: .utf8) } catch { print("ERROR writing file: \(stringsFilePath)") } } } } } else { print("Please provide the root directory for source code files as a command line argument.") }
3aa62b4e7876a707db8b0d42e5f9f327
34.852632
139
0.664856
false
false
false
false
peferron/algo
refs/heads/master
EPI/Dynamic Programming/The knapsack problem/swift/test.swift
mit
1
import Darwin func == (lhs: [Item], rhs: [Item]) -> Bool { guard lhs.count == rhs.count else { return false } for (i, array) in lhs.enumerated() { guard array == rhs[i] else { return false } } return true } let tests: [(items: [Item], subTests: [(capacity: Int, selection: [Int])])] = [ ( items: [ (value: 13, weight: 5), (value: 15, weight: 4), (value: 10, weight: 3), (value: 6, weight: 2), ], subTests: [ (capacity: 1, selection: []), (capacity: 2, selection: [3]), (capacity: 3, selection: [2]), (capacity: 4, selection: [1]), (capacity: 5, selection: [2, 3]), (capacity: 6, selection: [1, 3]), (capacity: 7, selection: [1, 2]), (capacity: 8, selection: [1, 2]), (capacity: 9, selection: [1, 2, 3]), (capacity: 10, selection: [1, 2, 3]), (capacity: 11, selection: [0, 1, 3]), (capacity: 12, selection: [0, 1, 2]), (capacity: 13, selection: [0, 1, 2]), (capacity: 14, selection: [0, 1, 2, 3]), ] ), ( items: [ (value: 65, weight: 20), (value: 35, weight: 8), (value: 245, weight: 60), (value: 195, weight: 55), (value: 65, weight: 40), (value: 150, weight: 70), (value: 275, weight: 85), (value: 155, weight: 25), (value: 120, weight: 30), (value: 320, weight: 65), (value: 75, weight: 75), (value: 40, weight: 10), (value: 200, weight: 95), (value: 100, weight: 50), (value: 220, weight: 40), (value: 99, weight: 10), ], subTests: [ (capacity: 130, selection: [7, 9, 14]), ] ) ] for test in tests { for subTest in test.subTests { let actual = select(test.items, capacity: subTest.capacity) guard actual == subTest.selection else { print("For items \(test.items) and capacity \(subTest.capacity), " + "expected selection to be \(subTest.selection), but was \(actual)") exit(1) } } }
5daf03f01b45b38021dbf982d9c8c684
30.310811
83
0.448856
false
true
false
false
Tomoki-n/iPhoneBeacon
refs/heads/master
iPhoneBeacon/ViewController.swift
mit
1
// // ViewController.swift // iPhoneBeacon // // Created by 山口将槻 on 2015/10/16. // Copyright © 2015年 山口将槻. All rights reserved. // import UIKit import CoreBluetooth import CoreLocation class ViewController: UIViewController, CBPeripheralManagerDelegate { @IBOutlet weak var cover: UIView! @IBOutlet weak var majorLabel: UILabel! @IBOutlet weak var minorLabel: UILabel! @IBOutlet weak var majorStepper: UIStepper! @IBOutlet weak var minorStepper: UIStepper! var peripheralManager:CBPeripheralManager! var myUUID:NSUUID! var startLocation:CGPoint? var major:UInt16 = 0 var minor:UInt16 = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil) self.myUUID = NSUUID(UUIDString: "00000000-88F6-1001-B000-001C4D2D20E6") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { print("state: \(peripheral.state)") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first self.startLocation = touch?.locationInView(self.view) let myRegion = CLBeaconRegion(proximityUUID: self.myUUID!, major: self.major, minor: self.minor, identifier: self.myUUID.UUIDString) self.peripheralManager.startAdvertising(myRegion.peripheralDataWithMeasuredPower(nil) as? [String : AnyObject]) } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first let location = touch?.locationInView(self.view) if touch?.view?.tag == 1 { if self.cover.frame.origin.x > -40 && location!.x - self.startLocation!.x < 0 { self.cover.frame.origin.x = location!.x - self.startLocation!.x } } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.peripheralManager.stopAdvertising() UIView.animateWithDuration(0.4) { () -> Void in self.cover.frame.origin.x = 0 } } @IBAction func major(sender: AnyObject) { let value = NSNumber(double: majorStepper.value) self.majorLabel.text = String(value.integerValue) self.major = value.unsignedShortValue } @IBAction func minor(sender: AnyObject) { let value = NSNumber(double: minorStepper.value) self.minorLabel.text = String(value.integerValue) self.minor = value.unsignedShortValue } }
0fe92d254b4771540dd8427fa44bf38c
33.170732
140
0.669879
false
false
false
false
imclean/JLDishWashers
refs/heads/master
JLDishwasher/PromoMessage.swift
gpl-3.0
1
// // PromoMessage.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class PromoMessages { public var customSpecialOffer : CustomSpecialOffer? public var priceMatched : String? public var offer : String? public var bundleHeadline : String? public var customPromotionalMessage : String? /** Returns an array of PromoMessages based on given dictionary. Sample usage: let promoMessages_list = PromoMessages.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of PromoMessages Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [PromoMessages] { var models:[PromoMessages] = [] for item in array { models.append(PromoMessages(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let promoMessages = PromoMessages(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: PromoMessages Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["customSpecialOffer"] != nil) { customSpecialOffer = CustomSpecialOffer(dictionary: dictionary["customSpecialOffer"] as! NSDictionary) } priceMatched = dictionary["priceMatched"] as? String offer = dictionary["offer"] as? String bundleHeadline = dictionary["bundleHeadline"] as? String customPromotionalMessage = dictionary["customPromotionalMessage"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.customSpecialOffer?.dictionaryRepresentation(), forKey: "customSpecialOffer") dictionary.setValue(self.priceMatched, forKey: "priceMatched") dictionary.setValue(self.offer, forKey: "offer") dictionary.setValue(self.bundleHeadline, forKey: "bundleHeadline") dictionary.setValue(self.customPromotionalMessage, forKey: "customPromotionalMessage") return dictionary } }
713f6bfdce6a0df940089732b941ee4f
31.076923
159
0.671463
false
false
false
false
cwaffles/Soulcast
refs/heads/master
Soulcast/HistoryVC.swift
mit
1
// // HistoryVC.swift // Soulcast // // Created by June Kim on 2016-11-17. // Copyright © 2016 Soulcast-team. All rights reserved. // import Foundation import UIKit protocol HistoryVCDelegate: class { //TODO: } ///displays a list of souls played in the past in reverse chronological order since 24 hours ago class HistoryVC: UIViewController, UITableViewDelegate, SoulPlayerDelegate, HistoryDataSourceDelegate { //title label let tableView = UITableView()//table view let dataSource = HistoryDataSource() var selectedSoul: Soul? var playlisting: Bool = false var startedPlaylisting: Bool = false weak var delegate: HistoryVCDelegate? let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() addTableView() dataSource.fetch() // view.addSubview(IntegrationTestButton(frame:CGRect(x: 10, y: 10, width: 100, height: 100))) } func addTableView() { let tableHeight = view.bounds.height * 0.95 tableView.frame = CGRect(x: 0, y: view.bounds.height - tableHeight, width: screenWidth, height: tableHeight) view.addSubview(tableView) tableView.delegate = self tableView.dataSource = dataSource tableView.allowsMultipleSelectionDuringEditing = false tableView.allowsMultipleSelection = false dataSource.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell())) tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: String(describing: UITableViewHeaderFooterView())) refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged) tableView.addSubview(refreshControl) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) soulPlayer.subscribe(self) startPlaylisting() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) soulPlayer.unsubscribe(self) deselectAllRows() } func startPlaylisting() { let first = IndexPath(row: 0, section: 0) tableView.selectRow(at: first, animated: true, scrollPosition: .none) selectedSoul = dataSource.soul(forIndex: 0) // play first soul soulPlayer.reset() if let thisSoul = selectedSoul { soulPlayer.startPlaying(thisSoul) playlisting = true } } func playNextSoul() { if selectedSoul != nil { let nextIndex = dataSource.indexPath(forSoul: selectedSoul!).row + 1 let nextIndexPath = IndexPath(item: nextIndex , section: 0) selectedSoul = dataSource.soul(forIndex: nextIndex) tableView.selectRow(at: nextIndexPath, animated: true, scrollPosition: .none) } if selectedSoul != nil { soulPlayer.reset() soulPlayer.startPlaying(selectedSoul) } } func refresh(_ refreshControl:UIRefreshControl) { dataSource.fetch() } // UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { playlisting = false selectedSoul = dataSource.soul(forIndex:indexPath.row) if SoulPlayer.playing { soulPlayer.reset() tableView.deselectRow(at: indexPath, animated: true) } else { soulPlayer.reset() soulPlayer.startPlaying(selectedSoul) } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UITableViewHeaderFooterView(reuseIdentifier: String(describing: UITableViewHeaderFooterView())) return headerView } func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return "Block" } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { soulPlayer.reset() selectedSoul = nil } // HistoryDataSourceDelegate func willFetch() { //show loading refreshControl.beginRefreshing() } func didFetch(_ success: Bool) { if success { } else { //show failure, retry button. } refreshControl.endRefreshing() } func didUpdate(_ soulcount: Int) { tableView.reloadData() } func didFinishUpdating(_ soulCount: Int) { guard isViewLoaded && view.window != nil else { return } tableView.reloadData() //TODO: // if !startedPlaylisting { startPlaylisting() // } startedPlaylisting = true } func didRequestBlock(_ soul: Soul) { present(blockAlertController(soul), animated: true) { // } return } fileprivate func block(_ soul:Soul) { ServerFacade.block(soul, success: { //remove soul at index self.dataSource.remove(soul) }) { statusCode in print(statusCode) } } func blockAlertController(_ soul:Soul) -> UIAlertController { let controller = UIAlertController(title: "Block Soul", message: "You will no longer hear from the device that casted this soul.", preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Block", style: .default, handler: {(action) in self.block(soul) })) controller.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in // })) return controller } //SoulPlayerDelegate func didStartPlaying(_ soul:Soul) { } func didFinishPlaying(_ soul:Soul) { //deselect current row if same if soul == selectedSoul { tableView.deselectRow(at: dataSource.indexPath(forSoul: soul) as IndexPath, animated: true) } if playlisting { playNextSoul() } } func didFailToPlay(_ soul:Soul) { } func deselectAllRows() { for rowIndex in 0...dataSource.soulCount() { let indexPath = IndexPath(row: rowIndex, section: 0) tableView.deselectRow(at: indexPath, animated: true) } } }
10f38a4995a87250653ea26774c05528
29.2891
158
0.697074
false
false
false
false
Doracool/BuildingBlock
refs/heads/master
BuildingBlock/BuildingBlock/ViewController.swift
mit
1
// // ViewController.swift // BuildingBlock // // Created by qingyun on 16/1/27. // Copyright © 2016年 河南青云信息技术有限公司. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController ,GameViewDelegate { // let 定义常量 var定义变量 //定义边距 let MARGINE:CGFloat = 10 //按钮的大小 let BUTTON_SIZE:CGFloat = 48 //按钮的透明度 let BUTTON_ALPHA:CGFloat = 0.4 //tabbar的高度 let TOOLBAR_HEIGHT:CGFloat = 44 //屏幕的宽度 //隐式解析 在可选类型的后边 加上 ! 就不用在使用时在后边加 ! 了 如果解析类型后边跟的是? 则在使用是需要解包 在后边加上 ! var screenWidth:CGFloat! //屏幕的高度 var screenHeight:CGFloat! var gameView:GameView! //播放音乐的方法库 var bgMusicPlayer:AVAudioPlayer! //速度的label var speedShow:UILabel! //分数的label var scoreShow:UILabel! var stopButton:UIButton! var button1: UIButton! var BGimg:UIImageView! var backBtn:UIButton! var btn:UIButton! override func viewDidLoad() { super.viewDidLoad() BGimg = UIImageView.init(frame: self.view.frame) // BGimg.image = UIImage(named: "时光十年") BGimg.backgroundColor = UIColor.blueColor() BGimg.alpha = 0.5 self.view.addSubview(BGimg) //背景颜色 self.view.backgroundColor = UIColor.whiteColor() //设置大小 let rect = UIScreen.mainScreen().bounds screenWidth = rect.size.width screenHeight = rect.size.height addToolBar() let gameRect = CGRectMake(rect.origin.x + MARGINE + 4, rect.origin.y + TOOLBAR_HEIGHT + 2 * MARGINE + 60 , rect.size.width - MARGINE * 2 - 9, rect.size.height - BUTTON_SIZE * 2 - TOOLBAR_HEIGHT - 89) gameView = GameView(frame: gameRect) gameView.delegate = self self.view.addSubview(gameView) backBtn = UIButton.init(type: UIButtonType.Custom) backBtn.addTarget(self, action: "back", forControlEvents: UIControlEvents.TouchUpInside) backBtn.setBackgroundImage(UIImage(named: "iconfont-fanhui"), forState: UIControlState.Normal) backBtn.setBackgroundImage(UIImage(named: "iconfont-fanhui"), forState: UIControlState.Highlighted) backBtn.frame.size = (backBtn.currentBackgroundImage?.size)! self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: backBtn) btn = UIButton.init(type: UIButtonType.Custom) btn.addTarget(self, action: "stopMusic", forControlEvents: UIControlEvents.TouchUpInside) btn.setBackgroundImage(UIImage(named: "OpenMusic"), forState: UIControlState.Normal) btn.setTitle("asd", forState: UIControlState.Normal) btn.titleLabel?.alpha = 0 btn.frame.size = (btn.currentBackgroundImage?.size)! self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn) //添加背景音乐 let bgMusicUrl = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "mp3") gameView.startGame() addButtons() do { try bgMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicUrl!)//解包 }catch { } bgMusicPlayer.numberOfLoops = -1 bgMusicPlayer.play() } //添加toolbar func addToolBar() { let toolBar = UIToolbar(frame: CGRectMake(0,MARGINE*2 + 44,screenWidth,TOOLBAR_HEIGHT)) self.view.addSubview(toolBar) //创建 一个显示速度的标签 let speedLabel = UILabel() speedLabel.frame = CGRectMake(0, 0, 50, TOOLBAR_HEIGHT) speedLabel.text = "速度:" let speedLabelItem = UIBarButtonItem(customView: speedLabel) //创建第二个显示速度值的标签 speedShow = UILabel() speedShow.frame = CGRectMake(0, 0, 20, TOOLBAR_HEIGHT) speedShow.textColor = UIColor.redColor() let speedShowItem = UIBarButtonItem(customView: speedShow) //创建第三个显示当前积分的标签 let scoreLabel = UILabel() scoreLabel.frame = CGRectMake(0, 0, 90, TOOLBAR_HEIGHT) scoreLabel.text = "升级分数:" let scoreLabelItem = UIBarButtonItem(customView: scoreLabel) //创建第四个显示积分值的标签 scoreShow = UILabel() scoreShow.frame = CGRectMake(0, 0, 40, TOOLBAR_HEIGHT) scoreShow.textColor = UIColor.redColor() let scoreShowItem = UIBarButtonItem(customView: scoreShow) let flexItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) toolBar.items = [speedLabelItem,speedShowItem,flexItem,scoreLabelItem,scoreShowItem] } //定义方向 func addButtons() { //左 let leftBtn = UIButton() leftBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE * 3 - MARGINE - 14, screenHeight - BUTTON_SIZE * 2 - MARGINE, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) leftBtn.setImage(UIImage(named: "left"), forState: UIControlState.Normal) leftBtn.addTarget(self, action: "left:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(leftBtn) //旋转 let upBtn = UIButton() upBtn.frame = CGRectMake( MARGINE, screenHeight - BUTTON_SIZE - MARGINE * 3 + 5, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) upBtn.setImage(UIImage(named: "xuanzhuan"), forState: UIControlState.Normal) upBtn.addTarget(self, action: "up:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(upBtn) //右 let rightBtn = UIButton() rightBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE - MARGINE, screenHeight - BUTTON_SIZE * 2 - MARGINE, BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) rightBtn.setImage(UIImage(named: "right"), forState: UIControlState.Normal) rightBtn.addTarget(self, action: "right:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(rightBtn) //下 let downBtn = UIButton() downBtn.frame = CGRectMake(screenWidth - BUTTON_SIZE * 2 - MARGINE - 7, screenHeight - BUTTON_SIZE - MARGINE , BUTTON_SIZE * 1.2, BUTTON_SIZE * 1.2) downBtn.setImage(UIImage(named: "down"), forState: UIControlState.Normal) downBtn.addTarget(self, action: "down:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(downBtn) stopButton = UIButton.init(type: UIButtonType.Custom) stopButton.frame = CGRectMake(MARGINE * 2 + BUTTON_SIZE * 2, screenHeight - BUTTON_SIZE - MARGINE * 2, BUTTON_SIZE, BUTTON_SIZE) stopButton.setTitle("暂停", forState: UIControlState.Normal) stopButton.titleLabel?.alpha = 0 stopButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) stopButton.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal) stopButton.addTarget(self, action: "stop:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(stopButton) } func left(sender:UIButton) { gameView.moveLeft() } func up(sender:UIButton){ gameView.rotate() } func right(sender:UIButton){ gameView.moveRight() } func down(sender:UIButton){ gameView.moveDown() } func stop(sender:UIButton){ if stopButton.titleLabel?.text == "暂停" { stopButton.setTitle("继续", forState: UIControlState.Normal) stopButton.setImage(UIImage(named: "countin"), forState: UIControlState.Normal) bgMusicPlayer.pause() gameView.gameSTop() }else { stopButton.setTitle("暂停", forState: UIControlState.Normal) stopButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) bgMusicPlayer.play() gameView.gameSTop() } } func Continue(sender:UIButton){ button1.setTitle("zanting", forState: UIControlState.Normal) gameView.countinue() } func updataScore(score: Int) { self.title = "积分:\(score)" // self.scoreShow.text = "\(score)" } func updataSpeed(speed: Int) { // let SPlabel = UILabel() let string = speed * speed * 200 self.scoreShow.text = "\(string)" self.speedShow.text = "\(speed)" } func stopMusic() { if btn.titleLabel?.text == "asd" { bgMusicPlayer.pause() btn.setImage(UIImage(named: "StopMucic"), forState: UIControlState.Normal) btn.setTitle("dsa", forState: UIControlState.Normal) }else { bgMusicPlayer.play() btn.setImage(UIImage(named: "OpenMusic"), forState: UIControlState.Normal) btn.setTitle("asd", forState: UIControlState.Normal) } } func back() { bgMusicPlayer.pause() gameView.gameSTop() self.navigationController!.popToRootViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
dc65eed9f2dd57fe8ace1e16ae302b5b
35.294821
207
0.634248
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUPacket.swift
bsd-3-clause
1
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal class SecureDFUPacket: DFUCharacteristic { private let packetSize: UInt32 internal var characteristic: CBCharacteristic internal var logger: LoggerHelper /// Number of bytes of firmware already sent. private(set) var bytesSent: UInt32 = 0 /// Number of bytes sent at the last progress notification. /// This value is used to calculate the current speed. private var totalBytesSentSinceProgessNotification: UInt32 = 0 private var totalBytesSentWhenDfuStarted: UInt32 = 0 /// Current progress in percents (0-99). private var progressReported: UInt8 = 0 private var startTime: CFAbsoluteTime? private var lastTime: CFAbsoluteTime? internal var valid: Bool { return characteristic.properties.contains(.writeWithoutResponse) } required init(_ characteristic: CBCharacteristic, _ logger: LoggerHelper) { self.characteristic = characteristic self.logger = logger if #available(iOS 9.0, macOS 10.12, *) { let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { packetSize = 20 // Default MTU is 23. return } // Make the packet size the first word-aligned value that's less than the maximum. packetSize = UInt32(peripheral.maximumWriteValueLength(for: .withoutResponse)) & 0xFFFFFFFC if packetSize > 20 { // MTU is 3 bytes larger than payload // (1 octet for Op-Code and 2 octets for Att Handle). logger.v("MTU set to \(packetSize + 3)") } } else { packetSize = 20 // Default MTU is 23. } } // MARK: - Characteristic API methods /** Sends the whole content of the data object. - parameter data: The data to be sent. - parameter report: Method called in case of an error. */ func sendInitPacket(_ data: Data, onError report: ErrorCallback?) { // Get the peripheral object. let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { report?(.invalidInternalState, "Assert characteristic.service?.peripheral != nil failed") return } // Data may be sent in up-to-20-bytes packets. var offset: UInt32 = 0 var bytesToSend = UInt32(data.count) let packetUUID = characteristic.uuid.uuidString repeat { let packetLength = min(bytesToSend, packetSize) let packet = data.subdata(in: Int(offset) ..< Int(offset + packetLength)) logger.v("Writing to characteristic \(packetUUID)...") logger.d("peripheral.writeValue(0x\(packet.hexString), for: \(packetUUID), type: .withoutResponse)") peripheral.writeValue(packet, for: characteristic, type: .withoutResponse) offset += packetLength bytesToSend -= packetLength } while bytesToSend > 0 } /** Sends a given range of data from given firmware over DFU Packet characteristic. If the whole object is completed the completition callback will be called. - parameters: - prnValue: Packet Receipt Notification value used in the process. 0 to disable PRNs. - range: The range of the firmware that is to be sent in this object. - firmware: The whole firmware to be sent in this part. - progress: An optional progress delegate. - queue: The queue to dispatch progress events on. - complete: The completon callback. - report: Method called in case of an error. */ func sendNext(_ prnValue: UInt16, packetsFrom range: Range<Int>, of firmware: DFUFirmware, andReportProgressTo progress: DFUProgressDelegate?, on queue: DispatchQueue, andCompletionTo complete: @escaping Callback, onError report: ErrorCallback?) { let optService: CBService? = characteristic.service guard let peripheral = optService?.peripheral else { report?(.invalidInternalState, "Assert characteristic.service?.peripheral != nil failed") return } let objectData = firmware.data.subdata(in: range) let objectSizeInBytes = UInt32(objectData.count) let objectSizeInPackets = (objectSizeInBytes + packetSize - 1) / packetSize let packetsSent = (bytesSent + packetSize - 1) / packetSize let packetsLeft = objectSizeInPackets - packetsSent // Calculate how many packets should be sent before EOF or next receipt notification. var packetsToSendNow = min(UInt32(prnValue), packetsLeft) if prnValue == 0 { packetsToSendNow = packetsLeft } // This is called when we no longer have data to send (PRN received after the whole // object was sent). Fixes issue IDFU-9. if packetsToSendNow == 0 { complete() return } // Initialize timers. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() lastTime = startTime totalBytesSentWhenDfuStarted = UInt32(range.lowerBound) totalBytesSentSinceProgessNotification = totalBytesSentWhenDfuStarted // Notify progress delegate that upload has started (0%). queue.async { progress?.dfuProgressDidChange( for: firmware.currentPart, outOf: firmware.parts, to: 0, currentSpeedBytesPerSecond: 0.0, avgSpeedBytesPerSecond: 0.0 ) } } let originalPacketsToSendNow = packetsToSendNow while packetsToSendNow > 0 { // Starting from iOS 11 and MacOS 10.13 the PRNs are no longer required due to new API. var canSendPacket = true if #available(iOS 11.0, macOS 10.13, *) { // The peripheral.canSendWriteWithoutResponse often returns false before even we // start sending, let's do a workaround. canSendPacket = bytesSent == 0 || peripheral.canSendWriteWithoutResponse } // If PRNs are enabled we will ignore the new API and base synchronization on PRNs only. guard canSendPacket || prnValue > 0 else { break } let bytesLeft = objectSizeInBytes - bytesSent let packetLength = min(bytesLeft, packetSize) let packet = objectData.subdata(in: Int(bytesSent) ..< Int(packetLength + bytesSent)) peripheral.writeValue(packet, for: characteristic, type: .withoutResponse) bytesSent += packetLength packetsToSendNow -= 1 // Calculate the total progress of the firmware, presented to the delegate. let totalBytesSent = UInt32(range.lowerBound) + bytesSent let currentProgress = UInt8(totalBytesSent * 100 / UInt32(firmware.data.count)) // in percantage (0-100) // Notify progress listener only if current progress has increased since last time. if currentProgress > progressReported { // Calculate current transfer speed in bytes per second. let now = CFAbsoluteTimeGetCurrent() let currentSpeed = Double(totalBytesSent - totalBytesSentSinceProgessNotification) / (now - lastTime!) let avgSpeed = Double(totalBytesSent - totalBytesSentWhenDfuStarted) / (now - startTime!) lastTime = now totalBytesSentSinceProgessNotification = totalBytesSent // Notify progress delegate of overall progress. queue.async { progress?.dfuProgressDidChange( for: firmware.currentPart, outOf: firmware.parts, to: Int(currentProgress), currentSpeedBytesPerSecond: currentSpeed, avgSpeedBytesPerSecond: avgSpeed ) } progressReported = currentProgress } // Notify handler of current object progress to start sending next one. if bytesSent == objectSizeInBytes { if prnValue == 0 || originalPacketsToSendNow < UInt32(prnValue) { complete() } else { // The whole object has been sent but the DFU target will // send a PRN notification as expected. // The sendData method will be called again // with packetsLeft = 0 (see line 132). // Do nothing. } } } } func resetCounters() { bytesSent = 0 } }
ad6ecb5c221bef8f4e5e1bb7262f013d
43.665289
118
0.616986
false
false
false
false
piersb/macsterplan
refs/heads/master
Macsterplan/Campaign.swift
gpl-3.0
1
// // Campaign.swift // // // Created by Piers Beckley on 10/08/2015. // // import Foundation import CoreData public class Campaign: NSManagedObject { @NSManaged public var name: String @NSManaged public var characters: Set<GameCharacter>? @NSManaged public var players: Set<Player>? @NSManaged public var dateCreated: NSDate convenience init(context: NSManagedObjectContext) { // may be necessary to avoid the nil-return bug described at http://www.jessesquires.com/swift-coredata-and-testing/ let entityDescription = NSEntityDescription.entityForName("Campaign", inManagedObjectContext: context)! self.init(entity: entityDescription, insertIntoManagedObjectContext: context) } public func isPlayerInCampaign (aPlayer: Player) -> Bool { return players!.contains(aPlayer) } public func addPlayer (aNewPlayer: Player) { var items = self.mutableSetValueForKey("players") items.addObject(aNewPlayer) } public func listPlayers () -> Set<Player> { return players! } func removeList(values: NSSet) { var items = self.mutableSetValueForKey("lists"); for value in values { items.removeObject(value) } } public func addCharacter (aNewCharacter: GameCharacter) { var items = self.mutableSetValueForKey("characters") items.addObject(aNewCharacter) } public override func awakeFromInsert() { super.awakeFromInsert() self.dateCreated = NSDate() players = Set<Player>() } public override func awakeFromFetch() { super.awakeFromFetch() println("awaking from fetch") } }
bc62fae44e9de0cce2c608a8b4fe863c
25.477612
124
0.642978
false
false
false
false
lzpfmh/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Main/MainSplitViewController.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class MainSplitViewController: UISplitViewController { init() { super.init(nibName: nil, bundle: nil) preferredDisplayMode = .AllVisible if (interfaceOrientation == UIInterfaceOrientation.Portrait || interfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown) { minimumPrimaryColumnWidth = CGFloat(300.0) maximumPrimaryColumnWidth = CGFloat(300.0) } else { minimumPrimaryColumnWidth = CGFloat(360.0) maximumPrimaryColumnWidth = CGFloat(360.0) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willRotateToInterfaceOrientation(toInterfaceOrientation, duration: duration) if (toInterfaceOrientation == UIInterfaceOrientation.Portrait || toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown) { minimumPrimaryColumnWidth = CGFloat(300.0) maximumPrimaryColumnWidth = CGFloat(300.0) } else { minimumPrimaryColumnWidth = CGFloat(360.0) maximumPrimaryColumnWidth = CGFloat(360.0) } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
ecdf710cf458f0385f611f14b3ec3b78
35.902439
143
0.681878
false
false
false
false
penniooi/TestKichen
refs/heads/master
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendLikeCell.swift
mit
1
// // CBRecommendLikeCell.swift // TestKitchen // // Created by aloha on 16/8/17. // Copyright © 2016年 胡颉禹. All rights reserved. // import UIKit class CBRecommendLikeCell: UITableViewCell { //显示的数据 var model: CBRecommendwidgetListModel?{ didSet{ //显示按钮的文字和属性 showData() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } //显示图片和文字 func showData(){ for var i in 0..<8{ //显示图片的model if model?.widget_data?.count>i{ let imagemodel = model?.widget_data![i] if imagemodel?.type == "image"{ //获取图片视图 let index = i/2 let subView = self.contentView.viewWithTag(200+index) if subView?.isKindOfClass(UIImageView.self) == true{ let imageView = subView as! UIImageView imageView.kf_setImageWithURL(NSURL(string: (imagemodel?.content)!), placeholderImage: UIImage(named: "sdefaultImage.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) } } } if model?.widget_data?.count>i+1{ let textModel = model?.widget_data![i+1] if textModel?.type == "text"{ let subView = self.contentView.viewWithTag(300+i/2) if subView?.isKindOfClass(UILabel.self) == true{ let label = subView as! UILabel label.text = textModel?.content } } } i += 1 } } //创建cell的方法 class func creatLikeCellFor(tabView:UITableView,atIndexPath indexPath:NSIndexPath,withlistModel listModel:CBRecommendwidgetListModel)->CBRecommendLikeCell{ //猜你喜欢 let cellId = "CBRecommendLikeCellId" var cell = tabView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendLikeCell if nil == cell { cell = NSBundle.mainBundle().loadNibNamed("CBRecommendLikeCell", owner: nil, options: nil).last as? CBRecommendLikeCell } cell?.model = listModel return cell! } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
ddc3669f89d7339f078f26831c62f6f6
25.663462
208
0.49405
false
false
false
false
primetimer/PrimeFactors
refs/heads/master
PrimeFactors/Classes/PhiTable.swift
mit
1
// // PhiTable.swift // PrimeBase // // Created by Stephan Jancar on 29.11.16. // Copyright © 2016 esjot. All rights reserved. // import Foundation public class PhiTable { var usebackward = true //Use backward calculation via known pi var usecache = true var pcalc : PrimeCalculator! var pitable : PiTable! var maxpintable : UInt64 = 0 var primorial : [UInt64] = [] var primorial1 : [UInt64] = [] var phi : [[UInt64]] = [] var phitablesize = 7 var phicache = NSCache<NSString, NSNumber>() func ReleaseCache() { phicache = NSCache<NSString, NSNumber>() } var first : [UInt64] = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,71,73,79,83,89,97] private func CalcPrimorial(maxp: UInt64 = 23) { //23 because 2*3*...*23 < UInt32.max var prod : UInt64 = 1 var prod1 : UInt64 = 1 for p in self.first { if p > maxp { break } prod = prod * p prod1 = prod1 * (p-1) primorial.append(prod) primorial1.append(prod1) } } init(pcalc : PrimeCalculator, pitable: PiTable, phitablesize : Int = 7) { //verbose = piverbose self.pcalc = pcalc self.pitable = pitable self.phitablesize = phitablesize self.maxpintable = pitable.Pin(m: pitable.ValidUpto()) CalcPrimorial() Initphitable() } private func Initphitable() { phi = [[UInt64]] (repeating: [], count: phitablesize) for l in 0..<phitablesize { phi[l] = [UInt64] (repeating : 0, count : Int(primorial[l])) var count : UInt64 = 0 for k in 0..<primorial[l] { var relativeprime = true for pindex in 0...l { let p = pitable.NthPrime(n: pindex+1) if k % p == 0 { relativeprime = false break } } if relativeprime { count = count + 1 } phi[l][Int(k)] = count } } } //The Number of integers of the for form n = pi * pj //with pj >= pi > a-tth Prime func P2(x: UInt64, a: UInt64) -> UInt64 { #if true let starttime = CFAbsoluteTimeGetCurrent() #endif let r2 = x.squareRoot() let pib = pitable.Pin(m: r2) if a >= pib { return 0 } var p2 : UInt64 = 0 for i in a+1...pib { let p = pitable.NthPrime(n: Int(i)) let xp = x / p let pi = pitable.Pin(m: xp) p2 = p2 + pi - (i - 1) } #if false phideltap2time = phideltap2time + CFAbsoluteTimeGetCurrent() - starttime #endif return p2 } var rekurs = 0 //The Number of integers of the for form n = pi * pj * pk //with k >= pj >= pi > a-tth Prime func P3(x: UInt64, a: UInt64) -> UInt64 { let r3 = x.iroot3() let pi3 = pitable.Pin(m: r3) if a >= pi3 { return 0 } var p3 : UInt64 = 0 for i in a+1...pi3 { let p = pitable.NthPrime(n: Int(i)) let xp = x / p let rxp = xp.squareRoot() let bi = pitable.Pin(m: rxp) for j in i...bi { let q = pitable.NthPrime(n: (Int(j))) let xpq = x / (p*q) let pixpq = pitable.Pin(m: xpq) p3 = p3 + pixpq - (j-1) } } return p3 } //Calculates Phi aka Legendre sum func Phi(x: UInt64, nr: Int) -> UInt64 { if x == 0 { return 0 } assert (UInt64(nr) <= pitable.ValidUpto()) // phi(x) = primorial1 * (x / primorial) + phitable if nr == 0 { return x } if nr == 1 { return x - x/2 } if nr == 2 { return x - x/2 - x/3 + x/6 } if nr == 3 { return x - x/2 - x/3 + x/6 - x/5 + x/10 + x/15 - x/30 } if x < pitable.NthPrime(n: nr+1) { return 1 } if nr < phitablesize { let t = x / primorial[nr-1] let r = x - primorial[nr-1] * t let q = primorial1[nr-1] let y = q * t + phi[nr-1][Int(r)] return y } //Look in Cache var nskey : NSString = "" if usecache && nr < 500 { let key = String(x) + ":" + String(nr) nskey = NSString(string: key) if let cachedVersion = phicache.object(forKey: nskey) { return cachedVersion.uint64Value } } rekurs = rekurs + 1 let value = PhiCalc(x: x, nr: nr) if usecache && nr < 500 { let cachevalue = NSNumber(value: value) phicache.setObject(cachevalue, forKey: nskey) } //print("time: ",rekurs, x,nr,phideltafwdtime,phideltap2time) rekurs = rekurs - 1 return value } var phideltafwdtime = 0.0 var phideltap2time = 0.0 private func IsPhiByPix(x: UInt64, a: Int) -> Bool { if x>maxpintable { return false } let pa = pitable.NthPrime(n: a) if x < pa*pa { return true } return false } private func PhiCalc(x: UInt64, nr : Int) -> UInt64 { #if false if IsPhiByPix(x: x,a: nr) { let pix = pitable.Pin(m: x) let phi = pix - UInt64(nr) + 1 return phi } #endif if usebackward && x < maxpintable { // Use backward Formula // phi = 1 + pi(x) - nr + P2(x,nr) + P3(x,nr) // for x in p(nr) ... p(nr+1)^4 let pa = pitable.NthPrime(n: nr) //let pa1 = pitable.NthPrime(n: nr+1) if x <= pa { return 1 } let papow2 = pa * pa let papow4 = papow2 * papow2 #if false if pa1pow >= UInt64(UInt32.max / 2) { pa1pow = x+1 } // to avoid overflow else { pa1pow = pa1pow * pa1pow } #endif if x < papow4 { let pix = pitable.Pin(m: x) var p2 : UInt64 = 0 if x >= papow2 { p2 = P2(x: x, a : UInt64(nr)) } var p3 : UInt64 = 0 if x >= pa * pa * pa { p3 = P3(x: x, a: UInt64(nr)) } let phi = 1 + pix + p2 + p3 - UInt64(nr) return phi } } //Use forward Recursion #if true let starttime = CFAbsoluteTimeGetCurrent() #endif var result = Phi(x: x, nr: phitablesize - 1) #if false phideltafwdtime = phideltafwdtime + CFAbsoluteTimeGetCurrent() - starttime #endif var i = phitablesize while i <= nr { let p = self.pitable.NthPrime(n: i) let n2 = x / p if n2 < p { break } let dif = Phi(x: n2,nr: i-1) result = result - dif i = i + 1 } var k = nr while x < self.pitable.NthPrime(n: k+1) { k = k - 1 } let delta = (Int(i)-Int(k)-1) result = UInt64(Int(result) + delta) return result } }
71aca7725075b27619976174c64c08ff
19.67474
97
0.570879
false
false
false
false
tsolomko/SWCompression
refs/heads/develop
Sources/TAR/ContainerEntryType+Tar.swift
mit
1
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension ContainerEntryType { init(_ fileTypeIndicator: UInt8) { switch fileTypeIndicator { case 0, 48: // "0" self = .regular case 49: // "1" self = .hardLink case 50: // "2" self = .symbolicLink case 51: // "3" self = .characterSpecial case 52: // "4" self = .blockSpecial case 53: // "5" self = .directory case 54: // "6" self = .fifo case 55: // "7" self = .contiguous default: self = .unknown } } var fileTypeIndicator: UInt8 { switch self { case .regular: return 48 case .hardLink: return 49 case .symbolicLink: return 50 case .characterSpecial: return 51 case .blockSpecial: return 52 case .directory: return 53 case .fifo: return 54 case .contiguous: return 55 case .socket: return 0 case .unknown: return 0 } } }
e5e36c754d108b48b71766df54f406fd
21.137931
38
0.469626
false
false
false
false
4np/UitzendingGemist
refs/heads/master
UitzendingGemist/StillCollectionViewCell.swift
apache-2.0
1
// // StillCollectionViewCell.swift // UitzendingGemist // // Created by Jeroen Wesbeek on 18/07/16. // Copyright © 2016 Jeroen Wesbeek. All rights reserved. // import Foundation import UIKit import NPOKit import CocoaLumberjack class StillCollectionViewCell: UICollectionViewCell { @IBOutlet weak fileprivate var stillImageView: UIImageView! // MARK: Lifecycle override func layoutSubviews() { super.layoutSubviews() } override func prepareForReuse() { super.prepareForReuse() self.stillImageView.image = nil } // MARK: Focus engine override var canBecomeFocused: Bool { return false } // MARK: Configuration func configure(withStill still: NPOStill) { // Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000 // causing the images to look compressed so hardcode the dimensions for now... // TODO: check if this is solved in later releases... //let size = self.stillImageView.frame.size let size = CGSize(width: 260, height: 146) _ = still.getImage(ofSize: size) { [weak self] image, error, _ in guard let image = image else { DDLogError("Could not fetch still image (\(String(describing: error)))") return } self?.stillImageView.image = image } } }
ce0cb20561e779e9f8495d2aeb3bcb50
26.358491
88
0.614483
false
false
false
false
schrockblock/subway-stations
refs/heads/master
SubwayStations/Classes/Station.swift
mit
1
// // Station.swift // Pods // // Created by Elliot Schrock on 6/28/16. // // import UIKit public protocol Station { var name: String! { get set } var stops: Array<Stop> { get set } } extension Station { public func distance(to point: (Double, Double), _ metric: ((Double, Double), (Double, Double)) -> Double) -> Double { let sortedStops = stops.filter { $0.location() != nil }.sorted { metric(point, $0.location()!) < metric(point, $1.location()!)} if let stop = sortedStops.first { return metric(point, stop.location()!) } return Double.infinity } } public func ==(lhs: Station, rhs: Station) -> Bool { if let lhsName = lhs.name { if let rhsName = rhs.name { if lhsName.lowercased() == rhsName.lowercased() { return true } let lhsArray = lhsName.lowercased().components(separatedBy: " ") let rhsArray = rhsName.lowercased().components(separatedBy: " ") if lhsArray.count == rhsArray.count { for lhsComponent in lhsArray { if !rhsArray.contains(lhsComponent){ return false } } for rhsComponent in rhsArray { if !lhsArray.contains(rhsComponent) { return false } } }else{ return false } return true; }else{ return false } }else{ return false } }
c65479577bcb0110f56c6b24eefae8b8
26.881356
135
0.487538
false
false
false
false
novi/proconapp
refs/heads/master
ProconApp/ProconManager/GameResultManageViewController.swift
bsd-3-clause
1
// // GameResultManageViewController.swift // ProconApp // // Created by ito on 2015/09/13. // Copyright (c) 2015年 Procon. All rights reserved. // import UIKit import AVFoundation import APIKit import ProconBase class GameResultManageViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var session: AVCaptureSession = AVCaptureSession() var previewLayer: CALayer = CALayer() var capturedStrings: Set<String> = Set() var isSending: Bool = false @IBOutlet weak var previewView: UIView! @IBOutlet weak var startStopButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let layer = AVCaptureVideoPreviewLayer(session: session) layer.videoGravity = AVLayerVideoGravityResizeAspect; layer.frame = previewView.bounds self.previewLayer = layer self.previewView.layer.addSublayer(layer) reloadButtonState() /*let data = NSData(contentsOfFile: "") let str = NSString(data: data!, encoding: NSUTF8StringEncoding) self.processQRCode(str as! String) */ println(Constants.ManageAPIBaseURL) #if HOST_DEV self.navigationItem.title = "Dev" #elseif HOST_RELEASE self.navigationItem.title = "Prod" #endif #if HOST_RELEASE let alert = UIAlertController(title: "本番環境", message: Constants.ManageAPIBaseURL, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) #endif } func reloadButtonState() { if session.running { startStopButton.setTitle("読み取り停止", forState: .Normal) } else { startStopButton.setTitle("読み取り開始", forState: .Normal) } } @IBAction func startOrStopTapped(sender: AnyObject) { if session.running { session.stopRunning() for input in session.inputs { session.removeInput(input as! AVCaptureInput) } for output in session.outputs { session.removeOutput(output as! AVCaptureOutput) } } else { let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).filter { if let device = $0 as? AVCaptureDevice { return device.position == .Back } return false } if devices.count == 0 { let alert = UIAlertController(title: "no device", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } if let device = devices.first as? AVCaptureDevice { let input = AVCaptureDeviceInput(device: device, error: nil) self.session.addInput(input) let output = AVCaptureMetadataOutput() self.session.addOutput(output) Logger.debug("\(output.availableMetadataObjectTypes)") if output.availableMetadataObjectTypes.count > 0 { output.metadataObjectTypes = [AVMetadataObjectTypeQRCode] output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) } else { let alert = UIAlertController(title: "no detector", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } session.startRunning() } self.reloadButtonState() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer.frame = previewView.bounds } // MARK: Capture Delegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { for obj in metadataObjects { if let obj = obj as? AVMetadataMachineReadableCodeObject { if obj.type == AVMetadataObjectTypeQRCode, let str = obj.stringValue { // QR Code detected // base64 decode and decompress let compressed = NSData(base64EncodedString: str, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) if let data = compressed?.pr_decompress(), let str = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { self.processQRCode(str) } } } } } func processQRCode(str: String) { if capturedStrings.contains(str) { return // already captured } if isSending { return } capturedStrings.insert(str) let alert = UIAlertController(title: "送信しますか?", message: str, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "キャンセル", style: .Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "送信", style: .Default, handler: { _ in self.sendQRCode(str) })) self.presentViewController(alert, animated: true, completion: nil) let delay = 3.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { self.capturedStrings.remove(str) }) } func showError(str: String) { let alert = UIAlertController(title: "パースエラー", message: str, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } func sendQRCode(str: String) { let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) if data == nil { // TODO: guard showError("data conversion error") return } var error: NSError? = nil let obj = NSJSONSerialization.JSONObjectWithData(data!, options: .allZeros, error: &error) as? [String: AnyObject] if obj == nil || error != nil { showError("\(error ?? String())") return } let req = ManageAPI.Endpoint.UpdateGameResult(result: obj!) self.isSending = true let alert = UIAlertController(title: "送信中...", message: nil, preferredStyle: .Alert) self.presentViewController(alert, animated: true, completion: nil) AppAPI.sendRequest(req) { res in self.isSending = false alert.dismissViewControllerAnimated(true) { switch res { case .Success(_): break case .Failure(let box): // TODO, error Logger.error("\(box.value)") self.showError("\(box.value)") } } } } }
f2f59496e0c45f03429cc9de64fad73a
35.269231
162
0.574761
false
false
false
false
apple/swift-syntax
refs/heads/main
Sources/SwiftParser/Patterns.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension Parser { /// Parse a pattern. /// /// Grammar /// ======= /// /// pattern → wildcard-pattern type-annotation? /// pattern → identifier-pattern type-annotation? /// pattern → value-binding-pattern /// pattern → tuple-pattern type-annotation? /// pattern → enum-case-pattern /// pattern → optional-pattern /// pattern → type-casting-pattern /// pattern → expression-pattern /// /// wildcard-pattern → _ /// /// identifier-pattern → identifier /// /// value-binding-pattern → 'var' pattern | 'let' pattern /// /// tuple-pattern → ( tuple-pattern-element-list opt ) /// /// enum-case-pattern → type-identifier? '.' enum-case-name tuple-pattern? /// /// optional-pattern → identifier-pattern '?' /// /// type-casting-pattern → is-pattern | as-pattern /// is-pattern → 'is' type /// as-pattern → pattern 'as' type /// /// expression-pattern → expression @_spi(RawSyntax) public mutating func parsePattern() -> RawPatternSyntax { enum ExpectedTokens: RawTokenKindSubset { case leftParen case wildcardKeyword case identifier case dollarIdentifier // For recovery case letKeyword case varKeyword init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .leftParen: self = .leftParen case .wildcardKeyword: self = .wildcardKeyword case .identifier: self = .identifier case .dollarIdentifier: self = .dollarIdentifier case .letKeyword: self = .letKeyword case .varKeyword: self = .varKeyword default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .leftParen: return .leftParen case .wildcardKeyword: return .wildcardKeyword case .identifier: return .identifier case .dollarIdentifier: return .dollarIdentifier case .letKeyword: return .letKeyword case .varKeyword: return .varKeyword } } } switch self.at(anyIn: ExpectedTokens.self) { case (.leftParen, let handle)?: let lparen = self.eat(handle) let elements = self.parsePatternTupleElements() let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawPatternSyntax(RawTuplePatternSyntax( leftParen: lparen, elements: elements, unexpectedBeforeRParen, rightParen: rparen, arena: self.arena )) case (.wildcardKeyword, let handle)?: let wildcard = self.eat(handle) return RawPatternSyntax(RawWildcardPatternSyntax( wildcard: wildcard, typeAnnotation: nil, arena: self.arena )) case (.identifier, let handle)?: let identifier = self.eat(handle) return RawPatternSyntax(RawIdentifierPatternSyntax( identifier: identifier, arena: self.arena )) case (.dollarIdentifier, let handle)?: let dollarIdent = self.eat(handle) let unexpectedBeforeIdentifier = RawUnexpectedNodesSyntax(elements: [RawSyntax(dollarIdent)], arena: self.arena) return RawPatternSyntax(RawIdentifierPatternSyntax( unexpectedBeforeIdentifier, identifier: missingToken(.identifier), arena: self.arena )) case (.letKeyword, let handle)?, (.varKeyword, let handle)?: let letOrVar = self.eat(handle) let value = self.parsePattern() return RawPatternSyntax(RawValueBindingPatternSyntax( letOrVarKeyword: letOrVar, valuePattern: value, arena: self.arena )) case nil: if self.currentToken.tokenKind.isKeyword, !self.currentToken.isAtStartOfLine { // Recover if a keyword was used instead of an identifier let keyword = self.consumeAnyToken() return RawPatternSyntax(RawIdentifierPatternSyntax( RawUnexpectedNodesSyntax([keyword], arena: self.arena), identifier: missingToken(.identifier, text: nil), arena: self.arena )) } else { return RawPatternSyntax(RawMissingPatternSyntax(arena: self.arena)) } } } /// Parse a typed pattern. /// /// Grammar /// ======= /// /// typed-pattern → pattern ':' attributes? inout? type mutating func parseTypedPattern(allowRecoveryFromMissingColon: Bool = true) -> (RawPatternSyntax, RawTypeAnnotationSyntax?) { let pattern = self.parsePattern() // Now parse an optional type annotation. let colon = self.consume(if: .colon) var lookahead = self.lookahead() var type: RawTypeAnnotationSyntax? if let colon = colon { let result = self.parseResultType() type = RawTypeAnnotationSyntax( colon: colon, type: result, arena: self.arena ) } else if allowRecoveryFromMissingColon && !self.currentToken.isAtStartOfLine && lookahead.canParseType() { // Recovery if the user forgot to add ':' let result = self.parseResultType() type = RawTypeAnnotationSyntax( colon: self.missingToken(.colon, text: nil), type: result, arena: self.arena ) } return (pattern, type) } /// Parse the elements of a tuple pattern. /// /// Grammar /// ======= /// /// tuple-pattern-element-list → tuple-pattern-element | tuple-pattern-element ',' tuple-pattern-element-list /// tuple-pattern-element → pattern | identifier ':' pattern mutating func parsePatternTupleElements() -> RawTuplePatternElementListSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawTuplePatternElementListSyntax(elements: [ RawTuplePatternElementSyntax( remainingTokens, labelName: nil, labelColon: nil, pattern: RawPatternSyntax(RawMissingPatternSyntax(arena: self.arena)), trailingComma: nil, arena: self.arena ) ], arena: self.arena) } var elements = [RawTuplePatternElementSyntax]() do { var keepGoing = true var loopProgress = LoopProgressCondition() while !self.at(any: [.eof, .rightParen]) && keepGoing && loopProgress.evaluate(currentToken) { // If the tuple element has a label, parse it. let labelAndColon = self.consume(if: .identifier, followedBy: .colon) let (label, colon) = (labelAndColon?.0, labelAndColon?.1) let pattern = self.parsePattern() let trailingComma = self.consume(if: .comma) keepGoing = trailingComma != nil elements.append(RawTuplePatternElementSyntax( labelName: label, labelColon: colon, pattern: pattern, trailingComma: trailingComma, arena: self.arena)) } } return RawTuplePatternElementListSyntax(elements: elements, arena: self.arena) } } extension Parser { /// Parse a pattern that appears immediately under syntax for conditionals like /// for-in loops and guard clauses. mutating func parseMatchingPattern(context: PatternContext) -> RawPatternSyntax { // Parse productions that can only be patterns. switch self.at(anyIn: MatchingPatternStart.self) { case (.varKeyword, let handle)?, (.letKeyword, let handle)?: let letOrVar = self.eat(handle) let value = self.parseMatchingPattern(context: .letOrVar) return RawPatternSyntax(RawValueBindingPatternSyntax( letOrVarKeyword: letOrVar, valuePattern: value, arena: self.arena)) case (.isKeyword, let handle)?: let isKeyword = self.eat(handle) let type = self.parseType() return RawPatternSyntax(RawIsTypePatternSyntax( isKeyword: isKeyword, type: type, arena: self.arena )) case nil: // matching-pattern ::= expr // Fall back to expression parsing for ambiguous forms. Name lookup will // disambiguate. let patternSyntax = self.parseSequenceExpression(.basic, pattern: context) if let pat = patternSyntax.as(RawUnresolvedPatternExprSyntax.self) { // The most common case here is to parse something that was a lexically // obvious pattern, which will come back wrapped in an immediate // RawUnresolvedPatternExprSyntax. // // FIXME: This is pretty gross. Let's find a way to disambiguate let // binding patterns much earlier. return RawPatternSyntax(pat.pattern) } let expr = RawExprSyntax(patternSyntax) return RawPatternSyntax(RawExpressionPatternSyntax(expression: expr, arena: self.arena)) } } } // MARK: Lookahead extension Parser.Lookahead { /// pattern ::= identifier /// pattern ::= '_' /// pattern ::= pattern-tuple /// pattern ::= 'var' pattern /// pattern ::= 'let' pattern mutating func canParsePattern() -> Bool { enum PatternStartTokens: RawTokenKindSubset { case identifier case wildcardKeyword case letKeyword case varKeyword case leftParen init?(lexeme: Lexer.Lexeme) { switch lexeme.tokenKind { case .identifier: self = .identifier case .wildcardKeyword: self = .wildcardKeyword case .letKeyword: self = .letKeyword case .varKeyword: self = .varKeyword case .leftParen: self = .leftParen default: return nil } } var rawTokenKind: RawTokenKind { switch self { case .identifier: return .identifier case .wildcardKeyword: return .wildcardKeyword case .letKeyword: return .letKeyword case .varKeyword: return .varKeyword case .leftParen: return .leftParen } } } switch self.at(anyIn: PatternStartTokens.self) { case (.identifier, let handle)?, (.wildcardKeyword, let handle)?: self.eat(handle) return true case (.letKeyword, let handle)?, (.varKeyword, let handle)?: self.eat(handle) return self.canParsePattern() case (.leftParen, _)?: return self.canParsePatternTuple() case nil: return false } } private mutating func canParsePatternTuple() -> Bool { guard self.consume(if: .leftParen) != nil else { return false } if !self.at(.rightParen) { var loopProgress = LoopProgressCondition() repeat { guard self.canParsePattern() else { return false } } while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken) } return self.consume(if: .rightParen) != nil } /// typed-pattern ::= pattern (':' type)? mutating func canParseTypedPattern() -> Bool { guard self.canParsePattern() else { return false } if self.consume(if: .colon) != nil { return self.canParseType() } return true } /// Determine whether we are at the start of a parameter name when /// parsing a parameter. /// If `allowMisplacedSpecifierRecovery` is `true`, then this will skip over any type /// specifiers before checking whether this lookahead starts a parameter name. mutating func startsParameterName(isClosure: Bool, allowMisplacedSpecifierRecovery: Bool) -> Bool { if allowMisplacedSpecifierRecovery { while self.consume(ifAnyIn: TypeSpecifier.self) != nil {} } // To have a parameter name here, we need a name. guard self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) else { return false } // If the next token is ':', this is a name. let nextTok = self.peek() if nextTok.tokenKind == .colon { return true } // If the next token can be an argument label, we might have a name. if nextTok.canBeArgumentLabel(allowDollarIdentifier: true) { // If the first name wasn't "isolated", we're done. if !self.atContextualKeyword("isolated") && !self.atContextualKeyword("some") && !self.atContextualKeyword("any") { return true } // "isolated" can be an argument label, but it's also a contextual keyword, // so look ahead one more token (two total) see if we have a ':' that would // indicate that this is an argument label. do { if self.at(.colon) { return true // isolated : } self.consumeAnyToken() return self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon } } if nextTok.isOptionalToken || nextTok.isImplicitlyUnwrappedOptionalToken { return false } // The identifier could be a name or it could be a type. In a closure, we // assume it's a name, because the type can be inferred. Elsewhere, we // assume it's a type. return isClosure } }
eb39e773d9a6f6a4fe3c6d12cf89c1d7
33.197436
127
0.63545
false
false
false
false
apple/swift-lldb
refs/heads/stable
packages/Python/lldbsuite/test/lang/swift/protocol_optional/main.swift
apache-2.0
2
protocol Key { associatedtype Value } struct Key1: Key { typealias Value = Int? } struct KeyTransformer<K1: Key> { let input: K1.Value func printOutput() { let patatino = input print(patatino) //%self.expect('frame variable -d run-target -- patatino', substrs=['(Int?) patatino = 5']) //%self.expect('expr -d run-target -- patatino', substrs=['(Int?) $R0 = 5']) } } var xformer: KeyTransformer<Key1> = KeyTransformer(input: 5) xformer.printOutput()
35e80f1b30dff36890d8327f7c59d7be
24.65
115
0.614035
false
false
false
false
GitHubOfJW/JavenKit
refs/heads/master
JavenKit/JWCalendarViewController/View/JWCalendarView.swift
mit
1
// // JWCalendarView.swift // KitDemo // // Created by 朱建伟 on 2017/1/3. // Copyright © 2017年 zhujianwei. All rights reserved. // import UIKit //协议 public protocol JWCalendarViewDelegate: NSObjectProtocol { //天数 func numberOfDay(in calendarView:JWCalendarView) -> Int //缩进 func placeholders(in calendarView:JWCalendarView) -> Int; //单天的状态 func dayState(in calendarView:JWCalendarView,dayIndex:Int) -> JWCalendarView.DayItemType; //间隙 func rowPadding(in calendarView:JWCalendarView)-> CGFloat; //间隙 func columnPadding(in calendarView:JWCalendarView)-> CGFloat; } //展示日期的View public class JWCalendarView: UIView { //类型 public enum DayItemType:Int { case normal//普通 case selected//选中 case disabled//禁用 } weak var delegate:JWCalendarViewDelegate? //刷新 func reloadData() { self.setNeedsDisplay() } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //绘制 override public func draw(_ rect: CGRect) { super.draw(rect) if let delegate = self.delegate{ //天数 let numberOfDays:Int = delegate.numberOfDay(in: self) if numberOfDays <= 0{ return } //缩进 let placeholders:Int = delegate.placeholders(in: self) //总行数 let totlaRows:Int = (numberOfDays+placeholders + 7 - 1)/7 //行间距 let rowPadding:CGFloat = delegate.rowPadding(in: self) //列间距 let columnPadding:CGFloat = delegate.columnPadding(in: self) //按钮宽度 let itemW:CGFloat = (self.bounds.width-(8*columnPadding))/7 //高度 let itemH:CGFloat = (self.bounds.height-(CGFloat(totlaRows+1)*rowPadding))/CGFloat(totlaRows) //遍历刷新 for index in 0...numberOfDays{ //计算位置 let x:CGFloat = CGFloat((index + placeholders) % 7)*(itemW+columnPadding)+columnPadding let y:CGFloat = CGFloat((index + placeholders) / 7)*(itemH+rowPadding)+rowPadding let rect:CGRect = CGRect(x: x, y: y, width: itemW, height: itemH) let state:DayItemType = delegate.dayState(in: self, dayIndex: index) //上下文 let context:CGContext = UIGraphicsGetCurrentContext()! let fontSize:CGFloat = itemH * 0.5 let titleStr:NSString = NSString(string:String(format:"%zd",index+1)) let titleSize:CGSize = titleStr.boundingRect(with: CGSize(width:itemW,height:itemH), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize)], context: nil).size let offSetX:CGFloat = (itemW - titleSize.width)/2 let offSetY:CGFloat = (itemH - titleSize.height)/2 //绘制背景 switch state { case .normal: //普通 context.setFillColor(dayNormalColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:dayNormalTextColor]) break case .selected: //选中 context.setFillColor(daySelectedColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:daySelectedTextColor]) break case .disabled: //禁用 context.setFillColor(dayDisabledColor.cgColor) context.addEllipse(in: rect) context.fillPath() //文字 titleStr.draw(at: CGPoint(x:rect.minX+offSetX,y: rect.minY + offSetY) , withAttributes: [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName:dayDisabledTextColor]) break } } } } }
050110fe82bada0769fc6049211f3ae4
30.378049
246
0.520793
false
false
false
false
chanhx/Octogit
refs/heads/master
iGithub/ViewControllers/List/RepositoryTableViewController.swift
gpl-3.0
2
// // RepositoryTableViewController.swift // iGithub // // Created by Chan Hocheung on 7/31/16. // Copyright © 2016 Hocheung. All rights reserved. // import UIKit class RepositoryTableViewController: BaseTableViewController { var viewModel: RepositoryTableViewModel! { didSet { viewModel.dataSource.asDriver() .skip(1) .do(onNext: { [unowned self] _ in self.tableView.refreshHeader?.endRefreshing() self.viewModel.hasNextPage ? self.tableView.refreshFooter?.endRefreshing() : self.tableView.refreshFooter?.endRefreshingWithNoMoreData() }) .do(onNext: { [unowned self] in if $0.count <= 0 { self.show(statusType: .empty) } else { self.hide(statusType: .empty) } }) .drive(tableView.rx.items(cellIdentifier: "RepositoryCell", cellType: RepositoryCell.self)) { row, element, cell in cell.shouldDisplayFullName = self.viewModel.shouldDisplayFullName cell.configure(withRepository: element) } .disposed(by: viewModel.disposeBag) viewModel.error.asDriver() .filter { $0 != nil } .drive(onNext: { [unowned self] in self.tableView.refreshHeader?.endRefreshing() self.tableView.refreshFooter?.endRefreshing() MessageManager.show(error: $0!) }) .disposed(by: viewModel.disposeBag) } } override func viewDidLoad() { super.viewDidLoad() tableView.register(RepositoryCell.self, forCellReuseIdentifier: "RepositoryCell") tableView.refreshHeader = RefreshHeader(target: viewModel, selector: #selector(viewModel.refresh)) tableView.refreshFooter = RefreshFooter(target: viewModel, selector: #selector(viewModel.fetchData)) tableView.refreshHeader?.beginRefreshing() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let repoVC = RepositoryViewController.instantiateFromStoryboard() repoVC.viewModel = viewModel.repoViewModel(forRow: indexPath.row) self.navigationController?.pushViewController(repoVC, animated: true) } }
10b2490c38fd31f284812b8abeff9ccb
37.044118
131
0.565906
false
false
false
false
ambas/Impala
refs/heads/master
Pod/Classes/CellProtocol.swift
mit
1
// // CellProtocol.swift // Impala // // Created by Ambas Chobsanti on 1/30/16. // Copyright © 2016 AM. All rights reserved. // import UIKit protocol ReuseableView { static var defaultReuseIdentifier: String { get } } extension ReuseableView where Self: UIView { static var defaultReuseIdentifier: String { return NSStringFromClass(self) } } extension UICollectionViewCell: ReuseableView { } extension UITableViewCell: ReuseableView { } protocol NibLoadableView: class { static var nibName:String { get } } extension NibLoadableView where Self: UIView { static var nibName: String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } } extension UICollectionView { func register<T: UICollectionViewCell where T: ReuseableView>(_: T.Type){ registerClass(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func register<T: UICollectionViewCell where T: ReuseableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UICollectionViewCell where T: ReuseableView>(indexPath: NSIndexPath) -> T { guard let cell = dequeueReusableCellWithReuseIdentifier(T.defaultReuseIdentifier, forIndexPath: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } } extension UITableView { func register<T: UITableViewCell where T: ReuseableView>(_: T.Type) { registerClass(T.self, forCellReuseIdentifier: T.defaultReuseIdentifier) } func register<T: UITableViewCell where T: ReuseableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellReuseIdentifier: T.defaultReuseIdentifier) } func dequeueReusableCell<T: UITableViewCell where T: ReuseableView>(indexPath: NSIndexPath) -> T { guard let cell = dequeueReusableCellWithIdentifier(T.defaultReuseIdentifier) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } }
a8256383e0a01eeaff5ba1875c0dffc2
30.723684
127
0.69834
false
false
false
false
danger/danger-swift
refs/heads/master
Sources/Danger/DangerResults.swift
mit
1
import Foundation // MARK: - Violation /// The result of a warn, message, or fail. public struct Violation: Encodable { let message: String let file: String? let line: Int? init(message: String, file: String? = nil, line: Int? = nil) { self.message = message self.file = file self.line = line } } /// Meta information for showing in the text info public struct Meta: Encodable { let runtimeName = "Danger Swift" let runtimeHref = "https://danger.systems/swift" } // MARK: - Results /// The representation of what running a Dangerfile generates. struct DangerResults: Encodable { /// Failed messages. var fails = [Violation]() /// Messages for info. var warnings = [Violation]() /// A set of messages to show inline. var messages = [Violation]() /// Markdown messages to attach at the bottom of the comment. var markdowns = [Violation]() /// Information to pass back to Danger JS about the runtime let meta = Meta() }
0cd1ce294b93a6d8649dcf9df03aed9b
23.261905
66
0.647694
false
false
false
false
chrisamanse/UsbongKit
refs/heads/master
UsbongKit/LanguagesTableViewController.swift
apache-2.0
2
// // LanguagesTableViewController.swift // UsbongKit // // Created by Chris Amanse on 12/31/15. // Copyright © 2015 Usbong Social Systems, Inc. All rights reserved. // import UIKit class LanguagesTableViewController: UITableViewController { var store: IAPHelper = IAPHelper(bundles: []) { didSet { if isViewLoaded { tableView.reloadData() } } } var languages: [String] = [] { didSet { if isViewLoaded { tableView.reloadData() } } } var selectedLanguage = "" var didSelectLanguageCompletion: ((_ selectedLanguage: String) -> Void)? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismiss(_:))) // Subscribe to a notification that fires when a product is purchased. NotificationCenter.default.addObserver(self, selector: #selector(productPurchased(_:)), name: NSNotification.Name(rawValue: IAPHelperProductPurchasedNotification), object: nil) } func dismiss(_ sender: AnyObject?) { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { NotificationCenter.default.removeObserver(self) } func productPurchased(_ sender: AnyObject?) { tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "defaultCell", for: indexPath) let language = languages[indexPath.row] cell.textLabel?.text = language // If purchased, set text color to black if store.isLanguagePurchased(language) { cell.textLabel?.textColor = .black } else { cell.textLabel?.textColor = .lightGray } if language == selectedLanguage { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let targetLanguage = languages[indexPath.row] // Show purchase screen if unpurchased guard store.isLanguagePurchased(targetLanguage) else { print("Language is for purchase!") performSegue(withIdentifier: "showProducts", sender: tableView) return } // Pass through if not unpurchased // guard !IAPProducts.isUnpurchasedLanguage(targetLanguage) else { // // Unavailable // print("Language is for purchase!") // // performSegueWithIdentifier("showProducts", sender: tableView) // // return // } selectedLanguage = targetLanguage tableView.reloadData() self.dismiss(animated: true) { self.didSelectLanguageCompletion?(targetLanguage) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier ?? "" { case "showProducts": let destinationViewController = segue.destination as! PurchasesTableViewController destinationViewController.store = store default: break } } }
7c8b62363efa1c39e5a356baa98f2634
29.769231
184
0.59825
false
false
false
false
PGSSoft/AutoMate
refs/heads/master
AutoMate/Models/ServiceRequestAlerts.swift
mit
1
// swiftlint:disable identifier_name type_body_length trailing_comma file_length line_length /// Represents possible system service messages and label values on buttons. import XCTest #if os(iOS) extension SystemAlertAllow { /// Represents all possible "allow" buttons in system service messages. public static var allow: [String] { return readMessages(from: "SystemAlertAllow") } } extension SystemAlertDeny { /// Represents all possible "deny" buttons in system service messages. public static var deny: [String] { return readMessages(from: "SystemAlertDeny") } } /// Represents `AddressBookAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = AddressBookAlert(element: alert) else { /// XCTFail("Cannot create AddressBookAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct AddressBookAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `AddressBookAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `AddressBookAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `BluetoothPeripheralAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = BluetoothPeripheralAlert(element: alert) else { /// XCTFail("Cannot create BluetoothPeripheralAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct BluetoothPeripheralAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `BluetoothPeripheralAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `BluetoothPeripheralAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CalendarAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CalendarAlert(element: alert) else { /// XCTFail("Cannot create CalendarAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CalendarAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CalendarAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CalendarAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CallsAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CallsAlert(element: alert) else { /// XCTFail("Cannot create CallsAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CallsAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CallsAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CallsAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `CameraAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = CameraAlert(element: alert) else { /// XCTFail("Cannot create CameraAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct CameraAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `CameraAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `CameraAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MediaLibraryAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MediaLibraryAlert(element: alert) else { /// XCTFail("Cannot create MediaLibraryAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MediaLibraryAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MediaLibraryAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MediaLibraryAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MicrophoneAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MicrophoneAlert(element: alert) else { /// XCTFail("Cannot create MicrophoneAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MicrophoneAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MicrophoneAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MicrophoneAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `MotionAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = MotionAlert(element: alert) else { /// XCTFail("Cannot create MotionAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct MotionAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `MotionAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `MotionAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `PhotosAddAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = PhotosAddAlert(element: alert) else { /// XCTFail("Cannot create PhotosAddAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct PhotosAddAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `PhotosAddAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `PhotosAddAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `PhotosAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = PhotosAlert(element: alert) else { /// XCTFail("Cannot create PhotosAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct PhotosAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `PhotosAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `PhotosAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `RemindersAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = RemindersAlert(element: alert) else { /// XCTFail("Cannot create RemindersAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct RemindersAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `RemindersAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `RemindersAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `SiriAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = SiriAlert(element: alert) else { /// XCTFail("Cannot create SiriAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct SiriAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `SiriAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `SiriAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `SpeechRecognitionAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = SpeechRecognitionAlert(element: alert) else { /// XCTFail("Cannot create SpeechRecognitionAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct SpeechRecognitionAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `SpeechRecognitionAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `SpeechRecognitionAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } /// Represents `WillowAlert` service alert. /// /// System alert supposed to be used in the handler of the `XCTestCase.addUIInterruptionMonitor(withDescription:handler:)` method. /// /// **Example:** /// /// ```swift /// let token = addUIInterruptionMonitor(withDescription: "Alert") { (alert) -> Bool in /// guard let alert = WillowAlert(element: alert) else { /// XCTFail("Cannot create WillowAlert object") /// return false /// } /// /// alert.denyElement.tap() /// return true /// } /// /// mainPage.goToPermissionsPageMenu() /// // Interruption won't happen without some kind of action. /// app.tap() /// removeUIInterruptionMonitor(token) /// ``` /// /// - note: /// Handlers should return `true` if they handled the UI, `false` if they did not. public struct WillowAlert: SystemAlert, SystemAlertAllow, SystemAlertDeny { /// Represents all possible messages in `WillowAlert` service alert. public static let messages = readMessages() /// System service alert element. public var alert: XCUIElement /// Initialize `WillowAlert` with alert element. /// /// - Parameter element: An alert element. public init?(element: XCUIElement) { guard element.staticTexts.elements(withLabelsLike: type(of: self).messages).first != nil else { return nil } self.alert = element } } #endif
ca64fb0131d9a79df6338d370e449cf4
30.006135
130
0.662693
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Objects/data types/enumerable/CMType.swift
gpl-2.0
1
// // CMType.swift // Colosseum Tool // // Created by The Steez on 06/06/2018. // import Foundation var kFirstTypeOffset: Int { switch region { case .US: return 0x358500 case .JP: return 0x344C40 case .EU: return 0x3A55C0 case .OtherGame: return 0 } } let kCategoryOffset = 0x0 let kTypeIconBigIDOffset = 0x02 let kTypeNameIDOffset = 0x4 let kFirstEffectivenessOffset = 0x9 let kSizeOfTypeData = 0x2C let kNumberOfTypes = 0x12 // name id list in dol in colo 0x2e2458 final class XGType: NSObject, Codable { var index = 0 var nameID = 0 var category = XGMoveCategories.none var effectivenessTable = [XGEffectivenessValues]() var name : XGString { get { return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID) } } var startOffset = 0 init(index: Int) { super.init() let dol = XGFiles.dol.data! self.index = index startOffset = kFirstTypeOffset + (index * kSizeOfTypeData) self.nameID = dol.getWordAtOffset(startOffset + kTypeNameIDOffset).int self.category = XGMoveCategories(rawValue: dol.getByteAtOffset(startOffset + kCategoryOffset))! var offset = startOffset + kFirstEffectivenessOffset for _ in 0 ..< kNumberOfTypes { let value = dol.getByteAtOffset(offset) let effectiveness = XGEffectivenessValues(rawValue: value) ?? .neutral effectivenessTable.append(effectiveness) offset += 2 } } func save() { let dol = XGFiles.dol.data! dol.replaceByteAtOffset(startOffset + kCategoryOffset, withByte: self.category.rawValue) for i in 0 ..< self.effectivenessTable.count { let value = effectivenessTable[i].rawValue dol.replaceByteAtOffset(startOffset + kFirstEffectivenessOffset + (i * 2), withByte: value) // i*2 because each value is 2 bytes apart } dol.save() } } extension XGType: XGEnumerable { var enumerableName: String { return name.string } var enumerableValue: String? { return String(format: "%02d", index) } static var className: String { return "Types" } static var allValues: [XGType] { var values = [XGType]() for i in 0 ..< kNumberOfTypes { values.append(XGType(index: i)) } return values } }
02f0447615724351e23b5cfac5ddbe91
19.472222
97
0.697422
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/ToastView.swift
gpl-3.0
1
// // ToastManager.Swift // Habitica // // Created by Collin Ruffenach on 11/6/14. // Copyright (c) 2014 Notion. All rights reserved. // import UIKit class ToastView: UIView { @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var priceContainer: UIView! @IBOutlet weak var priceIconLabel: IconLabel! @IBOutlet weak var statsDiffStackView: UIStackView! @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var bottomSpacing: NSLayoutConstraint! @IBOutlet weak var topSpacing: NSLayoutConstraint! @IBOutlet weak var leadingSpacing: NSLayoutConstraint! @IBOutlet weak var trailingSpacing: NSLayoutConstraint! @IBOutlet weak var leftImageWidth: NSLayoutConstraint! @IBOutlet weak var leftImageHeight: NSLayoutConstraint! @IBOutlet weak var priceContainerWidth: NSLayoutConstraint! @IBOutlet weak var priceTrailingPadding: NSLayoutConstraint! @IBOutlet weak var priceLeadingPadding: NSLayoutConstraint! @IBOutlet weak var priceIconLabelWidth: NSLayoutConstraint! var options: ToastOptions = ToastOptions() public convenience init(title: String, subtitle: String, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) options.title = title options.subtitle = subtitle options.backgroundColor = background if let duration = duration { options.displayDuration = duration } if let delay = delay { options.delayDuration = delay } loadOptions() accessibilityLabel = "\(title), \(subtitle)" } public convenience init(title: String, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) options.title = title options.backgroundColor = background if let duration = duration { options.displayDuration = duration } if let delay = delay { options.delayDuration = delay } loadOptions() accessibilityLabel = title } public convenience init(title: String, subtitle: String, icon: UIImage, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) options.title = title options.subtitle = subtitle options.leftImage = icon options.backgroundColor = background if let duration = duration { options.displayDuration = duration } if let delay = delay { options.delayDuration = delay } loadOptions() accessibilityLabel = "\(title), \(subtitle)" } public convenience init(title: String, icon: UIImage, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) options.title = title options.backgroundColor = background options.leftImage = icon if let duration = duration { options.displayDuration = duration } if let delay = delay { options.delayDuration = delay } loadOptions() accessibilityLabel = title } public convenience init(title: String, rightIcon: UIImage, rightText: String, rightTextColor: UIColor, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) options.title = title options.backgroundColor = background options.rightIcon = rightIcon options.rightText = rightText options.rightTextColor = rightTextColor if let duration = duration { options.displayDuration = duration } if let delay = delay { options.delayDuration = delay } loadOptions() accessibilityLabel = title } public convenience init(healthDiff: Float, magicDiff: Float, expDiff: Float, goldDiff: Float, questDamage: Float, background: ToastColor, duration: Double? = nil, delay: Double? = nil) { self.init(frame: CGRect.zero) accessibilityLabel = "You received " addStatsView(HabiticaIcons.imageOfHeartDarkBg, diff: healthDiff, label: "Health") addStatsView(HabiticaIcons.imageOfExperience, diff: expDiff, label: "Experience") addStatsView(HabiticaIcons.imageOfMagic, diff: magicDiff, label: "Mana") addStatsView(HabiticaIcons.imageOfGold, diff: goldDiff, label: "Gold") addStatsView(HabiticaIcons.imageOfDamage, diff: questDamage, label: "Damage") options.backgroundColor = background loadOptions() } private func addStatsView(_ icon: UIImage, diff: Float, label: String) { if diff != 0 { let iconLabel = IconLabel() iconLabel.icon = icon iconLabel.text = diff > 0 ? String(format: "+%.2f", diff) : String(format: "%.2f", diff) iconLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal) statsDiffStackView.addArrangedSubview(iconLabel) accessibilityLabel = (accessibilityLabel ?? "") + "\(Int(diff)) \(label), " } } override init(frame: CGRect) { super.init(frame: frame) configureViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureViews() } private func configureViews() { self.backgroundColor = .clear if let view = viewFromNibForClass() { translatesAutoresizingMaskIntoConstraints = false view.frame = bounds addSubview(view) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": view])) backgroundView.layer.borderColor = UIColor.black.withAlphaComponent(0.1).cgColor backgroundView.layer.borderWidth = 1 isUserInteractionEnabled = false backgroundView.isUserInteractionEnabled = true isAccessibilityElement = false } } func loadOptions() { backgroundView.backgroundColor = options.backgroundColor.getUIColor() backgroundView.layer.borderColor = options.backgroundColor.getUIColor().darker(by: 10).cgColor topSpacing.constant = 6 bottomSpacing.constant = 6 leadingSpacing.constant = 8 trailingSpacing.constant = 8 configureTitle(options.title) configureSubtitle(options.subtitle) configureLeftImage(options.leftImage) configureRightView(icon: options.rightIcon, text: options.rightText, textColor: options.rightTextColor) priceContainerWidth.constant = 0 setNeedsUpdateConstraints() updateConstraints() setNeedsLayout() layoutIfNeeded() } private func configureTitle(_ title: String?) { if let title = title { titleLabel.isHidden = false titleLabel.text = title titleLabel.sizeToFit() titleLabel.numberOfLines = -1 titleLabel.font = UIFont.systemFont(ofSize: 13) titleLabel.textAlignment = .center } else { titleLabel.isHidden = true titleLabel.text = nil } } private func configureSubtitle(_ subtitle: String?) { if let subtitle = subtitle { subtitleLabel.isHidden = false subtitleLabel.text = subtitle subtitleLabel.sizeToFit() subtitleLabel.numberOfLines = -1 titleLabel.font = UIFont.systemFont(ofSize: 16) titleLabel.textAlignment = .center } else { subtitleLabel.isHidden = true subtitleLabel.text = nil } } private func configureLeftImage(_ leftImage: UIImage?) { if let leftImage = leftImage { leftImageView.isHidden = false leftImageView.image = leftImage leadingSpacing.constant = 4 leftImageWidth.constant = 46 leftImageHeight.priority = UILayoutPriority(rawValue: 999) } else { leftImageView.isHidden = true leftImageWidth.constant = 0 leftImageHeight.priority = UILayoutPriority(rawValue: 500) } } private func configureRightView(icon: UIImage?, text: String?, textColor: UIColor?) { if let icon = icon, let text = text, let textColor = textColor { priceContainer.isHidden = false priceIconLabel.icon = icon priceIconLabel.text = text priceIconLabel.textColor = textColor trailingSpacing.constant = 0 backgroundView.layer.borderColor = options.backgroundColor.getUIColor().cgColor } else { priceContainer.isHidden = true priceIconLabel.removeFromSuperview() } } }
fdc4966c450c4e504bd302a15d5d4679
37.545082
190
0.634024
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
TranslationEditor/ParagraphBindingView.swift
mit
1
// // ParagraphBindingView.swift // TranslationEditor // // Created by Mikko Hilpinen on 11.1.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // This is the view used for querying paragraph binding data final class ParagraphBindingView: View { // TYPES -------------------- typealias Queried = ParagraphBinding typealias MyQuery = Query<ParagraphBindingView> // ATTRIBUTES ---------------- static let KEY_CODE = "code" static let KEY_TARGET_BOOK = "target" static let KEY_SOURCE_BOOK = "source" static let KEY_CREATED = "created" static let instance = ParagraphBindingView() static let keyNames = [KEY_CODE, KEY_TARGET_BOOK, KEY_SOURCE_BOOK, KEY_CREATED] let view: CBLView // INIT ------------------------ private init() { view = DATABASE.viewNamed("paragraph_bindings") view.setMapBlock(createMapBlock { binding, emit in let key = [Book.code(fromId: binding.targetBookId).code, binding.targetBookId, binding.sourceBookId, binding.created] as [Any] // let value = [binding.idString, binding.created] as [Any] emit(key, nil) }/*, reduce: { // Finds the most recent id keys, values, rereduce in var mostRecentId = "" var mostRecentTime = 0.0 for value in values { let value = value as! [Any] let created = value[1] as! TimeInterval if created > mostRecentTime { let id = value[0] as! String mostRecentId = id mostRecentTime = created } } return [mostRecentId, mostRecentTime] }*/, version: "6") } // OTHER METHODS --------- func createQuery(targetBookId: String, sourceBookId: String? = nil) -> MyQuery { return createQuery(code: Book.code(fromId: targetBookId), targetBookId: targetBookId, sourceBookId: sourceBookId) } // Finds the latest existing binding between the two books func latestBinding(from sourceBookId: String, to targetBookId: String) throws -> ParagraphBinding? { return try createQuery(code: Book.code(fromId: targetBookId), targetBookId: targetBookId, sourceBookId: sourceBookId).firstResultObject() } // Finds all bindings that have the provided book id as either source or target func bindings(forBookWithId bookId: String) throws -> [ParagraphBinding] { return try createQuery(code: Book.code(fromId: bookId), targetBookId: nil, sourceBookId: nil).resultRows().filter { $0.keys[ParagraphBindingView.KEY_TARGET_BOOK]?.string == bookId || $0.keys[ParagraphBindingView.KEY_SOURCE_BOOK]?.string == bookId }.map { try $0.object() } } private func createQuery(code: BookCode?, targetBookId: String?, sourceBookId: String?) -> MyQuery { let keys = ParagraphBindingView.makeKeys(from: [code?.code, targetBookId, sourceBookId]) var query = createQuery(withKeys: keys) query.descending = true return query } }
91c6e94819d7ae7fcc70c33a77d524b7
26.911765
274
0.687741
false
false
false
false
thanhtrdang/FluentYogaKit
refs/heads/master
FluentYogaKit/CardViewController.swift
apache-2.0
1
// // CardViewController.swift // FluentYogaKit // // Created by Thanh Dang on 6/12/17. // Copyright © 2017 Thanh Dang. All rights reserved. // import UIKit import YetAnotherAnimationLibrary class CardViewController: UIViewController { let gr = UIPanGestureRecognizer() var card: UIView! var backCard: UIView? fileprivate var cardFrame: CGRect! func generateCard() -> UIView { let card = UIView() view.insertSubview(card, at: 0) view.yoga .background(card, edges: [.vertical: 120, .horizontal: 50]) .layout() card.layer.cornerRadius = 8 card.backgroundColor = .white card.layer.shadowOffset = .zero card.layer.shadowOpacity = 0.5 card.layer.shadowRadius = 5 card.yaal.center.value => { [weak view] newCenter in if let view = view { return (newCenter.x - view.center.x) / view.bounds.width } return nil } => card.yaal.rotation card.yaal.scale.value => { $0 * $0 } => card.yaal.alpha return card } override func viewDidLoad() { super.viewDidLoad() cardFrame = UIEdgeInsetsInsetRect(view.bounds, UIEdgeInsets(top: 120, left: 50, bottom: 120, right: 50)) view.backgroundColor = UIColor(red: 1.0, green: 0.5, blue: 0.5, alpha: 1.0) gr.addTarget(self, action: #selector(pan(gr:))) view.addGestureRecognizer(gr) card = generateCard() } @objc func pan(gr: UIPanGestureRecognizer) { let translation = gr.translation(in: view) switch gr.state { case .began: backCard = generateCard() backCard!.yaal.scale.setTo(0.7) fallthrough case .changed: card.yaal.center.setTo(CGPoint(x: translation.x + view.center.x, y: translation.y / 10 + view.center.y)) backCard!.yaal.scale.setTo(abs(translation.x) / view.bounds.width * 0.3 + 0.7) default: if let backCard = backCard, abs(translation.x) > view.bounds.width / 4 { let finalX = translation.x < 0 ? -view.bounds.width : view.bounds.width * 2 card.yaal.center.animateTo(CGPoint(x: finalX, y: view.center.y)) { [card] _ in card?.removeFromSuperview() } card = backCard card.yaal.scale.animateTo(1) } else { backCard?.yaal.scale.animateTo(0) { [backCard] _ in backCard?.removeFromSuperview() } card.yaal.center.animateTo(view.center) } backCard = nil } } }
60a27578a250fbd92935e7ea7c1eaa8a
26.931034
110
0.630453
false
false
false
false
Skyus/Swiftlog
refs/heads/master
Swiftlog/Utils.swift
gpl-2.0
1
import Foundation import VPIAssistant public class Control { public static func finish() { vpi_finish(); } } extension String { public var cPointer: (cLiteral: UnsafePointer<CChar>, cMutable: UnsafeMutablePointer<CChar>, mutable: UnsafeMutablePointer<UInt8>, elementCount: Int) { var utf8Representation = Array(self.utf8) utf8Representation.append(0) //0 terminator let mutablePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8Representation.count) let cMutablePointer = UnsafeMutableRawPointer(mutablePointer).bindMemory(to: CChar.self, capacity: utf8Representation.count) let immutablePointer = UnsafeRawPointer(mutablePointer).bindMemory(to: CChar.self, capacity: utf8Representation.count) let _ = UnsafeMutableBufferPointer<UInt8>(start: mutablePointer, count: utf8Representation.count).initialize(from: utf8Representation) return (cLiteral: immutablePointer, cMutable: cMutablePointer, mutable: mutablePointer, elementCount: utf8Representation.count) } }
36a98ff1ea187432f8ecd3c16a444050
52
155
0.757318
false
false
false
false
JWShroyer/CollectionViewTransitions
refs/heads/master
CollectionViewTransitions/CollectionViewTransitions/CollectionViewController.swift
mit
1
// // CollectionViewController.swift // CollectionViewTransitions // // Created by Joshua Shroyer on 7/23/15. // Copyright (c) 2015 Full Sail University. All rights reserved. // import UIKit let cellIdentifier = "cellReuse" class CollectionViewController: UICollectionViewController { var cellCount = 5; override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { collectionView?.dataSource = self; collectionView?.delegate = self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { //#warning Incomplete method implementation -- Return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { //#warning Incomplete method implementation -- Return the number of items in the section return 5; } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell // Configure the cell cell.backgroundColor = UIColor.redColor(); return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let tVC = segue.destinationViewController as? TransitionCollectionViewController { tVC.useLayoutToLayoutNavigationTransitions = true; } } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
05ab3119c50dbccc1cab440dceb6972c
33.046296
183
0.752244
false
false
false
false
kevinvanderlugt/Exercism-Solutions
refs/heads/master
swift/octal/Octal.swift
mit
1
// // Octal.swift // exercism-test-runner // // Created by Kevin VanderLugt on 4/11/15. // Copyright (c) 2015 Alpine Pipeline, LLC. All rights reserved. // // import Foundation infix operator ** { } func ** (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power))) } struct Octal { private let base = 8 var octalNumbers: String init(_ octalNumbers: String) { self.octalNumbers = octalNumbers } var toDecimal: Int { var decimal: Int = 0 if(validOctal) { for (index, trinary) in enumerate(reverse(octalNumbers)) { if let digit = String(trinary).toInt() { decimal += digit*(base**index) } } } return decimal } private var validOctal: Bool { return filter(octalNumbers) { !contains(self.validNumbers, String($0)) }.isEmpty } private var validNumbers: [String] { return Array(0..<base).map({String($0)}) } }
ac34384dda7e8b23352683804b6ecf61
22.044444
88
0.557915
false
false
false
false
filestack/filestack-ios
refs/heads/master
Sources/Filestack/UI/Internal/Controllers/MonitorViewController.swift
mit
1
// // MonitorViewController.swift // Filestack // // Created by Ruben Nine on 11/9/17. // Copyright © 2017 Filestack. All rights reserved. // import FilestackSDK import UIKit final class MonitorViewController: UIViewController { // MARK: - Private Properties private let progressable: Cancellable & Monitorizable private var progressObservers: [NSKeyValueObservation] = [] private lazy var progressView: UIProgressView = { let progressView = UIProgressView() progressView.observedProgress = progressable.progress return progressView }() private lazy var activityIndicator: UIActivityIndicatorView = { let activityIndicator: UIActivityIndicatorView if #available(iOS 13.0, *) { activityIndicator = UIActivityIndicatorView(style: .large) } else { activityIndicator = UIActivityIndicatorView(style: .white) } activityIndicator.hidesWhenStopped = true return activityIndicator }() private let cancelButton: UIButton = { let button = UIButton() button.setTitle("Cancel", for: .normal) button.addTarget(self, action: #selector(cancel), for: .touchUpInside) return button }() private lazy var descriptionLabel: UILabel = { let label = UILabel() label.text = progressable.progress.localizedDescription return label }() private lazy var additionalDescriptionLabel: UILabel = { let label = UILabel() label.text = progressable.progress.localizedAdditionalDescription return label }() // MARK: - Lifecycle required init(progressable: Cancellable & Monitorizable) { self.progressable = progressable super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - View Overrides extension MonitorViewController { override func viewDidLoad() { super.viewDidLoad() setupViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if progressable.progress.isIndeterminate { progressView.isHidden = true activityIndicator.startAnimating() } else { progressView.isHidden = false activityIndicator.stopAnimating() } setupObservers() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) removeObservers() progressView.observedProgress = nil } } // MARK: - Actions private extension MonitorViewController { @IBAction func cancel(_: AnyObject) { progressable.cancel() } } // MARK: - Private Functions private extension MonitorViewController { func setupViews() { let stackView = UIStackView(arrangedSubviews: [UIView(), UIView(), descriptionLabel, activityIndicator, progressView, additionalDescriptionLabel, UIView(), cancelButton] ) progressView.leadingAnchor.constraint(equalTo: stackView.layoutMarginsGuide.leadingAnchor).isActive = true progressView.trailingAnchor.constraint(equalTo: stackView.layoutMarginsGuide.trailingAnchor).isActive = true stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.alignment = .center stackView.spacing = 22 stackView.layoutMargins = .init(top: 22, left: 44, bottom: 22, right: 44) stackView.isLayoutMarginsRelativeArrangement = true if #available(iOS 13.0, *) { view.backgroundColor = .systemBackground } else { view.backgroundColor = .white } view.fill(with: stackView) } func setupObservers() { progressObservers.append(progressable.progress.observe(\.totalUnitCount) { (_, _) in DispatchQueue.main.async { self.updateUI() } }) progressObservers.append(progressable.progress.observe(\.completedUnitCount) { (_, _) in DispatchQueue.main.async { self.updateUI() } }) progressObservers.append(progressable.progress.observe(\.fractionCompleted) { (_, _) in DispatchQueue.main.async { self.updateUI() } }) } func updateUI() { if progressable.progress.isIndeterminate && !progressView.isHidden { UIView.animate(withDuration: 0.25) { self.activityIndicator.startAnimating() self.progressView.isHidden = true } } if !progressable.progress.isIndeterminate && !activityIndicator.isHidden { UIView.animate(withDuration: 0.25) { self.activityIndicator.stopAnimating() self.progressView.isHidden = false } } descriptionLabel.text = progressable.progress.localizedDescription additionalDescriptionLabel.text = progressable.progress.localizedAdditionalDescription } func removeObservers() { progressObservers.removeAll() } }
9e1251ead2326acfcfd4ead70a1c7e79
27.416667
135
0.65044
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
refs/heads/main
snippets/MapsSnippets/MapsSnippets/Swift/Markers.swift
apache-2.0
1
// Copyright 2020 Google LLC // // 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. // [START maps_ios_markers_icon_view] import CoreLocation import GoogleMaps class MarkerViewController: UIViewController, GMSMapViewDelegate { var mapView: GMSMapView! var london: GMSMarker? var londonView: UIImageView? override func viewDidLoad() { super.viewDidLoad() let camera = GMSCameraPosition.camera( withLatitude: 51.5, longitude: -0.127, zoom: 14 ) let mapView = GMSMapView.map(withFrame: .zero, camera: camera) view = mapView mapView.delegate = self let house = UIImage(named: "House")!.withRenderingMode(.alwaysTemplate) let markerView = UIImageView(image: house) markerView.tintColor = .red londonView = markerView let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127) let marker = GMSMarker(position: position) marker.title = "London" marker.iconView = markerView marker.tracksViewChanges = true marker.map = mapView london = marker } func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { UIView.animate(withDuration: 5.0, animations: { () -> Void in self.londonView?.tintColor = .blue }, completion: {(finished) in // Stop tracking view changes to allow CPU to idle. self.london?.tracksViewChanges = false }) } } // [END maps_ios_markers_icon_view] var mapView: GMSMapView! func addMarker() { // [START maps_ios_markers_add_marker] let position = CLLocationCoordinate2D(latitude: 10, longitude: 10) let marker = GMSMarker(position: position) marker.title = "Hello World" marker.map = mapView // [END maps_ios_markers_add_marker] } func removeMarker() { // [START maps_ios_markers_remove_marker] let camera = GMSCameraPosition.camera( withLatitude: -33.8683, longitude: 151.2086, zoom: 6 ) let mapView = GMSMapView.map(withFrame: .zero, camera: camera) // ... mapView.clear() // [END maps_ios_markers_remove_marker] // [START maps_ios_markers_remove_marker_modifications] let position = CLLocationCoordinate2D(latitude: 10, longitude: 10) let marker = GMSMarker(position: position) marker.map = mapView // ... marker.map = nil // [END maps_ios_markers_remove_marker_modifications] // [START maps_ios_markers_customize_marker_color] marker.icon = GMSMarker.markerImage(with: .black) // [END maps_ios_markers_customize_marker_color] // [START maps_ios_markers_customize_marker_image] let positionLondon = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127) let london = GMSMarker(position: positionLondon) london.title = "London" london.icon = UIImage(named: "house") london.map = mapView // [END maps_ios_markers_customize_marker_image] // [START maps_ios_markers_opacity] marker.opacity = 0.6 // [END maps_ios_markers_opacity] } func moreCustomizations() { // [START maps_ios_markers_flatten] let positionLondon = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127) let londonMarker = GMSMarker(position: positionLondon) londonMarker.isFlat = true londonMarker.map = mapView // [END maps_ios_markers_flatten] // [START maps_ios_markers_rotate] let degrees = 90.0 londonMarker.groundAnchor = CGPoint(x: 0.5, y: 0.5) londonMarker.rotation = degrees londonMarker.map = mapView // [END maps_ios_markers_rotate] } func infoWindow() { // [START maps_ios_markers_info_window_title] let position = CLLocationCoordinate2D(latitude: 51.5, longitude: -0.127) let london = GMSMarker(position: position) london.title = "London" london.map = mapView // [END maps_ios_markers_info_window_title] // [START maps_ios_markers_info_window_title_and_snippet] london.title = "London" london.snippet = "Population: 8,174,100" london.map = mapView // [END maps_ios_markers_info_window_title_and_snippet] // [START maps_ios_markers_info_window_changes] london.tracksInfoWindowChanges = true // [END maps_ios_markers_info_window_changes] // [START maps_ios_markers_info_window_change_position] london.infoWindowAnchor = CGPoint(x: 0.5, y: 0.5) london.icon = UIImage(named: "house") london.map = mapView // [END maps_ios_markers_info_window_change_position] // [START maps_ios_markers_info_window_show_hide] london.title = "London" london.snippet = "Population: 8,174,100" london.map = mapView // Show marker mapView.selectedMarker = london // Hide marker mapView.selectedMarker = nil // [END maps_ios_markers_info_window_show_hide] }
2627576873d2a8780ba5d9d42ed419cb
30.7
80
0.710371
false
false
false
false
randallli/material-components-ios
refs/heads/develop
components/Snackbar/tests/unit/MDCSnackbarColorThemerTests.swift
apache-2.0
1
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest import MaterialComponents.MaterialSnackbar import MaterialComponents.MaterialSnackbar_ColorThemer class SnackbarColorThemerTests: XCTestCase { func testColorThemerChangesTheCorrectParameters() { // Given let colorScheme = MDCSemanticColorScheme() let message = MDCSnackbarMessage() message.text = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" colorScheme.surfaceColor = .red colorScheme.onSurfaceColor = .blue MDCSnackbarManager.snackbarMessageViewBackgroundColor = .white MDCSnackbarManager.messageTextColor = .white MDCSnackbarManager.setButtonTitleColor(.white, for: .normal) MDCSnackbarManager.setButtonTitleColor(.white, for: .highlighted) // When MDCSnackbarColorThemer.applySemanticColorScheme(colorScheme) MDCSnackbarManager.show(message) // Then XCTAssertEqual(MDCSnackbarManager.snackbarMessageViewBackgroundColor?.withAlphaComponent(1), colorScheme.onSurfaceColor) XCTAssertEqual(MDCSnackbarManager.messageTextColor?.withAlphaComponent(1), colorScheme.surfaceColor) XCTAssertEqual(MDCSnackbarManager.buttonTitleColor(for: .normal)?.withAlphaComponent(1), colorScheme.surfaceColor) XCTAssertEqual(MDCSnackbarManager.buttonTitleColor(for: .highlighted)?.withAlphaComponent(1), colorScheme.surfaceColor) } }
4b6c3526d59e8dc80a7cff4ab9ee2627
39.76
97
0.768891
false
true
false
false
dezinezync/YapDatabase
refs/heads/master
YapDatabase/Extensions/View/Swift/YapDatabaseView.swift
bsd-3-clause
2
/// Add Swift extensions here extension YapDatabaseViewConnection { public func getChanges(forNotifications notifications: [Notification], withMappings mappings: YapDatabaseViewMappings) -> (sectionChanges: [YapDatabaseViewSectionChange], rowChanges: [YapDatabaseViewRowChange]) { var sectionChanges = NSArray() var rowChanges = NSArray() self.__getSectionChanges(&sectionChanges, rowChanges: &rowChanges, for: notifications, with: mappings) return (sectionChanges as! [YapDatabaseViewSectionChange], rowChanges as! [YapDatabaseViewRowChange]) } } extension YapDatabaseViewTransaction { public func getCollectionKey(atIndex index: Int, inGroup group: String) -> (String, String)? { var key: NSString? = nil var collection: NSString? = nil self.__getKey(&key, collection: &collection, at: UInt(index), inGroup: group) if let collection = collection as String?, let key = key as String? { return (collection, key) } else { return nil } } public func getGroupIndex(forKey key: String, inCollection collection: String?) -> (String, Int)? { var group: NSString? = nil var index: UInt = 0 self.__getGroup(&group, index: &index, forKey: key, inCollection: collection) if let group = group as String? { return (group, Int(index)) } else { return nil } } // MARK: Iteration public func iterateKeys(inGroup group: String, using block: (String, String, Int, inout Bool) -> Void) { self.iterateKeys(inGroup: group, reversed: false, using: block) } public func iterateKeys(inGroup group: String, reversed: Bool, using block: (String, String, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeys(inGroup: group, with: options, using: enumBlock) } public func iterateKeys(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeys(inGroup: group, with: options, range: range, using: enumBlock) } public func iterateKeysAndMetadata(inGroup group: String, using block: (String, String, Any?, Int, inout Bool) -> Void) { self.iterateKeysAndMetadata(inGroup: group, reversed: false, using: block) } public func iterateKeysAndMetadata(inGroup group: String, reversed: Bool, using block: (String, String, Any?, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, metadata, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeysAndMetadata(inGroup: group, with: options, using: enumBlock) } public func iterateKeysAndMetadata(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any?, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, metadata, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeysAndMetadata(inGroup: group, with: options, range: range, using: enumBlock) } public func iterateKeysAndObjects(inGroup group: String, using block: (String, String, Any, Int, inout Bool) -> Void) { self.iterateKeysAndObjects(inGroup: group, reversed: false, using: block) } public func iterateKeysAndObjects(inGroup group: String, reversed: Bool, using block: (String, String, Any, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, object: Any, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, object, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeysAndObjects(inGroup: group, with: options, using: enumBlock) } public func iterateKeysAndObjects(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any?, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, object: Any, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, object, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateKeysAndObjects(inGroup: group, with: options, range: range, using: enumBlock) } public func iterateRows(inGroup group: String, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) { self.iterateRows(inGroup: group, reversed: false, using: block) } public func iterateRows(inGroup group: String, reversed: Bool, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, object: Any, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, object, metadata, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateRows(inGroup: group, with: options, using: enumBlock) } public func iterateRows(inGroup group: String, reversed: Bool, range: NSRange, using block: (String, String, Any, Any?, Int, inout Bool) -> Void) { let enumBlock = {(collection: String, key: String, object: Any, metadata: Any?, index: UInt, outerStop: UnsafeMutablePointer<ObjCBool>) -> Void in var innerStop = false block(collection, key, object, metadata, Int(index), &innerStop) if innerStop { outerStop.pointee = true } } let options: NSEnumerationOptions = reversed ? .reverse : .init() self.__enumerateRows(inGroup: group, with: options, range: range, using: enumBlock) } // MARK: Mappings public func getCollectionKey(atIndexPath indexPath: IndexPath, withMappings mappings: YapDatabaseViewMappings) -> (String, String)? { var key: NSString? = nil var collection: NSString? = nil self.__getKey(&key, collection: &collection, at: indexPath, with: mappings) if let collection = collection as String?, let key = key as String? { return (collection, key) } else { return nil } } public func getCollectionKey(forRow row: Int, section: Int, withMappings mappings: YapDatabaseViewMappings) -> (String, String)? { var key: NSString? = nil var collection: NSString? = nil self.__getKey(&key, collection: &collection, forRow: UInt(row), inSection: UInt(section), with: mappings) if let collection = collection as String?, let key = key as String? { return (collection, key) } else { return nil } } }
0466e55fd59754301b3deb851a885930
31.734177
213
0.69322
false
false
false
false
zning1994/practice
refs/heads/master
Swift学习/code4xcode6/ch10/10.1闭包表达式.playground/section-1.swift
gpl-2.0
1
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:jylong06@163.com func calculate(opr :String)-> (Int,Int)-> Int { var result : (Int,Int)-> Int switch (opr) { case "+" : result = {(a:Int, b:Int) -> Int in return a + b } default: result = {(a:Int, b:Int) -> Int in return a - b } } return result } let f1:(Int,Int)-> Int = calculate("+") println("10 + 5 = \(f1(10,5))") let f2:(Int,Int)-> Int = calculate("-") println("10 - 5 = \(f2(10,5))")
f051605c45bb468a4570e3346b27de1d
22.78125
62
0.558476
false
false
false
false
OverSwift/VisualReader
refs/heads/develop
MangaReader/Fameworks/MediaManager/MediaManager/Sources/MediaController.swift
bsd-3-clause
1
// // MediaController.swift // MediaManager // // Created by Sergiy Loza on 08.04.17. // Copyright © 2017 Sergiy Loza. All rights reserved. // import Foundation class ImageStoreOperation: Operation { private(set) var data: Data init(data: Data) { self.data = data } } class DiskCacheManager { private(set) var diskCapasity = 1024 private let fileManager = FileManager.default fileprivate func imgesCacheDirectory() -> URL { let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true); let path = (paths.first! as NSString).appendingPathComponent("MediaControllerCache") var isDirectory = ObjCBool(false) if !FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories:true, attributes: nil) } catch { print("Coudn't create directory at \(path) with error: \(error)") } } else if !isDirectory.boolValue { print("Path \(path) exists but is no directory") } let url = URL(fileURLWithPath: path) self.addSkipBackupAttributeToItemAtURL(url) return url } @discardableResult fileprivate func addSkipBackupAttributeToItemAtURL(_ URL: Foundation.URL) -> Bool { var isSkiAttributeSet = false do { try (URL as NSURL).setResourceValue(true, forKey:URLResourceKey.isExcludedFromBackupKey) isSkiAttributeSet = true } catch { print("Error excluding \(URL) from backup \(error)") } return isSkiAttributeSet } }
74fde6adf72dc6d361097aa7ca535b73
30.472727
120
0.640092
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/NewTeamState.swift
mit
1
// // NewTeamState.swift // Stats // // Created by Parker Rushton on 4/4/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit struct Loading<T>: Event { var object: T? init(_ object: T? = nil) { self.object = object } } struct NewTeamState: State { var imageURL: URL? var isLoading = false mutating func react(to event: Event) { switch event { case let event as Selected<URL>: imageURL = event.item isLoading = false case _ as Loading<URL>: isLoading = true default: break } } }
c250c22bfb7aa797180c46e87b7d1297
16.648649
51
0.534456
false
false
false
false
DDSwift/SwiftDemos
refs/heads/master
Day01-LoadingADView/LoadingADView/LoadingADView/Class/MainTabBarViewController.swift
gpl-3.0
1
// // MainTabBarViewController.swift // LoadingADView // // Created by SuperDanny on 16/3/7. // Copyright © 2016年 SuperDanny. All rights reserved. // import UIKit class MainTabBarViewController: UITabBarController { private var adImageView: UIImageView? var adImage: UIImage? { didSet { weak var tmpSelf = self adImageView = UIImageView(frame: ScreenBounds) adImageView!.image = adImage! view.addSubview(adImageView!) UIImageView.animateWithDuration(2.0, animations: { () -> Void in tmpSelf!.adImageView!.transform = CGAffineTransformMakeScale(1.2, 1.2) tmpSelf!.adImageView!.alpha = 0 }) { (finsch) -> Void in tmpSelf!.adImageView!.removeFromSuperview() tmpSelf!.adImageView = nil } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
73be5b8789d8ff73614f0683ea24d4ed
28.584906
106
0.616709
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/Supporting Files/UIComponents/UIIncrementSlider/UIIncrementSliderView.swift
gpl-3.0
1
// // UIIncrementSliderView.swift // FalconMessenger // // Created by Roman Mizin on 3/4/19. // Copyright © 2019 Roman Mizin. All rights reserved. // import UIKit protocol UIIncrementSliderUpdateDelegate: class { func incrementSliderDidUpdate(to value: CGFloat) } class UIIncrementSliderView: UIView { fileprivate let slider: UIIncrementSlider = { let slider = UIIncrementSlider() slider.translatesAutoresizingMaskIntoConstraints = false return slider }() fileprivate let minimumValueImage: UIImageView = { let minimumValueImage = UIImageView() minimumValueImage.image = UIImage(named: "FontMinIcon")?.withRenderingMode(.alwaysTemplate) minimumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor minimumValueImage.translatesAutoresizingMaskIntoConstraints = false return minimumValueImage }() fileprivate let maximumValueImage: UIImageView = { let maximumValueImage = UIImageView() maximumValueImage.image = UIImage(named: "FontMaxIcon")?.withRenderingMode(.alwaysTemplate) maximumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor maximumValueImage.translatesAutoresizingMaskIntoConstraints = false return maximumValueImage }() weak var delegate: UIIncrementSliderUpdateDelegate? init(values: [Float], currentValue: Float? = 0) { super.init(frame: .zero) addSubview(slider) addSubview(minimumValueImage) addSubview(maximumValueImage) NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil) if #available(iOS 11.0, *) { NSLayoutConstraint.activate([ minimumValueImage.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 15), maximumValueImage.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -15) ]) } else { NSLayoutConstraint.activate([ minimumValueImage.leftAnchor.constraint(equalTo: leftAnchor, constant: 15), maximumValueImage.rightAnchor.constraint(equalTo: rightAnchor, constant: -15) ]) } NSLayoutConstraint.activate([ slider.topAnchor.constraint(equalTo: topAnchor), slider.leftAnchor.constraint(equalTo: minimumValueImage.rightAnchor, constant: 10), slider.rightAnchor.constraint(equalTo: maximumValueImage.leftAnchor, constant: -10), minimumValueImage.centerYAnchor.constraint(equalTo: slider.centerYAnchor), minimumValueImage.widthAnchor.constraint(equalToConstant: (minimumValueImage.image?.size.width ?? 0)), minimumValueImage.heightAnchor.constraint(equalToConstant: (minimumValueImage.image?.size.height ?? 0)), maximumValueImage.centerYAnchor.constraint(equalTo: slider.centerYAnchor), maximumValueImage.widthAnchor.constraint(equalToConstant: (maximumValueImage.image?.size.width ?? 0)), maximumValueImage.heightAnchor.constraint(equalToConstant: (maximumValueImage.image?.size.height ?? 0)) ]) slider.initializeSlider(with: values, currentValue: currentValue ?? 0) { [weak self] actualValue in self?.delegate?.incrementSliderDidUpdate(to: CGFloat(actualValue)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } @objc fileprivate func changeTheme() { minimumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor maximumValueImage.tintColor = ThemeManager.currentTheme().generalTitleColor slider.changeTheme() } }
771c77aab9152fc4847c2a04261c7cdb
36.48913
114
0.787765
false
false
false
false