repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
PointerFLY/ReaLog
ReaLog/MinimizeButton.swift
1
1889
// // MinimizeButton.swift // ReaLog // // Created by PointerFLY on 10/02/2017. // Copyright © 2017 PointerFLY. All rights reserved. // import UIKit class MinimizeButton: UIButton { override init(frame: CGRect) { _minimizeSymbol = MinimizeSymbol() _minimizeSymbol.frame.size = frame.size _minimizeSymbol.center = CGPoint(x: frame.width / 2.0, y: frame.height / 2.0) super.init(frame: frame) self.setImage(UIImage.rl_imageWithColor(UIColor(rl_r: 255, g: 196, b: 48), size: frame.size), for: .normal) self.setImage(UIImage.rl_imageWithColor(UIColor(rl_r: 191, g: 145, b: 35), size: frame.size), for: .selected) self.addSubview(_minimizeSymbol) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview() self.layer.cornerRadius = self.frame.width / 2.0 self.clipsToBounds = true } private let _minimizeSymbol: MinimizeSymbol private class MinimizeSymbol: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear self.isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { let size = self.frame.size let context = UIGraphicsGetCurrentContext()! context.setLineWidth(1.0) context.setStrokeColor(UIColor(rl_r: 0, g: 0, b: 0, a: 0.6).cgColor) context.move(to: CGPoint(x: size.width * 0.2, y: size.height / 2.0)) context.addLine(to: CGPoint(x: size.width * 0.8, y: size.height / 2.0)) context.strokePath() } } }
mit
0db3f754cb1862337df7682c22db5145
29.451613
117
0.615996
3.900826
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/FoundationErrors.swift
2
8982
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // public struct NSCocoaError : RawRepresentable, ErrorType, __BridgedNSError { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static var __NSErrorDomain: String { return NSCocoaErrorDomain } } /// Enumeration that describes the error codes within the Cocoa error /// domain. public extension NSCocoaError { public static var FileNoSuchFileError: NSCocoaError { return NSCocoaError(rawValue: 4) } public static var FileLockingError: NSCocoaError { return NSCocoaError(rawValue: 255) } public static var FileReadUnknownError: NSCocoaError { return NSCocoaError(rawValue: 256) } public static var FileReadNoPermissionError: NSCocoaError { return NSCocoaError(rawValue: 257) } public static var FileReadInvalidFileNameError: NSCocoaError { return NSCocoaError(rawValue: 258) } public static var FileReadCorruptFileError: NSCocoaError { return NSCocoaError(rawValue: 259) } public static var FileReadNoSuchFileError: NSCocoaError { return NSCocoaError(rawValue: 260) } public static var FileReadInapplicableStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 261) } public static var FileReadUnsupportedSchemeError: NSCocoaError { return NSCocoaError(rawValue: 262) } public static var FileReadTooLargeError: NSCocoaError { return NSCocoaError(rawValue: 263) } public static var FileReadUnknownStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 264) } public static var FileWriteUnknownError: NSCocoaError { return NSCocoaError(rawValue: 512) } public static var FileWriteNoPermissionError: NSCocoaError { return NSCocoaError(rawValue: 513) } public static var FileWriteInvalidFileNameError: NSCocoaError { return NSCocoaError(rawValue: 514) } public static var FileWriteFileExistsError: NSCocoaError { return NSCocoaError(rawValue: 516) } public static var FileWriteInapplicableStringEncodingError: NSCocoaError { return NSCocoaError(rawValue: 517) } public static var FileWriteUnsupportedSchemeError: NSCocoaError { return NSCocoaError(rawValue: 518) } public static var FileWriteOutOfSpaceError: NSCocoaError { return NSCocoaError(rawValue: 640) } public static var FileWriteVolumeReadOnlyError: NSCocoaError { return NSCocoaError(rawValue: 642) } public static var FileManagerUnmountUnknownError: NSCocoaError { return NSCocoaError(rawValue: 768) } public static var FileManagerUnmountBusyError: NSCocoaError { return NSCocoaError(rawValue: 769) } public static var KeyValueValidationError: NSCocoaError { return NSCocoaError(rawValue: 1024) } public static var FormattingError: NSCocoaError { return NSCocoaError(rawValue: 2048) } public static var UserCancelledError: NSCocoaError { return NSCocoaError(rawValue: 3072) } public static var FeatureUnsupportedError: NSCocoaError { return NSCocoaError(rawValue: 3328) } public static var ExecutableNotLoadableError: NSCocoaError { return NSCocoaError(rawValue: 3584) } public static var ExecutableArchitectureMismatchError: NSCocoaError { return NSCocoaError(rawValue: 3585) } public static var ExecutableRuntimeMismatchError: NSCocoaError { return NSCocoaError(rawValue: 3586) } public static var ExecutableLoadError: NSCocoaError { return NSCocoaError(rawValue: 3587) } public static var ExecutableLinkError: NSCocoaError { return NSCocoaError(rawValue: 3588) } public static var PropertyListReadCorruptError: NSCocoaError { return NSCocoaError(rawValue: 3840) } public static var PropertyListReadUnknownVersionError: NSCocoaError { return NSCocoaError(rawValue: 3841) } public static var PropertyListReadStreamError: NSCocoaError { return NSCocoaError(rawValue: 3842) } public static var PropertyListWriteStreamError: NSCocoaError { return NSCocoaError(rawValue: 3851) } public static var PropertyListWriteInvalidError: NSCocoaError { return NSCocoaError(rawValue: 3852) } public static var XPCConnectionInterrupted: NSCocoaError { return NSCocoaError(rawValue: 4097) } public static var XPCConnectionInvalid: NSCocoaError { return NSCocoaError(rawValue: 4099) } public static var XPCConnectionReplyInvalid: NSCocoaError { return NSCocoaError(rawValue: 4101) } public static var UbiquitousFileUnavailableError: NSCocoaError { return NSCocoaError(rawValue: 4353) } public static var UbiquitousFileNotUploadedDueToQuotaError: NSCocoaError { return NSCocoaError(rawValue: 4354) } public static var UbiquitousFileUbiquityServerNotAvailable: NSCocoaError { return NSCocoaError(rawValue: 4355) } public static var UserActivityHandoffFailedError: NSCocoaError { return NSCocoaError(rawValue: 4608) } public static var UserActivityConnectionUnavailableError: NSCocoaError { return NSCocoaError(rawValue: 4609) } public static var UserActivityRemoteApplicationTimedOutError: NSCocoaError { return NSCocoaError(rawValue: 4610) } public static var UserActivityHandoffUserInfoTooLargeError: NSCocoaError { return NSCocoaError(rawValue: 4611) } public static var CoderReadCorruptError: NSCocoaError { return NSCocoaError(rawValue: 4864) } public static var CoderValueNotFoundError: NSCocoaError { return NSCocoaError(rawValue: 4865) } public var isCoderError: Bool { return rawValue >= 4864 && rawValue <= 4991; } public var isExecutableError: Bool { return rawValue >= 3584 && rawValue <= 3839; } public var isFileError: Bool { return rawValue >= 0 && rawValue <= 1023; } public var isFormattingError: Bool { return rawValue >= 2048 && rawValue <= 2559; } public var isPropertyListError: Bool { return rawValue >= 3840 && rawValue <= 4095; } public var isUbiquitousFileError: Bool { return rawValue >= 4352 && rawValue <= 4607; } public var isUserActivityError: Bool { return rawValue >= 4608 && rawValue <= 4863; } public var isValidationError: Bool { return rawValue >= 1024 && rawValue <= 2047; } public var isXPCConnectionError: Bool { return rawValue >= 4096 && rawValue <= 4224; } } #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif internal func _NSErrorWithErrno(posixErrno : Int32, reading : Bool, path : String? = nil, url : NSURL? = nil, extraUserInfo : [String : AnyObject]? = nil) -> NSError { var cocoaError : NSCocoaError if reading { switch posixErrno { case EFBIG: cocoaError = NSCocoaError.FileReadTooLargeError case ENOENT: cocoaError = NSCocoaError.FileReadNoSuchFileError case EPERM, EACCES: cocoaError = NSCocoaError.FileReadNoPermissionError case ENAMETOOLONG: cocoaError = NSCocoaError.FileReadUnknownError default: cocoaError = NSCocoaError.FileReadUnknownError } } else { switch posixErrno { case ENOENT: cocoaError = NSCocoaError.FileNoSuchFileError case EPERM, EACCES: cocoaError = NSCocoaError.FileWriteNoPermissionError case ENAMETOOLONG: cocoaError = NSCocoaError.FileWriteInvalidFileNameError case EDQUOT, ENOSPC: cocoaError = NSCocoaError.FileWriteOutOfSpaceError case EROFS: cocoaError = NSCocoaError.FileWriteVolumeReadOnlyError case EEXIST: cocoaError = NSCocoaError.FileWriteFileExistsError default: cocoaError = NSCocoaError.FileWriteUnknownError } } var userInfo = extraUserInfo ?? [String : AnyObject]() if let path = path { userInfo[NSFilePathErrorKey] = path._nsObject } else if let url = url { userInfo[NSURLErrorKey] = url } return NSError(domain: NSCocoaErrorDomain, code: cocoaError.rawValue, userInfo: userInfo) }
apache-2.0
cd464b4709bd32a0d530284b8e4f2f4f
30.851064
167
0.683812
5.547869
false
false
false
false
myafer/AFUIKit
AFUIKit/UITableView+AFExtension.swift
1
3323
// // UITableView+AFExtension.swift // AFUIKitExample // // Created by 口贷网 on 16/8/8. // Copyright © 2016年 Afer. All rights reserved. // import UIKit extension UITableView { public func dataSource(_ value: UITableViewDataSource?) -> Self { dataSource = value return self } // public func delegate(_ value: UITableViewDelegate?) -> Self { // delegate = value // return self // } public func rowHeight(_ value: CGFloat) -> Self { rowHeight = value return self } public func sectionHeaderHeight(_ value: CGFloat) -> Self { sectionHeaderHeight = value return self } public func sectionFooterHeight(_ value: CGFloat) -> Self { sectionFooterHeight = value return self } @available(iOS 7.0, *) public func estimatedRowHeight(_ value: CGFloat) -> Self { estimatedRowHeight = value return self } @available(iOS 7.0, *) public func estimatedSectionHeaderHeight(_ value: CGFloat) -> Self { estimatedSectionHeaderHeight = value return self } @available(iOS 7.0, *) public func estimatedSectionFooterHeight(_ value: CGFloat) -> Self { estimatedSectionFooterHeight = value return self } @available(iOS 7.0, *) public func separatorInset(_ value: UIEdgeInsets) -> Self { separatorInset = value return self } @available(iOS 3.2, *) public func backgroundView(_ value: UIView?) -> Self { backgroundView = value return self } public func sectionIndexMinimumDisplayRowCount(_ value: Int) -> Self { sectionIndexMinimumDisplayRowCount = value return self } @available(iOS 6.0, *) public func sectionIndexColor(_ value: UIColor?) -> Self { sectionIndexColor = value return self } @available(iOS 7.0, *) public func sectionIndexBackgroundColor(_ value: UIColor?) -> Self { sectionIndexBackgroundColor = value return self } @available(iOS 6.0, *) public func sectionIndexTrackingBackgroundColor(_ value: UIColor?) -> Self { sectionIndexTrackingBackgroundColor = value return self } public func separatorStyle(_ value: UITableViewCellSeparatorStyle) -> Self { separatorStyle = value return self } public func separatorColor(_ value: UIColor?) -> Self { separatorColor = value return self } @available(iOS 8.0, *) public func separatorEffect(_ value: UIVisualEffect?) -> Self { separatorEffect = value return self } @available(iOS 9.0, *) public func cellLayoutMarginsFollowReadableWidth(_ value: Bool) -> Self { cellLayoutMarginsFollowReadableWidth = value return self } public func tableHeaderView(_ value: UIView?) -> Self { tableHeaderView = value return self } public func tableFooterView(_ value: UIView?) -> Self { tableFooterView = value return self } @available(iOS 9.0, *) public func remembersLastFocusedIndexPath(_ value: Bool) -> Self { remembersLastFocusedIndexPath = value return self } }
mit
1a5c6b4e70ae04bbe224aad5203f7770
24.689922
80
0.610441
5.137984
false
false
false
false
alexjohnj/spotijack
LibSpotijackTests/Mocks/MockAudioHijackApplication.swift
1
1967
// // MockAudioHijackApplication.swift // LibSpotijackTests // // Created by Alex Jackson on 10/08/2017. // Copyright © 2017 Alex Jackson. All rights reserved. // import Foundation import ScriptingBridge import LibSpotijack internal class MockAudioHijackApplication: NSObject { var _activated: Bool = false var _sessions: [MockSpotijackAudioHijackApplicationSession] { didSet { _sessions.forEach { $0.parentApplication = self } } } var _recordings: [MockAudioHijackAudioRecording] = [] init(sessions: [MockSpotijackAudioHijackApplicationSession]) { _sessions = sessions super.init() _sessions.forEach { $0.parentApplication = self } } } // MARK: - SBApplicationProtocol Conformance extension MockAudioHijackApplication: SBApplicationProtocol { func activate() { _activated = true } var delegate: SBApplicationDelegate! { get { fatalError("Not implemented") } set { // swiftlint:disable:this unused_setter_value fatalError("Not implemented") } } var isRunning: Bool { return true } func get() -> Any! { fatalError("Not implemented") } } // MARK: - AudioHijackApplication Conformance extension MockAudioHijackApplication: AudioHijackApplication { func sessions() -> [AudioHijackApplicationSession] { return _sessions } } // MARK: - Factory Method extension MockAudioHijackApplication { /// Returns a MockAudioHijackApplication with two sessions named "Spotijack" and "Not-Spotijack" respectively. static func makeStandardApplication() -> MockAudioHijackApplication { let audioHijackPro = MockAudioHijackApplication( sessions: [MockSpotijackAudioHijackApplicationSession(name: "Spotijack"), MockSpotijackAudioHijackApplicationSession(name: "Not-Spotijack")]) return audioHijackPro } }
mit
c815780d687228989a060eb694d56976
25.931507
114
0.676501
4.561485
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Hard/Hard_033_Search_In_Rotated_Sorted_Array.swift
1
1336
/* https://leetcode.com/problems/search-in-rotated-sorted-array/ #33 Search in Rotated Sorted Array Level: hard Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Inspired by @sean hyuntaek at https://leetcode.com/discuss/5707/algorithm-using-binary-search-accepted-some-suggestions-else */ import Foundation class Hard_033_Search_In_Rotated_Sorted_Array { class func search(nums: [Int], target: Int) -> Int { var start: Int = 0 var end: Int = nums.count - 1 while start <= end { let mid: Int = (start + end) / 2 if nums[mid] == target { return mid } if nums[start] <= nums[mid] { if nums[start] <= target && target <= nums[mid] { end = mid - 1 } else { start = mid + 1 } } else { if nums[mid] <= target && target <= nums[end] { start = mid + 1 } else { end = mid - 1 } } } return -1 } }
mit
1c978ac783ce24211466151050ca18ca
26.833333
124
0.521707
3.929412
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/iAds/SearchAdsAttribution.swift
1
4744
/// Implementation of Search Ads attribution details /// More info: https://searchads.apple.com/help/measure-results/#attribution-api import Foundation import iAd import AutomatticTracks @objc final class SearchAdsAttribution: NSObject { private static let lock = NSLock() @objc static var instance: SearchAdsAttribution { lock.lock() let output = _instance ?? SearchAdsAttribution() _instance = output lock.unlock() return output } /// Keep the instance alive /// private static var _instance: SearchAdsAttribution? private static let userDefaultsSentKey = "search_ads_attribution_details_sent" private static let userDefaultsLimitedAdTrackingKey = "search_ads_limited_tracking" private let searchAdsApiVersion = "Version3.1" private let searchAdsAttributionKey = "iad_attribution" /// Is ad tracking limited? /// If the user has limited ad tracking, and this API won't return data /// private var isTrackingLimited: Bool { get { return UserPersistentStoreFactory.instance().bool(forKey: SearchAdsAttribution.userDefaultsLimitedAdTrackingKey) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: SearchAdsAttribution.userDefaultsLimitedAdTrackingKey) } } /// Has the attribution details been sent already? /// Once the attribution details are sent, it won't change; so it is not necesary to send it again /// private var isAttributionDetailsSent: Bool { get { return UserPersistentStoreFactory.instance().bool(forKey: SearchAdsAttribution.userDefaultsSentKey) } set { UserPersistentStoreFactory.instance().set(newValue, forKey: SearchAdsAttribution.userDefaultsSentKey) } } private override init() { super.init() } @objc func requestDetails() { guard UIDevice.current.isSimulator() == false, // Requests from simulator will always fail isTrackingLimited == false, isAttributionDetailsSent == false else { finish() return } requestAttributionDetails() } private func requestAttributionDetails() { ADClient.shared().requestAttributionDetails { [weak self] (attributionDetails, error) in DispatchQueue.main.async { if let error = error as NSError? { self?.didReceiveError(error) } else { self?.didReceiveAttributionDetails(attributionDetails) } } } } private func didReceiveAttributionDetails(_ details: [String: NSObject]?) { defer { finish() } guard let details = details?[searchAdsApiVersion] as? [String: Any] else { return } sendAttributionDetailsToTracksIfNeeded(sanitize(details)) isAttributionDetailsSent = true } /// Send SearchAds data to Tracks if needed /// private func sendAttributionDetailsToTracksIfNeeded(_ parameters: [String: Any]) { guard let didTapSearchAd = parameters[searchAdsAttributionKey] as? String else { return } // Only send SearchAds attribution details to Tracks if the "iad_attribution" parameter is true (which means // the user actually tapped on a SearchAd within the last 30 days). if didTapSearchAd.lowercased() == "true" { WPAnalytics.track(.searchAdsAttribution, withProperties: parameters) } } /// Fix key format to send to Tracks /// private func sanitize(_ parameters: [String: Any]) -> [String: Any] { var sanitized = [String: String]() parameters.forEach { let key = $0.key.replacingOccurrences(of: "-", with: "_") let value: String = $0.value as? String ?? String(describing: $0.value) sanitized[key] = value } return sanitized } private func didReceiveError(_ error: Error) { let nsError = error as NSError guard nsError.code == ADClientError.Code.trackingRestrictedOrDenied.rawValue else { tryAgain(after: 5) // Possible connectivity issues return } // Not possible to get data isTrackingLimited = true finish() } private func tryAgain(after delay: TimeInterval) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.requestDetails() } } /// Free this instance after all work is done. /// private func finish() { SearchAdsAttribution._instance = nil } }
gpl-2.0
97798f7ab99e973400fdcda90896019c
31.272109
126
0.63027
4.962343
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/CreatePassword/Views/ErroredBackingView.swift
1
5227
import KsApi import Library import Prelude import ReactiveSwift import UIKit private enum Layout { enum Button { static let height: CGFloat = 48 static let width: CGFloat = 98 } enum ImageView { static let minWidth: CGFloat = 16.0 } } protocol ErroredBackingViewDelegate: AnyObject { func erroredBackingViewDidTapManage(_ view: ErroredBackingView, backing: ProjectAndBackingEnvelope) } final class ErroredBackingView: UIView { // MARK: - Properties public weak var delegate: ErroredBackingViewDelegate? private let backingInfoStackView: UIStackView = { UIStackView(frame: .zero) }() private let finalCollectionDateLabel: UILabel = { UILabel(frame: .zero) }() private let finalCollectionDateStackView: UIStackView = { UIStackView(frame: .zero) }() private lazy var fixIconImageView: UIImageView = { UIImageView(image: image(named: "fix-icon", inBundle: Bundle.framework)) |> \.translatesAutoresizingMaskIntoConstraints .~ false }() private let manageButton: UIButton = { UIButton(type: .custom) }() private let projectNameLabel: UILabel = { UILabel(frame: .zero) }() private let rootStackView: UIStackView = { UIStackView(frame: .zero) }() private let viewModel: ErroredBackingViewViewModelType = ErroredBackingViewViewModel() // MARK: - Life cycle override init(frame: CGRect) { super.init(frame: frame) self.manageButton.addTarget(self, action: #selector(self.manageButtonTapped), for: .touchUpInside) self.configureViews() self.configureConstraints() self.bindViewModel() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Configuration func configureWith(value: ProjectAndBackingEnvelope) { self.viewModel.inputs.configure(with: value) } private func configureViews() { _ = ([self.fixIconImageView, self.finalCollectionDateLabel], self.finalCollectionDateStackView) |> ksr_addArrangedSubviewsToStackView() _ = ([self.projectNameLabel, self.finalCollectionDateStackView], self.backingInfoStackView) |> ksr_addArrangedSubviewsToStackView() _ = ([self.backingInfoStackView, self.manageButton], self.rootStackView) |> ksr_addArrangedSubviewsToStackView() _ = (self.rootStackView, self) |> ksr_addSubviewToParent() |> ksr_constrainViewToMarginsInParent() } private func configureConstraints() { NSLayoutConstraint.activate([ self.fixIconImageView.widthAnchor.constraint(equalToConstant: Layout.ImageView.minWidth), self.manageButton.widthAnchor.constraint(equalToConstant: Layout.Button.width), self.manageButton.heightAnchor.constraint(equalToConstant: Layout.Button.height) ]) } // MARK: - View model override func bindViewModel() { super.bindViewModel() self.projectNameLabel.rac.text = self.viewModel.outputs.projectName self.finalCollectionDateLabel.rac.text = self.viewModel.outputs.finalCollectionDateText self.viewModel.outputs.notifyDelegateManageButtonTapped .observeForUI() .observeValues { [weak self] backing in guard let self = self else { return } self.delegate?.erroredBackingViewDidTapManage(self, backing: backing) } } // MARK: - Actions @objc func manageButtonTapped() { self.viewModel.inputs.manageButtonTapped() } // MARK: - Styles override func bindStyles() { super.bindStyles() _ = self |> \.backgroundColor .~ .ksr_support_300 _ = self.fixIconImageView |> \.clipsToBounds .~ true |> \.contentMode .~ .scaleAspectFit |> \.tintColor .~ .ksr_alert _ = self.finalCollectionDateStackView |> finalCollectionStackViewStyle _ = self.finalCollectionDateLabel |> \.textColor .~ .ksr_alert |> \.font .~ .ksr_headline(size: 13) _ = self.backingInfoStackView |> backingInfoStackViewStyle _ = self.manageButton |> manageButtonStyle _ = self.manageButton.titleLabel ?|> manageButtonTitleLabelStyle _ = self.projectNameLabel |> projectNameLabelStyle _ = self.rootStackView |> rootStackViewStyle } } // MARK: - Styles private let backingInfoStackViewStyle: StackViewStyle = { stackView in stackView |> verticalStackViewStyle |> \.spacing .~ Styles.grid(2) } private let finalCollectionStackViewStyle: StackViewStyle = { stackView in stackView |> \.axis .~ NSLayoutConstraint.Axis.horizontal |> \.spacing .~ Styles.grid(1) } private let manageButtonStyle: ButtonStyle = { button in button |> redButtonStyle |> UIButton.lens.title(for: .normal) %~ { _ in Strings.Manage() } } private let manageButtonTitleLabelStyle: LabelStyle = { (label: UILabel) in label |> \.lineBreakMode .~ .byTruncatingTail } private let projectNameLabelStyle: LabelStyle = { label in label |> \.font .~ UIFont.ksr_footnote().bolded |> \.numberOfLines .~ 0 } private let rootStackViewStyle: StackViewStyle = { stackView in stackView |> \.alignment .~ .center |> \.axis .~ NSLayoutConstraint.Axis.horizontal |> \.isLayoutMarginsRelativeArrangement .~ true |> \.layoutMargins .~ .init(topBottom: Styles.grid(1)) |> \.spacing .~ Styles.grid(1) }
apache-2.0
ba6e40945298cd9c50783b85b2127128
27.71978
102
0.706524
4.589113
false
false
false
false
djbe/AppwiseCore
Sources/Core/Other/Version.swift
1
6531
// // Version.swift // AppwiseCore // // Created by David Jennes on 27/11/2018. // import Foundation // Based on the Version type from SPM, which can be found here: // https://github.com/apple/swift-package-manager/blob/master/Sources/TSCUtility/Version.swift // Last check on 19 November 2019 // swiftlint:disable all /// A struct representing a semver version. public struct Version: Hashable { /// The major version. public let major: Int /// The minor version. public let minor: Int /// The patch version. public let patch: Int /// The pre-release identifier. public let prereleaseIdentifiers: [String] /// The build metadata. public let buildMetadataIdentifiers: [String] /// Create a version object. public init( _ major: Int, _ minor: Int, _ patch: Int, prereleaseIdentifiers: [String] = [], buildMetadataIdentifiers: [String] = [] ) { precondition(major >= 0 && minor >= 0 && patch >= 0, "Negative versioning is invalid.") self.major = major self.minor = minor self.patch = patch self.prereleaseIdentifiers = prereleaseIdentifiers self.buildMetadataIdentifiers = buildMetadataIdentifiers } } extension Version: Comparable { func isEqualWithoutPrerelease(_ other: Version) -> Bool { return major == other.major && minor == other.minor && patch == other.patch } public static func < (lhs: Version, rhs: Version) -> Bool { let lhsComparators = [lhs.major, lhs.minor, lhs.patch] let rhsComparators = [rhs.major, rhs.minor, rhs.patch] if lhsComparators != rhsComparators { return lhsComparators.lexicographicallyPrecedes(rhsComparators) } guard lhs.prereleaseIdentifiers.count > 0 else { return false // Non-prerelease lhs >= potentially prerelease rhs } guard rhs.prereleaseIdentifiers.count > 0 else { return true // Prerelease lhs < non-prerelease rhs } let zippedIdentifiers = zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers) for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zippedIdentifiers { if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier { continue } let typedLhsIdentifier: Any = Int(lhsPrereleaseIdentifier) ?? lhsPrereleaseIdentifier let typedRhsIdentifier: Any = Int(rhsPrereleaseIdentifier) ?? rhsPrereleaseIdentifier switch (typedLhsIdentifier, typedRhsIdentifier) { case let (int1 as Int, int2 as Int): return int1 < int2 case let (string1 as String, string2 as String): return string1 < string2 case (is Int, is String): return true // Int prereleases < String prereleases case (is String, is Int): return false default: return false } } return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count } } extension Version: CustomStringConvertible { public var description: String { var base = "\(major).\(minor).\(patch)" if !prereleaseIdentifiers.isEmpty { base += "-" + prereleaseIdentifiers.joined(separator: ".") } if !buildMetadataIdentifiers.isEmpty { base += "+" + buildMetadataIdentifiers.joined(separator: ".") } return base } } public extension Version { /// Create a version object from string. /// /// - Parameters: /// - string: The string to parse. init?(string: String) { let prereleaseStartIndex = string.firstIndex(of: "-") let metadataStartIndex = string.firstIndex(of: "+") let requiredEndIndex = prereleaseStartIndex ?? metadataStartIndex ?? string.endIndex let requiredCharacters = string.prefix(upTo: requiredEndIndex) let requiredComponents = requiredCharacters .split(separator: ".", maxSplits: 2, omittingEmptySubsequences: false) .map(String.init).compactMap({ Int($0) }).filter({ $0 >= 0 }) guard requiredComponents.count == 3 else { return nil } self.major = requiredComponents[0] self.minor = requiredComponents[1] self.patch = requiredComponents[2] func identifiers(start: String.Index?, end: String.Index) -> [String] { guard let start = start else { return [] } let identifiers = string[string.index(after: start)..<end] return identifiers.split(separator: ".").map(String.init) } self.prereleaseIdentifiers = identifiers( start: prereleaseStartIndex, end: metadataStartIndex ?? string.endIndex) self.buildMetadataIdentifiers = identifiers( start: metadataStartIndex, end: string.endIndex) } } extension Version: ExpressibleByStringLiteral { public init(stringLiteral value: String) { guard let version = Version(string: value) else { fatalError("\(value) is not a valid version") } self = version } public init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } public init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } } // MARK:- Range operations extension ClosedRange where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } // Disabled because compiler hits an assertion https://bugs.swift.org/browse/SR-5014 #if false extension CountableRange where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } #endif extension Range where Bound == Version { /// Marked as unavailable because we have custom rules for contains. public func contains(_ element: Version) -> Bool { // Unfortunately, we can't use unavailable here. fatalError("contains(_:) is unavailable, use contains(version:)") } } extension Range where Bound == Version { public func contains(version: Version) -> Bool { // Special cases if version contains prerelease identifiers. if !version.prereleaseIdentifiers.isEmpty { // If the ranage does not contain prerelease identifiers, return false. if lowerBound.prereleaseIdentifiers.isEmpty && upperBound.prereleaseIdentifiers.isEmpty { return false } // At this point, one of the bounds contains prerelease identifiers. // // Reject 2.0.0-alpha when upper bound is 2.0.0. if upperBound.prereleaseIdentifiers.isEmpty && upperBound.isEqualWithoutPrerelease(version) { return false } } if lowerBound == version { return true } // Otherwise, apply normal contains rules. return version >= lowerBound && version < upperBound } }
mit
ae882b97b4be33b19b8ecaf8aaede37d
29.096774
96
0.72286
3.943841
false
false
false
false
stulevine/firefox-ios
Client/Frontend/Home/RemoteTabsPanel.swift
1
6083
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Account import Shared import Snap import Storage import Sync import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() private struct RemoteTabsPanelUX { static let HeaderHeight: CGFloat = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight: CGFloat = SiteTableViewControllerUX.RowHeight } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" /** * Display a tree hierarchy of remote clients and tabs, like: * client * tab * tab * client * tab * tab * This is not a SiteTableViewController because it is inherently tree-like and not list-like; * a technical detail is that STVC is backed by a Cursor and this is backed by a richer data * structure. However, the styling here should agree with STVC where possible. */ class RemoteTabsPanel: UITableViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? = nil var profile: Profile! private var clientAndTabs: [ClientAndTabs]? private func tabAtIndexPath(indexPath: NSIndexPath) -> RemoteTab? { return self.clientAndTabs?[indexPath.section].tabs[indexPath.item] } override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = UIEdgeInsetsZero refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "SELrefresh", forControlEvents: UIControlEvents.ValueChanged) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.SELrefresh() } @objc private func SELrefresh() { self.refreshControl?.beginRefreshing() self.profile.getClientsAndTabs().upon({ tabs in if let tabs = tabs.successValue { log.info("\(tabs.count) tabs fetched.") self.clientAndTabs = tabs // Maybe show a background view. let tableView = self.tableView if tabs.isEmpty { // TODO: Bug 1144760 - Populate background view with UX-approved content. tableView.backgroundView = UIView() tableView.backgroundView?.frame = tableView.frame tableView.backgroundView?.backgroundColor = UIColor.redColor() // Hide dividing lines. tableView.separatorStyle = UITableViewCellSeparatorStyle.None } else { tableView.backgroundView = nil // Show dividing lines. tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine } tableView.reloadData() } else { log.error("Failed to fetch tabs.") } // Always end refreshing, even if we failed! self.refreshControl?.endRefreshing() }) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { log.debug("We have \(self.clientAndTabs?.count) sections.") return self.clientAndTabs?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { log.debug("Section \(section) has \(self.clientAndTabs?[section].tabs.count) tabs.") return self.clientAndTabs?[section].tabs.count ?? 0 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let clientTabs = self.clientAndTabs?[section] { let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel.text = client.name // TODO: Bug 1154088 - Convert timestamp to locale-relative timestring. // TODO: note that this is very likely to be wrong; it'll show the last time the other device // uploaded a record, *or another device sent that device a command*. let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time") view.detailTextLabel.text = String(format: label, String(client.modified)) if client.type == "desktop" { view.imageView.image = UIImage(named: "deviceTypeDesktop") } else { view.imageView.image = UIImage(named: "deviceTypeMobile") } return view } return nil } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(RemoteTabIdentifier, forIndexPath: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab?.title, detailText: tab?.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) if let tab = tabAtIndexPath(indexPath) { homePanelDelegate?.homePanel(self, didSelectURL: tab.URL) } } }
mpl-2.0
7383b5c8b8874c85a5102ae79597fdbd
40.101351
133
0.671708
5.280382
false
false
false
false
zh-wang/TwitterGifComposer
Example/TwitterGifComposer/ViewController.swift
1
1463
// // ViewController.swift // TwitterGifComposer // // Created by zh-wang on 08/18/2015. // Copyright (c) 2015 zh-wang. All rights reserved. // import UIKit import TwitterGifComposer import FLAnimatedImage class ViewController: UIViewController, TwitterGifComposerDelegate { var twitterGifComposer: TwitterGifComposer? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func onPostFailed() { } func onPostSuccessed() { } func onStopPost() { } @IBAction func touchUpInside(sender: AnyObject) { let path = NSBundle.mainBundle().pathForResource("abc", ofType: "gif") let data = NSData(contentsOfFile: path!) self.twitterGifComposer = TwitterGifComposer.defaultComposer(delegate: self, rootViewController: self).withText("Post Gif").withGifData(data!) let animatedImageView = FLAnimatedImageView(frame: CGRectZero) animatedImageView.animatedImage = FLAnimatedImage(GIFData: data!) animatedImageView.startAnimating() self.twitterGifComposer!.attachFLAnimatedImageView(animatedImageView) self.twitterGifComposer!.chooseTwitterAccount() } }
mit
1d16198e4b2b73eda78507a8ad58d64d
26.603774
150
0.676692
5.044828
false
false
false
false
superk589/CGSSGuide
DereGuide/View/UpdatingStatusView.swift
2
3997
// // UpdatingStatusView.swift // DereGuide // // Created by zzk on 16/7/22. // Copyright © 2016 zzk. All rights reserved. // import UIKit import SnapKit protocol UpdatingStatusViewDelegate: class { func cancelUpdate(updateStatusView: UpdatingStatusView) } class UpdatingStatusView: UIView { weak var delegate: UpdatingStatusViewDelegate? let statusLabel = UILabel() private let loadingView = LoadingImageView() let cancelButton = UIButton() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) layer.cornerRadius = 10 loadingView.hideWhenStopped = true addSubview(loadingView) loadingView.snp.makeConstraints { (make) in make.left.equalTo(5) make.centerY.equalToSuperview() make.width.height.equalTo(40) } cancelButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) cancelButton.setImage(#imageLiteral(resourceName: "433-x").withRenderingMode(.alwaysTemplate), for: UIControl.State()) cancelButton.tintColor = .white cancelButton.layer.cornerRadius = 10 cancelButton.layer.masksToBounds = true cancelButton.addTarget(self, action: #selector(cancelUpdate), for: .touchUpInside) addSubview(cancelButton) cancelButton.snp.makeConstraints { (make) in make.centerY.equalToSuperview() make.width.height.equalTo(40) make.right.equalTo(-5) } statusLabel.textColor = .white addSubview(statusLabel) statusLabel.snp.makeConstraints { (make) in make.center.equalToSuperview() make.left.equalTo(loadingView.snp.right) make.right.equalTo(cancelButton.snp.left) } statusLabel.textAlignment = .center statusLabel.font = UIFont.boldSystemFont(ofSize: 17) statusLabel.adjustsFontSizeToFitWidth = true statusLabel.baselineAdjustment = .alignCenters } private var isShowing = false func show() { isShowing = true stopFading() if let window = UIApplication.shared.keyWindow { window.addSubview(self) snp.remakeConstraints { (make) in make.width.equalTo(240) make.height.equalTo(50) make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-95) } } } func hide(animated: Bool) { isShowing = false stopAnimating() cancelButton.isHidden = true if animated { layer.removeAllAnimations() UIView.animate(withDuration: 2.5, animations: { [weak self] in self?.alpha = 0 }) { [weak self] (finished) in self?.alpha = 1 if let strongSelf = self, !strongSelf.isShowing { self?.removeFromSuperview() } } } else { removeFromSuperview() } } private var isAnimating = false private func startAnimating() { isAnimating = true loadingView.startAnimating() } private func stopAnimating() { isAnimating = false loadingView.stopAnimating() } private func stopFading() { layer.removeAllAnimations() } func setup(_ text: String, animated: Bool, cancelable: Bool) { if animated && !isAnimating { startAnimating() } statusLabel.text = text cancelButton.isHidden = !cancelable } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func cancelUpdate() { stopAnimating() hide(animated: false) delegate?.cancelUpdate(updateStatusView: self) } }
mit
4696d96370b220f0c035e073117a7a61
29.503817
126
0.600601
5.142857
false
false
false
false
hyp/SwiftSourceKit
SwiftSourceKit/DocumentInfo.swift
1
851
// // DocumentInfo.swift // SwiftSourceKit // import sourcekitd extension Request { public static func createDocumentInfoRequestForModule(_ module: String, compilerArgs: [String] = []) -> Request { return Request(dictionary: [ KeyRequest: .uid(RequestDocInfo), KeyModuleName: .str(module), ], compilerArgs: compilerArgs) } } extension Response { public var documentEntities: Entities? { let value = self.value.variant guard sourcekitd_variant_get_type(value) == SOURCEKITD_VARIANT_TYPE_DICTIONARY && sourcekitd_variant_get_type(sourcekitd_variant_dictionary_get_value(value, KeyEntities)) == SOURCEKITD_VARIANT_TYPE_ARRAY else { return nil } return Entities(value: sourcekitd_variant_dictionary_get_value(value, KeyEntities)) } }
mit
aeaa5d346694c1cbea6e63b1c235209d
31.730769
140
0.668625
4.29798
false
false
false
false
JacksunYX/DYLiving
DYLiving/DYLiving/Classes/Main/View/PageTitleView.swift
1
6436
// // PageTitleView.swift // DYLiving // // Created by 黑色o.o表白 on 2017/3/23. // Copyright © 2017年 黑色o.o表白. All rights reserved. // import UIKit //表示协议只能被类遵守 protocol PageTitleViewDelegate: class { func pageTitleView(titleView : PageTitleView,selectedIndex index : Int) } //定义常量 let sScrollLineH : CGFloat = 4 let sNormalColor : (CGFloat , CGFloat , CGFloat) = (85,85,85) let sSelectColor : (CGFloat , CGFloat , CGFloat) = (255,128,0) class PageTitleView: UIView { //定义属性 var titles:[String] //保存所有已设置过的的label lazy var titleLabelsArr : [UILabel] = [UILabel]() var currentIndex : NSInteger = 0 weak var delegate: PageTitleViewDelegate? //懒加载滚动视图 lazy var scrollView : UIScrollView = { let scrollview = UIScrollView() scrollview.scrollsToTop = false scrollview.showsHorizontalScrollIndicator = false scrollview.bounces = false return scrollview }() //懒加载滑块 lazy var scrollLine:UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //自定义构造函数 init(frame: CGRect,titles:[String]) { self.titles = titles; super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI界面 extension PageTitleView{ //设置UI func setupUI(){ //1.添加滚动视图 addSubview(scrollView) scrollView.frame = bounds //2.添加title对应的label setupTitleLabels() //3.设置底线和滚动的滑块 setupBottomLineAndScrollLine() } //添加title对应的label func setupTitleLabels(){ let labelW : CGFloat = frame.width/CGFloat(titles.count) let labelH : CGFloat = frame.height - sScrollLineH let labelY : CGFloat = 0 for (index, title) in titles.enumerated() { //1.创建label let label = UILabel() label.tag = index label.text = title label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r:sNormalColor.0 ,g:sNormalColor.1,b:sNormalColor.2) label.textAlignment = .center //2.设置label的frame let labelX :CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //3. 添加到滚动视图上 scrollView.addSubview(label) titleLabelsArr.append(label) //4.给label添加点击效果 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } //添加底线和滑块 func setupBottomLineAndScrollLine(){ //1.添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height, width: frame.width, height: lineH) addSubview(bottomLine) //获取第一个label guard let firstLabel = titleLabelsArr.first else { return } firstLabel.textColor = UIColor(r: sSelectColor.0, g: sSelectColor.1, b: sSelectColor.2) //2.添加滑块 scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height-sScrollLineH, width: firstLabel.frame.width, height:sScrollLineH) } } //监听label点击回调 extension PageTitleView{ @objc func titleLabelClick(tapGes : UITapGestureRecognizer){ //1.先得到当前label guard let currentLabel = tapGes.view as?UILabel else { return } //2.获取之前的label let oldLabel = titleLabelsArr[currentIndex] //3.切换颜色 oldLabel.textColor = UIColor(r:sNormalColor.0 ,g:sNormalColor.1,b:sNormalColor.2) currentLabel.textColor = UIColor(r: sSelectColor.0, g: sSelectColor.1, b: sSelectColor.2) //4.保存最新label的下标 currentIndex = currentLabel.tag //5.滚动条位置发生变化 let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width UIView.animate(withDuration: 0.2) { self.scrollLine.frame.origin.x = scrollLineX } //通知代理执行协议方法 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } //对外暴露方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat ,sourceIndex : Int ,targetIndex : Int){ //1.取出sourceLabel和targetLabel let sourceLabel = titleLabelsArr[sourceIndex] let targetLabel = titleLabelsArr[targetIndex] //2.处理滑块的逻辑 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveX = moveTotalX * progress UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX } //3.颜色渐变 //计算三色的变化范围 let colorDelta = (sSelectColor.0 - sNormalColor.0,sSelectColor.1 - sNormalColor.1,sSelectColor.2 - sNormalColor.2) let changeR : CGFloat = colorDelta.0 * progress let changeG : CGFloat = colorDelta.1 * progress let changeB : CGFloat = colorDelta.2 * progress //由深色变为浅色,使用减法 sourceLabel.textColor = UIColor(r: sSelectColor.0 - changeR, g: sSelectColor.1 - changeG, b: sSelectColor.2 - changeB) //由浅变深,使用加法 targetLabel.textColor = UIColor(r: sNormalColor.0 + changeR, g: sNormalColor.1 + changeG, b: sNormalColor.2 + changeB) //4.记录最新的index currentIndex = targetIndex } }
mit
7a9a49bbcc70234691eb141a073d9a78
26.417431
145
0.596955
4.504145
false
false
false
false
djflsdl08/BasicIOS
FaceIt/FaceIt/FaceView.swift
1
5369
// // FaceView.swift // FaceIt // // Created by 김예진 on 2017. 10. 9.. // Copyright © 2017년 Kim,Yejin. All rights reserved. // import UIKit @IBDesignable class FaceView: UIView { @IBInspectable var scale : CGFloat = 0.90 { didSet { setNeedsDisplay() } } @IBInspectable var mouthCurvature : Double = 1.0 { didSet { setNeedsDisplay() } } // 1.0 : full smile, -1 : full frown @IBInspectable var eyesOpen : Bool = true { didSet { setNeedsDisplay() } } @IBInspectable var eyeBrowTilt : Double = 1.0 { didSet { setNeedsDisplay() } } // 1.0 : fully relaxed, -1 : full furrow @IBInspectable var color : UIColor = UIColor.purple { didSet { setNeedsDisplay() } } @IBInspectable var lineWidth : CGFloat = 5.0 { didSet { setNeedsDisplay() } } func changeScale(recognizer : UIPinchGestureRecognizer) { switch recognizer.state { case .changed,.ended : scale *= recognizer.scale recognizer.scale = 1.0 default : break } } private var skullRadius : CGFloat { return min(bounds.size.width,bounds.size.height)/2 * scale } private var skullCenter : CGPoint { return CGPoint(x : bounds.midX, y : bounds.midY) } private struct Ratios { static let SkullRadiusToEyeOffset : CGFloat = 3 static let SkullRadiusToEyeRadius : CGFloat = 10 static let SkullRadiusToMouthWidth : CGFloat = 1 static let SkullRadiusToMouthHeight : CGFloat = 3 static let SkullRadiusToMouthOffset : CGFloat = 3 static let SkullRadiusToBrowOffset : CGFloat = 5 } private enum Eye { case Left case Right } private func pathForCircleCenterAtPoint(midPoint : CGPoint,withRadius radius: CGFloat) -> UIBezierPath { let path = UIBezierPath ( arcCenter: midPoint, radius: radius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: false ) path.lineWidth = lineWidth return path } private func getEyeCenter(eye : Eye) -> CGPoint { let eyeOffset = skullRadius / Ratios.SkullRadiusToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset // y -= : up, y += : down switch eye { case .Left : eyeCenter.x -= eyeOffset case .Right : eyeCenter.x += eyeOffset } return eyeCenter } private func pathForBrow(eye : Eye) -> UIBezierPath { var tilt = eyeBrowTilt switch eye { case .Left : tilt *= -1.0 case .Right : break } var browCenter = getEyeCenter(eye: eye) browCenter.y -= skullRadius / Ratios.SkullRadiusToBrowOffset let eyeRadius = skullRadius / Ratios.SkullRadiusToEyeRadius let tiltOffset = CGFloat(max(-1,min(tilt,1))) * eyeRadius / 2 let browStart = CGPoint(x : browCenter.x - eyeRadius, y : browCenter.y - tiltOffset) let browEnd = CGPoint(x : browCenter.x + eyeRadius, y : browCenter.y + tiltOffset) let path = UIBezierPath() path.move(to: browStart) path.addLine(to: browEnd) path.lineWidth = lineWidth return path } private func pathForEye(eye : Eye) -> UIBezierPath { let eyeRadius = skullRadius / Ratios.SkullRadiusToEyeRadius let eyeCenter = getEyeCenter(eye : eye) if eyesOpen { return pathForCircleCenterAtPoint(midPoint: eyeCenter, withRadius: eyeRadius) } else { let path = UIBezierPath() path.move(to : CGPoint(x : eyeCenter.x - eyeRadius, y : eyeCenter.y)) path.addLine(to: CGPoint(x : eyeCenter.x + eyeRadius, y : eyeCenter.y)) path.lineWidth = lineWidth return path } } private func pathForMouth() -> UIBezierPath { let mouthOffset = skullRadius / Ratios.SkullRadiusToMouthOffset let mouthWidth = skullRadius / Ratios.SkullRadiusToMouthWidth let mouthHeight = skullRadius / Ratios.SkullRadiusToMouthHeight let mouthRect = CGRect ( x: skullCenter.x - mouthWidth/2, y: skullCenter.y + mouthOffset, width: mouthWidth, height: mouthHeight ) let smileOffset = CGFloat(max(-1,min(mouthCurvature,1))) * mouthRect.height let start = CGPoint(x : mouthRect.minX, y : mouthRect.minY) let end = CGPoint(x : mouthRect.maxX, y : mouthRect.minY) let cp1 = CGPoint(x : mouthRect.minX + mouthRect.width/3, y : mouthRect.minY + smileOffset) let cp2 = CGPoint(x : mouthRect.maxX - mouthRect.width/3, y : mouthRect.minY + smileOffset) let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } override func draw(_ rect: CGRect) { color.set() pathForCircleCenterAtPoint(midPoint: skullCenter, withRadius: skullRadius).stroke() pathForEye(eye: .Left).stroke() pathForEye(eye : .Right).stroke() pathForMouth().stroke() pathForBrow(eye : .Left).stroke() pathForBrow(eye : .Right).stroke() } }
mit
06b6eb7182b7c75ba954d5c5cfc766bc
33.805195
109
0.603731
4.250595
false
false
false
false
FlappyHeart/balloonCat
ballooncat/GameScene.swift
1
10113
// // GameScene.swift // ballooncat // // Created by Alfred on 14-8-28. // Copyright (c) 2014年 HackSpace. All rights reserved. // import SpriteKit class GameScene: SKScene ,SKPhysicsContactDelegate{ var catTexture:SKTexture! var catLeftTexture:SKTexture! var catRightTexture:SKTexture! var cloudTexture:SKTexture! var groundTexture:SKTexture! var grassTexture:SKTexture! var cloudyBgTexture:SKTexture! var sunBgTexture:SKTexture! var mountainTexture:SKTexture! var gameOverTexture:SKTexture! var cat:SKSpriteNode! var cloud:SKSpriteNode! var ground:SKSpriteNode! var grass:SKSpriteNode! var cloudyBg:SKSpriteNode! var mountain:SKSpriteNode! var sunBg1:SKSpriteNode! var sunBg2:SKSpriteNode! var sunBg3:SKSpriteNode! var backGroundScene:SKNode! var levelGroup:SKNode! var score:Int = 0 var scoreLabel:SKLabelNode! var catCategory:UInt32 = 1<<1 var worldCategory:UInt32 = 1<<2 var cloudyCategory:UInt32 = 1<<3 var scoreCategory:UInt32 = 1<<4 var flyLeft:CGFloat = 1.0 var userDefault = NSUserDefaults.standardUserDefaults() var touchSound = SKAction.playSoundFileNamed("touch.mp3", waitForCompletion: false) var bonusSound = SKAction.playSoundFileNamed("bonus.mp3", waitForCompletion: false) override init(size:CGSize){ super.init(size: size) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { self.physicsWorld.contactDelegate = self self.physicsWorld.gravity = CGVectorMake(0, 0) catTexture = SKTexture(imageNamed: "cat") catLeftTexture = SKTexture(imageNamed: "catleft") catRightTexture = SKTexture(imageNamed: "catright") cloudTexture = SKTexture(imageNamed: "cloud") groundTexture = SKTexture(imageNamed: "ground") grassTexture = SKTexture(imageNamed: "grass") cloudyBgTexture = SKTexture(imageNamed: "cloudybg") sunBgTexture = SKTexture(imageNamed: "sunbg") mountainTexture = SKTexture(imageNamed: "mountain") gameOverTexture = SKTexture(imageNamed: "gameover") cat = SKSpriteNode(texture: catTexture) ground = SKSpriteNode(texture: groundTexture) grass = SKSpriteNode(texture: grassTexture) cloudyBg = SKSpriteNode(texture: cloudyBgTexture) mountain = SKSpriteNode(texture: mountainTexture) sunBg1 = SKSpriteNode(texture: sunBgTexture) sunBg2 = SKSpriteNode(texture: sunBgTexture) sunBg3 = SKSpriteNode(texture: sunBgTexture) sunBg1.position = CGPointMake(0, ground.size.height + sunBg1.size.height * 0.5) sunBg1.zPosition = 3 sunBg2.position = CGPointMake(0, sunBg1.position.y + sunBg2.size.height - 2) sunBg2.zPosition = 3 sunBg3.position = CGPointMake(0, sunBg2.position.y + sunBg3.size.height - 2) sunBg3.zPosition = 3 ground.position = CGPointMake(0, ground.size.height * 0.5) ground.zPosition = 4 mountain.position = CGPointMake(0, ground.size.height + mountain.size.height * 0.5) mountain.zPosition = 4 grass.position = CGPointMake(0, ground.size.height + grass.size.height * 0.5) grass.zPosition = 6 var worldEdge = SKNode() worldEdge.physicsBody = SKPhysicsBody(edgeLoopFromRect: CGRectMake(0, -200, 320, 568)) worldEdge.physicsBody?.categoryBitMask = worldCategory worldEdge.physicsBody?.contactTestBitMask = catCategory worldEdge.physicsBody?.collisionBitMask = catCategory backGroundScene = SKNode() backGroundScene.position.x = self.frame.width * 0.5 backGroundScene.addChild(sunBg1) backGroundScene.addChild(sunBg2) backGroundScene.addChild(sunBg3) backGroundScene.addChild(ground) backGroundScene.addChild(mountain) backGroundScene.addChild(grass) // backGroundScene.addChild(physicsGround) self.addChild(worldEdge) self.addChild(backGroundScene) cat.position = CGPointMake(ground.size.width * 0.5, ground.size.height + cat.size.height * 0.5) cat.zPosition = 5 cat.physicsBody = SKPhysicsBody(circleOfRadius: cat.size.width * 0.5, center: CGPointMake(0, 15)) cat.physicsBody?.categoryBitMask = catCategory cat.physicsBody?.contactTestBitMask = cloudyCategory cat.physicsBody?.collisionBitMask = cloudyCategory cat.physicsBody?.dynamic = true // cat.physicsBody.affectedByGravity = false self.addChild(cat) levelGroup = SKNode() self.addChild(levelGroup) levelGroup.runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.waitForDuration(1.8),SKAction.runBlock({ var level = SKNode() level.zPosition = 7 var randX = CGFloat(rand() % 160) - 80 var leftCloud = SKSpriteNode(texture: self.cloudTexture) leftCloud.position = CGPointMake(-125, 0) leftCloud.physicsBody = SKPhysicsBody(rectangleOfSize: leftCloud.size) leftCloud.physicsBody?.categoryBitMask = self.cloudyCategory leftCloud.physicsBody?.contactTestBitMask = self.catCategory leftCloud.physicsBody?.collisionBitMask = self.catCategory leftCloud.physicsBody?.dynamic = false var rightCloud = SKSpriteNode(texture: self.cloudTexture) rightCloud.position = CGPointMake(125, 0) rightCloud.physicsBody = SKPhysicsBody(rectangleOfSize: rightCloud.size) rightCloud.physicsBody?.categoryBitMask = self.cloudyCategory rightCloud.physicsBody?.contactTestBitMask = self.catCategory rightCloud.physicsBody?.collisionBitMask = self.catCategory rightCloud.physicsBody?.dynamic = false var scoreField = SKNode() scoreField.position = CGPointMake(0, 0) scoreField.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(30, 1)) scoreField.physicsBody?.categoryBitMask = self.scoreCategory scoreField.physicsBody?.contactTestBitMask = self.catCategory scoreField.physicsBody?.collisionBitMask = self.catCategory scoreField.physicsBody?.dynamic = false level.addChild(leftCloud) level.addChild(rightCloud) level.addChild(scoreField) self.levelGroup.addChild(level) level.position = CGPointMake(self.frame.width * 0.5 + randX, self.frame.height + leftCloud.size.height) level.runAction(SKAction.sequence([SKAction.moveToY(-leftCloud.size.height, duration: 5),SKAction.removeFromParent()])) })]))) scoreLabel = SKLabelNode() scoreLabel.text = "\(score)" scoreLabel.zPosition = 10 scoreLabel.position = CGPointMake(self.frame.width * 0.5, self.frame.height * 0.7) scoreLabel.fontName = getFont().fontName scoreLabel.fontColor = SKColor.blackColor() self.addChild(scoreLabel) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { /* Called when a touch begins */ self.physicsWorld.gravity = CGVectorMake(2.5 * flyLeft,0) self.runAction(touchSound) flyLeft = -flyLeft if flyLeft == 1 { cat.texture = catLeftTexture }else{ cat.texture = catRightTexture } } override func update(currentTime: CFTimeInterval) { sunBg1.position.y -= 2 sunBg2.position.y -= 2 sunBg3.position.y -= 2 if sunBg1.position.y < -sunBg1.size.height * 0.5{ sunBg1.position.y = sunBg3.position.y + sunBg1.size.height - 2 } if sunBg2.position.y < -sunBg2.size.height * 0.5{ sunBg2.position.y = sunBg1.position.y + sunBg2.size.height - 2 } if sunBg3.position.y < -sunBg3.size.height * 0.5{ sunBg3.position.y = sunBg2.position.y + sunBg3.size.height - 2 } if ground.position.y < -200{ ground.removeFromParent() }else{ ground.position.y -= 2 } if grass.position.y < -200{ grass.removeFromParent() }else{ grass.position.y -= 2 } if mountain.position.y < -200{ mountain.removeFromParent() }else{ mountain.position.y -= 2 } /* Called before each frame is rendered */ } func didBeginContact(contact: SKPhysicsContact!) { if contact.bodyA.categoryBitMask == cloudyCategory || contact.bodyB.categoryBitMask == cloudyCategory || contact.bodyA.categoryBitMask == worldCategory || contact.bodyB.categoryBitMask == worldCategory{ self.view?.paused = true scoreLabel.hidden = true userDefault.setInteger(score, forKey: "total") var bestScore = userDefault.integerForKey("best") if score > bestScore{ userDefault.setInteger(score, forKey: "best") } userDefault.synchronize() NSNotificationCenter.defaultCenter().postNotificationName("gameOverNotification", object: nil) }else if contact.bodyA.categoryBitMask == scoreCategory || contact.bodyB.categoryBitMask == scoreCategory{ score++ scoreLabel.text = "\(score)" self.runAction(bonusSound) } } func getFont()->UIFont{ var hiloginbold = UIFont(name: "HILOGINBOLD", size: 28) return hiloginbold! } }
mit
4e16f8dd2a3043c1dc620d8c16026c0c
36.03663
210
0.627139
4.62746
false
false
false
false
QuarkX/Quark
Sources/Quark/Venice/Venice/Poll/Poll.swift
2
844
import CLibvenice public typealias FileDescriptor = Int32 public enum PollError : Error { case timeout case failure } public struct PollEvent : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let read = PollEvent(rawValue: Int(FDW_IN)) public static let write = PollEvent(rawValue: Int(FDW_OUT)) } /// Polls file descriptor for events public func poll(_ fileDescriptor: FileDescriptor, events: PollEvent, deadline: Double = .never) throws -> PollEvent { let event = mill_fdwait(fileDescriptor, Int32(events.rawValue), deadline.int64milliseconds, "pollFileDescriptor") if event == 0 { throw PollError.timeout } if event == FDW_ERR { throw PollError.failure } return PollEvent(rawValue: Int(event)) }
mit
8188b2ebd777bcbed62222d3de2a98e9
23.823529
118
0.691943
4.057692
false
false
false
false
Koolistov/Convenience
Convenience/NSURL+Convenience.swift
1
965
// // NSURL+Convenience.swift // Convenience // // Created by Johan Kool on 10/12/14. // Copyright (c) 2014 Koolistov Pte. Ltd. All rights reserved. // import Foundation import UIKit public extension NSURL { /** Returns query parameters as a dictionary */ public func queryParameters() -> [String:AnyObject] { var info: [String:AnyObject] = [:] if let queryString = self.query { for parameter in queryString.componentsSeparatedByString("&") { let parts = parameter.componentsSeparatedByString("=") if parts.count > 1 { let key = (parts[0] as String).stringByRemovingPercentEncoding let value = (parts[1] as String).stringByRemovingPercentEncoding if key != nil && value != nil { info[key!] = value } } } } return info } }
mit
da905828256c3663070d8ff7a015c7bb
27.411765
84
0.543005
5.026042
false
false
false
false
BradLarson/GPUImage2
examples/iOS/FilterShowcase/FilterShowcaseSwift/FilterDisplayViewController.swift
1
4123
import UIKit import GPUImage import AVFoundation let blendImageName = "WID-small.jpg" class FilterDisplayViewController: UIViewController, UISplitViewControllerDelegate { @IBOutlet var filterSlider: UISlider? @IBOutlet var filterView: RenderView? let videoCamera:Camera? var blendImage:PictureInput? required init(coder aDecoder: NSCoder) { do { videoCamera = try Camera(sessionPreset:.vga640x480, location:.backFacing) videoCamera!.runBenchmark = true } catch { videoCamera = nil print("Couldn't initialize camera with error: \(error)") } super.init(coder: aDecoder)! } var filterOperation: FilterOperationInterface? func configureView() { guard let videoCamera = videoCamera else { let errorAlertController = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: "Couldn't initialize camera", preferredStyle: .alert) errorAlertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default, handler: nil)) self.present(errorAlertController, animated: true, completion: nil) return } if let currentFilterConfiguration = self.filterOperation { self.title = currentFilterConfiguration.titleName // Configure the filter chain, ending with the view if let view = self.filterView { switch currentFilterConfiguration.filterOperationType { case .singleInput: videoCamera.addTarget(currentFilterConfiguration.filter) currentFilterConfiguration.filter.addTarget(view) case .blend: videoCamera.addTarget(currentFilterConfiguration.filter) self.blendImage = PictureInput(imageName:blendImageName) self.blendImage?.addTarget(currentFilterConfiguration.filter) self.blendImage?.processImage() currentFilterConfiguration.filter.addTarget(view) case let .custom(filterSetupFunction:setupFunction): currentFilterConfiguration.configureCustomFilter(setupFunction(videoCamera, currentFilterConfiguration.filter, view)) } videoCamera.startCapture() } // Hide or display the slider, based on whether the filter needs it if let slider = self.filterSlider { switch currentFilterConfiguration.sliderConfiguration { case .disabled: slider.isHidden = true // case let .Enabled(minimumValue, initialValue, maximumValue, filterSliderCallback): case let .enabled(minimumValue, maximumValue, initialValue): slider.minimumValue = minimumValue slider.maximumValue = maximumValue slider.value = initialValue slider.isHidden = false self.updateSliderValue() } } } } @IBAction func updateSliderValue() { if let currentFilterConfiguration = self.filterOperation { switch (currentFilterConfiguration.sliderConfiguration) { case .enabled(_, _, _): currentFilterConfiguration.updateBasedOnSliderValue(Float(self.filterSlider!.value)) case .disabled: break } } } override func viewDidLoad() { super.viewDidLoad() self.configureView() } override func viewWillDisappear(_ animated: Bool) { if let videoCamera = videoCamera { videoCamera.stopCapture() videoCamera.removeAllTargets() blendImage?.removeAllTargets() } super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bsd-3-clause
dd91d42e141b10f59e105302d0551acc
37.53271
172
0.615814
6.036603
false
true
false
false
fttios/PrcticeSwift3.0
Program/day02/Swift3.0--联系人Demo/Swift3.0--联系人Demo/ListTableViewController.swift
1
1989
// // ListTableViewController.swift // Swift3.0--联系人Demo // // Created by tan on 2017/2/21. // Copyright © 2017年 tantan. All rights reserved. // import UIKit class ListTableViewController: UITableViewController { ///联系人数组 var personList = [Person]() override func viewDidLoad() { super.viewDidLoad() loadData { (arr) in print(arr) self.personList += arr self.tableView.reloadData() } } // Function types cannot have argument label 'list'; use '_' instead /// 模拟异步,利用闭包回调 private func loadData(completion:@escaping (_ list: [Person]) -> ()) -> () { DispatchQueue.global().async { print("正在努力加载中") Thread.sleep(forTimeInterval: 1) var arrayM = [Person]() for i in 0..<20 { let p = Person() p.name = "zhangsan - \(i)" p.phone = "1860" + String(format: "%06d", arc4random_uniform(1000000)) p.title = "Boss" arrayM.append(p) } //主线程回调 DispatchQueue.main.async(execute: { completion(arrayM) }) } } //MARK: -数据源方法 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return personList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) cell.textLabel?.text = personList[indexPath.row].name cell.detailTextLabel?.text = personList[indexPath.row].phone return cell } }
mit
45ed6435cd04f52043cac42f7c995239
25.219178
109
0.514629
4.971429
false
false
false
false
frajaona/LiFXSwiftKit
Pods/socks/Sources/SocksCore/Pipe.swift
1
960
#if os(Linux) import Glibc let socket_socketpair = Glibc.socketpair #else import Darwin let socket_socketpair = Darwin.socketpair #endif public protocol Pipeable { static func pipe() throws -> (read: TCPReadableSocket, write: TCPWriteableSocket) } extension TCPEstablishedSocket: Pipeable { public static func pipe() throws -> (read: TCPReadableSocket, write: TCPWriteableSocket) { var descriptors: [Descriptor] = [0, 0] let socketType = SocketType.stream.toCType() guard socket_socketpair(AF_LOCAL, socketType, 0, &descriptors) != -1 else { throw SocksError(.pipeCreationFailed) } try descriptors.forEach { try TCPEstablishedSocket.disableSIGPIPE(descriptor: $0) } let read = TCPEstablishedReadableSocket(descriptor: descriptors[0]) let write = TCPEstablishedWriteableSocket(descriptor: descriptors[1]) return (read, write) } }
apache-2.0
83112e4fb2f3f3fcd116fc983f43edc5
33.285714
94
0.680208
4.067797
false
false
false
false
j-j-m/DataTableKit
DataTableKit/Classes/TableCellRegisterer.swift
1
2476
// // Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit class TableCellRegisterer { private var registeredIds = Set<String>() private weak var tableView: UITableView? init(tableView: UITableView?) { self.tableView = tableView } func register(cellType: AnyClass, forCellReuseIdentifier reuseIdentifier: String) { if registeredIds.contains(reuseIdentifier) { return } // check if cell is already registered, probably cell has been registered by storyboard if tableView?.dequeueReusableCell(withIdentifier: reuseIdentifier) != nil { registeredIds.insert(reuseIdentifier) return } let bundle = Bundle(for: cellType) // we hope that cell's xib file has name that equals to cell's class name // in that case we could register nib if let _ = bundle.path(forResource: reuseIdentifier, ofType: "nib") { tableView?.register(UINib(nibName: reuseIdentifier, bundle: bundle), forCellReuseIdentifier: reuseIdentifier) // otherwise, register cell class } else { tableView?.register(cellType, forCellReuseIdentifier: reuseIdentifier) } registeredIds.insert(reuseIdentifier) } }
mit
d49239b9c93975465b36bd7a4947fedf
41.689655
121
0.681745
5.03252
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Misc/Utils.swift
1
8653
// // Utils.swift // MT_iOS // // Created by CHEEBOW on 2015/05/21. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import Foundation import TMReachability class Utils { class func userAgent()->String { let uName = "MTiOS" let version: String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String let userAgent = uName + "/" + version return userAgent } class func dateFromISO8601StringWithFormat(string: String, format: String)->NSDate? { if string.isEmpty { return nil } let formatter: NSDateFormatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(abbreviation: "GMT") formatter.dateFormat = format return formatter.dateFromString(string) } class func dateTimeFromISO8601String(string: String)->NSDate? { return Utils.dateFromISO8601StringWithFormat(string, format: "yyyy-MM-dd'T'HH:mm:ssZ") } class func dateFromISO8601String(string: String)->NSDate? { return Utils.dateFromISO8601StringWithFormat(string, format: "yyyy-MM-dd") } class func timeFromISO8601String(string: String)->NSDate? { return Utils.dateFromISO8601StringWithFormat(string, format: "HH:mm:ssZ") } class func ISO8601StringFromDate(date: NSDate) -> String { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.timeZone = NSTimeZone(abbreviation: "GMT") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" return formatter.stringFromDate(date).stringByAppendingString("Z") } class func dateTimeFromString(string: String)->NSDate? { if string.isEmpty { return nil } let formatter: NSDateFormatter = NSDateFormatter() formatter.dateFormat = "yyyyMMddHHmmss"; return formatter.dateFromString(string) } class func dateTimeTextFromDate(date: NSDate)->String { let formatter: NSDateFormatter = NSDateFormatter() formatter.dateFormat = "yyyyMMddHHmmss"; return formatter.stringFromDate(date) } class func dateTimeStringFromDate(date: NSDate, template: String)->String { let dateFormatter: NSDateFormatter = NSDateFormatter() let dateFormat: NSString = NSDateFormatter.dateFormatFromTemplate(template, options: 0, locale: NSLocale.currentLocale())! dateFormatter.dateFormat = dateFormat as String return dateFormatter.stringFromDate(date) } class func fullDateTimeFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"yMMMMdEE HHmm") } class func mediumDateTimeFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"yMMMMd HHmm") } class func dateTimeFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"yMMMMd HHmm") } class func dateStringFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"yMMMMdEEE") } class func mediumDateStringFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"yMMMMd") } class func timeStringFromDate(date: NSDate)->String { return Utils.dateTimeStringFromDate(date, template:"HHmm") } class func getTextFieldFromView(view: UIView)->UITextField? { for subview in view.subviews { if subview.isKindOfClass(UITextField) { return subview as? UITextField } else { let textField = self.getTextFieldFromView(subview) if (textField != nil) { return textField } } } return nil } class func removeHTMLTags(html: String)-> String { var destination : String = html.stringByReplacingOccurrencesOfString("<(\"[^\"]*\"|'[^']*'|[^'\">])*>", withString:"", options:NSStringCompareOptions.RegularExpressionSearch, range: nil) destination = destination.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return destination } class func performAfterDelay(block: dispatch_block_t, delayTime: Double) { let delay = delayTime * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), block) } class func resizeImage(image: UIImage, width: CGFloat)-> UIImage { //オリジナルサイズのとき if width == 0.0 { return image } var w = image.size.width var h = image.size.height let scale = width / w if scale >= 1.0 { return image } w = width h = h * scale let size = CGSize(width: w, height: h) UIGraphicsBeginImageContext(size) image.drawInRect(CGRectMake(0, 0, size.width, size.height)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } class func convertImageToJPEG(image: UIImage, quality: CGFloat)-> NSData { let imageData = UIImageJPEGRepresentation(image, quality) return imageData! } class func convertJpegData(image: UIImage, width: CGFloat, quality: CGFloat)->NSData { let resizedImage = Utils.resizeImage(image, width: width) let jpeg = Utils.convertImageToJPEG(resizedImage, quality: quality) return jpeg } class func makeJPEGFilename(date: NSDate)-> String { let filename = String(format: "mt-%04d%02d%02d%02d%02d%02d.jpg", arguments: [date.year, date.month, date.day, date.hour, date.minute, date.seconds]) return filename } class func hasConnectivity()-> Bool { let reachability = TMReachability.reachabilityForInternetConnection() let networkStatus = reachability.currentReachabilityStatus() return (networkStatus != NetworkStatus.NotReachable) } class func preferredLanguage()-> String { let languages = NSLocale.preferredLanguages() let language = languages[0] return language } class func confrimSave(vc: UIViewController, dismiss: Bool = false, block: (() -> Void)? = nil) { let alertController = UIAlertController( title: NSLocalizedString("Confirm", comment: "Confirm"), message: NSLocalizedString("Are you sure not have to save?", comment: "Are you sure not have to save?"), preferredStyle: .Alert) let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .Destructive) { action in if let block = block { block() } if dismiss { vc.dismissViewControllerAnimated(true, completion: nil) } else { vc.navigationController?.popViewControllerAnimated(true) } } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: .Cancel) { action in } alertController.addAction(okAction) alertController.addAction(cancelAction) vc.presentViewController(alertController, animated: true, completion: nil) } class func trimSpace(src: String)-> String { return src.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } class func regexpMatch(pattern: String, text: String)-> Bool { let regexp = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive) let matches = regexp.matchesInString(text, options: [], range:NSMakeRange(0, text.characters.count)) return matches.count > 0 } class func validatePath(path: String)-> Bool { let pattern = "[ \"%<>\\[\\\\\\]\\^`{\\|}~]" let replaceString = path.stringByReplacingOccurrencesOfString(pattern, withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil) let api = DataAPI.sharedInstance let str = api.urlencoding(replaceString) if let _ = str.rangeOfString("%") { return false } if let _ = path.rangeOfString("..") { return false } return true } }
mit
c31f2313dbdf8bbe026f987cd5219ae4
36.521739
194
0.640862
4.999421
false
false
false
false
TQtianqian/TQDYZB_swift
TQDouYuZB/TQDouYuZB/Classes/Home/Controller/HomeViewController.swift
1
3680
// // HomeViewController.swift // TQDouYuZB // // Created by worry on 2017/2/14. // Copyright © 2017年 worry. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { //mark:--懒加载属性 lazy var pageTitleView : PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) // titleView.backgroundColor = UIColor.purpl titleView.delegate = self return titleView }() lazy var pageContentView : PageContentView = {[weak self] in //1.确定内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) //2.确定所有的子控制器 var childVC = [UIViewController]() for _ in 0..<4{ let vc = UIViewController() vc.view.backgroundColor = UIColor(r:CGFloat( arc4random_uniform(255)), g: CGFloat( arc4random_uniform(255)), b: CGFloat( arc4random_uniform(255))) childVC.append(vc) } let contentView = PageContentView(frame: contentFrame, childVC: childVC, parentViewController: self) return contentView }() //系统回掉函数 override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() } } //mark:-- 设置UI界面 extension HomeViewController{ func setupUI(){ //0.不需要调整uiscrollView的内边距 automaticallyAdjustsScrollViewInsets = false //1.设置导航栏 setupNavigationBar() //2.添加titleView view.addSubview(pageTitleView) //3.添加contentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } private func setupNavigationBar(){ //1.设置左侧的item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //2.设置右侧的item let size = CGSize(width: 40, height: 40) /*类方法创建 let historyItem = UIBarButtonItem.createItem(imageName: "viewHistoryIconHL", hightImageName: "viewHistoryIconHL", size: size) let searchItem = UIBarButtonItem.createItem(imageName: "searchBtnIconHL", hightImageName: "searchBtnIconHL", size: size) let qrcodeItem = UIBarButtonItem.createItem(imageName: "scanIconHL", hightImageName: "scanIconHL", size: size) */ //构造函数创建 let historyItem = UIBarButtonItem(imageName: "viewHistoryIconHL", hightImageName: "viewHistoryIcon", size: size) let searchItem = UIBarButtonItem(imageName: "searchBtnIconHL", hightImageName: "searchBtnIcon", size: size) let qrcodeItem = UIBarButtonItem(imageName: "scanIconHL", hightImageName: "scanIcon", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } //mark:--遵守PageTitleDelegate extension HomeViewController : PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } }
mit
61a55f54c828eceb058e5324a675fdcc
25.413534
158
0.623683
5.098694
false
false
false
false
k06a/Linqwift
Pod/Classes/Linqwift.swift
1
6175
// // Linqwift.swift // Linqwift // // Created by Anton Bukov on 03.03.16. // import Foundation class AnyGeneratorWithLambda<Element> : AnyGenerator<Element> { private var nextLambda: () -> Element? init(lambda: () -> Element?) { nextLambda = lambda } override func next() -> Element? { return nextLambda() } } // public extension AnySequence { func Where(predicate: (Element,Int)->Bool) -> AnySequence<Element> { return AnySequence<Element> { () -> AnyGenerator<Element> in let gen = self.generate() var index = 0 return AnyGeneratorWithLambda<Element> { while let object = gen.next() { if predicate(object,index++) { return object } } return nil } } } func Where(predicate: (Element)->Bool) -> AnySequence<Element> { return Where { o,i in predicate(o) } } func Select<U>(transform: (Element,Int)->U) -> AnySequence<U> { return AnySequence<U> { () -> AnyGenerator<U> in let gen = self.generate() var index = 0 return AnyGeneratorWithLambda<U> { while let object = gen.next() { return transform(object,index++) } return nil } } } func Select<U>(transform: (Element)->U) -> AnySequence<U> { return Select { o,i in transform(o) } } func Distinct<U where U: Hashable>(transform: (Element)->U) -> AnySequence<Element> { return AnySequence<Element> { () -> AnyGenerator<Element> in let gen = self.generate() var set: Dictionary<U,Bool> = [:] return AnyGeneratorWithLambda<Element> { while let object = gen.next() { let result = transform(object) if set.updateValue(true, forKey: result) == nil { return object } } return nil } } } func SkipWhile(predicate: (Element)->Bool) -> AnySequence<Element> { return AnySequence<Element> { () -> AnyGenerator<Element> in let gen = self.generate() var skipping = true return AnyGeneratorWithLambda<Element> { while let object = gen.next() { if skipping { skipping = predicate(object) } else { return object } } return nil } } } func Skip(count: Int) -> AnySequence<Element> { var index = 0 return SkipWhile { _ in ++index < count } } func TakeWhile(predicate: (Element)->Bool) -> AnySequence<Element> { return AnySequence<Element> { () -> AnyGenerator<Element> in let gen = self.generate() var taking = true return AnyGeneratorWithLambda<Element> { while let object = gen.next() { if taking { taking = predicate(object) return object } else { return nil } } return nil } } } func Take(count: Int) -> AnySequence<Element> { var index = 0 return TakeWhile { _ in ++index < count } } } public extension AnySequence { // Aggregate and Elect func Aggregate<U>(block: (U,Element)->U, startValue: U) -> U { var result = startValue for object in self { result = block(result, object) } return result } func Elect(electLeft: (Element,Element)->Bool) -> (value: Element?, index: Int?) { var electedIndex: Int? = nil var index = 0 var result: Element? = nil for object in self { if result == nil || result != nil && !electLeft(result!, object) { result = object electedIndex = index } index++ } return (result, electedIndex) } // First and Last func First(predicate: (Element)->Bool) -> (value: Element?, index: Int?) { var index = 0 for object in self { if (predicate(object)) { return (object, index) } index++ } return (nil, nil) } func Last(predicate: (Element)->Bool) -> (value: Element?, index: Int?) { return self.Elect { a,b in false } } // Min and Max func Min<U: Comparable>(transform: (Element)->U) -> (transformed: U?, value: Element?, index: Int?) { var minTrans: U? = nil var minValue: Element? = nil var minIndex: Int? = nil var index = 0 for object in self { let trans = transform(object) if (minIndex == nil) || (trans < minTrans!) { minTrans = trans minValue = object minIndex = index } index++ } return (minTrans, minValue, minIndex) } func Max<U: Comparable>(transform: (Element)->U) -> (transformed: U?, value: Element?, index: Int?) { var maxTrans: U? = nil var maxValue: Element? = nil var maxIndex: Int? = nil var index = 0 for object in self { let trans = transform(object) if (maxIndex == nil) || (trans > maxTrans!) { maxTrans = trans maxValue = object maxIndex = index } index++ } return (maxTrans, maxValue, maxIndex) } } public extension AnySequence { // Export func ToArray() -> [Element] { var arr = [Element]() for a in self { arr.append(a) } return arr } }
mit
dfc7d5d17569333e8958ac4c26e3442b
25.616379
103
0.472227
4.720948
false
false
false
false
seungprk/PenguinJump
PenguinJump/PenguinJump/ItemSelectionScene.swift
1
21060
// // ItemSelectionScene.swift // PenguinJump // // Created by Matthew Tso on 6/11/16. // Copyright © 2016 De Anza. All rights reserved. // import SpriteKit import CoreData class ItemSelectionScene: SKScene { // CoreData Objects let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let gameDataFetchRequest = NSFetchRequest(entityName: "GameData") let unlockedPenguinsFetchRequest = NSFetchRequest(entityName: "UnlockedPenguins") // Scrolling selection objects var scrollNodes = [SKNode]() var selectedNode: SKNode? var penguinOffset: CGFloat! let penguinScrollNode = SKNode() var penguinTitle: SKLabelNode! var penguinButton: SKLabelNode! var penguinObjectsData = [(type: PenguinType, name: String, cost: Int, unlocked: Bool)]() var coinLabel = SKLabelNode(text: "0 coins") var totalCoins: Int? var previousNode: SKNode? var soundEffectsOn: Bool! var penguinAtlas = SKTextureAtlas(named: "penguin") override func didMoveToView(view: SKView) { scaleMode = SKSceneScaleMode.AspectFill backgroundColor = SKColor(red: 0, green: 93/255, blue: 134/255, alpha: 1) // Fetch data let unlockedPenguins = fetchUnlockedPenguins() let gameData = fetchGameData() totalCoins = Int(gameData.totalCoins) soundEffectsOn = gameData.soundEffectsOn as Bool // Set up scene UI let closeButton = SKLabelNode(text: "X") closeButton.name = "closeButton" closeButton.fontName = "Helvetica Neue Condensed Black" closeButton.fontColor = SKColor.whiteColor() closeButton.fontSize = 24 closeButton.position = CGPoint(x: view.frame.width * 0.95, y: view.frame.height * 0.95) coinLabel.text = "\(totalCoins!) coins" coinLabel.name = "coinLabel" coinLabel.fontName = "Helvetica Neue Condensed Black" coinLabel.fontColor = SKColor.whiteColor() coinLabel.fontSize = 18 coinLabel.horizontalAlignmentMode = .Right coinLabel.position = CGPoint(x: view.frame.width * 0.9, y: view.frame.height * 0.95) penguinTitle = SKLabelNode(text: "a") penguinTitle.name = "penguinTitle" penguinTitle.fontName = "Helvetica Neue Condensed Black" penguinTitle.fontColor = SKColor.whiteColor() penguinTitle.fontSize = 24 penguinTitle.horizontalAlignmentMode = .Center penguinTitle.position = CGPoint(x: view.frame.width * 0.5, y: view.frame.height * 0.8) penguinButton = SKLabelNode(text: "a") penguinButton.name = "penguinButton" penguinButton.fontName = "Helvetica Neue Condensed Black" penguinButton.fontColor = SKColor.whiteColor() penguinButton.fontSize = 36 penguinButton.horizontalAlignmentMode = .Center penguinButton.position = CGPoint(x: view.frame.width * 0.5, y: view.frame.height * 0.25) addChild(closeButton) addChild(coinLabel) addChild(penguinScrollNode) addChild(penguinTitle) addChild(penguinButton) // Create array of scroll node objects penguinObjectsData = [ (type: PenguinType.normal, name: "Penguin", cost: 0, unlocked: true), (type: PenguinType.tinfoil, name: "Paranoid Penguin", cost: 10, unlocked: Bool(unlockedPenguins.penguinTinfoil as NSNumber)), (type: PenguinType.parasol, name: "Parasol Penguin", cost: 20, unlocked: Bool(unlockedPenguins.penguinParasol as NSNumber)), (type: PenguinType.shark, name: "A Penguin in Shark's Clothing", cost: 50, unlocked: Bool(unlockedPenguins.penguinShark as NSNumber)), (type: PenguinType.penguinViking, name: "Ahhhh Penguin", cost: 300, unlocked: Bool(unlockedPenguins.penguinViking as NSNumber)), (type: PenguinType.penguinAngel, name: "Falling Angel", cost: 300, unlocked: Bool(unlockedPenguins.penguinAngel as NSNumber)), (type: PenguinType.penguinMarathon, name: "Ironpenguin", cost: 300, unlocked: Bool(unlockedPenguins.penguinMarathon as NSNumber)), (type: PenguinType.penguinMohawk, name: "Mohawk Penguin", cost: 300, unlocked: Bool(unlockedPenguins.penguinMohawk as NSNumber)), (type: PenguinType.penguinPropellerHat, name: "Propeller Penguin", cost: 300, unlocked: Bool(unlockedPenguins.penguinPropellerHat as NSNumber)), (type: PenguinType.penguinSuperman, name: "Super Penguin", cost: 300, unlocked: Bool(unlockedPenguins.penguinSuperman as NSNumber)), (type: PenguinType.penguinDuckyTube, name: "Kid Penguin", cost: 1000, unlocked: Bool(unlockedPenguins.penguinDuckyTube as NSNumber)), (type: PenguinType.penguinPolarBear, name: "Wannabe Penguin", cost: 1000, unlocked: Bool(unlockedPenguins.penguinPolarBear as NSNumber)), (type: PenguinType.penguinTophat, name: "Tux", cost: 1000, unlocked: Bool(unlockedPenguins.penguinTophat as NSNumber)), (type: PenguinType.penguinCrown, name: "Royal Penguin", cost: 10000, unlocked: Bool(unlockedPenguins.penguinCrown as NSNumber)), ] // Create array of scroll nodes for index in 0..<penguinObjectsData.count { let scrollNode = SKNode() scrollNode.name = "\(index)" if penguinObjectsData[index].unlocked { let penguin = Penguin(type: penguinObjectsData[index].type) penguin.name = "penguin" scrollNode.addChild(penguin) } else { let penguin = SKSpriteNode(texture: SKTexture(image: UIImage(named: "locked_penguin")!)) penguin.size = CGSize(width: 25, height: 44) penguin.name = "penguin" scrollNode.addChild(penguin) } scrollNodes.append(scrollNode) } // Add scroll nodes to main scrolling node penguinOffset = penguinAtlas.textureNamed("penguin-front").size().width * 0.15 penguinScrollNode.position = view.center for node in 0..<scrollNodes.count { scrollNodes[node].position.x += CGFloat(node) * penguinOffset penguinScrollNode.addChild(scrollNodes[node]) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches { let positionInScene = touch.locationInNode(self) let touchedNodes = self.nodesAtPoint(positionInScene) for touchedNode in touchedNodes { if touchedNode.name == "closeButton" { let gameScene = GameScene(size: self.size) let transition = SKTransition.pushWithDirection(.Up, duration: 0.5) gameScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(gameScene, transition: transition) } if touchedNode.name == "penguinButton" { let label = touchedNode as! SKLabelNode if label.text == "Play" { saveSelectedPenguin() let gameScene = GameScene(size: self.size) let transition = SKTransition.pushWithDirection(.Up, duration: 0.5) gameScene.scaleMode = SKSceneScaleMode.AspectFill self.scene!.view?.presentScene(gameScene, transition: transition) } else { tryUnlockingPenguin() } } } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch: AnyObject in touches { let positionInScene = touch.locationInNode(self) let previousPosition = touch.previousLocationInNode(self) let translation = CGPoint(x: (positionInScene.x - previousPosition.x) * 2, y: (positionInScene.y - previousPosition.y) * 2) if let lastNode = scrollNodes.last { let lastNodePositionInScene = convertPoint(lastNode.position, fromNode: penguinScrollNode) if let firstNode = scrollNodes.first { let firstNodePositionInScene = convertPoint(firstNode.position, fromNode: penguinScrollNode) if !(firstNodePositionInScene.x > view!.center.x + 0.1) && !(lastNodePositionInScene.x < view!.center.x - 0.1) { let pan = SKAction.moveBy(CGVector(dx: translation.x / 2, dy: 0), duration: 0.2) pan.timingMode = .EaseOut penguinScrollNode.runAction(pan) } } } } } override func update(currentTime: NSTimeInterval) { if let firstNode = scrollNodes.first { let firstNodePositionInScene = convertPoint(firstNode.position, fromNode: penguinScrollNode) if firstNodePositionInScene.x > view!.center.x + 0.1 { let leftResist = SKAction.moveTo(CGPoint(x: view!.center.x, y: view!.center.y), duration: 0.1) leftResist.timingMode = .EaseOut penguinScrollNode.runAction(leftResist) } } if let lastNode = scrollNodes.last { let lastNodePositionInScene = convertPoint(lastNode.position, fromNode: penguinScrollNode) if lastNodePositionInScene.x < view!.center.x - 0.1 { let rightResist = SKAction.moveTo(CGPoint(x: view!.center.x - penguinOffset * CGFloat(scrollNodes.count - 1), y: view!.center.y), duration: 0.1) rightResist.timingMode = .EaseOut penguinScrollNode.runAction(rightResist) } } // Calculate which penguin is closest to the middle var middleNode: SKNode! var closestX = penguinOffset * 10 for node in scrollNodes { let nodePositionInScene = convertPoint(node.position, fromNode: penguinScrollNode) let nodeDistanceFromCenter = nodePositionInScene.x - view!.center.x if nodeDistanceFromCenter < abs(closestX) { closestX = nodeDistanceFromCenter middleNode = node } } if previousNode != middleNode { previousNode = middleNode if soundEffectsOn! { runAction(SKAction.playSoundFileNamed("dial.wav", waitForCompletion: false)) } } selectedNode = middleNode // Scale unselected penguins smaller for node in scrollNodes { if node != middleNode && node.childNodeWithName("penguin")?.xScale > 2 { let normalScale = SKAction.scaleTo(1, duration: 0.2) normalScale.timingMode = .EaseOut let penguin = node.childNodeWithName("penguin") penguin?.runAction(normalScale) penguin?.position = CGPointZero node.zPosition = 0 } if node != middleNode { let penguin = node.childNodeWithName("penguin") as! SKSpriteNode penguin.position = CGPointZero } } // Scale selected penguin larger if middleNode.childNodeWithName("penguin")?.xScale < 1.001 { let selectedScale = SKAction.scaleTo(2.5, duration: 0.2) selectedScale.timingMode = .EaseOut let middlePenguin = middleNode.childNodeWithName("penguin") middlePenguin?.runAction(selectedScale) middleNode.zPosition = 30000 } middleNode.childNodeWithName("penguin")?.position = convertPoint(view!.center, toNode: middleNode) if let index = Int(middleNode.name!) { if penguinObjectsData[index].unlocked { penguinTitle.text = penguinObjectsData[index].name penguinButton.text = "Play" penguinButton.alpha = 1 } else { penguinTitle.text = "???" penguinButton.text = "Unlock with \(penguinObjectsData[index].cost) coins" if totalCoins >= penguinObjectsData[index].cost { penguinButton.alpha = 1 } else { penguinButton.alpha = 0.35 } } } } // MARK: - CoreData methods func fetchGameData() -> GameData { var fetchedData = [GameData]() do { fetchedData = try managedObjectContext.executeFetchRequest(gameDataFetchRequest) as! [GameData] if fetchedData.isEmpty { let newGameData = NSEntityDescription.insertNewObjectForEntityForName("GameData", inManagedObjectContext: managedObjectContext) as! GameData newGameData.highScore = 0 newGameData.totalCoins = 0 newGameData.selectedPenguin = "normal" do { try managedObjectContext.save() } catch { print(error) } do { fetchedData = try managedObjectContext.executeFetchRequest(gameDataFetchRequest) as! [GameData] } catch { print(error) } } } catch { print(error) } return fetchedData.first! } func fetchUnlockedPenguins() -> UnlockedPenguins { var fetchedData = [UnlockedPenguins]() do { fetchedData = try managedObjectContext.executeFetchRequest(unlockedPenguinsFetchRequest) as! [UnlockedPenguins] if fetchedData.isEmpty { // Create initial game data let newPenguinData = NSEntityDescription.insertNewObjectForEntityForName("UnlockedPenguins", inManagedObjectContext: managedObjectContext) as! UnlockedPenguins newPenguinData.penguinNormal = NSNumber(bool: true) newPenguinData.penguinParasol = NSNumber(bool: false) newPenguinData.penguinTinfoil = NSNumber(bool: false) newPenguinData.penguinShark = NSNumber(bool: false) newPenguinData.penguinViking = NSNumber(bool: false) newPenguinData.penguinAngel = NSNumber(bool: false) newPenguinData.penguinSuperman = NSNumber(bool: false) newPenguinData.penguinPolarBear = NSNumber(bool: false) newPenguinData.penguinTophat = NSNumber(bool: false) newPenguinData.penguinPropellerHat = NSNumber(bool: false) newPenguinData.penguinMohawk = NSNumber(bool: false) newPenguinData.penguinCrown = NSNumber(bool: false) newPenguinData.penguinMarathon = NSNumber(bool: false) newPenguinData.penguinDuckyTube = NSNumber(bool: false) do { try managedObjectContext.save() } catch { print(error) } do { fetchedData = try managedObjectContext.executeFetchRequest(unlockedPenguinsFetchRequest) as! [UnlockedPenguins] } catch { print(error) } } } catch { print(error) } return fetchedData.first! } func saveSelectedPenguin() { if let index = Int(selectedNode!.name!) { var selectedPenguinString = "" let type = penguinObjectsData[index].type switch (type) { case .normal: selectedPenguinString = "normal" case .parasol: selectedPenguinString = "parasol" case .tinfoil: selectedPenguinString = "tinfoil" case .shark: selectedPenguinString = "shark" case .penguinAngel: selectedPenguinString = "penguinAngel" case .penguinCrown: selectedPenguinString = "penguinCrown" case .penguinDuckyTube: selectedPenguinString = "penguinDuckyTube" case .penguinMarathon: selectedPenguinString = "penguinMarathon" case .penguinMohawk: selectedPenguinString = "penguinMohawk" case .penguinPolarBear: selectedPenguinString = "penguinPolarBear" case .penguinPropellerHat: selectedPenguinString = "penguinPropellerHat" case .penguinSuperman: selectedPenguinString = "penguinSuperman" case .penguinTophat: selectedPenguinString = "penguinTophat" case .penguinViking: selectedPenguinString = "penguinViking" } let gameData = fetchGameData() gameData.selectedPenguin = selectedPenguinString do { try managedObjectContext.save() } catch { print(error) } } } func tryUnlockingPenguin() { if let index = Int(selectedNode!.name!) { let gameData = fetchGameData() let cost = penguinObjectsData[index].cost if cost <= gameData.totalCoins as Int { // Save the total coins after the unlock in game data let totalCoinsAfterUnlock = (gameData.totalCoins as Int) - cost gameData.totalCoins = totalCoinsAfterUnlock do { try managedObjectContext.save() } catch { print(error) } // Save the penguin unlock let unlockedPenguins = fetchUnlockedPenguins() // Switch chooses which penguin type to unlock let type = penguinObjectsData[index].type switch (type) { case .normal: unlockedPenguins.penguinNormal = NSNumber(bool: true) case .parasol: unlockedPenguins.penguinParasol = NSNumber(bool: true) case .tinfoil: unlockedPenguins.penguinTinfoil = NSNumber(bool: true) case .shark: unlockedPenguins.penguinShark = NSNumber(bool: true) case .penguinAngel: unlockedPenguins.penguinAngel = NSNumber(bool: true) case .penguinCrown: unlockedPenguins.penguinCrown = NSNumber(bool: true) case .penguinDuckyTube: unlockedPenguins.penguinDuckyTube = NSNumber(bool: true) case .penguinMarathon: unlockedPenguins.penguinMarathon = NSNumber(bool: true) case .penguinMohawk: unlockedPenguins.penguinMohawk = NSNumber(bool: true) case .penguinPolarBear: unlockedPenguins.penguinPolarBear = NSNumber(bool: true) case .penguinPropellerHat: unlockedPenguins.penguinPropellerHat = NSNumber(bool: true) case .penguinSuperman: unlockedPenguins.penguinSuperman = NSNumber(bool: true) case .penguinTophat: unlockedPenguins.penguinTophat = NSNumber(bool: true) case .penguinViking: unlockedPenguins.penguinViking = NSNumber(bool: true) } do { try managedObjectContext.save() } catch { print(error) } // Update scene data penguinObjectsData[index].unlocked = true totalCoins = totalCoinsAfterUnlock // Update scene UI .. perhaps have a particle burst behind the character? coinLabel.text = "\(totalCoinsAfterUnlock) coins" scrollNodes[index].childNodeWithName("penguin")?.removeFromParent() let penguin = Penguin(type: penguinObjectsData[index].type) penguin.name = "penguin" scrollNodes[index].addChild(penguin) } else { // Not enough coins to unlock } } } }
bsd-2-clause
323c9f6b54ac04bd54dcbe35ccfc4cf6
42.964509
175
0.574434
4.785049
false
false
false
false
kamawshuang/iOS---Animation
梯度动画(五)/GradientAnimation/GradientAnimation/ViewController.swift
1
1217
// // ViewController.swift // GradientAnimation // // Created by 51Testing on 15/12/4. // Copyright © 2015年 HHW. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var gradientView: GradientView! @IBOutlet weak var timaLab: UILabel! override func viewDidLoad() { super.viewDidLoad() gradientView.text = "asdfadsfasdfasdf" let swipe = UISwipeGestureRecognizer(target: self, action: "didSlide") swipe.direction = .Right gradientView.addGestureRecognizer(swipe) } func didSlide() { UIView.animateWithDuration(0.5, animations: { self.timaLab.frame.origin.y -= 200 }, completion: { _ in UIView.animateWithDuration(0.3, delay: 2, options: [], animations: { self.timaLab.frame.origin.y += 200 }, completion: nil) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
aa66f5593dbda7776097ca752df67b3d
21.072727
84
0.551895
5.037344
false
false
false
false
nahitheper/TKSubmitTransition
SubmitTransition/Classes/TransitionSubmitButton.swift
1
4057
import Foundation import UIKit let PINK = UIColor(red:0.992157, green: 0.215686, blue: 0.403922, alpha: 1) let DARK_PINK = UIColor(red:0.798012, green: 0.171076, blue: 0.321758, alpha: 1) @IBDesignable public class TKTransitionSubmitButton : UIButton, UIViewControllerTransitioningDelegate { public var didEndFinishAnimation : (()->())? = nil let springGoEase = CAMediaTimingFunction(controlPoints: 0.45, -0.36, 0.44, 0.92) let shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05) let shrinkDuration: CFTimeInterval = 0.1 lazy var spiner: SpinerLayer! = { let s = SpinerLayer(frame: self.frame) self.layer.addSublayer(s) return s }() @IBInspectable public var highlightedBackgroundColor: UIColor? = DARK_PINK { didSet { self.setBackgroundColor() } } @IBInspectable public var normalBackgroundColor: UIColor? = PINK { didSet { self.setBackgroundColor() } } var cachedTitle: String? public override init(frame: CGRect) { super.init(frame: frame) self.setup() } override public var highlighted: Bool { didSet { self.setBackgroundColor() } } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } func setup() { self.layer.cornerRadius = self.frame.height / 2 self.clipsToBounds = true self.setBackgroundColor() } func setBackgroundColor() { if (highlighted) { self.backgroundColor = highlightedBackgroundColor } else { self.backgroundColor = normalBackgroundColor } } public func startLoadingAnimation() { self.cachedTitle = titleForState(.Normal) self.setTitle("", forState: .Normal) self.shrink() NSTimer.schedule(delay: shrinkDuration - 0.25) { timer in self.spiner.animation() } } public func startFinishAnimation(delay: NSTimeInterval, completion:(()->())?) { NSTimer.schedule(delay: delay) { timer in self.didEndFinishAnimation = completion self.expand() self.spiner.stopAnimation() } } public func animate(duration: NSTimeInterval, completion:(()->())?) { startLoadingAnimation() startFinishAnimation(duration, completion: completion) } public func setOriginalState() { self.returnToOriginalState() self.spiner.stopAnimation() } public override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { let a = anim as! CABasicAnimation if a.keyPath == "transform.scale" { didEndFinishAnimation?() NSTimer.schedule(delay: 1) { timer in self.returnToOriginalState() } } } func returnToOriginalState() { self.layer.removeAllAnimations() self.setTitle(self.cachedTitle, forState: .Normal) } func shrink() { let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnim.fromValue = frame.width shrinkAnim.toValue = frame.height shrinkAnim.duration = shrinkDuration shrinkAnim.timingFunction = shrinkCurve shrinkAnim.fillMode = kCAFillModeForwards shrinkAnim.removedOnCompletion = false layer.addAnimation(shrinkAnim, forKey: shrinkAnim.keyPath) } func expand() { let expandAnim = CABasicAnimation(keyPath: "transform.scale") expandAnim.fromValue = 1.0 expandAnim.toValue = 26.0 expandAnim.timingFunction = expandCurve expandAnim.duration = 0.3 expandAnim.delegate = self expandAnim.fillMode = kCAFillModeForwards expandAnim.removedOnCompletion = false layer.addAnimation(expandAnim, forKey: expandAnim.keyPath) } }
mit
e46cbc8ba71b4b299cb79aee5a205cad
29.503759
89
0.630269
4.695602
false
false
false
false
EstefaniaGilVaquero/ciceIOS
App_CustomCell_Dictionary_Practica/App_CustomCell_Dictionary_Practica/SYBPrincipalWallTableViewController.swift
1
4963
// // SYBPrincipalWallTableViewController.swift // App_CustomCell_Dictionary_Practica // // Created by cice on 13/6/16. // Copyright © 2016 cice. All rights reserved. // import UIKit class SYBPrincipalWallTableViewController: UITableViewController { //MARK: VARIABLES LOCALES GLOBALES var posteosArray = [] var posteosDiccionario = [:] override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("Contactos", ofType: "plist") posteosArray = NSArray(contentsOfFile: path!)! // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return posteosArray.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SYBCustomCell // Configure the cell... posteosDiccionario = posteosArray.objectAtIndex(indexPath.row) as! NSDictionary let nameuser = posteosDiccionario["firstName"] as! String let apellido = posteosDiccionario["lastName"] as! String let usernameTwitter = posteosDiccionario["usernameTwitter"] as! String let datePost = posteosDiccionario["createdPost"] as! String let likeButton = posteosDiccionario["likeButton"] as! String let share = posteosDiccionario["share"] as! String let comment = posteosDiccionario["description"] as! String let description = posteosDiccionario["description"] as! String let imageProfile = posteosDiccionario["imageProfile"] as! String let imagePost = posteosDiccionario["imagePost"] as! String let imageProfileCustom = UIImage(named: imageProfile) let imagePostCustom = UIImage(named: imagePost) cell.myNameuserLBL.text = nameuser cell.myApellidoLBL.text = apellido cell.myUsernameTwitterLBL.text = usernameTwitter cell.myDatePostBL.text = datePost cell.myLikeStringLBL.text = likeButton cell.myShareStringLBL.text = share cell.myCommentStringLBL.text = comment cell.myDescriptionLBL.text = description cell.myImageProfileIV.image = imageProfileCustom cell.myImagePostIV.image = imagePostCustom return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
a854f11f578e4075c1204b68e1ea374d
36.590909
157
0.689037
5.007064
false
false
false
false
jhliberty/GitLabKit
GitLabKit/UserFull.swift
1
3489
// // UserFull.swift // GitLabKit // // Copyright (c) 2015 orih. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public class UserFull: User { public var createdAt: NSDate? public var _isAdmin: NSNumber? public var bio: String? public var skype: String? public var linkedin: String? public var twitter: String? public var websiteUrl: String? public var email: String? public var themeId: NSNumber? public var colorSchemeId: NSNumber? public var externUid: String? public var provider: String? public var projectsLimit: NSNumber? public var _canCreateGroup: NSNumber? public var _canCreateProject: NSNumber? public var privateToken: String? public var isAdmin: Bool { get { return _isAdmin? != nil ? _isAdmin!.boolValue : false } set { _isAdmin = NSNumber(bool: newValue)} } public var canCreateGroup: Bool { get { return _canCreateGroup? != nil ? _canCreateGroup!.boolValue : false } set { _canCreateGroup = NSNumber(bool: newValue)} } public var canCreateProject: Bool { get { return _canCreateProject? != nil ? _canCreateProject!.boolValue : false } set { _canCreateProject = NSNumber(bool: newValue)} } public override class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { var baseKeys: [NSObject : AnyObject] = super.JSONKeyPathsByPropertyKey() var newKeys: [NSObject : AnyObject] = [ "createdAt" : "created_at", "_isAdmin" : "is_admin", "bio" : "bio", "skype" : "skype", "linkedin" : "linkedin", "twitter" : "twitter", "websiteUrl" : "website_url", "email" : "email", "themeId" : "theme_id", "colorSchemeId" : "color_scheme_id", "externUid" : "extern_uid", "provider" : "provider", "projectsLimit" : "projects_limit", "_canCreateGroup" : "can_create_group", "_canCreateProject" : "can_create_project", "privateToken" : "private_token" ] return baseKeys + newKeys } class func createdAtJSONTransformer() -> NSValueTransformer { return dateTimeTransformer } }
mit
16496cbecb4ebcfc1745bdc028b47bbb
40.058824
87
0.628547
4.427665
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/PaginationControllerTests.swift
2
4146
// // PaginationControllerTests.swift // edX // // Created by Akiva Leffert on 12/16/15. // Copyright © 2015 edX. All rights reserved. // import XCTest @testable import edX class PaginationControllerTests: XCTestCase { func testTableScrollStartsLoad() { let tableView = UITableView(frame:CGRect(x: 0, y: 0, width: 100, height: 100)) let dataSource = DummyTableViewDataSource<Int>() tableView.dataSource = dataSource tableView.delegate = dataSource let paginator = WrappedPaginator<Int> { page in let info = PaginationInfo(totalCount: 10, pageCount: 5) // Add a slight delay to make sure we get proper async behavior // to better match actual cases return Stream(value: Paginated(pagination: info, value: [1, 2, 3, 4, 5])).delay(0.1) } let paginationController = PaginationController(paginator: paginator, tableView: tableView) paginationController.stream.listen(self) { dataSource.items = $0.value ?? [] tableView.reloadData() } paginator.loadMore() waitForStream(paginationController.stream) XCTAssertFalse(paginationController.stream.active) // verify the table view has content let initialCount = paginationController.stream.value?.count ?? 0 XCTAssertGreaterThanOrEqual(initialCount, 0) XCTAssertEqual(tableView.contentSize.height, CGFloat(initialCount) * dataSource.rowHeight) // Now scroll to the bottom var bottomIndexPath = NSIndexPath(forRow: initialCount - 1, inSection: 0) tableView.scrollToRowAtIndexPath(bottomIndexPath, atScrollPosition: .Bottom, animated: false) XCTAssertNotNil(tableView.tableFooterView) // Should be showing spinner // and see if we get more content waitForStream(paginationController.stream, fireIfAlreadyLoaded: false) let newCount = paginationController.stream.value?.count ?? 0 XCTAssertGreaterThanOrEqual(newCount, initialCount) //Scrolling to the bottom second time to confirm that results are loaded bottomIndexPath = NSIndexPath(forRow: newCount - 1, inSection: 0) tableView.scrollToRowAtIndexPath(bottomIndexPath, atScrollPosition: .Bottom, animated: false) XCTAssertNil(tableView.tableFooterView) // Should not be showing spinner } func testPaginatorSwapClearsOldPaginator() { let tableView = UITableView(frame:CGRect(x: 0, y: 0, width: 100, height: 100)) let dataSource = DummyTableViewDataSource<Int>() tableView.dataSource = dataSource tableView.delegate = dataSource let paginator = WrappedPaginator<Int> { page in let info = PaginationInfo(totalCount: 60, pageCount: 20) // Add a slight delay to make sure we get proper async behavior // to better match actual cases return Stream(value: Paginated(pagination: info, value: [1, 2, 3, 4, 5])).delay(0.1) } func connectPaginator() { var cleared = false let paginationController = PaginationController(paginator: paginator, tableView: tableView) paginationController.loadMore() paginationController.stream.listen(self) { dataSource.items = $0.value ?? [] tableView.reloadData() if cleared { XCTFail("Unexpected callback. Pagination controller should be deallocated") } } waitForStream(paginationController.stream, fireIfAlreadyLoaded:false) cleared = true } // Make sure the new paginator has no stale references autoreleasepool { connectPaginator() } // Now scroll to the bottom let bottomIndexPath = NSIndexPath(forRow: tableView.numberOfRowsInSection(0) - 1, inSection: 0) tableView.scrollToRowAtIndexPath(bottomIndexPath, atScrollPosition: .Bottom, animated: false) } }
apache-2.0
803c09fa0f065d592c44bf709c10e059
40.45
103
0.646803
5.348387
false
true
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/Emoticon/EmoticonHelper.swift
1
1221
// // EmoticonHelper.swift // HiPDA // // Created by leizh007 on 2017/6/13. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation struct EmoticonHelper { static let groups: [EmoticonGroup] = { guard let path = Bundle.main.path(forResource: "Emoticon", ofType: "plist"), let arr = NSArray(contentsOfFile: path) as? [NSDictionary] else { return [] } return arr.flatMap { dic in guard let name = dic["displayName"] as? String, let emoticonAttributes = dic["emoticons"] as? [[String: String]] else { return nil } return EmoticonGroup(name: name, emoticons: emoticonAttributes.flatMap { emoticonAttribute in guard let name = emoticonAttribute["name"], let code = emoticonAttribute["code"] else { return nil } return Emoticon(name: name, code: code) }) } }() static let nameCodeDic: [String: String] = { var dic = [String: String]() for group in EmoticonHelper.groups { for emoticon in group.emoticons { dic[emoticon.name] = emoticon.code } } return dic }() }
mit
7d61b422298c5cbf9119c091ffcbc513
32.833333
105
0.577176
4.494465
false
false
false
false
Intermark/IMQuickSearch
Examples/Swift-Example/QuickSearchSwift/IMPerson.swift
2
1159
// // IMPerson.swift // QuickSearchSwift // // Created by Ben Gordon on 11/25/14. // Copyright (c) 2014 IMC. All rights reserved. // import UIKit let firstNames = ["Bob","Alan","Nancy","Jennifer","Jessica","Jim","Pam","Abdul","Fred","Ben","Wallace","Nick","Gus","Robert","Alexandra","Timothy","Demetrius","Catherine","Kathy","Erica","Mary"] let lastNames = ["Clark","Stephens","Gordon","Peterson","Robertson","Frederickson","Smith","Davidson","Wood","Jackson","Sampson","Alberts","West","Breland","Richardson","Ingram","Upchurch","Upshaw"] class IMPerson: NSObject { var firstName: String? = nil var lastName: String? = nil class func randomPerson() -> IMPerson { var p = IMPerson() let f = Int(arc4random() % UInt32(firstNames.count)) let l = Int(arc4random() % UInt32(lastNames.count)) p.firstName = firstNames[f] p.lastName = lastNames[l] return p } class func randomPeople(count: Int) -> [IMPerson] { var people: [IMPerson] = [] for (var i = 0; i < count; i++) { people.append(IMPerson.randomPerson()) } return people } }
mit
5839763a7850d412ea37b5483d1c0ed5
33.088235
198
0.606557
3.33046
false
false
false
false
beeth0ven/LTMorphingLabel
LTMorphingLabelDemo/LTDemoViewController.swift
5
2535
// // LTDemoViewController.swift // LTMorphingLabelDemo // // Created by Lex on 6/23/14. // Copyright (c) 2015 lexrus.com. All rights reserved. // import UIKit class LTDemoViewController : UIViewController, LTMorphingLabelDelegate { private var i = 0 private var textArray = [ "What is design?", "Design", "Design is not just", "what it looks like", "and feels like.", "Design", "is how it works.", "- Steve Jobs", "Older people", "sit down and ask,", "'What is it?'", "but the boy asks,", "'What can I do with it?'.", "- Steve Jobs", "", "Swift", "Objective-C", "iPhone", "iPad", "Mac Mini", "MacBook Pro", "Mac Pro", "爱老婆", "老婆和女儿"] private var text: String { if i >= textArray.count { i = 0 } return textArray[i++] } override func viewDidLoad() { super.viewDidLoad() label.delegate = self } deinit { label.delegate = nil } @IBOutlet private var label: LTMorphingLabel! @IBAction func changeText(sender: AnyObject) { label.text = text } @IBAction func segmentChanged(sender: UISegmentedControl) { let seg = sender switch seg.selectedSegmentIndex { case 1: label.morphingEffect = .Evaporate case 2: label.morphingEffect = .Fall case 3: label.morphingEffect = .Pixelate case 4: label.morphingEffect = .Sparkle case 5: label.morphingEffect = .Burn case 6: label.morphingEffect = .Anvil default: label.morphingEffect = .Scale } changeText(sender); } @IBAction func toggleLight(sender: UISegmentedControl) { let isNight = Bool(sender.selectedSegmentIndex == 0) view.backgroundColor = isNight ? UIColor.blackColor() : UIColor.whiteColor() label.textColor = isNight ? UIColor.whiteColor() : UIColor.blackColor() } @IBAction func changeFontSize(sender: UISlider) { label.font = label.font.fontWithSize(CGFloat(sender.value)) label.text = label.text label.setNeedsDisplay() } } extension LTDemoViewController { func morphingDidStart(label: LTMorphingLabel) { } func morphingDidComplete(label: LTMorphingLabel) { } func morphingOnProgress(label: LTMorphingLabel, _ progress: Float) { } }
mit
d641ada32071e32b628d584657c75daa
25.797872
91
0.578801
4.419298
false
false
false
false
edx/edx-app-ios
Source/CutomePlayer/TranscriptManager.swift
1
3129
// // TranscriptManager.swift // edX // // Created by Salman on 29/03/2018. // Copyright © 2018 edX. All rights reserved. // import UIKit protocol TranscriptManagerDelegate: AnyObject { func transcriptsLoaded(manager: TranscriptManager, transcripts: [TranscriptObject]) } class TranscriptManager: NSObject { typealias Environment = OEXInterfaceProvider private let environment : Environment private let video: OEXHelperVideoDownload private let transcriptParser = TranscriptParser() private var transcripts: [TranscriptObject] = [] weak var delegate: TranscriptManagerDelegate? { didSet { initializeSubtitle() } } init(environment: Environment, video: OEXHelperVideoDownload) { self.environment = environment self.video = video super.init() } private var captionURL: String { var url: String = "" if let ccSelectedLanguage = OEXInterface.getCCSelectedLanguage(), let transcriptURL = video.summary?.transcripts?[ccSelectedLanguage] as? String, !ccSelectedLanguage.isEmpty, !transcriptURL.isEmpty{ url = transcriptURL } else if let transcriptURL = video.summary?.transcripts?.values.first as? String { url = transcriptURL } return url } func loadTranscripts() { closedCaptioning(at: captionURL) } private func initializeSubtitle() { loadTranscripts() NotificationCenter.default.oex_addObserver(observer: self, name: DL_COMPLETE) { (notification, observer, _) -> Void in observer.downloadedTranscript(notification: notification) } } private func downloadedTranscript(notification: NSNotification) { if let task = notification.userInfo?[DL_COMPLETE_N_TASK] as? URLSessionDownloadTask, let taskURL = task.response?.url { if taskURL.absoluteString == captionURL { closedCaptioning(at: captionURL) } } } private func closedCaptioning(at URLString: String?) { if let localFile: String = OEXFileUtility.filePath(forRequestKey: URLString) { // File to string if FileManager.default.fileExists(atPath: localFile) { // File to string do { let transcript = try String(contentsOfFile: localFile, encoding: .utf8) transcriptParser.parse(transcript: transcript, completion: { (success, error) in transcripts = transcriptParser.transcripts delegate?.transcriptsLoaded(manager: self, transcripts: transcripts) }) } catch _ {} } else { environment.interface?.download(withRequest: URLString, forceUpdate: false) } } } func transcript(at time: TimeInterval) -> String { let filteredSubTitles = transcripts.filter { return time > $0.start && time < $0.end } return filteredSubTitles.first?.text ?? "" } }
apache-2.0
dd7b727493da50552c277e2c2233a386
34.146067
206
0.622442
5.053312
false
false
false
false
cdmx/MiniMancera
miniMancera/Controller/Option/COptionReformaCrossing.swift
1
1436
import SpriteKit class COptionReformaCrossing:ControllerGame<MOptionReformaCrossing> { override func didBegin(_ contact:SKPhysicsContact) { model.contact.addContact(contact:contact) } override func game1up() { super.game1up() let sound1up:SKAction = model.sounds.sound1up playSound(actionSound:sound1up) model.revertChanges() newGameScene() } override func gamePlayNoMore() { let soundFail:SKAction = model.sounds.soundFail playSound(actionSound:soundFail) super.gamePlayNoMore() } //MARK: private private func newGameScene() { let newScene:VOptionReformaCrossingScene = VOptionReformaCrossingScene( controller:self) presentScene(newScene:newScene) model.startLevel() } //MARK: public func nextLevel() { restartTimer() newGameScene() } func presentScene(newScene:SKScene) { let transition:SKTransition = model.actions.transitionCrossFade guard let view:SKView = self.view as? SKView else { return } view.presentScene(newScene, transition:transition) } func showGameOver() { model.strategyWait() postScore() } }
mit
6a5f766f5ca1d6b047ab2fdb9dbf671f
19.811594
79
0.569638
4.901024
false
false
false
false
jbannister/RoyalOfUr
GameOfUr/GameOfUr/GameUr.swift
1
9578
// // GameUr.swift // GameOfUr // // Created by Jan Bannister on 11/05/2017. // Copyright © 2017 Jan Bannister. All rights reserved. // import Foundation class GameUr: CustomStringConvertible { var autoID : String! var turn = Turn.white var whitePlayer : Player! var blackPlayer : Player! var moves = [Move]() var whitePieces = [Piece(turn: .white), Piece(turn: .white), Piece(turn: .white), Piece(turn: .white), Piece(turn: .white), Piece(turn: .white), Piece(turn: .white)] var blackPieces = [Piece(turn: .black), Piece(turn: .black), Piece(turn: .black), Piece(turn: .black), Piece(turn: .black), Piece(turn: .black), Piece(turn: .black)] var board = Board() private var dices = [Dice(), Dice(), Dice(), Dice()] init(autoID: String, turn: Turn, white: Player, black: Player!) { self.autoID = autoID self.turn = turn self.whitePlayer = white self.blackPlayer = black } var description: String { get { var output = "Game Ur\n" output += "\t White Player: \(whitePlayer.name)\n" output += "\t White Count: 0 \n" output += "\t White Piece: \n" for x in whitePieces { output += "\t\t \(x)\n" } output += "\t Black Player: \(blackPlayer.name) \n" output += "\t Black Count: 0 \n" output += "\t Black Piece: \n" for x in blackPieces { output += "\t\t \(x)\n" } output += "\n" output += "\t Board Piece: \n" for (key,value) in board.boardDict { output += "\t\t \(key) -> \(value)\n" } output += "\n" output += "\t Moves: \n" for x in moves { output += "\t\t \(x)\n" } return output } } func dollRoll() -> Int { var i = 0 for dice in dices { i += dice.diceRoll() } return i } func hasMove(count: Int) -> [Move] { var array = [Move]() for (_,piece) in board.boardDict { if piece.turn == turn { if let move = Move(game: self, old: piece, dice: count) { array.append(move) } } } if let home = homeBoard(count: count) { array.append(home) } return array } private func homeBoard(count: Int) -> Move! { if turn == .white { let testBoard = UrBoard.white0.count(turn: .white, count: count) for (_,piece) in board.boardDict { if testBoard == piece.board { return nil } } let w = whitePieces.popLast() if let w = w { return Move(game: self, old: w, dice: count) } } else { let testBoard = UrBoard.black0.count(turn: .black, count: count) for (_,piece) in board.boardDict { if testBoard == piece.board { return nil } } let b = blackPieces.popLast() if let b = b { return Move(game: self, old: b, dice: count) } } return nil } private func gamePiece(_ piece: Piece) -> String { switch piece.turn! { case .white: return "| W |" case .black: return "| B |" case .blank: return "| . |" } } func gameBoard() { var output = "" output += "\n" output += "Game of Ur Board\n" output += "_____________________\n" output += "WH: \(whitePlayer.home) | BH:\(blackPlayer.home)\n" output += "WS: \(whitePlayer.score) | BS:\(blackPlayer.score)\n" output += "_____________________\n" output += "\(gamePiece(board.boardDict[.white4]! ))" output += "\(gamePiece(board.boardDict[.unsafe5]! ))" output += "\(gamePiece(board.boardDict[.black4]! ))" output += "\n" output += "\(gamePiece(board.boardDict[.white3]! ))" output += "\(gamePiece(board.boardDict[.unsafe6]! ))" output += "\(gamePiece(board.boardDict[.black3]! ))" output += "\n" output += "\(gamePiece(board.boardDict[.white2]! ))" output += "\(gamePiece(board.boardDict[.unsafe7]! ))" output += "\(gamePiece(board.boardDict[.black2]! ))" output += "\n" output += "\(gamePiece(board.boardDict[.white1]! ))" output += "\(gamePiece(board.boardDict[.unsafe8]! ))" output += "\(gamePiece(board.boardDict[.black1]! ))" output += "\n" output += " " output += "\(gamePiece(board.boardDict[.unsafe9]! ))" output += " " output += "\n" output += "_______" output += "\(gamePiece(board.boardDict[.unsafe10]! ))" output += "_______" output += "\n" output += "\(gamePiece(board.boardDict[.white14]! ))" output += "\(gamePiece(board.boardDict[.unsafe11]! ))" output += "\(gamePiece(board.boardDict[.black14]! ))" output += "\n" output += "\(gamePiece(board.boardDict[.white13]! ))" output += "\(gamePiece(board.boardDict[.unsafe12]! ))" output += "\(gamePiece(board.boardDict[.black13]! ))" output += "\n" print(output) } func commitMove(move: Move, count: Int) -> Bool { move.older = board.boardDict[move.new.board] print("Move: Old: \(move.old.board)\t -> Dice: \(move.dice!) -> New: \(move.new.board)") print("Old B: Old: \(board.boardDict[move.old.board]!.board)\t -> Dice: \(move.dice!) -> New: \(board.boardDict[move.new.board]!.board) ") board.boardDict[move.old.board] = Piece() if move.new.board == .overstep { fatalError() } // Score Up if move.new.board == .end { if move.new.turn == .white { whitePlayer.score += 1 } if move.new.turn == .black { blackPlayer.score += 1 } } else { // Move dice let temp = board.boardDict[move.new.board] board.boardDict[move.new.board] = move.new // Take away if let temp = temp { if temp.turn == .white { temp.board = .white0 whitePieces.append(temp) whitePlayer.home = whitePlayer.home + 1 } if temp.turn == .black { temp.board = .black0 blackPieces.append(temp) blackPlayer.home = blackPlayer.home + 1 } } else { fatalError() } } // Leave Home if move.old.board == .black0 { blackPlayer.home = blackPlayer.home - 1 } if move.old.board == .white0 { whitePlayer.home = whitePlayer.home - 1 } print("New B: Old: \(board.boardDict[move.old.board]!.board)\t -> Dice: \(move.dice!) -> New: \(board.boardDict[move.new.board]!.board) ") moves.append(move) //ToDo -> 2 turn let i = UrBoard.hotPlace(hotMove: move) if i { print("asf") } return i } func endTurn(roll: Bool!) { if let r = roll { if !r { if turn == .white { turn = .black } else { turn = .white } } } else { if turn == .white { turn = .black } else { turn = .white } } } var endGame : Turn { if whitePlayer.score == 7 { return .white } if blackPlayer.score == 7 { return .black } return Turn.blank } func assert_game() { if whitePlayer.home + whitePlayer.score + assert_white() != 7 { print("\(whitePlayer.home) + \(whitePlayer.score) + \(assert_white()) != 7") fatalError() } if blackPlayer.home + blackPlayer.score + assert_black() != 7 { print("\(blackPlayer.home) + \(blackPlayer.score) + \(assert_black()) != 7") fatalError() } } private func assert_white() -> Int { var out = 0 for (key,value) in board.boardDict { if value.turn == .white { out += 1 } } return out } private func assert_black() -> Int { var out = 0 for (key,value) in board.boardDict { if value.turn == .black { out += 1 } } return out } }
mit
3a6bf924bc3fde9532ed5d17b3472ef6
27.846386
146
0.431972
4.260231
false
false
false
false
dourgulf/SwiftByProject
TaxCalculator/TaxCalculator/TaxItemView.swift
1
5560
// // TaxItemView.swift // TaxCalculator // // Created by DarwenRie on 16/3/4. // Copyright © 2016年 DarwenRie. All rights reserved. // import UIKit //@IBDesignable class TaxRateItemView: UIView, UITextFieldDelegate { var taxRateItem: TaxRateItem! { didSet { let formater = NSNumberFormatter() formater.numberStyle = .DecimalStyle self.percentInput.text = formater.stringFromNumber(self.taxRateItem.taxRate) self.updateResultLabel() self.taxRateItem.income.subscribeDidSet { (oldValue, newValue) -> Void in self.updateResultLabel() } } } var percentInput: UITextField! var percentLabel: UILabel! var resultLabel: UILabel! func setupSubviews() { let font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize()) percentInput = UITextField() percentInput.font = font percentInput.borderStyle = .RoundedRect percentInput.delegate = self self.addSubview(percentInput) percentLabel = UILabel() percentLabel.font = font percentLabel.text = "%" self.addSubview(percentLabel) resultLabel = UILabel() resultLabel.font = font self.addSubview(resultLabel) } override init(frame: CGRect) { super.init(frame: frame) self.setupSubviews() } convenience init() { self.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } override func layoutSubviews() { let size = self.bounds.size let centery = size.height/2 let inputWidth = CGFloat(40) self.percentInput.frame = CGRect(x: 0, y: 0, width: inputWidth, height: min(size.height, 22)); self.percentInput.center.y = centery self.percentLabel.sizeToFit() self.percentLabel.frame.origin = CGPoint(x: inputWidth+1, y: 0) self.percentLabel.center.y = centery let resultX = inputWidth + percentLabel.frame.size.width + 4 let resultWidth = size.width - resultX self.resultLabel.frame = CGRect(x: resultX, y: 0, width: resultWidth, height: size.height) self.resultLabel.center.y = centery } // var taxRate: Double { // let formater = NSNumberFormatter() // formater.numberStyle = .DecimalStyle // return formater.numberFromString(self.percentInput.text!) as! Double // } // // var tax: Int { // return Int(self.taxRateItem.income& * self.taxRate / 100.0) // } // // var taxRateChanged: ObservableType<Double> = ObservableType(0) func updateResultLabel() { let formater = NSNumberFormatter() formater.numberStyle = .DecimalStyle self.resultLabel.text = formater.stringFromNumber(self.taxRateItem.tax) } // // MARK: text field delegate func textFieldDidEndEditing(textField: UITextField) { self.updateResultLabel() // self.taxRateItem.taxRate = self.taxRate } } class TaxItemView: UIView { var taxModel: TaxModel! func setupModel(model: TaxModel, type: TaxRateType) { self.taxModel = model self.personalRateView.taxRateItem = model.getTaxRateItem(type, category: .Personal) self.companyRateView.taxRateItem = model.getTaxRateItem(type, category: .Company) self.typeNameLabel.text = type.labelText } var typeNameLabel: UILabel! var personalRateView: TaxRateItemView! var companyRateView: TaxRateItemView! func setupSubviews() { typeNameLabel = UILabel() typeNameLabel.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize()) self.addSubview(typeNameLabel) self.personalRateView = TaxRateItemView() // self.selfRateView.taxRateChanged.subscribeDidSet { (oldValue, newValue) -> Void in // TaxRateConfig.SaveSelfRateForType(self.typeName!, rate: self.selfTaxRate) // } self.addSubview(self.personalRateView) self.companyRateView = TaxRateItemView() // self.companyRateView.taxRateChanged.subscribeDidSet { (oldValue, newValue) -> Void in // TaxRateConfig.SaveCompanyRateForType(self.typeName!, rate: self.companyTaxRate) // } self.addSubview(self.companyRateView) } override init(frame: CGRect) { super.init(frame: frame) self.setupSubviews() } convenience init() { self.init(frame: CGRect.zero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } override func layoutSubviews() { // TODO: maybe move this code to other place let size = self.bounds self.typeNameLabel.frame = CGRect(x: 0, y: 0, width: 60, height: size.height) let centery = size.height/2 self.typeNameLabel.center.y = centery let xpos = self.typeNameLabel.bounds.width let width = (size.width - xpos) / 2 self.personalRateView.frame = CGRect(x: xpos, y: 0, width: width, height: size.height) self.personalRateView.center.y = centery self.companyRateView.frame = CGRect(x: xpos + width, y: 0, width: width, height: size.height) self.companyRateView.center.y = centery } func closeKeyboard() { self.personalRateView.percentInput.resignFirstResponder() self.companyRateView.percentInput.resignFirstResponder() } }
gpl-3.0
a25c17d932a9a955ee43a1f8de7e8213
33.515528
102
0.643153
4.175056
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/validate-binary-search-tree.swift
2
1382
/** * https://leetcode.com/problems/validate-binary-search-tree/ * * */ /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ class Solution { func isValidBST(_ root: TreeNode?) -> Bool { return isValidBSTNode(root).0 } func isValidBSTNode(_ root: TreeNode?) -> (Bool, Int?, Int?) { if let root = root { var min = root.val var max = root.val let left = isValidBSTNode(root.left) if !left.0 {return ( false, nil, nil) } if let lmax = left.2 { if lmax >= root.val { return (false, nil, nil) } } if let lmin = left.1 { min = lmin } let right = isValidBSTNode(root.right) if !right.0 {return (false, nil, nil)} if let rmin = right.1 { if rmin <= root.val { return (false, nil, nil) } } if let rmax = right.2 { max = rmax } return (true, min, max) } return (true, nil, nil) } }
mit
73607d730341e7d65a23f4d561fb0e41
25.576923
66
0.450072
3.926136
false
false
false
false
hanquochan/Charts
ChartsDemo/Classes/Components/BalloonMarker.swift
4
4473
// // BalloonMarker.swift // ChartsDemo // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import Charts open class BalloonMarker: MarkerImage { open var color: UIColor? open var arrowSize = CGSize(width: 15, height: 11) open var font: UIFont? open var textColor: UIColor? open var insets = UIEdgeInsets() open var minimumSize = CGSize() fileprivate var label: String? fileprivate var _labelSize: CGSize = CGSize() fileprivate var _paragraphStyle: NSMutableParagraphStyle? fileprivate var _drawAttributes = [String : AnyObject]() public init(color: UIColor, font: UIFont, textColor: UIColor, insets: UIEdgeInsets) { super.init() self.color = color self.font = font self.textColor = textColor self.insets = insets _paragraphStyle = NSParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle _paragraphStyle?.alignment = .center } open override func offsetForDrawing(atPoint point: CGPoint) -> CGPoint { let size = self.size var point = point point.x -= size.width / 2.0 point.y -= size.height return super.offsetForDrawing(atPoint: point) } open override func draw(context: CGContext, point: CGPoint) { guard let label = label else { return } let offset = self.offsetForDrawing(atPoint: point) let size = self.size var rect = CGRect( origin: CGPoint( x: point.x + offset.x, y: point.y + offset.y), size: size) rect.origin.x -= size.width / 2.0 rect.origin.y -= size.height context.saveGState() if let color = color { context.setFillColor(color.cgColor) context.beginPath() context.move(to: CGPoint( x: rect.origin.x, y: rect.origin.y)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width + arrowSize.width) / 2.0, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x + rect.size.width / 2.0, y: rect.origin.y + rect.size.height)) context.addLine(to: CGPoint( x: rect.origin.x + (rect.size.width - arrowSize.width) / 2.0, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y + rect.size.height - arrowSize.height)) context.addLine(to: CGPoint( x: rect.origin.x, y: rect.origin.y)) context.fillPath() } rect.origin.y += self.insets.top rect.size.height -= self.insets.top + self.insets.bottom UIGraphicsPushContext(context) label.draw(in: rect, withAttributes: _drawAttributes) UIGraphicsPopContext() context.restoreGState() } open override func refreshContent(entry: ChartDataEntry, highlight: Highlight) { setLabel(String(entry.y)) } open func setLabel(_ newLabel: String) { label = newLabel _drawAttributes.removeAll() _drawAttributes[NSFontAttributeName] = self.font _drawAttributes[NSParagraphStyleAttributeName] = _paragraphStyle _drawAttributes[NSForegroundColorAttributeName] = self.textColor _labelSize = label?.size(attributes: _drawAttributes) ?? CGSize.zero var size = CGSize() size.width = _labelSize.width + self.insets.left + self.insets.right size.height = _labelSize.height + self.insets.top + self.insets.bottom size.width = max(minimumSize.width, size.width) size.height = max(minimumSize.height, size.height) self.size = size } }
apache-2.0
e5e6b69b1eef699d1143cd363b0cc79f
32.133333
92
0.579924
4.424332
false
false
false
false
czerenkow/LublinWeather
App/Camera Permission/CameraPermissionBuilder.swift
1
793
// // CameraPermissionBuilder.swift // LublinWeather // // Created by Damian Rzeszot on 05/05/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import UIKit protocol CameraPermissionDependency: Dependency { var localizer: Localizer { get } } final class CameraPermissionBuilder: Builder<CameraPermissionDependency> { func build() -> CameraPermissionRouter { let vc = CameraPermissionViewController() let router = CameraPermissionRouter() let interactor = CameraPermissionInteractor() router.controller = vc router.interactor = interactor interactor.presenter = vc interactor.router = router vc.localizer = dependency.localizer vc.output = interactor return router } }
mit
c50cf2ec0be4ab8616afb352c064b2dd
20.405405
74
0.686869
4.95
false
false
false
false
finn-no/Finjinon
Sources/Services/LowLight/LowLightService.swift
1
1986
// // Copyright (c) 2019 FINN.no AS. All rights reserved. // import CoreMedia final class LowLightService { private let maxNumberOfResults = 3 private var results = [LightingCondition]() func getLightningCondition(from sampleBuffer: CMSampleBuffer) -> LightingCondition? { let rawMetadata = CMCopyDictionaryOfAttachments( allocator: nil, target: sampleBuffer, attachmentMode: CMAttachmentMode(kCMAttachmentMode_ShouldPropagate) ) do { let metadata = CFDictionaryCreateCopy(nil, rawMetadata) as NSDictionary let exifData: NSDictionary = try metadata.value(forKey: "{Exif}") let fNumber: Double = try exifData.value(forKey: kCGImagePropertyExifFNumber) let exposureTime: Double = try exifData.value(forKey: kCGImagePropertyExifExposureTime) let isoSpeedRatings: NSArray = try exifData.value(forKey: kCGImagePropertyExifISOSpeedRatings) guard let isoSpeedRating = isoSpeedRatings[0] as? Double else { throw MetatataError() } let explosureValue = log2((100 * fNumber * fNumber) / (exposureTime * isoSpeedRating)) let lightningCondition = LightingCondition(value: explosureValue) results.append(lightningCondition) if results.count == maxNumberOfResults + 1 { results = Array(results.dropFirst()) } return results.count > 1 && Set(results).count == 1 ? lightningCondition : nil } catch { return nil } } } // MARK: - Private types private extension NSDictionary { func value<T>(forKey key: CFString) throws -> T { return try value(forKey: key as String) } func value<T>(forKey key: String) throws -> T { guard let value = self[key] as? T else { throw MetatataError() } return value } } private struct MetatataError: Error {}
mit
c3cac6935c3bb2fbea86fcb3af931241
31.557377
106
0.635448
4.565517
false
false
false
false
sahat/github
GitHub/GitHub/AppDelegate.swift
1
7592
// // AppDelegate.swift // GitHub // // Created by Sahat Yalkabov on 9/18/14. // Copyright (c) 2014 Sahat Yalkabov. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as UINavigationController navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController let controller = masterNavigationController.topViewController as MasterViewController controller.managedObjectContext = self.managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.yahoo.GitHub" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("GitHub", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("GitHub.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
apache-2.0
7044097f0f03c8de5054b0b75681bfee
56.515152
290
0.724842
6.132472
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/Revisions/Browser/Preview/RevisionPreviewViewController.swift
2
4815
import Aztec import WordPressEditor // View Controller for the Revision Visual preview // class RevisionPreviewViewController: UIViewController, StoryboardLoadable { static var defaultStoryboardName: String = "Revisions" var revision: Revision? { didSet { showRevision() } } private let mainContext = ContextManager.sharedInstance().mainContext private let textViewManager = RevisionPreviewTextViewManager() private var titleInsets = UIEdgeInsets(top: 8.0, left: 8.0, bottom: 8.0, right: 8.0) private var textViewInsets = UIEdgeInsets(top: 0.0, left: 6.0, bottom: 0.0, right: 6.0) private lazy var textView: TextView = { let aztext = TextView(defaultFont: WPFontManager.notoRegularFont(ofSize: 16), defaultMissingImage: UIImage()) aztext.translatesAutoresizingMaskIntoConstraints = false aztext.isEditable = false return aztext }() private lazy var titleLabel: UILabel = { let label = UILabel() label.font = WPFontManager.notoBoldFont(ofSize: 24.0) label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.textAlignment = .natural return label }() override func viewDidLoad() { super.viewDidLoad() addSubviews() configureConstraints() setupAztec() } override func updateViewConstraints() { updateTitleHeight() super.updateViewConstraints() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.updateTitleHeight() }) } } private extension RevisionPreviewViewController { private func setupAztec() { textView.load(WordPressPlugin()) textView.textAttachmentDelegate = textViewManager textView.preBackgroundColor = .preformattedBackground let providers: [TextViewAttachmentImageProvider] = [ SpecialTagAttachmentRenderer(), CommentAttachmentRenderer(font: AztecPostViewController.Fonts.regular), HTMLAttachmentRenderer(font: AztecPostViewController.Fonts.regular), GutenpackAttachmentRenderer() ] providers.forEach { textView.registerAttachmentImageProvider($0) } } private func showRevision() { guard let revision = revision else { return } let predicate = NSPredicate(format: "(blog.blogID == %@ AND postID == %@)", revision.siteId, revision.postId) textViewManager.post = mainContext.firstObject(ofType: AbstractPost.self, matching: predicate) titleLabel.text = revision.postTitle ?? NSLocalizedString("Untitled", comment: "Label for an untitled post in the revision browser") let html = revision.postContent ?? "" textView.setHTML(html) updateTitleHeight() } } // Aztec editor implementation for the title Label and text view. // Like the post editor, title and content are separate views. // private extension RevisionPreviewViewController { private func addSubviews() { view.backgroundColor = .basicBackground view.addSubview(textView) textView.addSubview(titleLabel) } private func configureConstraints() { updateTitleHeight() let guide = view.readableContentGuide NSLayoutConstraint.activate([ textView.leadingAnchor.constraint(equalTo: guide.leadingAnchor), textView.trailingAnchor.constraint(equalTo: guide.trailingAnchor), textView.topAnchor.constraint(equalTo: view.topAnchor), textView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } private func updateTitleHeight() { let size = titleLabel.sizeThatFits(CGSize(width: textView.frame.width, height: CGFloat.greatestFiniteMagnitude)) titleLabel.frame = CGRect(x: 0, y: -(titleInsets.top + size.height), width: size.width, height: size.height) var contentInset = textView.contentInset contentInset.top = titleInsets.top + size.height + titleInsets.bottom textView.contentInset = contentInset textView.setContentOffset(CGPoint(x: 0, y: -textView.contentInset.top), animated: false) updateScrollInsets() } private func updateScrollInsets() { var scrollInsets = textView.contentInset var rightMargin = (view.frame.maxX - textView.frame.maxX) rightMargin -= view.safeAreaInsets.right scrollInsets.right = -rightMargin textView.scrollIndicatorInsets = scrollInsets } }
gpl-2.0
064b0c4011a081cae2fe8341f407371c
34.145985
140
0.671236
5.338137
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Tools/NotificationMediaDownloader.swift
1
9396
import Foundation import UIKit /// The purpose of this class is to provide a simple API to download assets from the web. /// Assets are downloaded, and resized to fit a maximumWidth, specified in the initial download call. /// Internally, images get downloaded and resized: both copies of the image get cached. /// Since the user may rotate the device, we also provide a second helper (resizeMediaWithIncorrectSize), /// which will take care of resizing the original image, to fit the new orientation. /// class NotificationMediaDownloader: NSObject { /// Active Download Tasks /// private let imageDownloader = ImageDownloader() /// Resize OP's will never hit the main thread /// private let resizeQueue = DispatchQueue(label: "notifications.media.resize", attributes: .concurrent) /// Original Images Cache /// private var originalImagesMap = [URL: UIImage]() /// Resized Images Cache /// private var resizedImagesMap = [URL: UIImage]() /// Collection of the URL(S) with active downloads /// private var urlsBeingDownloaded = Set<URL>() /// Failed downloads collection /// private var urlsFailed = Set<URL>() /// Downloads a set of assets, resizes them (if needed), and hits a completion block. /// The completion block will get called just once all of the assets are downloaded, and properly sized. /// /// - Parameters: /// - urls: Is the collection of unique Image URL's we'd need to download. /// - maximumWidth: Represents the maximum width that a returned image should have. /// - completion: Is a closure that will get executed once all of the assets are ready /// func downloadMedia(urls: Set<URL>, maximumWidth: CGFloat, completion: @escaping () -> Void) { let missingUrls = urls.filter { self.shouldDownloadImage(url: $0) } let group = DispatchGroup() let shouldHitCompletion = !missingUrls.isEmpty for url in missingUrls { group.enter() downloadImage(url) { (error, image) in guard let image = image else { group.leave() return } // On success: Cache the original image, and resize (if needed) self.originalImagesMap[url] = image self.resizeImageIfNeeded(image, maximumWidth: maximumWidth) { self.resizedImagesMap[url] = $0 group.leave() } } } // When all of the workers are ready, hit the completion callback, *if needed* if !shouldHitCompletion { return } group.notify(queue: .main) { completion() } } /// Resizes the downloaded media to fit a "new" maximumWidth ***if needed**. /// This method will check the cache of "resized images", and will verify if the original image *could* /// be resized again, so that it better fits the *maximumWidth* received. /// Once all of the images get resized, we'll hit the completion block /// /// Useful to handle rotation events: the downloaded images may need to be resized, again, to fit onscreen. /// /// - Parameters: /// - maximumWidth: Represents the maximum width that a returned image should have /// - completion: Is a closure that will get executed just one time, after all of the assets get resized /// func resizeMediaWithIncorrectSize(_ maximumWidth: CGFloat, completion: @escaping () -> Void) { let group = DispatchGroup() var shouldHitCompletion = false for (url, originalImage) in originalImagesMap { let targetSize = cappedImageSize(originalImage.size, maximumWidth: maximumWidth) let resizedImage = resizedImagesMap[url] if resizedImage == nil || resizedImage?.size == targetSize || resizedImage as? AnimatedImageWrapper != nil { continue } group.enter() shouldHitCompletion = true resizeImageIfNeeded(originalImage, maximumWidth: maximumWidth) { self.resizedImagesMap[url] = $0 group.leave() } } group.notify(queue: .main) { if shouldHitCompletion { completion() } } } /// Returns a collection of images, ready to be displayed onscreen. /// For convenience, we return a map with URL as Key, and Image as Value, so that each asset can be easily /// addressed. /// /// - Parameter urls: The collection of URL's of the assets you'd need. /// /// - Returns: A dictionary with URL as Key, and Image as Value. /// func imagesForUrls(_ urls: [URL]) -> [URL: UIImage] { var filtered = [URL: UIImage]() for (url, image) in resizedImagesMap where urls.contains(url) { filtered[url] = image } return filtered } // MARK: - Private Helpers /// Downloads an asset, given its URL. /// - Note: On failure, this method will attempt the download *maximumRetryCount* times. /// If the URL cannot be downloaded, it'll be marked to be skipped. /// /// - Parameters: /// - url: The URL of the media we should download /// - retryCount: Number of times the download has been attempted /// - success: A closure to be executed, on success. /// private func downloadImage(_ url: URL, retryCount: Int = 0, completion: @escaping (Error?, UIImage?) -> Void) { guard retryCount < Constants.maximumRetryCount else { completion(NotificationMediaError.retryCountExceeded, nil) urlsBeingDownloaded.remove(url) urlsFailed.insert(url) return } imageDownloader.downloadImage(at: url) { (image, error) in guard let image = image else { self.downloadImage(url, retryCount: retryCount + 1, completion: completion) return } completion(nil, image) self.urlsBeingDownloaded.remove(url) } urlsBeingDownloaded.insert(url) } /// Checks if an image should be downloaded, or not. An image should be downloaded if: /// /// - It's not already being downloaded /// - Isn't already in the cache! /// - Hasn't exceeded the retry count /// /// - Parameter urls: The collection of URL's of the assets you'd need. /// /// - Returns: A dictionary with URL as Key, and Image as Value. /// private func shouldDownloadImage(url: URL) -> Bool { return originalImagesMap[url] == nil && !urlsBeingDownloaded.contains(url) && !urlsFailed.contains(url) } /// Resizes -in background- a given image, if needed, to fit a maximum width /// /// - Parameters: /// - image: The image to resize /// - maximumWidth: The maximum width in which the image should fit /// - callback: A closure to be called, on the main thread, on completion /// private func resizeImageIfNeeded(_ image: UIImage, maximumWidth: CGFloat, callback: @escaping (UIImage) -> Void) { // Animated images aren't actually resized, so return the image itself if we've already recorded the target size if let animatedImage = image as? AnimatedImageWrapper, animatedImage.targetSize != nil { callback(animatedImage) return } let targetSize = cappedImageSize(image.size, maximumWidth: maximumWidth) if image.size == targetSize { callback(image) return } resizeQueue.async { let resizedImage: UIImage? // If we try to resize the animate image it will lose all of its frames // Instead record the target size so we can properly set the bounds of the view later if let animatedImage = image as? AnimatedImageWrapper, animatedImage.gifData != nil { animatedImage.targetSize = targetSize resizedImage = animatedImage } else { resizedImage = image.resizedImage(targetSize, interpolationQuality: .high) } DispatchQueue.main.async { callback(resizedImage!) } } } /// Returns the scaled size, scaled down proportionally (if needed) to fit a maximumWidth /// /// - Parameters: /// - originalSize: The original size of the image /// - maximumWidth: The maximum width we've got available /// /// - Returns: The size, scaled down proportionally (if needed) to fit a maximum width /// private func cappedImageSize(_ originalSize: CGSize, maximumWidth: CGFloat) -> CGSize { var targetSize = originalSize if targetSize.width > maximumWidth { targetSize.height = round(maximumWidth * targetSize.height / targetSize.width) targetSize.width = maximumWidth } return targetSize } } // MARK: - Settings // private extension NotificationMediaDownloader { struct Constants { static let maximumRetryCount = 3 } } // MARK: - Errors // enum NotificationMediaError: Error { case retryCountExceeded }
gpl-2.0
d3ff75f8b8172ffedd7878f4e1040921
35.138462
120
0.613985
4.940063
false
false
false
false
elpassion/el-space-ios
ELSpaceTests/TestCases/Coordinators/SelectionCoordinatorSpec.swift
1
2063
import Quick import Nimble @testable import ELSpace class SelectionCoordinatorSpec: QuickSpec { override func spec() { describe("SelectionCoordinator") { var sut: SelectionCoordinator! var selectionViewControllerStub: SelectionViewControllerStub! var selectionScreenPresenterMock: SelectionScreenPresenterMock! var viewControllerFake: UIViewController! var hubSession: HubSession! beforeEach { hubSession = HubSession() selectionViewControllerStub = SelectionViewControllerStub() selectionScreenPresenterMock = SelectionScreenPresenterMock() viewControllerFake = UIViewController() sut = SelectionCoordinator(viewController: viewControllerFake, selectionViewController: selectionViewControllerStub, selectionScreenPresenter: selectionScreenPresenterMock, hubSession: hubSession) } it("should have correrct initial view controller") { expect(sut.initialViewController).to(equal(viewControllerFake)) } afterEach { selectionViewControllerStub = nil selectionScreenPresenterMock = nil hubSession = nil viewControllerFake = nil sut = nil } context("when selection view controller emit openHubWithToken next event") { beforeEach { selectionViewControllerStub.openHubWithTokenSubject.onNext("fake_token") } it("should call presentHub") { expect(selectionScreenPresenterMock.didCallPresentHub).to(beTrue()) } it("should hubSession have correct token") { expect(hubSession.accessToken).to(equal("fake_token")) } } } } }
gpl-3.0
f6ae4b7021d23e77131c745d8383a784
35.839286
98
0.572467
6.71987
false
false
false
false
VoIPGRID/vialer-ios
Vialer/Calling/SIP/Controllers/SecondCallViewController.swift
1
7737
// // SecondCallViewController.swift // Copyright © 2016 VoIPGRID. All rights reserved. // private var myContext = 0 class SecondCallViewController: SIPCallingViewController { // MARK: - Configuration enum SecondCallVCSegue : String { // TODO: find a way to handle subclassed ViewControllers with SegueHandler. case transferInProgress = "TransferInProgressSegue" case unwindToFirstCall = "UnwindToFirstCallSegue" case showKeypad = "ShowKeypadSegue" case unwindToActiveCall = "UnwindToActiveCall" } // MARK: - Properties private var firstCallObserversWereSet = false var firstCall: VSLCall? { didSet { guard let call = firstCall else { return } call.addObserver(self, forKeyPath: "callState", options: .new, context: &myContext) call.addObserver(self, forKeyPath: "mediaState", options: .new, context: &myContext) firstCallObserversWereSet = true updateUI() } } var firstCallPhoneNumberLabelText: String? { didSet { updateUI() } } // MARK: - Outlets @IBOutlet weak var firstCallNumberLabel: UILabel! @IBOutlet weak var firstCallStatusLabel: UILabel! } // MARK: - Lifecycle extension SecondCallViewController{ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) VialerGAITracker.trackScreenForController(name: controllerName) UIDevice.current.isProximityMonitoringEnabled = true updateUI() startConnectDurationTimer() } override func viewWillDisappear(_ animated: Bool) { UIDevice.current.isProximityMonitoringEnabled = false if firstCallObserversWereSet { firstCall?.removeObserver(self, forKeyPath: "callState") firstCall?.removeObserver(self, forKeyPath: "mediaState") firstCallObserversWereSet = false } super.viewWillDisappear(animated) } } // MARK: - Actions extension SecondCallViewController { override func transferButtonPressed(_ sender: SipCallingButton) { guard let firstCall = firstCall, firstCall.callState == .confirmed, let secondCall = activeCall, firstCall.callState == .confirmed else { return } if firstCall.transfer(to: secondCall) { callManager.end(firstCall) { error in if error != nil { VialerLogError("Error hanging up call: \(String(describing: error))") } } callManager.end(secondCall) { error in if error != nil { VialerLogError("Error hanging up call: \(String(describing: error))") } } DispatchQueue.main.async { self.performSegue(withIdentifier: SecondCallVCSegue.transferInProgress.rawValue, sender: nil) } } } @IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) { guard let activeCall = activeCall, activeCall.callState != .disconnected else { DispatchQueue.main.async { self.performSegue(withIdentifier: SecondCallVCSegue.unwindToFirstCall.rawValue, sender: nil) } return } // If current call is not disconnected, hangup the call. callManager.end(activeCall) { error in if error != nil { VialerLogError("Error hanging up call: \(String(describing: error))") } else { DispatchQueue.main.async { self.performSegue(withIdentifier: SecondCallVCSegue.unwindToFirstCall.rawValue, sender: nil) } } } } } // MARK: - Helper functions extension SecondCallViewController { override func updateUI() { DispatchQueue.main.async { super.updateUI() // Only enable transferButton if both calls are confirmed. self.transferButton?.isEnabled = self.activeCall?.callState == .confirmed && self.firstCall?.callState == .confirmed self.firstCallNumberLabel?.text = self.firstCallPhoneNumberLabelText self.numberLabel?.isHidden = false if self.statusLabelTopConstraint != nil { self.statusLabelTopConstraint.constant = 20 } guard let call = self.firstCall else { return } if call.callState == .disconnected { self.firstCallStatusLabel?.text = NSLocalizedString("Disconnected", comment: "Disconnected phone state") } else { self.firstCallStatusLabel?.text = NSLocalizedString("On hold", comment: "On hold") } } } // Don't present wifi notification on second call. override func shouldPresentWiFiNotification() -> Bool { return false } } // MARK: - Segues extension SecondCallViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch SecondCallVCSegue(rawValue: segue.identifier!)! { case .transferInProgress: let transferInProgressVC = segue.destination as! TransferInProgressViewController transferInProgressVC.firstCall = firstCall transferInProgressVC.firstCallPhoneNumberLabelText = firstCallPhoneNumberLabelText transferInProgressVC.currentCall = activeCall transferInProgressVC.currentCallPhoneNumberLabelText = phoneNumberLabelText case .unwindToFirstCall: let firstCallVC = segue.destination as! SIPCallingViewController firstCallVC.activeCall = firstCall firstCallVC.phoneNumberLabelText = firstCallPhoneNumberLabelText case .showKeypad: let keypadVC = segue.destination as! KeypadViewController keypadVC.call = activeCall keypadVC.delegate = self keypadVC.phoneNumberLabelText = phoneNumberLabelText case .unwindToActiveCall: let firstCallVC = segue.destination as! SIPCallingViewController firstCallVC.activeCall = activeCall firstCallVC.phoneNumberLabelText = phoneNumberLabelText } } } // MARK: - KVO extension SecondCallViewController { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // If the first call is disconnected and the second call is in progress, unwind to CallViewController. // In prepare the second call will be set as the activeCall. if let call = object as? VSLCall, call == firstCall && call.callState == .disconnected && call.transferStatus == .unkown, let activeCall = activeCall, activeCall.callState != .null { DispatchQueue.main.async { [weak self] in self?.performSegue(withIdentifier: SecondCallVCSegue.unwindToActiveCall.rawValue, sender: nil) } return } if context == &myContext { DispatchQueue.main.async { [weak self] in if let call = self?.activeCall, keyPath == #keyPath(activeCall.callState) && call.callState == .disconnected && self?.firstCall?.transferStatus != .unkown { // If the transfer is in progress, the active call will be Disconnected. Perform the segue. self?.performSegue(withIdentifier: SecondCallVCSegue.transferInProgress.rawValue, sender: nil) } self?.updateUI() } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
gpl-3.0
90e3677f265500991afe5b5b138082c4
39.291667
173
0.638831
5.153897
false
false
false
false
cqix/icf
app/icf/icf/AboutViewController.swift
1
3669
// // AboutViewController.swift // icf // // Created by Patrick Gröller, Christian Koller, Helmut Kopf on 22.10.15. // Copyright © 2015 FH. All rights reserved. // // shows the route to Kapfenberg import UIKit import MapKit class AboutViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! let initialLocation = CLLocation(latitude: 47.453877, longitude: 15.331709) let regionRadius: CLLocationDistance = 1000 let locationManager = CLLocationManager() let request = MKDirectionsRequest() //let geocoder = CLGeocoder() func centerMapOnLocation(location: CLLocation, _ title: String, _ subtitle: String, var _ distance: CLLocationDistance?) { if distance==nil { distance = regionRadius * 4.0; } let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, distance!, distance!) mapView.setRegion(coordinateRegion, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) annotation.title = title annotation.subtitle = subtitle mapView.addAnnotation(annotation) } override func viewDidLoad() { centerMapOnLocation(initialLocation, "FH-Joanneum Kapfenberg", "Developers location", nil) mapView.delegate = self self.locationManager.requestWhenInUseAuthorization() if (CLLocationManager.locationServicesEnabled()) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let distance = manager.location?.distanceFromLocation(initialLocation) centerMapOnLocation(manager.location!, "You", "Your current location", distance!*2.1) //geocoder.reverseGeocodeLocation(initialLocation, completionHandler: { // //}) let source_place = MKPlacemark(coordinate: CLLocationCoordinate2DMake(manager.location!.coordinate.latitude, manager.location!.coordinate.longitude), addressDictionary: nil) request.source = MKMapItem(placemark: source_place) let target_place = MKPlacemark(coordinate: CLLocationCoordinate2DMake(initialLocation.coordinate.latitude, initialLocation.coordinate.longitude), addressDictionary: nil) request.destination = MKMapItem(placemark: target_place) request.requestsAlternateRoutes = false let directions = MKDirections(request: request) directions.calculateDirectionsWithCompletionHandler({(response: MKDirectionsResponse?, error: NSError?) -> Void in if error != nil { // Handle error } else { self.showRoute(response!) } }) } func showRoute(response: MKDirectionsResponse) { for route in response.routes { mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads) } } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.blueColor() renderer.lineWidth = 5.0 return renderer } }
gpl-2.0
88bf2d6e88fa65d89487fbf51618ed9a
37.197917
181
0.665394
5.702955
false
false
false
false
Desgard/Guardia-Swift-Server
src/Sources/App/main.swift
1
1053
import Vapor import Foundation let drop = Droplet() drop.get{ req in return try drop.view.make("welcome", [ "message": drop.localization[req.lang, "welcome", "title"] ]) } drop.get("index") { request in return try drop.view.make("index", [ ]) } drop.post("post") { request in guard let codeText = request.data["codeText"]?.string else { throw Abort.badRequest } guard let timestamp = request.data["timestamp"]?.string else { throw Abort.badRequest } var codefile: CodeFile = CodeFile(code: codeText, timestamp: timestamp) codefile.creatFile() let retLog: String = codefile.runFile() return try JSON(node: [ "result": "success", "data": retLog, ]) } drop.post("release-log") { request in guard let rellog = request.data["log"]?.string else { throw Abort.badRequest } return try JSON(node: [ "result": "success", "data": rellog, ]) } drop.resource("posts", PostController()) drop.run()
mit
f45bce20492b851a4b0d36a5d9220cd9
20.06
75
0.598291
3.774194
false
false
false
false
gaurav1981/BluetoothKit
Example/Vendor/CryptoSwift/CryptoSwift/NSDataExtension.swift
11
2785
// // PGPDataExtension.swift // SwiftPGP // // Created by Marcin Krzyzanowski on 05/07/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation extension NSMutableData { /** Convenient way to append bytes */ internal func appendBytes(arrayOfBytes: [UInt8]) { self.appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } extension NSData { public func checksum() -> UInt16 { var s:UInt32 = 0; var bytesArray = self.arrayOfBytes() for (var i = 0; i < bytesArray.count; i++) { _ = bytesArray[i] s = s + UInt32(bytesArray[i]) } s = s % 65536; return UInt16(s); } public func md5() -> NSData? { return Hash.md5(self).calculate() } public func sha1() -> NSData? { return Hash.sha1(self).calculate() } public func sha224() -> NSData? { return Hash.sha224(self).calculate() } public func sha256() -> NSData? { return Hash.sha256(self).calculate() } public func sha384() -> NSData? { return Hash.sha384(self).calculate() } public func sha512() -> NSData? { return Hash.sha512(self).calculate() } public func crc32() -> NSData? { return Hash.crc32(self).calculate() } public func encrypt(cipher: Cipher) throws -> NSData? { let encrypted = try cipher.encrypt(self.arrayOfBytes()) return NSData.withBytes(encrypted) } public func decrypt(cipher: Cipher) throws -> NSData? { let decrypted = try cipher.decrypt(self.arrayOfBytes()) return NSData.withBytes(decrypted) } public func authenticate(authenticator: Authenticator) -> NSData? { if let result = authenticator.authenticate(self.arrayOfBytes()) { return NSData.withBytes(result) } return nil } } extension NSData { public var hexString: String { return self.toHexString() } func toHexString() -> String { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) var s:String = ""; for byte in bytesArray { s = s + String(format:"%02x", byte) } return s } public func arrayOfBytes() -> [UInt8] { let count = self.length / sizeof(UInt8) var bytesArray = [UInt8](count: count, repeatedValue: 0) self.getBytes(&bytesArray, length:count * sizeof(UInt8)) return bytesArray } class public func withBytes(bytes: [UInt8]) -> NSData { return NSData(bytes: bytes, length: bytes.count) } }
mit
29e63554149603652cfd2db4db70e5fa
24.318182
73
0.584201
4.219697
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Mesh/StepGetEthernetFeatureStatus.swift
1
1582
// // Created by Raimundas Sakalauskas on 2019-03-04. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class StepGetEthernetFeatureStatus: Gen3SetupStep { override func start() { guard let context = self.context else { return } if context.targetDevice.ethernetDetectionFeature == nil { self.getFeatureFlag() } else { self.stepCompleted() } } private func getFeatureFlag() { guard let context = self.context else { return } context.targetDevice.transceiver?.sendGetFeature(feature: .ethernetDetection) { [weak self, weak context] result, enabled in guard let self = self, let context = context, !context.canceled else { return } self.log("targetDevice.sendGetFeature: \(result.description()) enabled: \(enabled as Optional)") if (result == .NONE) { context.targetDevice.ethernetDetectionFeature = enabled! self.start() } else if (result == .NOT_SUPPORTED) { context.targetDevice.ethernetDetectionFeature = false self.stepCompleted() } else { self.handleBluetoothErrorResult(result) } } } override func rewindTo(context: Gen3SetupContext) { super.rewindTo(context: context) guard let context = self.context else { return } context.targetDevice.ethernetDetectionFeature = nil } }
apache-2.0
e3fc4b96777c8d57f6c4e03acbe3493c
27.25
132
0.585967
4.990536
false
false
false
false
VladiMihaylenko/omim
iphone/Maps/Classes/CarPlay/CarPlayService.swift
1
27121
import CarPlay import Contacts @available(iOS 12.0, *) @objc(MWMCarPlayService) final class CarPlayService: NSObject { @objc static let shared = CarPlayService() @objc var isCarplayActivated: Bool = false private var searchService: CarPlaySearchService? private var router: CarPlayRouter? private var window: CPWindow? private var interfaceController: CPInterfaceController? private var sessionConfiguration: CPSessionConfiguration? var currentPositionMode: MWMMyPositionMode = .pendingPosition var isSpeedCamActivated: Bool { set { router?.updateSpeedCameraMode(newValue ? .always: .never) } get { let mode: SpeedCameraManagerMode = router?.speedCameraMode ?? .never return mode == .always ? true : false } } var isKeyboardLimited: Bool { return sessionConfiguration?.limitedUserInterfaces.contains(.keyboard) ?? false } private var carplayVC: CarPlayMapViewController? { return window?.rootViewController as? CarPlayMapViewController } private var rootMapTemplate: CPMapTemplate? { return interfaceController?.rootTemplate as? CPMapTemplate } var preparedToPreviewTrips: [CPTrip] = [] @objc func setup(window: CPWindow, interfaceController: CPInterfaceController) { isCarplayActivated = true self.window = window self.interfaceController = interfaceController self.interfaceController?.delegate = self sessionConfiguration = CPSessionConfiguration(delegate: self) searchService = CarPlaySearchService() let router = CarPlayRouter() router.addListener(self) router.subscribeToEvents() router.setupCarPlaySpeedCameraMode() self.router = router MWMRouter.unsubscribeFromEvents() applyRootViewController() if let sessionData = router.restoredNavigationSession() { applyNavigationRootTemplate(trip: sessionData.0, routeInfo: sessionData.1) } else { applyBaseRootTemplate() router.restoreTripPreviewOnCarplay(beforeRootTemplateDidAppear: true) } ThemeManager.invalidate() } @objc func destroy() { if let carplayVC = carplayVC { carplayVC.removeMapView() } MapViewController.shared()?.disableCarPlayRepresentation() MapViewController.shared()?.remove(self) router?.removeListener(self) router?.unsubscribeFromEvents() router?.setupInitialSpeedCameraMode() MWMRouter.subscribeToEvents() isCarplayActivated = false if router?.currentTrip != nil { MWMRouter.showNavigationMapControls() } else if router?.previewTrip != nil { MWMRouter.rebuild(withBestRouter: true) } searchService = nil router = nil sessionConfiguration = nil interfaceController = nil ThemeManager.invalidate() } @objc func interfaceStyle() -> UIUserInterfaceStyle { if let window = window, window.traitCollection.userInterfaceIdiom == .carPlay { return window.traitCollection.userInterfaceStyle } return .unspecified } private func applyRootViewController() { guard let window = window else { return } let carplaySotyboard = UIStoryboard.instance(.carPlay) let carplayVC = carplaySotyboard.instantiateInitialViewController() as! CarPlayMapViewController window.rootViewController = carplayVC if let mapVC = MapViewController.shared() { currentPositionMode = mapVC.currentPositionMode mapVC.enableCarPlayRepresentation() carplayVC.addMapView(mapVC.mapView, mapButtonSafeAreaLayoutGuide: window.mapButtonSafeAreaLayoutGuide) mapVC.add(self) } } private func applyBaseRootTemplate() { let mapTemplate = MapTemplateBuilder.buildBaseTemplate(positionMode: currentPositionMode) mapTemplate.mapDelegate = self interfaceController?.setRootTemplate(mapTemplate, animated: true) } private func applyNavigationRootTemplate(trip: CPTrip, routeInfo: RouteInfo) { let mapTemplate = MapTemplateBuilder.buildNavigationTemplate() mapTemplate.mapDelegate = self interfaceController?.setRootTemplate(mapTemplate, animated: true) router?.startNavigationSession(forTrip: trip, template: mapTemplate) if let estimates = createEstimates(routeInfo: routeInfo) { mapTemplate.updateEstimates(estimates, for: trip) } if let carplayVC = carplayVC { carplayVC.updateCurrentSpeed(routeInfo.speed) carplayVC.showSpeedControl() } } func pushTemplate(_ templateToPush: CPTemplate, animated: Bool) { if let interfaceController = interfaceController { switch templateToPush { case let list as CPListTemplate: list.delegate = self case let search as CPSearchTemplate: search.delegate = self case let map as CPMapTemplate: map.mapDelegate = self default: break } interfaceController.pushTemplate(templateToPush, animated: animated) } } func popTemplate(animated: Bool) { interfaceController?.popTemplate(animated: animated) } func cancelCurrentTrip() { router?.cancelTrip() if let carplayVC = carplayVC { carplayVC.hideSpeedControl() } updateMapTemplateUIToBase() } func updateCameraUI(isCameraOnRoute: Bool, speedLimit limit: String?) { if let carplayVC = carplayVC { let speedLimit = limit == nil ? nil : Int(limit!) carplayVC.updateCameraInfo(isCameraOnRoute: isCameraOnRoute, speedLimit: speedLimit) } } func updateMapTemplateUIToBase() { guard let mapTemplate = rootMapTemplate else { return } MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate) if currentPositionMode == .pendingPosition { mapTemplate.leadingNavigationBarButtons = [] } else if currentPositionMode == .follow || currentPositionMode == .followAndRotate { MapTemplateBuilder.setupDestinationButton(mapTemplate: mapTemplate) } else { MapTemplateBuilder.setupRecenterButton(mapTemplate: mapTemplate) } updateVisibleViewPortState(.default) } func updateMapTemplateUIToTripFinished(_ trip: CPTrip) { guard let mapTemplate = rootMapTemplate else { return } mapTemplate.leadingNavigationBarButtons = [] mapTemplate.trailingNavigationBarButtons = [] mapTemplate.mapButtons = [] let doneAction = CPAlertAction(title: L("done"), style: .cancel) { [unowned self] _ in self.updateMapTemplateUIToBase() } var subtitle = "" if let locationName = trip.destination.name { subtitle = locationName } if let address = trip.destination.placemark.addressDictionary?[CNPostalAddressStreetKey] as? String { subtitle = subtitle + "\n" + address } let alert = CPNavigationAlert(titleVariants: [L("trip_finished")], subtitleVariants: [subtitle], imageSet: nil, primaryAction: doneAction, secondaryAction: nil, duration: 0) mapTemplate.present(navigationAlert: alert, animated: true) } func updateVisibleViewPortState(_ state: CPViewPortState) { guard let carplayVC = carplayVC else { return } carplayVC.updateVisibleViewPortState(state) } func updateRouteAfterChangingSettings() { router?.rebuildRoute() } @objc func showNoMapAlert() { guard let mapTemplate = interfaceController?.topTemplate as? CPMapTemplate, let info = mapTemplate.userInfo as? MapInfo, info.type == CPConstants.TemplateType.main else { return } let alert = CPAlertTemplate(titleVariants: [L("download_map_carplay")], actions: []) alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.downloadMap] interfaceController?.dismissTemplate(animated: true) interfaceController?.presentTemplate(alert, animated: true) } @objc func hideNoMapAlert() { if let presentedTemplate = interfaceController?.presentedTemplate, let info = presentedTemplate.userInfo as? [String: String], let alertType = info[CPConstants.TemplateKey.alert], alertType == CPConstants.TemplateType.downloadMap { interfaceController?.dismissTemplate(animated: true) } } } // MARK: - CPInterfaceControllerDelegate implementation @available(iOS 12.0, *) extension CarPlayService: CPInterfaceControllerDelegate { func templateWillAppear(_ aTemplate: CPTemplate, animated: Bool) { guard let info = aTemplate.userInfo as? MapInfo else { return } switch info.type { case CPConstants.TemplateType.main: updateVisibleViewPortState(.default) case CPConstants.TemplateType.preview: updateVisibleViewPortState(.preview) case CPConstants.TemplateType.navigation: updateVisibleViewPortState(.navigation) case CPConstants.TemplateType.previewSettings: aTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.preview) default: break } } func templateDidAppear(_ aTemplate: CPTemplate, animated: Bool) { guard let mapTemplate = aTemplate as? CPMapTemplate, let info = aTemplate.userInfo as? MapInfo else { return } if !preparedToPreviewTrips.isEmpty && info.type == CPConstants.TemplateType.main { preparePreview(trips: preparedToPreviewTrips) preparedToPreviewTrips = [] return } if info.type == CPConstants.TemplateType.preview, let trips = info.trips { showPreview(mapTemplate: mapTemplate, trips: trips) } } func templateWillDisappear(_ aTemplate: CPTemplate, animated: Bool) { guard let info = aTemplate.userInfo as? MapInfo else { return } if info.type == CPConstants.TemplateType.preview { router?.completeRouteAndRemovePoints() } } func templateDidDisappear(_ aTemplate: CPTemplate, animated: Bool) { guard !preparedToPreviewTrips.isEmpty, let info = aTemplate.userInfo as? [String: String], let alertType = info[CPConstants.TemplateKey.alert], alertType == CPConstants.TemplateType.redirectRoute || alertType == CPConstants.TemplateType.restoreRoute else { return } preparePreview(trips: preparedToPreviewTrips) preparedToPreviewTrips = [] } } // MARK: - CPSessionConfigurationDelegate implementation @available(iOS 12.0, *) extension CarPlayService: CPSessionConfigurationDelegate { func sessionConfiguration(_ sessionConfiguration: CPSessionConfiguration, limitedUserInterfacesChanged limitedUserInterfaces: CPLimitableUserInterface) { } } // MARK: - CPMapTemplateDelegate implementation @available(iOS 12.0, *) extension CarPlayService: CPMapTemplateDelegate { public func mapTemplateDidShowPanningInterface(_ mapTemplate: CPMapTemplate) { MapTemplateBuilder.configurePanUI(mapTemplate: mapTemplate) FrameworkHelper.stopLocationFollow() } public func mapTemplateWillDismissPanningInterface(_ mapTemplate: CPMapTemplate) { if let info = mapTemplate.userInfo as? MapInfo, info.type == CPConstants.TemplateType.navigation { MapTemplateBuilder.configureNavigationUI(mapTemplate: mapTemplate) } else { MapTemplateBuilder.configureBaseUI(mapTemplate: mapTemplate) } FrameworkHelper.switchMyPositionMode() } func mapTemplate(_ mapTemplate: CPMapTemplate, panEndedWith direction: CPMapTemplate.PanDirection) { var offset = UIOffset(horizontal: 0.0, vertical: 0.0) let offsetStep: CGFloat = 0.25 if direction.contains(.up) { offset.vertical -= offsetStep } if direction.contains(.down) { offset.vertical += offsetStep } if direction.contains(.left) { offset.horizontal += offsetStep } if direction.contains(.right) { offset.horizontal -= offsetStep } FrameworkHelper.moveMap(offset) } func mapTemplate(_ mapTemplate: CPMapTemplate, panWith direction: CPMapTemplate.PanDirection) { var offset = UIOffset(horizontal: 0.0, vertical: 0.0) let offsetStep: CGFloat = 0.1 if direction.contains(.up) { offset.vertical -= offsetStep } if direction.contains(.down) { offset.vertical += offsetStep } if direction.contains(.left) { offset.horizontal += offsetStep } if direction.contains(.right) { offset.horizontal -= offsetStep } FrameworkHelper.moveMap(offset) } func mapTemplate(_ mapTemplate: CPMapTemplate, startedTrip trip: CPTrip, using routeChoice: CPRouteChoice) { guard let info = routeChoice.userInfo as? RouteInfo else { if let info = routeChoice.userInfo as? [String: Any], let code = info[CPConstants.Trip.errorCode] as? RouterResultCode, let countries = info[CPConstants.Trip.missedCountries] as? [String] { showErrorAlert(code: code, countries: countries) } return } mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.previewAccepted) mapTemplate.hideTripPreviews() guard let router = router, let interfaceController = interfaceController, let rootMapTemplate = rootMapTemplate else { return } MapTemplateBuilder.configureNavigationUI(mapTemplate: rootMapTemplate) interfaceController.popToRootTemplate(animated: false) router.startNavigationSession(forTrip: trip, template: rootMapTemplate) router.startRoute() if let estimates = createEstimates(routeInfo: info) { rootMapTemplate.updateEstimates(estimates, for: trip) } if let carplayVC = carplayVC { carplayVC.updateCurrentSpeed(info.speed) carplayVC.showSpeedControl() } updateVisibleViewPortState(.navigation) } func mapTemplate(_ mapTemplate: CPMapTemplate, displayStyleFor maneuver: CPManeuver) -> CPManeuverDisplayStyle { if let type = maneuver.userInfo as? String, type == CPConstants.Maneuvers.secondary { return .trailingSymbol } return .leadingSymbol } func mapTemplate(_ mapTemplate: CPMapTemplate, selectedPreviewFor trip: CPTrip, using routeChoice: CPRouteChoice) { guard let previewTrip = router?.previewTrip, previewTrip == trip else { applyUndefinedEstimates(template: mapTemplate, trip: trip) router?.buildRoute(trip: trip) return } guard let info = routeChoice.userInfo as? RouteInfo, let estimates = createEstimates(routeInfo: info) else { applyUndefinedEstimates(template: mapTemplate, trip: trip) return } mapTemplate.updateEstimates(estimates, for: trip) } } // MARK: - CPListTemplateDelegate implementation @available(iOS 12.0, *) extension CarPlayService: CPListTemplateDelegate { func listTemplate(_ listTemplate: CPListTemplate, didSelect item: CPListItem, completionHandler: @escaping () -> Void) { if let userInfo = item.userInfo as? ListItemInfo { switch userInfo.type { case CPConstants.ListItemType.history: let locale = window?.textInputMode?.primaryLanguage ?? "en" guard let searchService = searchService else { completionHandler() return } searchService.searchText(item.text ?? "", forInputLocale: locale, completionHandler: { [weak self] results in guard let self = self else { return } let template = ListTemplateBuilder.buildListTemplate(for: .searchResults(results: results)) completionHandler() self.pushTemplate(template, animated: true) }) case CPConstants.ListItemType.bookmarkLists where userInfo.metadata is CategoryInfo: let metadata = userInfo.metadata as! CategoryInfo let template = ListTemplateBuilder.buildListTemplate(for: .bookmarks(category: metadata.category)) completionHandler() pushTemplate(template, animated: true) case CPConstants.ListItemType.bookmarks where userInfo.metadata is BookmarkInfo: let metadata = userInfo.metadata as! BookmarkInfo let bookmark = MWMCarPlayBookmarkObject(bookmarkId: metadata.bookmarkId) preparePreview(forBookmark: bookmark) completionHandler() case CPConstants.ListItemType.searchResults where userInfo.metadata is SearchResultInfo: let metadata = userInfo.metadata as! SearchResultInfo preparePreviewForSearchResults(selectedRow: metadata.originalRow) completionHandler() default: completionHandler() } } } } // MARK: - CPSearchTemplateDelegate implementation @available(iOS 12.0, *) extension CarPlayService: CPSearchTemplateDelegate { func searchTemplate(_ searchTemplate: CPSearchTemplate, updatedSearchText searchText: String, completionHandler: @escaping ([CPListItem]) -> Void) { let locale = window?.textInputMode?.primaryLanguage ?? "en" guard let searchService = searchService else { completionHandler([]) return } searchService.searchText(searchText, forInputLocale: locale, completionHandler: { results in var items = [CPListItem]() for object in results { let item = CPListItem(text: object.title, detailText: object.address) item.userInfo = ListItemInfo(type: CPConstants.ListItemType.searchResults, metadata: SearchResultInfo(originalRow: object.originalRow)) items.append(item) } completionHandler(items) }) } func searchTemplate(_ searchTemplate: CPSearchTemplate, selectedResult item: CPListItem, completionHandler: @escaping () -> Void) { searchService?.saveLastQuery() if let info = item.userInfo as? ListItemInfo, let metadata = info.metadata as? SearchResultInfo { preparePreviewForSearchResults(selectedRow: metadata.originalRow) } completionHandler() } } // MARK: - CarPlayRouterListener implementation @available(iOS 12.0, *) extension CarPlayService: CarPlayRouterListener { func didCreateRoute(routeInfo: RouteInfo, trip: CPTrip) { guard let currentTemplate = interfaceController?.topTemplate as? CPMapTemplate, let info = currentTemplate.userInfo as? MapInfo, info.type == CPConstants.TemplateType.preview else { return } if let estimates = createEstimates(routeInfo: routeInfo) { currentTemplate.updateEstimates(estimates, for: trip) } } func didUpdateRouteInfo(_ routeInfo: RouteInfo, forTrip trip: CPTrip) { if let carplayVC = carplayVC { carplayVC.updateCurrentSpeed(routeInfo.speed) } guard let router = router, let template = rootMapTemplate else { return } router.updateUpcomingManeuvers() if let estimates = createEstimates(routeInfo: routeInfo) { template.updateEstimates(estimates, for: trip) } trip.routeChoices.first?.userInfo = routeInfo } func didFailureBuildRoute(forTrip trip: CPTrip, code: RouterResultCode, countries: [String]) { guard let template = interfaceController?.topTemplate as? CPMapTemplate else { return } trip.routeChoices.first?.userInfo = [CPConstants.Trip.errorCode: code, CPConstants.Trip.missedCountries: countries] applyUndefinedEstimates(template: template, trip: trip) } func routeDidFinish(_ trip: CPTrip) { if router?.currentTrip == nil { return } router?.finishTrip() if let carplayVC = carplayVC { carplayVC.hideSpeedControl() } updateMapTemplateUIToTripFinished(trip) } } // MARK: - LocationModeListener implementation @available(iOS 12.0, *) extension CarPlayService: LocationModeListener { func processMyPositionStateModeEvent(_ mode: MWMMyPositionMode) { currentPositionMode = mode guard let rootMapTemplate = rootMapTemplate, let info = rootMapTemplate.userInfo as? MapInfo, info.type == CPConstants.TemplateType.main else { return } switch mode { case .follow, .followAndRotate: MapTemplateBuilder.setupDestinationButton(mapTemplate: rootMapTemplate) case .notFollow: if !rootMapTemplate.isPanningInterfaceVisible { MapTemplateBuilder.setupRecenterButton(mapTemplate: rootMapTemplate) } default: break } } func processMyPositionPendingTimeout() { } } // MARK: - Alerts and Trip Previews @available(iOS 12.0, *) extension CarPlayService { func preparePreviewForSearchResults(selectedRow row: Int) { var results = searchService?.lastResults ?? [] if let currentItemIndex = results.firstIndex(where: { $0.originalRow == row }) { let item = results.remove(at: currentItemIndex) results.insert(item, at: 0) } else { results.insert(MWMCarPlaySearchResultObject(forRow: row), at: 0) } if let router = router, let startPoint = MWMRoutePoint(lastLocationAndType: .start, intermediateIndex: 0) { let endPoints = results.compactMap({ MWMRoutePoint(cgPoint: $0.mercatorPoint, title: $0.title, subtitle: $0.address, type: .finish, intermediateIndex: 0) }) let trips = endPoints.map({ router.createTrip(startPoint: startPoint, endPoint: $0) }) if router.currentTrip == nil { preparePreview(trips: trips) } else { showRerouteAlert(trips: trips) } } } func preparePreview(forBookmark bookmark: MWMCarPlayBookmarkObject) { if let router = router, let startPoint = MWMRoutePoint(lastLocationAndType: .start, intermediateIndex: 0), let endPoint = MWMRoutePoint(cgPoint: bookmark.mercatorPoint, title: bookmark.prefferedName, subtitle: bookmark.address, type: .finish, intermediateIndex: 0) { let trip = router.createTrip(startPoint: startPoint, endPoint: endPoint) if router.currentTrip == nil { preparePreview(trips: [trip]) } else { showRerouteAlert(trips: [trip]) } } } func preparePreview(trips: [CPTrip]) { let mapTemplate = MapTemplateBuilder.buildTripPreviewTemplate(forTrips: trips) pushTemplate(mapTemplate, animated: false) } func showPreview(mapTemplate: CPMapTemplate, trips: [CPTrip]) { let tripTextConfig = CPTripPreviewTextConfiguration(startButtonTitle: L("trip_start"), additionalRoutesButtonTitle: nil, overviewButtonTitle: nil) mapTemplate.showTripPreviews(trips, textConfiguration: tripTextConfig) } func createEstimates(routeInfo: RouteInfo) -> CPTravelEstimates? { if let distance = Double(routeInfo.targetDistance) { let measurement = Measurement(value: distance, unit: routeInfo.targetUnits) let estimates = CPTravelEstimates(distanceRemaining: measurement, timeRemaining: routeInfo.timeToTarget) return estimates } return nil } func applyUndefinedEstimates(template: CPMapTemplate, trip: CPTrip) { let measurement = Measurement(value: -1, unit: UnitLength.meters) let estimates = CPTravelEstimates(distanceRemaining: measurement, timeRemaining: -1) template.updateEstimates(estimates, for: trip) } func showRerouteAlert(trips: [CPTrip]) { let yesAction = CPAlertAction(title: L("redirect_route_yes"), style: .default, handler: { [unowned self] _ in self.router?.cancelTrip() self.updateMapTemplateUIToBase() self.preparedToPreviewTrips = trips self.interfaceController?.dismissTemplate(animated: true) }) let noAction = CPAlertAction(title: L("redirect_route_no"), style: .cancel, handler: { [unowned self] _ in self.interfaceController?.dismissTemplate(animated: true) }) let alert = CPAlertTemplate(titleVariants: [L("redirect_route_alert")], actions: [noAction, yesAction]) alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.redirectRoute] interfaceController?.presentTemplate(alert, animated: true) } func showKeyboardAlert() { let okAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in self.interfaceController?.dismissTemplate(animated: true) }) let alert = CPAlertTemplate(titleVariants: [L("keyboard_availability_alert")], actions: [okAction]) interfaceController?.presentTemplate(alert, animated: true) } func showErrorAlert(code: RouterResultCode, countries: [String]) { var titleVariants = [String]() switch code { case .noCurrentPosition: titleVariants = ["\(L("dialog_routing_check_gps_carplay"))"] case .startPointNotFound: titleVariants = ["\(L("dialog_routing_change_start_carplay"))"] case .endPointNotFound: titleVariants = ["\(L("dialog_routing_change_end_carplay"))"] case .routeNotFoundRedressRouteError, .routeNotFound, .inconsistentMWMandRoute: titleVariants = ["\(L("dialog_routing_unable_locate_route_carplay"))"] case .routeFileNotExist, .fileTooOld, .needMoreMaps, .pointsInDifferentMWM: titleVariants = ["\(L("dialog_routing_download_files_carplay"))"] case .internalError: titleVariants = ["\(L("dialog_routing_system_error_carplay"))"] default: return } let okAction = CPAlertAction(title: L("ok"), style: .cancel, handler: { [unowned self] _ in self.interfaceController?.dismissTemplate(animated: true) }) let alert = CPAlertTemplate(titleVariants: titleVariants, actions: [okAction]) interfaceController?.presentTemplate(alert, animated: true) } func showRecoverRouteAlert(trip: CPTrip, isTypeCorrect: Bool) { let yesAction = CPAlertAction(title: L("ok"), style: .default, handler: { [unowned self] _ in var info = trip.userInfo as? [String: MWMRoutePoint] if let startPoint = MWMRoutePoint(lastLocationAndType: .start, intermediateIndex: 0) { info?[CPConstants.Trip.start] = startPoint } trip.userInfo = info self.preparedToPreviewTrips = [trip] self.router?.updateStartPointAndRebuild(trip: trip) self.interfaceController?.dismissTemplate(animated: true) }) let noAction = CPAlertAction(title: L("cancel"), style: .cancel, handler: { [unowned self] _ in self.router?.completeRouteAndRemovePoints() self.interfaceController?.dismissTemplate(animated: true) }) let title = isTypeCorrect ? L("dialog_routing_rebuild_from_current_location_carplay") : L("dialog_routing_rebuild_for_vehicle_carplay") let alert = CPAlertTemplate(titleVariants: [title], actions: [noAction, yesAction]) alert.userInfo = [CPConstants.TemplateKey.alert: CPConstants.TemplateType.restoreRoute] interfaceController?.presentTemplate(alert, animated: true) } }
apache-2.0
526616f496f3e1e705426c1e7e280341
38.420058
150
0.693595
4.582024
false
false
false
false
Quaggie/Quaggify
Quaggify/TabBarController.swift
1
3163
// // TabBarController.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class TabBarController: UITabBarController { var previousViewController: UIViewController? var didLogin = false // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() delegate = self UITabBar.appearance().tintColor = ColorPalette.white UITabBar.appearance().isTranslucent = false UITabBar.appearance().barTintColor = ColorPalette.gray // Fetching updated user if !didLogin { if let user = User.getFromDefaults() { User.current = user } API.fetchCurrentUser { (user, error) in if let user = user { User.current = user User.current.saveToDefaults() } } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let homeViewController = NavigationController(rootViewController: HomeViewController()) let homeIcon = #imageLiteral(resourceName: "tab_icon_home").withRenderingMode(.alwaysTemplate) let homeIconFilled = #imageLiteral(resourceName: "tab_icon_home_filled").withRenderingMode(.alwaysTemplate) homeViewController.tabBarItem = UITabBarItem(title: "Home", image: homeIcon, selectedImage: homeIconFilled) homeViewController.tabBarItem.tag = 0 if previousViewController == nil { previousViewController = homeViewController } let searchViewController = NavigationController(rootViewController: SearchViewController()) let searchIcon = #imageLiteral(resourceName: "tab_icon_search").withRenderingMode(.alwaysTemplate) searchViewController.tabBarItem = UITabBarItem(title: "Search", image: searchIcon, tag: 1) let libraryViewController = NavigationController(rootViewController: LibraryViewController()) let libraryIcon = #imageLiteral(resourceName: "tab_icon_library").withRenderingMode(.alwaysTemplate) let libraryIconFilled = #imageLiteral(resourceName: "tab_icon_library_filled").withRenderingMode(.alwaysTemplate) libraryViewController.tabBarItem = UITabBarItem(title: "Your Library", image: libraryIcon, selectedImage: libraryIconFilled) libraryViewController.tabBarItem.tag = 2 viewControllers = [homeViewController, searchViewController, libraryViewController] } } extension TabBarController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { if previousViewController == viewController { if let navController = viewController as? NavigationController { if let homeVC = navController.topViewController as? HomeViewController { homeVC.scrollToTop() } if let searchVC = navController.topViewController as? SearchViewController { searchVC.scrollToTop() } if let libraryVC = navController.topViewController as? LibraryViewController { libraryVC.scrollToTop() } } } previousViewController = viewController } }
mit
012d51a0297101ba213ed085a3c38d20
30.306931
128
0.719165
5.65653
false
false
false
false
pengjinning/AppKeFu_iOS_Demo_V4
AppKeFuDemo7Swift/AppKeFuDemo7Swift/Controllers/KFTagsChangeTableViewController.swift
1
4544
// // TagsChangeTableViewController.swift // AppKeFuDemo7Swift // // Created by jack on 16/8/5. // Copyright © 2016年 appkefu.com. All rights reserved. // import Foundation class KFTagsChangeTableViewController: UITableViewController, UITextFieldDelegate { var tag: NSString? = "", value: String? = "" var tagChangeField: UITextField = UITextField.init(); override init(style: UITableViewStyle) { super.init(style: style) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "修改用户标签" self.tableView.allowsSelection = false self.tableView.allowsSelectionDuringEditing = false let singleFingerTap: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(handleSingleTap(_:))) self.view.addGestureRecognizer(singleFingerTap) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tagChangeField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1; } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) tagChangeField.frame = CGRect(x: 10, y: 7, width: UIScreen.main.bounds.size.width - 30, height: 30) tagChangeField.placeholder = "请输入内容"; tagChangeField.borderStyle = UITextBorderStyle.none; tagChangeField.clearButtonMode = UITextFieldViewMode.always; tagChangeField.autocapitalizationType = UITextAutocapitalizationType.none; tagChangeField.contentVerticalAlignment = UIControlContentVerticalAlignment.center; tagChangeField.returnKeyType = UIReturnKeyType.send; tagChangeField.becomeFirstResponder(); tagChangeField.delegate = self; tagChangeField.text = value! as String; cell.contentView.addSubview(tagChangeField) return cell; } /* */ func tagChange() -> Void { if (tag!.isEqual(to: "NICKNAME")) { AppKeFuLib.sharedInstance().setTagNickname(tagChangeField.text) } else if (tag!.isEqual(to: "SEX")) { AppKeFuLib.sharedInstance().setTagSex(tagChangeField.text) } else if (tag!.isEqual(to: "LANGUAGE")) { AppKeFuLib.sharedInstance().setTagLanguage(tagChangeField.text) } else if (tag!.isEqual(to: "CITY")) { AppKeFuLib.sharedInstance().setTagCity(tagChangeField.text) } else if (tag!.isEqual(to: "PROVINCE")) { AppKeFuLib.sharedInstance().setTagProvince(tagChangeField.text) } else if (tag!.isEqual(to: "COUNTRY")) { AppKeFuLib.sharedInstance().setTagCountry(tagChangeField.text) } else if (tag!.isEqual(to: "OTHER")) { AppKeFuLib.sharedInstance().setTagOther(tagChangeField.text) } tagChangeField.text = ""; self.navigationController?.popViewController(animated: true) } /* */ func textFieldShouldReturn(_ textFiled: UITextField) -> Bool { // NSLog(textFiled.text!); if(textFiled.text!.lengthOfBytes(using: String.Encoding.utf8) <= 0) { let alert: UIAlertView = UIAlertView.init(title: "提示", message: "内容不能为空", delegate: nil, cancelButtonTitle: "确定") alert.show() return false; } else { self.tagChange() } return true; } /* */ func handleSingleTap(_ gestureRecognizer: UIGestureRecognizer) -> Void { self.view.endEditing(true) } }
mit
0774f0b515f7dcd9af9b09dd0215830a
29.398649
135
0.611469
4.811765
false
false
false
false
benlangmuir/swift
test/StringProcessing/Parse/regex_parse_error.swift
5
1582
// RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking // REQUIRES: swift_in_compiler _ = /(/ // expected-error@:7 {{expected ')'}} _ = #/(/# // expected-error@:8 {{expected ')'}} // FIXME: Should be 'group openings' _ = /)/ // expected-error@:6 {{closing ')' does not balance any groups openings}} _ = #/)/# // expected-error@:7 {{closing ')' does not balance any groups openings}} _ = #/\\/''/ // expected-error@:5 {{unterminated regex literal}} _ = #/\| // expected-error@:5 {{unterminated regex literal}} _ = #// // expected-error@:5 {{unterminated regex literal}} _ = #/xy // expected-error@:5 {{unterminated regex literal}} _ = #/(?/# // expected-error@:9 {{expected group specifier}} _ = #/(?'/# // expected-error@:10 {{expected group name}} _ = #/(?'abc/# // expected-error@:13 {{expected '''}} _ = #/(?'abc /# // expected-error@:13 {{expected '''}} do { _ = #/(?'a // expected-error@-1:7 {{unterminated regex literal}} // expected-error@-2:13 {{cannot parse regular expression: expected '''}} } _ = #/\(?'abc/# do { _ = /\ / // expected-error@-1:3 {{expected expression path in Swift key path}} } do { _ = #/\ /# // expected-error@-2:7 {{unterminated regex literal}} // expected-error@-3:10 {{expected escape sequence}} // expected-error@-3:4 {{expected expression}} } func foo<T>(_ x: T, _ y: T) {} foo(#/(?/#, #/abc/#) // expected-error@:9 {{expected group specifier}} foo(#/(?C/#, #/abc/#) // expected-error@:10 {{expected ')'}} foo(#/(?'/#, #/abc/#) // expected-error@:10 {{expected group name}}
apache-2.0
06af7a4785248de345b14f6264e0ab3b
31.958333
94
0.588496
3.268595
false
false
false
false
esttorhe/Hermes
HermesApp/ViewController.swift
3
3001
import UIKit import Hermes class ViewController: UIViewController, HermesDelegate { let hermes = Hermes.sharedInstance override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .whiteColor() hermes.delegate = self let notification1 = HermesNotification() notification1.text = "Upload complete! Tap here to show an alert!" notification1.image = UIImage(named: "logo") notification1.color = .greenColor() notification1.action = { notification in let alert = UIAlertView(title: "Success", message: "Hermes notifications are actionable", delegate: nil, cancelButtonTitle: "Close") alert.show() } notification1.soundPath = NSBundle.mainBundle().pathForResource("notify", ofType: "wav") var notification2 = HermesNotification() var attributedText = NSMutableAttributedString(string: "Alan ") attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(0, attributedText.length)) attributedText.addAttribute(NSFontAttributeName , value: UIFont(name: "Helvetica-Bold", size: 14)!, range: NSMakeRange(0, attributedText.length)) attributedText.appendAttributedString(NSAttributedString(string: "commented on your ")) var imageText = NSMutableAttributedString(string: "image") imageText.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(0, imageText.length)) imageText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 15)!, range: NSMakeRange(0, imageText.length)) attributedText.appendAttributedString(imageText) notification2.attributedText = attributedText notification2.image = UIImage(named: "logo") notification2.color = .redColor() var notification3 = HermesNotification() notification3.text = "ATTN: There is a major update to your app! Please go to the app store now and download it! Also, this message is purposely really long." notification3.image = UIImage(named: "logo") notification3.color = .yellowColor() var delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.hermes.postNotifications([notification1, notification2, notification3, notification1, notification2, notification3]) } delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(4 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.hermes.postNotifications([notification1, notification2, notification3, notification1, notification2, notification3]) } } // MARK: - HermesDelegate func hermesNotificationViewForNotification(#hermes: Hermes, notification: HermesNotification) -> HermesNotificationView? { // You can create your own HermesNotificationView subclass and return it here :D (or return nil for the default notification view) return nil } }
mit
2cf2a1465ac131ced0458fc92ae6e322
45.890625
163
0.73942
4.711146
false
false
false
false
silence0201/Swift-Study
Swifter/44OutputFormat.playground/Contents.swift
1
515
//: Playground - noun: a place where people can play import Foundation let a = 3; let b = 1.234567 // 我们在这里不去区分 float 和 Double 了 let c = "Hello" print("int:\(a) double:\(b) string:\(c)") // 输出: // int:3 double:1.234567 string:Hello let format = String(format:"%.2f",b) print("double:\(format)") // 输出: // double:1.23 extension Double { func format(_ f: String) -> String { return String(format: "%\(f)f", self) } } let f = ".2" print("double:\(b.format(f))")
mit
74e986eddfdff499aab28d9a2b2df4f9
19.041667
52
0.607069
2.89759
false
false
false
false
iAladdin/SwiftyFORM
Example/DatePicker/DatePickerLocaleViewController.swift
1
3048
// // DatePickerLocaleViewController.swift // SwiftyFORM // // Created by Simon Strandgaard on 07/12/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit import SwiftyFORM class DatePickerLocaleViewController: FormViewController { lazy var datePicker_time_currentLocale: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Time") instance.datePickerMode = .Time return instance }() lazy var datePicker_date_currentLocale: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Date") instance.datePickerMode = .Date return instance }() lazy var datePicker_dateAndTime_currentLocale: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("DateAndTime") instance.datePickerMode = .DateAndTime return instance }() lazy var datePicker_time_da_DK: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Time") instance.datePickerMode = .Time instance.locale = NSLocale(localeIdentifier: "da_DK") return instance }() lazy var datePicker_date_da_DK: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Date") instance.datePickerMode = .Date instance.locale = NSLocale(localeIdentifier: "da_DK") return instance }() lazy var datePicker_dateAndTime_da_DK: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("DateAndTime") instance.datePickerMode = .DateAndTime instance.locale = NSLocale(localeIdentifier: "da_DK") return instance }() lazy var datePicker_time_zh_CN: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Time") instance.datePickerMode = .Time instance.locale = NSLocale(localeIdentifier: "zh_CN") return instance }() lazy var datePicker_date_zh_CN: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("Date") instance.datePickerMode = .Date instance.locale = NSLocale(localeIdentifier: "zh_CN") return instance }() lazy var datePicker_dateAndTime_zh_CN: DatePickerFormItem = { let instance = DatePickerFormItem() instance.title("DateAndTime") instance.datePickerMode = .DateAndTime instance.locale = NSLocale(localeIdentifier: "zh_CN") return instance }() override func populate(builder: FormBuilder) { builder.navigationTitle = "DatePicker & Locale" builder.toolbarMode = .Simple builder.demo_showInfo("Demonstration of\nUIDatePicker with locale") builder += SectionHeaderTitleFormItem().title("Current locale") builder += datePicker_time_currentLocale builder += datePicker_date_currentLocale builder += datePicker_dateAndTime_currentLocale builder += SectionHeaderTitleFormItem().title("da_DK") builder += datePicker_time_da_DK builder += datePicker_date_da_DK builder += datePicker_dateAndTime_da_DK builder += SectionHeaderTitleFormItem().title("zh_CN") builder += datePicker_time_zh_CN builder += datePicker_date_zh_CN builder += datePicker_dateAndTime_zh_CN } }
mit
4cabd80273a6aa359a4326ab986716bf
28.882353
70
0.745735
4.037086
false
false
false
false
juvs/FormValidators
FormValidators/Classes/FormValidator.swift
1
5315
// // MainValidator.swift // Pods // // Created by Juvenal Guzman on 6/27/17. // // import Foundation //----------------------------------------------------------- // MARK: - FormValidator groups all validator... open class FormValidator: ValidatorHandler { var fieldValidators: [FieldValidator] = [] var anyObjectValidators: [AnyObjectValidator] = [] func attach(textField: UITextField, fieldValidator: FieldValidator) { var localFieldValidator = fieldValidator if let index = fieldValidators.index(of: fieldValidator) { localFieldValidator = fieldValidators[index] } else { fieldValidators.append(localFieldValidator) } localFieldValidator.attachTo(textField) } public func attach(textField: UITextField, validators: [ValidatorType], domain: String? = nil, successStyleTransform: SucessStyleTransform? = nil, errorStyleTransform: ErrorStyleTransform? = nil, detailLabel: UILabel? = nil, returnCallback: ReturnCallback? = nil) { if validators.count == 0 { return } if let fieldValidator = textField.delegate as? FieldValidator { fieldValidator.validators = validators fieldValidator.successStyleTransform = successStyleTransform fieldValidator.errorStyleTransform = errorStyleTransform fieldValidator.returnCallback = returnCallback fieldValidator.domain = domain fieldValidator.detailLabel = detailLabel attach(textField: textField, fieldValidator: fieldValidator) } else { if textField.delegate != nil { debugPrint("Field already has delegate and is different from FieldValidator, couldn't attach validators") } else { let fieldValidator = FieldValidator(validators: validators, formValidator: self, domain: domain, detailLabel: detailLabel, successStyleTransform: successStyleTransform, errorStyleTransform: errorStyleTransform, returnCallback: returnCallback) fieldValidator.attachTo(textField) fieldValidators.append(fieldValidator) } } } public func attach(object: AnyObject, property: String, validators: [ValidatorType], domain: String? = nil, detailLabel: UILabel? = nil, successStyleTransform: SucessStyleTransform? = nil, errorStyleTransform: ErrorStyleTransform? = nil) { let container = ValidatorObjectContainer(object, property: property) let anyObjectValidator = AnyObjectValidator(container, validators: validators, domain: domain, detailLabel: detailLabel, successStyleTransform: successStyleTransform, errorStyleTransform: errorStyleTransform) anyObjectValidators.append(anyObjectValidator) } // public func attach(container: ValidatorObjectContainer, validators: [ValidatorType], domain: String? = nil, detailLabel: UILabel? = nil, successStyleTransform: SucessStyleTransform? = nil, errorStyleTransform: ErrorStyleTransform? = nil) { // let anyObjectValidator = AnyObjectValidator(container, validators: validators, domain: domain, detailLabel: detailLabel, successStyleTransform: successStyleTransform, errorStyleTransform: errorStyleTransform) // anyObjectValidators.append(anyObjectValidator) // } public func setReturnCallback(textField: UITextField, callback: @escaping ReturnCallback) { if let fieldValidator = textField.delegate as? FieldValidator { fieldValidator.setReturnCallback(textField, callback: callback) } else { if textField.delegate != nil { debugPrint("Field already has delegate and is different from FieldValidator, couldn't attach return callback") } else { let fieldValidator = FieldValidator(formValidator: self) attach(textField: textField, fieldValidator: fieldValidator) } } } public func isValid(domain: String? = nil) -> Bool { var allIsValid = true var fValidators = fieldValidators var aValidators = anyObjectValidators if let domain = domain { if !domain.isEmpty { fValidators = fieldValidators.filter({$0.domain == domain}) aValidators = anyObjectValidators.filter({$0.domain == domain}) } } for fieldValidator in fValidators { let response = fieldValidator.isValid() if !response.valid { allIsValid = false } } for anyObjectValidator in aValidators { let response = anyObjectValidator.isValid() if !response.valid { allIsValid = false } } if allIsValid { if let onIsValid = self.onIsValid { onIsValid() } else if let onIsValid = SharedFormValidator.sharedManager().onIsValid { onIsValid() } } else { if let onIsInvalid = self.onIsInvalid { onIsInvalid() } else if let onIsInvalid = SharedFormValidator.sharedManager().onIsInvalid { onIsInvalid() } } return allIsValid } }
mit
bbcd27e77e1a6114af9293bf87f21a24
43.663866
269
0.64572
5.145208
false
false
false
false
mcgraw/tomorrow
TextFieldEffects/YokoTextField.swift
1
7141
// // YokoTextField.swift // TextFieldEffects // // Created by Raúl Riera on 30/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // @IBDesignable public class YokoTextField: TextFieldEffects { override public var placeholder: String? { didSet { updatePlaceholder() } } @IBInspectable public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } @IBInspectable public var foregroundColor: UIColor = UIColor.blackColor() { didSet { updateForeground() } } override public var bounds: CGRect { didSet { updateForeground() updatePlaceholder() } } private let foregroundView = UIView() private let foregroundLayer = CALayer() private let borderThickness: CGFloat = 3 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) override func drawViewsForRect(rect: CGRect) { updateForeground() updatePlaceholder() addSubview(foregroundView) addSubview(placeholderLabel) layer.addSublayer(foregroundLayer) } private func updateForeground() { foregroundView.frame = rectForForeground(frame) foregroundView.userInteractionEnabled = false foregroundView.layer.transform = rotationAndPerspectiveTransformForView(foregroundView) foregroundView.backgroundColor = foregroundColor foregroundLayer.borderWidth = borderThickness foregroundLayer.borderColor = colorWithBrightnessFactor(foregroundColor, factor: 0.8).CGColor foregroundLayer.frame = rectForBorder(foregroundView.frame, isFill: true) } private func updatePlaceholder() { placeholderLabel.font = placeholderFontFromFont(font) placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || !text.isEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.7) return smallerFont } private func rectForForeground(bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y - borderThickness) return newRect } private func rectForBorder(bounds: CGRect, isFill: Bool) -> CGRect { var newRect = CGRect(x: 0, y: bounds.size.height, width: bounds.size.width, height: isFill ? borderThickness : 0) if !CATransform3DIsIdentity(foregroundView.layer.transform) { newRect.origin = CGPoint(x: 0, y: bounds.origin.y) } return newRect } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } override func animateViewsForTextEntry() { UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.foregroundView.layer.transform = CATransform3DIdentity }, completion: nil) foregroundLayer.frame = rectForBorder(foregroundView.frame, isFill: false) } override func animateViewsForTextDisplay() { if text.isEmpty { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.6, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in self.foregroundLayer.frame = self.rectForBorder(self.foregroundView.frame, isFill: true) self.foregroundView.layer.transform = self.rotationAndPerspectiveTransformForView(self.foregroundView) }, completion: nil) } } // MARK: - private func setAnchorPoint(anchorPoint:CGPoint, forView view:UIView) { var newPoint:CGPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y) var oldPoint:CGPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y) newPoint = CGPointApplyAffineTransform(newPoint, view.transform) oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform) var position = view.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y view.layer.position = position view.layer.anchorPoint = anchorPoint } private func colorWithBrightnessFactor(color: UIColor, factor: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor(hue: hue, saturation: saturation, brightness: brightness * factor, alpha: alpha) } else { return color; } } private func rotationAndPerspectiveTransformForView(view: UIView) -> CATransform3D { setAnchorPoint(CGPoint(x: 0.5, y: 1.0), forView:view) var rotationAndPerspectiveTransform = CATransform3DIdentity rotationAndPerspectiveTransform.m34 = 1.0/800 let radians = ((-90) / 180.0 * CGFloat(M_PI)) rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0, 0.0, 0.0) return rotationAndPerspectiveTransform } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font.lineHeight + textFieldInsets.y) return CGRectInset(newBounds, textFieldInsets.x, 0) } }
bsd-2-clause
15189dc5f00dad056b9f9eea4fb71105
37.181818
193
0.646078
5.125628
false
false
false
false
uchuugaka/OysterKit
Common/Framework/States/Keywords.swift
1
2442
// // CharSequences.swift // OysterKit Mac // // Created by Nigel Hughes on 09/07/2014. // Copyright (c) 2014 RED When Excited Limited. All rights reserved. // import Foundation public class Keywords : TokenizationState { override func stateClassName()->String { return "Keywords" } let validStrings : [String] public init(validStrings:Array<String>){ self.validStrings = validStrings super.init() } public override func scan(operation: TokenizeOperation) { operation.debug(operation: "Entered Keywords \(validStrings)") var didAdvance = false if completions(operation.context.consumedCharacters+"\(operation.current)") == nil { return } while let allCompletions = completions(operation.context.consumedCharacters+"\(operation.current)") { if allCompletions.count == 1 && allCompletions[0] == operation.context.consumedCharacters { //Pursue our branches emitToken(operation) scanBranches(operation) return } else { operation.advance() didAdvance = true } } if (didAdvance){ scanBranches(operation) return } } func completions(string:String) -> Array<String>?{ var allMatches = Array<String>() for validString in validStrings{ if validString.hasPrefix(string){ allMatches.append(validString) } } if allMatches.count == 0{ return nil } else { return allMatches } } override func serialize(indentation: String) -> String { var output = "" output+="[" var first = true for keyword in validStrings { if !first { output+="," } else { first = false } output+="\"\(keyword)\"" } output+="]" return output+serializeBranches(indentation+"\t") } override public func clone() -> TokenizationState { var newState = Keywords(validStrings: validStrings) newState.__copyProperities(self) return newState } }
bsd-2-clause
55b6b40823845c1900405815ed56c7a2
24.447917
109
0.522523
5.308696
false
false
false
false
iosyaowei/Weibo
WeiBo/Classes/View(视图和控制器)/Home/StatusCell/YWStatusPictureView.swift
1
3152
// // YWStatusPictureView.swift // WeiBo // // Created by yao wei on 16/9/20. // Copyright © 2016年 yao wei. All rights reserved. // import UIKit class YWStatusPictureView: UIView { var viewModel: YWStatusViewModel?{ didSet{ calcViewSize() /// 设置配图 (被转发和原创) urls = viewModel?.picURLs } } /// 根据视图模型的配图大小 调整显示内容 private func calcViewSize(){ //处理宽度 //单图,根据配图视图大小 修改 subview(0)的宽度 if viewModel?.picURLs?.count == 1 { let viewSize = viewModel?.pictureViewSize ?? CGSize() let v = subviews[0] v.frame = CGRect(x: 0, y: pictureOutterMargin, width:viewSize.width , height: viewSize.height - pictureOutterMargin) }else{ //多图 、无图 恢复 subview【0】的宽度 保证九宫格布局 let v = subviews[0] v.frame = CGRect(x: 0, y: pictureOutterMargin, width:YWStatusPictureItemWith , height:YWStatusPictureItemWith) } //修改高度约束 heightCons.constant = viewModel?.pictureViewSize.height ?? 0 } private var urls: [YWStatusPictures]? { didSet{ //隐藏所有的 imageView for v in subviews { v.isHidden = true } var index = 0 //设置图像 for url in urls ?? [] { let iv = subviews[index] as! UIImageView if index == 1 && urls?.count == 4 { index += 1 } iv.yw_setImage(urlStr: url.thumbnail_pic, placeholderImage: UIImage(named: "paceholder")) iv.isHidden = false index += 1 } } } @IBOutlet weak var heightCons: NSLayoutConstraint! override func awakeFromNib() { steupUI() } } // MARK: - 设置界面 extension YWStatusPictureView { /// Cell 中所有的控件都是提前准备好 fileprivate func steupUI() { backgroundColor = superview?.backgroundColor /// 超出范围不显示 clipsToBounds = true let rect = CGRect(x: 0, y: pictureOutterMargin, width: YWStatusPictureItemWith, height: YWStatusPictureItemWith) let count = 3 for i in 0..<9 { let row = CGFloat(i / count) let col = CGFloat(i % count) let iv = UIImageView(frame: rect) iv.contentMode = .scaleAspectFill iv.clipsToBounds = true let xOffset = col * (YWStatusPictureItemWith + pictureInnerMargin) let yOffset = row * (YWStatusPictureItemWith + pictureInnerMargin) iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset) iv.backgroundColor = UIColor.red addSubview(iv) } } }
mit
ff3bca9ec2bb5dfea8bc716a5b76d016
25.205357
128
0.508688
4.629338
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MQ/MQ_API.swift
1
12797
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS MQ service. Amazon MQ is a managed message broker service for Apache ActiveMQ that makes it easy to set up and operate message brokers in the cloud. A message broker allows software applications and components to communicate using various programming languages, operating systems, and formal messaging protocols. */ public struct MQ: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the MQ client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, service: "mq", serviceProtocol: .restjson, apiVersion: "2017-11-27", endpoint: endpoint, errorType: MQErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Creates a broker. Note: This API is asynchronous. public func createBroker(_ input: CreateBrokerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateBrokerResponse> { return self.client.execute(operation: "CreateBroker", path: "/v1/brokers", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a new configuration for the specified configuration name. Amazon MQ uses the default configuration (the engine type and version). public func createConfiguration(_ input: CreateConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateConfigurationResponse> { return self.client.execute(operation: "CreateConfiguration", path: "/v1/configurations", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Add a tag to a resource. @discardableResult public func createTags(_ input: CreateTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "CreateTags", path: "/v1/tags/{resource-arn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates an ActiveMQ user. public func createUser(_ input: CreateUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateUserResponse> { return self.client.execute(operation: "CreateUser", path: "/v1/brokers/{broker-id}/users/{username}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a broker. Note: This API is asynchronous. public func deleteBroker(_ input: DeleteBrokerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteBrokerResponse> { return self.client.execute(operation: "DeleteBroker", path: "/v1/brokers/{broker-id}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes a tag from a resource. @discardableResult public func deleteTags(_ input: DeleteTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return self.client.execute(operation: "DeleteTags", path: "/v1/tags/{resource-arn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes an ActiveMQ user. public func deleteUser(_ input: DeleteUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteUserResponse> { return self.client.execute(operation: "DeleteUser", path: "/v1/brokers/{broker-id}/users/{username}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns information about the specified broker. public func describeBroker(_ input: DescribeBrokerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeBrokerResponse> { return self.client.execute(operation: "DescribeBroker", path: "/v1/brokers/{broker-id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describe available engine types and versions. public func describeBrokerEngineTypes(_ input: DescribeBrokerEngineTypesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeBrokerEngineTypesResponse> { return self.client.execute(operation: "DescribeBrokerEngineTypes", path: "/v1/broker-engine-types", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describe available broker instance options. public func describeBrokerInstanceOptions(_ input: DescribeBrokerInstanceOptionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeBrokerInstanceOptionsResponse> { return self.client.execute(operation: "DescribeBrokerInstanceOptions", path: "/v1/broker-instance-options", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns information about the specified configuration. public func describeConfiguration(_ input: DescribeConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeConfigurationResponse> { return self.client.execute(operation: "DescribeConfiguration", path: "/v1/configurations/{configuration-id}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the specified configuration revision for the specified configuration. public func describeConfigurationRevision(_ input: DescribeConfigurationRevisionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeConfigurationRevisionResponse> { return self.client.execute(operation: "DescribeConfigurationRevision", path: "/v1/configurations/{configuration-id}/revisions/{configuration-revision}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns information about an ActiveMQ user. public func describeUser(_ input: DescribeUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeUserResponse> { return self.client.execute(operation: "DescribeUser", path: "/v1/brokers/{broker-id}/users/{username}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of all brokers. public func listBrokers(_ input: ListBrokersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListBrokersResponse> { return self.client.execute(operation: "ListBrokers", path: "/v1/brokers", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of all revisions for the specified configuration. public func listConfigurationRevisions(_ input: ListConfigurationRevisionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListConfigurationRevisionsResponse> { return self.client.execute(operation: "ListConfigurationRevisions", path: "/v1/configurations/{configuration-id}/revisions", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of all configurations. public func listConfigurations(_ input: ListConfigurationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListConfigurationsResponse> { return self.client.execute(operation: "ListConfigurations", path: "/v1/configurations", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists tags for a resource. public func listTags(_ input: ListTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsResponse> { return self.client.execute(operation: "ListTags", path: "/v1/tags/{resource-arn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns a list of all ActiveMQ users. public func listUsers(_ input: ListUsersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListUsersResponse> { return self.client.execute(operation: "ListUsers", path: "/v1/brokers/{broker-id}/users", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Reboots a broker. Note: This API is asynchronous. public func rebootBroker(_ input: RebootBrokerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RebootBrokerResponse> { return self.client.execute(operation: "RebootBroker", path: "/v1/brokers/{broker-id}/reboot", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Adds a pending configuration change to a broker. public func updateBroker(_ input: UpdateBrokerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateBrokerResponse> { return self.client.execute(operation: "UpdateBroker", path: "/v1/brokers/{broker-id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the specified configuration. public func updateConfiguration(_ input: UpdateConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateConfigurationResponse> { return self.client.execute(operation: "UpdateConfiguration", path: "/v1/configurations/{configuration-id}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates the information for an ActiveMQ user. public func updateUser(_ input: UpdateUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateUserResponse> { return self.client.execute(operation: "UpdateUser", path: "/v1/brokers/{broker-id}/users/{username}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension MQ { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: MQ, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
68ff3b33d9473c85b2a80f6d9dec13b8
68.928962
301
0.721107
4.583453
false
true
false
false
LawrenceHan/iOS-project-playground
Swift_Algorithm/Swift_Algorithm/Puzzle.swift
1
5460
// // Puzzle.swift // Swift_algorithm // // Created by Hanguang on 23/11/2016. // Copyright © 2016 Hanguang. All rights reserved. // import Foundation enum Block { case White case Red case Blue } enum Direction: String { case Upward = "U" case Downward = "D" case Leftward = "L" case Rightward = "R" } public final class Puzzle { let puzzleBegin = "wrbbrrbbrrbbrrbb" let puzzleEnd = "wbrbbrbrrbrbbrbr" let stepBegin: Int = 0 let stepEnd: Int = 0 let columnCount: Int = 4 let rowCount: Int = 4 var totalBlockCount: Int { return columnCount * rowCount } var stepResults = [String]() fileprivate var routeList = [Route]() var routeCount: Int = 0 var snapshots = [String : Int]() public func drawTable() { if stepResults.count > 0 { var results = "" for steps in stepResults { results = results.appending("Total routes count: \(routeCount), result: \(steps), total steps count: \(steps.characters.count)\n") } } else { print("No results") } } public func calcuateShortestWay() { let route = Route(previousStep: stepBegin, nextStep: stepBegin, frame: puzzleBegin) routeList = [Route]() stepResults = [String]() routeCount = 0 snapshots = [String : Int]() routeList.append(route) routeCount = 1 snapshots[route.frame] = route.stepsList.characters.count var found = false while found == false { var routesNext = [Route]() var routeIndexNext = 0; for index in 0..<routeCount { let routeOld = routeList[index] let currentStep = routeOld.nextStep let previousStep = routeOld.previousStep var nextStep = currentStep - 4 // upward if nextStep >= 0 && nextStep != previousStep { moveBlock(routeOld: routeOld, nextStep: nextStep, direction: .Upward, routesNext: &routesNext, routeIndexNext: &routeIndexNext) } nextStep = currentStep + 4 // downward if nextStep < totalBlockCount && nextStep != previousStep { moveBlock(routeOld: routeOld, nextStep: nextStep, direction: .Downward, routesNext: &routesNext, routeIndexNext: &routeIndexNext) } nextStep = currentStep - 1 // leftward if currentStep % columnCount - 1 >= 0 && nextStep != previousStep { moveBlock(routeOld: routeOld, nextStep: nextStep, direction: .Leftward, routesNext: &routesNext, routeIndexNext: &routeIndexNext) } nextStep = currentStep + 1 // rightward if currentStep % columnCount + 1 < columnCount && nextStep != previousStep { moveBlock(routeOld: routeOld, nextStep: nextStep, direction: .Rightward, routesNext: &routesNext, routeIndexNext: &routeIndexNext) } } if stepResults.count > 0 { for steps in stepResults { print("Result: \(steps), total steps count: \(steps.characters.count)") } found = true } routeList = routesNext routeCount = routeIndexNext } } private func moveBlock(routeOld: Route, nextStep: Int, direction: Direction, routesNext: inout [Route], routeIndexNext: inout Int) { let routeNew = Route(previousStep: routeOld.nextStep, nextStep: nextStep, frame: "") routeNew.stepsList = routeOld.stepsList.appending(direction.rawValue) var frame = routeOld.frame let previousIndex = frame.index(frame.startIndex, offsetBy: routeNew.previousStep) let nextIndex = frame.index(frame.startIndex, offsetBy: routeNew.nextStep) let previousBlock = frame[previousIndex] let nextBlock = frame[nextIndex] frame = frame.replacingCharacters(in: previousIndex..<frame.index(after: previousIndex), with: String(nextBlock)) frame = frame.replacingCharacters(in: nextIndex..<frame.index(after: nextIndex), with: String(previousBlock)) routeNew.frame = frame if routeNew.frame.hashValue == puzzleEnd.hashValue { stepResults.append(routeNew.stepsList) } if snapshots[routeNew.frame] != nil { if snapshots[routeNew.frame]! < routeNew.stepsList.characters.count { return } } else { snapshots[routeNew.frame] = routeNew.stepsList.characters.count } routesNext.append(routeNew) routeIndexNext += 1 } } private class Route: CustomStringConvertible { var previousStep: Int = 0 var nextStep: Int = 0 var frame: String var stepsList: String init(previousStep: Int, nextStep: Int, frame: String) { self.previousStep = previousStep; self.nextStep = nextStep self.frame = frame self.stepsList = "" } open var description: String { return "previous step: \(previousStep), current step: \(nextStep), frame: \(frame), steps: \(stepsList)" } }
mit
72ca9deb63fbbf4801e93a586c275d57
34.448052
150
0.577395
4.665812
false
false
false
false
tjw/swift
test/Prototypes/Algorithms.swift
2
23885
//===--- Algorithms.swift.gyb ---------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test import Swift import StdlibUnittest //===--- Rotate -----------------------------------------------------------===// //===----------------------------------------------------------------------===// // In the stdlib, this would simply be MutableCollection public protocol MutableCollectionAlgorithms : MutableCollection where SubSequence : MutableCollectionAlgorithms { /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult mutating func rotate(shiftingToStart middle: Index) -> Index } // In the stdlib, these conformances wouldn't be needed extension Array : MutableCollectionAlgorithms { } extension ArraySlice : MutableCollectionAlgorithms { } extension Slice : MutableCollectionAlgorithms where Base: MutableCollection { } /// In the stdlib, this would simply be MutableCollection extension MutableCollectionAlgorithms { /// Swaps the elements of the two given subranges, up to the upper bound of /// the smaller subrange. The returned indices are the ends of the two ranges /// that were actually swapped. /// /// Input: /// [a b c d e f g h i j k l m n o p] /// ^^^^^^^ ^^^^^^^^^^^^^ /// lhs rhs /// /// Output: /// [i j k l e f g h a b c d m n o p] /// ^ ^ /// p q /// /// - Precondition: !lhs.isEmpty && !rhs.isEmpty /// - Postcondition: For returned indices `(p, q)`: /// - distance(from: lhs.lowerBound, to: p) == /// distance(from: rhs.lowerBound, to: q) /// - p == lhs.upperBound || q == rhs.upperBound @inline(__always) internal mutating func _swapNonemptySubrangePrefixes( _ lhs: Range<Index>, _ rhs: Range<Index> ) -> (Index, Index) { _sanityCheck(!lhs.isEmpty) _sanityCheck(!rhs.isEmpty) var p = lhs.lowerBound var q = rhs.lowerBound repeat { swapAt(p, q) formIndex(after: &p) formIndex(after: &q) } while p != lhs.upperBound && q != rhs.upperBound return (p, q) } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotate(shiftingToStart middle: Index) -> Index { var m = middle, s = startIndex let e = endIndex // Handle the trivial cases if s == m { return e } if m == e { return s } // We have two regions of possibly-unequal length that need to be // exchanged. The return value of this method is going to be the // position following that of the element that is currently last // (element j). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e // var ret = e // start with a known incorrect result. while true { // Exchange the leading elements of each region (up to the // length of the shorter region). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^^^^^ ^^^^^ ^^^^^ ^^^^^ // [h i j d e f g|a b c] or [d e f|a b c g h i j] // ^ ^ ^ ^ ^ ^ ^ ^ // s s1 m m1/e s s1/m m1 e // let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e) if m1 == e { // Left-hand case: we have moved element j into position. if // we haven't already, we can capture the return value which // is in s1. // // Note: the STL breaks the loop into two just to avoid this // comparison once the return value is known. I'm not sure // it's a worthwhile optimization, though. if ret == e { ret = s1 } // If both regions were the same size, we're done. if s1 == m { break } } // Now we have a smaller problem that is also a rotation, so we // can adjust our bounds and repeat. // // h i j[d e f g|a b c] or d e f[a b c|g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e s = s1 if s == m { m = m1 } } return ret } } extension MutableCollection where Self: BidirectionalCollection { /// Reverses the elements of the collection, moving from each end until /// `limit` is reached from either direction. The returned indices are the /// start and end of the range of unreversed elements. /// /// Input: /// [a b c d e f g h i j k l m n o p] /// ^ /// limit /// Output: /// [p o n m e f g h i j k l d c b a] /// ^ ^ /// f l /// /// - Postcondition: For returned indices `(f, l)`: /// `f == limit || l == limit` @inline(__always) @discardableResult internal mutating func _reverseUntil(_ limit: Index) -> (Index, Index) { var f = startIndex var l = endIndex while f != limit && l != limit { formIndex(before: &l) swapAt(f, l) formIndex(after: &f) } return (f, l) } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotate(shiftingToStart middle: Index) -> Index { // FIXME: this algorithm should be benchmarked on arrays against // the forward Collection algorithm above to prove that it's // actually faster. The other one sometimes does more swaps, but // has better locality properties. Similarly, we've omitted a // specialization of rotate for RandomAccessCollection that uses // cycles per section 11.4 in "From Mathematics to Generic // Programming" by A. Stepanov because it has *much* worse // locality properties than either of the other implementations. // Benchmarks should be performed for that algorithm too, just to // be sure. self[..<middle].reverse() self[middle...].reverse() let (p, q) = _reverseUntil(middle) self[p..<q].reverse() return middle == p ? q : p } } /// Returns the greatest common denominator for `m` and `n`. internal func _gcd(_ m: Int, _ n: Int) -> Int { var (m, n) = (m, n) while n != 0 { let t = m % n m = n n = t } return m } extension MutableCollection where Self: RandomAccessCollection { /// Rotates elements through a cycle, using `sourceForIndex` to generate /// the source index for each movement. @inline(__always) internal mutating func _rotateCycle( start: Index, sourceOffsetForIndex: (Index) -> Int ) { let tmp = self[start] var i = start var j = index(start, offsetBy: sourceOffsetForIndex(start)) while j != start { self[i] = self[j] i = j j = index(j, offsetBy: sourceOffsetForIndex(j)) } self[i] = tmp } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotateRandomAccess( shiftingToStart middle: Index) -> Index { if middle == startIndex { return endIndex } if middle == endIndex { return startIndex } // The distance to move an element that is moving -> let plus = distance(from: startIndex, to: middle) // The distance to move an element that is moving <- let minus = distance(from: endIndex, to: middle) // The new pivot point, aka the destination for the first element let pivot = index(startIndex, offsetBy: -minus) // If the difference moving forward and backward are relative primes, // the entire rotation will be completed in one cycle. Otherwise, repeat // cycle, moving the start point forward with each cycle. let cycles = _gcd(numericCast(plus), -numericCast(minus)) for cycle in 1...cycles { _rotateCycle( start: index(startIndex, offsetBy: numericCast(cycle)), sourceOffsetForIndex: { $0 < pivot ? plus : minus }) } return pivot } } //===--- ConcatenatedCollection -------------------------------------------===// //===----------------------------------------------------------------------===// // ConcatenatedCollection improves on a flattened array or other collection by // allowing random-access traversal if the underlying collections are // random-access. // // Q: Add a ConcatenatedSequence for consistency? Would be nice to be able to // call `let seqAB = concatenate(seqA, seqB)`. /// A concatenation of two collections with the same element type. public struct Concatenation<C1 : Collection, C2: Collection>: Collection where C1.Element == C2.Element { let _base1: C1 let _base2: C2 init(_base1: C1, base2: C2) { self._base1 = _base1 self._base2 = base2 } /// A position in a `Concatenation`. public struct Index : Comparable { internal enum _Representation : Equatable { case first(C1.Index) case second(C2.Index) } /// Creates a new index into the first underlying collection. internal init(first i: C1.Index) { _position = .first(i) } /// Creates a new index into the second underlying collection. internal init(second i: C2.Index) { _position = .second(i) } internal let _position: _Representation public static func < (lhs: Index, rhs: Index) -> Bool { switch (lhs._position, rhs._position) { case (.first, .second): return true case (.second, .first): return false case let (.first(l), .first(r)): return l < r case let (.second(l), .second(r)): return l < r } } } public var startIndex: Index { // If `_base1` is empty, then `_base2.startIndex` is either a valid position // of an element or equal to `_base2.endIndex`. return _base1.isEmpty ? Index(second: _base2.startIndex) : Index(first: _base1.startIndex) } public var endIndex: Index { return Index(second: _base2.endIndex) } public subscript(i: Index) -> C1.Element { switch i._position { case let .first(i): return _base1[i] case let .second(i): return _base2[i] } } public func index(after i: Index) -> Index { switch i._position { case let .first(i): _sanityCheck(i != _base1.endIndex) let next = _base1.index(after: i) return next == _base1.endIndex ? Index(second: _base2.startIndex) : Index(first: next) case let .second(i): return Index(second: _base2.index(after: i)) } } } extension Concatenation : BidirectionalCollection where C1: BidirectionalCollection, C2: BidirectionalCollection { public func index(before i: Index) -> Index { assert(i != startIndex, "Can't advance before startIndex") switch i._position { case let .first(i): return Index(first: _base1.index(before: i)) case let .second(i): return i == _base2.startIndex ? Index(first: _base1.index(before: _base1.endIndex)) : Index(second: _base2.index(before: i)) } } } extension Concatenation : RandomAccessCollection where C1: RandomAccessCollection, C2: RandomAccessCollection { public func index(_ i: Index, offsetBy n: Int) -> Index { if n == 0 { return i } return n > 0 ? _offsetForward(i, by: n) : _offsetBackward(i, by: -n) } internal func _offsetForward( _ i: Index, by n: Int ) -> Index { switch i._position { case let .first(i): let d: Int = _base1.distance(from: i, to: _base1.endIndex) if n < d { return Index(first: _base1.index(i, offsetBy: numericCast(n))) } else { return Index( second: _base2.index(_base2.startIndex, offsetBy: numericCast(n - d))) } case let .second(i): return Index(second: _base2.index(i, offsetBy: numericCast(n))) } } internal func _offsetBackward( _ i: Index, by n: Int ) -> Index { switch i._position { case let .first(i): return Index(first: _base1.index(i, offsetBy: -numericCast(n))) case let .second(i): let d: Int = _base2.distance(from: _base2.startIndex, to: i) if n <= d { return Index(second: _base2.index(i, offsetBy: -numericCast(n))) } else { return Index( first: _base1.index(_base1.endIndex, offsetBy: -numericCast(n - d))) } } } } /// Returns a new collection that presents a view onto the elements of the /// first collection and then the elements of the second collection. func concatenate<C1 : Collection, C2 : Collection>( _ first: C1, _ second: C2) -> Concatenation<C1, C2> where C1.Element == C2.Element { return Concatenation(_base1: first, base2: second) } //===--- RotatedCollection ------------------------------------------------===// //===----------------------------------------------------------------------===// /// A rotated view onto a collection. public struct RotatedCollection<Base : Collection> : Collection { let _base: Base let _indices: Concatenation<Base.Indices, Base.Indices> init(_base: Base, shiftingToStart i: Base.Index) { self._base = _base self._indices = concatenate(_base.indices[i...], _base.indices[..<i]) } /// A position in a rotated collection. public struct Index : Comparable { internal let _index: Concatenation<Base.Indices, Base.Indices>.Index public static func < (lhs: Index, rhs: Index) -> Bool { return lhs._index < rhs._index } } public var startIndex: Index { return Index(_index: _indices.startIndex) } public var endIndex: Index { return Index(_index: _indices.endIndex) } public subscript(i: Index) -> Base.SubSequence.Element { return _base[_indices[i._index]] } public func index(after i: Index) -> Index { return Index(_index: _indices.index(after: i._index)) } public func index(_ i: Index, offsetBy n: Int) -> Index { return Index(_index: _indices.index(i._index, offsetBy: n)) } public func distance(from start: Index, to end: Index) -> Int { return _indices.distance(from: start._index, to: end._index) } /// The shifted position of the base collection's `startIndex`. public var shiftedStartIndex: Index { return Index( _index: Concatenation<Base.Indices, Base.Indices>.Index( second: _indices._base2.startIndex) ) } public func rotated(shiftingToStart i: Index) -> RotatedCollection<Base> { return RotatedCollection(_base: _base, shiftingToStart: _indices[i._index]) } } extension RotatedCollection : BidirectionalCollection where Base : BidirectionalCollection { public func index(before i: Index) -> Index { return Index(_index: _indices.index(before: i._index)) } } extension RotatedCollection : RandomAccessCollection where Base : RandomAccessCollection {} extension Collection { /// Returns a view of this collection with the elements reordered such the /// element at the given position ends up first. /// /// The subsequence of the collection up to `i` is shifted to after the /// subsequence starting at `i`. The order of the elements within each /// partition is otherwise unchanged. /// /// let a = [10, 20, 30, 40, 50, 60, 70] /// let r = a.rotated(shiftingToStart: 3) /// // r.elementsEqual([40, 50, 60, 70, 10, 20, 30]) /// /// - Parameter i: The position in the collection that should be first in the /// result. `i` must be a valid index of the collection. /// - Returns: A rotated view on the elements of this collection, such that /// the element at `i` is first. func rotated(shiftingToStart i: Index) -> RotatedCollection<Self> { return RotatedCollection(_base: self, shiftingToStart: i) } } //===--- Stable Partition -------------------------------------------------===// //===----------------------------------------------------------------------===// extension BidirectionalCollection where Self : MutableCollectionAlgorithms { @discardableResult mutating func stablePartition( choosingStartGroupBy p: (Element) -> Bool ) -> Index { return _stablePartition( distance: distance(from: startIndex, to: endIndex), choosingStartGroupBy: p ) } mutating func _stablePartition( distance n: Int, choosingStartGroupBy p: (Element) -> Bool ) -> Index { assert(n >= 0) assert(n == distance(from: startIndex, to: endIndex)) if n == 0 { return startIndex } if n == 1 { return p(self[startIndex]) ? endIndex : startIndex } // divide and conquer. let d = n / numericCast(2) let m = index(startIndex, offsetBy: d) // TTTTTTTTT s FFFFFFF m ????????????? let s = self[..<m]._stablePartition( distance: numericCast(d), choosingStartGroupBy: p) // TTTTTTTTT s FFFFFFF m TTTTTTT e FFFFFFFF let e = self[m...]._stablePartition( distance: numericCast(n - d), choosingStartGroupBy: p) // TTTTTTTTT s TTTTTTT m FFFFFFF e FFFFFFFF return self[s..<e].rotate(shiftingToStart: m) } } extension Collection { func stablyPartitioned( choosingStartGroupBy p: (Element) -> Bool ) -> [Element] { var a = Array(self) a.stablePartition(choosingStartGroupBy: p) return a } } extension LazyCollectionProtocol where Element == Elements.Element { func stablyPartitioned( choosingStartGroupBy p: (Element) -> Bool ) -> LazyCollection<[Element]> { return elements.stablyPartitioned(choosingStartGroupBy: p).lazy } } extension Collection { /// Returns the index of the first element in the collection /// that matches the predicate. /// /// The collection must already be partitioned according to the /// predicate, as if `self.partition(by: predicate)` had already /// been called. func partitionPoint( where predicate: (Element) throws -> Bool ) rethrows -> Index { var n = distance(from: startIndex, to: endIndex) var l = startIndex while n > 0 { let half = n / 2 let mid = index(l, offsetBy: half) if try predicate(self[mid]) { n = half } else { l = index(after: mid) n -= half + 1 } } return l } } //===--- Tests ------------------------------------------------------------===// //===----------------------------------------------------------------------===// func address<T>(_ p: UnsafePointer<T>) -> UInt { return UInt(bitPattern: p )} var suite = TestSuite("Algorithms") suite.test("reverseSubrange") { for l in 0..<10 { let a = Array(0..<l) for p in a.startIndex...a.endIndex { let prefix = a[..<p] for q in p...l { let suffix = a[q...] var b = a b.reserveCapacity(b.count) // guarantee unique storage let id = address(b) b[p..<q].reverse() expectEqual( b, Array([prefix, ArraySlice(a[p..<q].reversed()), suffix].joined())) expectEqual(address(b), id) } } } } suite.test("rotate") { for l in 0..<11 { let a = Array(0..<l) for p in a.startIndex...a.endIndex { let prefix = a[..<p] for q in p...l { let suffix = a[q...] for m in p...q { var b = a b.reserveCapacity(b.count) // guarantee unique storage let id = address(b) let r = b[p..<q].rotate(shiftingToStart: m) let rotated = Array([prefix, a[m..<q], a[p..<m], suffix].joined()) expectEqual(b, rotated) expectEqual(r, a.index(p, offsetBy: a[m..<q].count)) expectEqual(address(b), id) } } var b = a b.rotate(shiftingToStart: p) expectEqual(b, Array(a.rotated(shiftingToStart: p))) } } } suite.test("rotateRandomAccess") { for l in 0..<11 { let a = Array(0..<l) for p in a.startIndex...a.endIndex { let prefix = a[..<p] for q in p...l { let suffix = a[q...] for m in p...q { var b = a b.reserveCapacity(b.count) // guarantee unique storage let id = address(b) let r = b[p..<q].rotateRandomAccess(shiftingToStart: m) let rotated = Array([prefix, a[m..<q], a[p..<m], suffix].joined()) expectEqual(b, rotated) expectEqual(r, a.index(p, offsetBy: a[m..<q].count)) expectEqual(address(b), id) } } var b = a b.rotateRandomAccess(shiftingToStart: p) expectEqual(b, Array(a.rotated(shiftingToStart: p))) } } } suite.test("concatenate") { for x in 0...6 { for y in 0...x { let r1 = 0..<y let r2 = y..<x expectEqual(Array(0..<x), Array(concatenate(r1, r2))) } } let c1 = concatenate([1, 2, 3, 4, 5], 6...10) let c2 = concatenate(1...5, [6, 7, 8, 9, 10]) expectEqual(Array(1...10), Array(c1)) expectEqual(Array(1...10), Array(c2)) let h = "Hello, " let w = "world!" let hw = concatenate(h, w) expectEqual("Hello, world!", String(hw)) } suite.test("stablePartition") { // FIXME: add test for stability for l in 0..<13 { let a = Array(0..<l) for p in a.startIndex...a.endIndex { let prefix = a[..<p] for q in p...l { let suffix = a[q...] let subrange = a[p..<q] for modulus in 1...5 { let f = { $0 % modulus == 0 } let notf = { !f($0) } var b = a b.reserveCapacity(b.count) // guarantee unique storage let id = address(b) var r = b[p..<q].stablePartition(choosingStartGroupBy: f) expectEqual(b[..<p], prefix) expectEqual(b.suffix(from:q), suffix) expectEqual(b[p..<r], ArraySlice(subrange.filter(f))) expectEqual(b[r..<q], ArraySlice(subrange.filter(notf))) expectEqual(address(b), id) b = a r = b[p..<q].stablePartition(choosingStartGroupBy: notf) expectEqual(b[..<p], prefix) expectEqual(b.suffix(from:q), suffix) expectEqual(b[p..<r], ArraySlice(subrange.filter(notf))) expectEqual(b[r..<q], ArraySlice(subrange.filter(f))) } } for modulus in 1...5 { let f = { $0 % modulus == 0 } let notf = { !f($0) } var b = a var r = b.stablePartition(choosingStartGroupBy: f) expectEqual(b[..<r], ArraySlice(a.filter(f))) expectEqual(b[r...], ArraySlice(a.filter(notf))) b = a r = b.stablePartition(choosingStartGroupBy: notf) expectEqual(b[..<r], ArraySlice(a.filter(notf))) expectEqual(b[r...], ArraySlice(a.filter(f))) } } } } suite.test("partitionPoint") { for i in 0..<7 { for j in i..<11 { for k in i...j { let p = (i..<j).partitionPoint { $0 >= k } expectGE(p, i) expectLE(p, j) expectEqual(p, k) } } } } runAllTests()
apache-2.0
283393dc89498b2c9db93429af746c15
29.661104
80
0.577727
3.866764
false
false
false
false
olivier38070/OAuthSwift
OAuthSwiftTests/OAuthSwiftRequestTests.swift
3
2055
// // OAuthSwiftRequestTests.swift // OAuthSwift // // Created by phimage on 17/11/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import XCTest @testable import OAuthSwift import Swifter class OAuthSwiftRequestTests: XCTestCase { var port: in_port_t = 8765 override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testFailure() { let oAuthSwiftHTTPRequest = OAuthSwiftHTTPRequest(URL: NSURL(string: "http://127.0.0.1:\(port)")!) let failureExpectation = expectationWithDescription("Expected `failure` to be called") oAuthSwiftHTTPRequest.failureHandler = { _ in failureExpectation.fulfill() } oAuthSwiftHTTPRequest.successHandler = { _ in XCTFail("The success handler should not be called. This can happen if you have a\nlocal server running on :\(self.port)") } oAuthSwiftHTTPRequest.start() waitForExpectationsWithTimeout(DefaultTimeout, handler: nil) } func testSuccess() { let server = HttpServer() server["/"] = { request in return HttpResponse.OK( HttpResponseBody.STRING("Success!" as String) ) } server.start(self.port) defer { server.stop() } let oAuthSwiftHTTPRequest = OAuthSwiftHTTPRequest(URL: NSURL(string: "http://127.0.0.1:\(port)")!) let successExpectation = expectationWithDescription("Expected `failure` to be called") oAuthSwiftHTTPRequest.failureHandler = { error in XCTFail("The failure handler should not be called.\(error)") } oAuthSwiftHTTPRequest.successHandler = { (data, response) in if String(data: data, encoding: NSUTF8StringEncoding) == "Success!" { successExpectation.fulfill() } } oAuthSwiftHTTPRequest.start() waitForExpectationsWithTimeout(DefaultTimeout, handler: nil) } }
mit
331f3fd4737aa7424adb99d7b15cf703
30.6
133
0.620253
4.985437
false
true
false
false
OpenStack-mobile/OAuth2-Swift
Sources/OAuth2/AuthorizationRequest.swift
1
4077
// // AuthorizationRequest.swift // OAuth2 // // Created by Alsey Coleman Miller on 12/16/16. // Copyright © 2016 OpenStack. All rights reserved. // import SwiftFoundation /// OAuth2 Authorization Request public struct AuthorizationRequest: Request { // MARK: - Supporting Types /// The client constructs the request URI by adding the following /// parameters to the query component of the authorization endpoint URI /// using the `"application/x-www-form-urlencoded"` format. public enum Parameter: String { /// REQUIRED. Value MUST be set to "code" or "token". case response_type /// REQUIRED. The client identifier as described in // [Section 2.2](https://tools.ietf.org/html/rfc6749#section-2.2). case client_id /// OPTIONAL. As described in [Section 3.1.2](https://tools.ietf.org/html/rfc6749#section-3.1.2). case redirect_uri /// OPTIONAL. The scope of the access request as described by /// [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). case scope /// RECOMMENDED. An opaque value used by the client to maintain /// state between the request and callback. The authorization /// server includes this value when redirecting the user-agent back /// to the client. The parameter SHOULD be used for preventing /// cross-site request forgery as described in /// [Section 10.12](https://tools.ietf.org/html/rfc6749#section-10.12). case state } /// Response type for Authorization Grant requests. public enum ResponseType: String { /// Expected response type for requesting an /// authorization code as described by /// [Section 4.1.1](https://tools.ietf.org/html/rfc6749#section-4.1.1) case authorizationCode = "code" /// Expected response type for requesting an /// access token (implicit grant) as described by /// [Section 4.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2) case implicit = "token" } // MARK: - Properties /// The URL of the OAuth2 endpoint for authentication grants. public var endpoint: String /// The kind of authentication grant flow. /// /// - SeeAlso: `AuthorizationRequest.ResponseType` public var responseType: ResponseType /// The client identifier. public var clientIdentifier: String /// The redirection endpoint URI /// as described in [Section 3.1.2](https://tools.ietf.org/html/rfc6749#section-3.1.2). public var redirectURI: String? /// The scope of the access request. public var scope: String? /// An opaque value used by the client to maintain state between the request and callback. public var state: String? // MARK: - Methods public func toURLRequest() -> HTTP.Request { guard var urlComponents = URLComponents(string: endpoint) else { fatalError("Invalid URL: \(endpoint)") } var queryItems = [URLQueryItem]() queryItems.append(URLQueryItem(name: Parameter.client_id.rawValue, value: clientIdentifier)) if let redirectURI = self.redirectURI { queryItems.append(URLQueryItem(name: Parameter.redirect_uri.rawValue, value: redirectURI)) } if let scope = self.scope { queryItems.append(URLQueryItem(name: Parameter.scope.rawValue, value: scope)) } if let state = self.state { queryItems.append(URLQueryItem(name: Parameter.state.rawValue, value: state)) } urlComponents.queryItems = queryItems guard let url = urlComponents.url else { fatalError("Invalid URL components: \(urlComponents)") } return HTTP.Request(url: url, headers: ["Content-Type": "application/x-www-form-urlencoded"]) } }
mit
68f5979fab2ef54bcaa7891be2f67ded
34.754386
106
0.619971
4.637088
false
false
false
false
SanctionCo/pilot-ios
pilot/SettingsConnectionCell.swift
1
2367
// // ConnectionTableViewCell.swift // pilot // // Created by Nick Eckert on 9/24/17. // Copyright © 2017 sanction. All rights reserved. // import UIKit class ConnectionTableViewCell: UITableViewCell { var platformImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.contentMode = UIViewContentMode.scaleAspectFit return image }() var platformName: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }() var disclosureMessage: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }() var platform: Platform? { didSet { platformImage.image = platform?.image platformName.text = platform?.type.rawValue if !platform!.isConnected { disclosureMessage.text = "Connect" disclosureMessage.textColor = UIColor.TextGreen } } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(platformImage) contentView.addSubview(platformName) contentView.addSubview(disclosureMessage) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() setupPlatformImage() setupPlatformName() setupDisclosureMessage() } func setupPlatformImage() { platformImage.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true platformImage.heightAnchor.constraint(equalToConstant: 35).isActive = true platformImage.widthAnchor.constraint(equalToConstant: 35).isActive = true platformImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true } func setupPlatformName() { platformName.leftAnchor.constraint(equalTo: platformImage.rightAnchor, constant: 10).isActive = true platformName.centerYAnchor.constraint(equalTo: platformImage.centerYAnchor).isActive = true } func setupDisclosureMessage() { disclosureMessage.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true disclosureMessage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true } }
mit
b7f6d3ee02f130fa88dc379200b0a10f
28.575
109
0.741758
4.960168
false
false
false
false
roland9/Yolandia
Yolandia/User.swift
1
4253
// // User.swift // Yolandia // // Created by Roland on 19/06/2014. // Copyright (c) 2014 mapps. All rights reserved. // import Foundation import CloudKit // switch between local mockups & CloudKit calls let isLocalMockupActive = false // records in public database let recordTypePublic = "AllUsers" let userNameField = "userName" // records in private database let recordTypeMyUsersPrivate = "MyUsers" class User { // public class func checkIfUserExists(userName: String, completionHandler: ((Bool!, NSError!) -> Void)!) { assert(userName != .None, "userName mandatory") if (isLocalMockupActive) { self.localCheckIfUserExists(userName, completionHandler) return } let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase let predicate = NSPredicate(format: "\(userNameField) = '\(userName)'") let query = CKQuery(recordType: recordTypePublic, predicate: predicate) publicDatabase.performQuery(query, inZoneWithID: nil, completionHandler: { (results, error) in println("found records \(results) with userName=\(userName)") if (error != nil) { completionHandler(results.count>0, error) } else { println("ERROR \(error.localizedDescription) performing query") completionHandler(false, error) } } ) } class func saveNewUser(userName: String, completionHandler: ((CKRecord!, NSError!) -> Void)!) { assert(userName != .None, "userName mandatory") if (isLocalMockupActive) { self.localSaveNewUser(userName, completionHandler) return } let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase var user = CKRecord(recordType: recordTypePublic) user.setObject(userName, forKey:userNameField) publicDatabase.saveRecord(user, completionHandler: { (savedRecord, error) in if (error == nil) { println("saved record: \(savedRecord)") completionHandler(savedRecord, error) } else { println("ERROR \(error.localizedDescription) saving record") completionHandler(nil, error) } } ) } class func getMyUsers(completionHandler:(([String]!, NSError!) -> Void)!) { if (isLocalMockupActive) { self.localGetMyUsers(completionHandler) return } let privateDatabase = CKContainer.defaultContainer().privateCloudDatabase let predicate = NSPredicate(value: true) let query = CKQuery(recordType: recordTypeMyUsersPrivate, predicate: predicate) privateDatabase.performQuery(query, inZoneWithID: nil, completionHandler: { (results, error) in if (error == nil) { let resultsArray = results as [CKRecord] let userNamesArray = resultsArray.map( { (userRecord: CKRecord) -> String in return userRecord.objectForKey(userNameField) as String }) println("found records: \(results)") completionHandler(nil, error) } else { println("ERROR \(error.localizedDescription) finding record") completionHandler(nil, error) } } ) } // private class func localCheckIfUserExists(userName: String, completionHandler: ((Bool!, NSError!) -> Void)!) { if (userName.hasPrefix("t")) { completionHandler( true, nil ) } else { completionHandler( false, nil) } } class func localSaveNewUser(userName: String, completionHandler: ((CKRecord!, NSError!) -> Void)!) { let userRecord = CKRecord(recordType: recordTypePublic) completionHandler( userRecord, nil ) } class func localGetMyUsers(completionHandler:(([String]!, NSError!) -> Void)!) { let userNames = [ "Roland", "Batman", "DummyUser" ] completionHandler(userNames, nil) } }
gpl-2.0
ee32db8269b2d997446f14354bbf5c19
33.868852
106
0.594404
5.130277
false
false
false
false
johnno1962d/swift
test/DebugInfo/inlinedAt.swift
1
2042
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -emit-verbose-sil -o - \ // RUN: | FileCheck %s --check-prefix=CHECK-SIL // RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o - | FileCheck %s public var glob : Int = 0 @inline(never) public func hold(_ n : Int) { glob = n } #sourceLocation(file: "abc.swift", line: 100) @inline(__always) func h(_ k : Int) -> Int { // 101 hold(k) // 102 return k // 103 } #sourceLocation(file: "abc.swift", line: 200) @inline(__always) func g(_ j : Int) -> Int { // 201 hold(j) // 202 return h(j) // 203 } #sourceLocation(file: "abc.swift", line: 301) public func f(_ i : Int) -> Int { // 301 return g(i) // 302 } // CHECK-SIL: sil {{.*}}@_TF9inlinedAt1fFSiSi : // CHECK-SIL-NOT: return // CHECK-SIL: debug_value %0 : $Int, let, name "k", argno 1 // CHECK-SIL-SAME: line:101:10:in_prologue // CHECK-SIL-SAME: perf_inlined_at line:203:10 // CHECK-SIL-SAME: perf_inlined_at line:302:10 // CHECK: define {{.*}}@_TF9inlinedAt1fFSiSi // CHECK-NOT: ret // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value // CHECK: @llvm.dbg.value({{.*}}), !dbg ![[L1:.*]] // CHECK: ![[F:.*]] = distinct !DISubprogram(name: "f", // CHECK: ![[G:.*]] = distinct !DISubprogram(name: "g", // CHECK: ![[H:.*]] = distinct !DISubprogram(name: "h", // CHECK: ![[L3:.*]] = !DILocation(line: 302, column: 13, // CHECK-SAME: scope: ![[F_SCOPE:.*]]) // CHECK: ![[F_SCOPE]] = distinct !DILexicalBlock(scope: ![[F]], // CHECK-SAME: line: 301, column: 33) // CHECK: ![[G_SCOPE:.*]] = distinct !DILexicalBlock(scope: ![[G]], // CHECK-SAME: line: 201, column: 26) // CHECK: ![[L1]] = !DILocation(line: 101, column: 8, scope: ![[H]], // CHECK-SAME: inlinedAt: ![[L2:.*]]) // CHECK: ![[L2]] = !DILocation(line: 203, column: 13, scope: ![[G_SCOPE]], // CHECK-SAME: inlinedAt: ![[L3]])
apache-2.0
d5873dbb731baf8dcfe6ada33af0a5c1
37.528302
77
0.522527
3.098634
false
false
false
false
Tsiems/mobile-sensing-apps
AirDrummer/DrumKit.swift
1
2489
// // DrumKit.swift // AirDrummer // // Created by Travis Siems on 12/8/16. // Copyright © 2016 Danh Nguyen. All rights reserved. // import UIKit class DrumKit: NSObject,NSCoding { let name: String let gestures: Dictionary<String, Gesture> init(name:String,gestures:Dictionary<String, Gesture>) { self.name = name self.gestures = gestures } required convenience init(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: "kitName") as! String let gestures = aDecoder.decodeObject(forKey: "gestures") as! Dictionary<String, Gesture> self.init(name:name,gestures:gestures) } public func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "kitName") aCoder.encode(gestures, forKey: "gestures") } } //global constant for default gestures in case no saved data is found let defaultGestures = ["Gesture 1":Gesture(id: "Gesture 1",gesture_name: "Face Up", gif_name: "popcorn",instrument: "Snare"), "Gesture 2":Gesture(id: "Gesture 2",gesture_name: "Up High",gif_name:"popcorn",instrument: "Hi-Hat"), "Gesture 3":Gesture(id: "Gesture 3",gesture_name: "Face Down",gif_name:"popcorn",instrument: "Toms")] //global variables for selecting and managing drum kits var selectedDrumKit = 0 var drumKits = [DrumKit(name:"Default Kit",gestures:["Gesture 1":Gesture(id: "Gesture 1",gesture_name: "Face Up", gif_name: "popcorn",instrument: "Snare")])] func saveDrumKits(data: [DrumKit]) { let drumKitData = NSKeyedArchiver.archivedData(withRootObject: data) UserDefaults.standard.set(drumKitData, forKey: "drumKits") } func saveSelectedKit(index:Int) { UserDefaults.standard.set(index, forKey: "selectedDrumKitIndex") } func loadDrumKits() -> [DrumKit] { if let drumkits = UserDefaults.standard.object(forKey: "drumKits") as? Data { if let drumkits = NSKeyedUnarchiver.unarchiveObject(with: drumkits) as? [DrumKit] { return drumkits } else { return [DrumKit(name: "Default Kit", gestures: defaultGestures)] //use default kit } } else { return [DrumKit(name: "Default Kit", gestures: defaultGestures)] //use default kit } } func loadSelectedKit() -> Int { if let index = UserDefaults.standard.object(forKey: "selectedDrumKitIndex") as? Int { return index } else { return 0 } }
mit
ee47b63868143b985a6e35a729e89bde
29.716049
157
0.653939
3.781155
false
false
false
false
Draveness/Neuron
Pod/Classes/Neuron.swift
1
1474
// // Neuron.swift // Pods // // Created by Draveness on 15/11/9. // // import Foundation import ObjectiveC public typealias NNBehaviorBlock = Any -> () public extension NSObject { private struct AssociatedKey { static var Neuron = "neuron" } public var neuron: Neuron { get { if let neuron = objc_getAssociatedObject(self, &AssociatedKey.Neuron) { return neuron as! Neuron } else { let neuron = Neuron(object: self) objc_setAssociatedObject(self, &AssociatedKey.Neuron, neuron, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return neuron } } } } public class Neuron: NSObject { private var behaviorDictionary: [String: NNBehaviorBlock] = [:] private weak var object: AnyObject? public init(object: AnyObject) { self.object = object } public func basedOnTarget(target: TargetObject, behaviorBlock: NNBehaviorBlock) -> Neuron { NSNotificationCenter.defaultCenter().addObserver(self, selector: "stimulus:", name: target.name, object: nil) behaviorDictionary[target.identifier] = behaviorBlock return self } func stimulus(notification: NSNotification) { if let signal = notification.object as? NeuronSignal { if let behaviorBlock = behaviorDictionary[signal.target.identifier] { behaviorBlock(signal.value) } } } }
mit
753db0f0ff34d26185ccb88148587e8c
25.818182
117
0.627544
4.507645
false
false
false
false
zhihaozhang/recordVideo
recordVideo/ViewController.swift
1
2360
// // ViewController.swift // recordVideo // // Created by Chih-Hao on 9/3/15. // Copyright (c) 2015 Chih-Hao. All rights reserved. // import UIKit import MobileCoreServices import MediaPlayer class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { var picker : UIImagePickerController! var videoUrl:NSURL? var player:MPMoviePlayerViewController! @IBAction func record(sender: AnyObject) { picker = UIImagePickerController() picker.mediaTypes=[kUTTypeMovie!] picker.sourceType=UIImagePickerControllerSourceType.Camera picker.cameraCaptureMode=UIImagePickerControllerCameraCaptureMode.Video presentViewController(picker, animated: true, completion: nil) picker.delegate=self } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL! picker.dismissViewControllerAnimated(true, completion: nil) } @IBAction func play(sender: AnyObject) { if let url=videoUrl{ player=MPMoviePlayerViewController(contentURL: url) presentViewController(player, animated: true, completion: nil) }else{ } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var url = NSURL(string: "http://www.weather.com.cn/data/sk/101110101.html") var data = NSData(contentsOfURL: url!, options: NSDataReadingOptions.UncachedRead, error: nil) var json = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments, error: nil) var weatherinfo = json?.objectForKey("weatherinfo") println(weatherinfo) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ddcb0aa7f84bc2a7dda0e948ef18be36
28.135802
125
0.660593
5.686747
false
false
false
false
sunlijian/sinaBlog_repository
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Public/Tool/IWNetWorkTools.swift
1
1536
// // IWNetWorkTools.swift // sinaBlog_sunlijian // // Created by sunlijian on 15/10/18. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit import AFNetworking enum IWNetWorkToolRequestType: String{ case GET = "GET" case POST = "POST" } class IWNetWorkTools: NSObject { class func request(type: IWNetWorkToolRequestType,url: String, paramters:[String: AnyObject], success:(result:[String: AnyObject])->(), failure:(error: NSError)->()){ //请求一个管理对象 let manager = AFHTTPSessionManager() //设置可接受和 contentType manager.responseSerializer.acceptableContentTypes?.insert("text/plain") //请求成功的闭包 let successCallBack = {(dataTask: NSURLSessionDataTask, result: AnyObject)->Void in if let res = (result as? [String: AnyObject]){ success(result: res) }else{ failure(error: NSError(domain: "com.itcast.weibo", code: 10001, userInfo: ["errorMsg": "The type of result isn't [String: AnyObject]"])) } } //请求失败的闭包 let failureCallBack = {(dataTask:NSURLSessionDataTask, error: NSError)->Void in failure(error: error) } if type == .GET{ manager.GET(url, parameters: paramters, success: successCallBack, failure: failureCallBack) }else{ manager.POST(url, parameters: paramters, success: successCallBack, failure: failureCallBack) } } }
apache-2.0
a179a54f8bf0c610465ae92e38d5a4c0
32.568182
170
0.631009
4.369822
false
false
false
false
wunshine/FoodStyle
FoodStyle/FoodStyle/Classes/Viewcontroller/AccountSetController.swift
1
3108
// // AccountSetController.swift // FoodStyle // // Created by Woz Wong on 16/3/9. // Copyright © 2016年 code4Fun. All rights reserved. // import UIKit class AccountSetController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() title = "账号设置" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dissMissVC") view.backgroundColor = UIColor.lightGrayColor() } @objc func dissMissVC(){ self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
b5baa99f3e7464aca83267ca9fad00ed
32.989011
157
0.684772
5.341969
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/PromiseKit/Sources/State.swift
42
6270
import class Dispatch.DispatchQueue import func Foundation.NSLog enum Seal<T> { case pending(Handlers<T>) case resolved(Resolution<T>) } enum Resolution<T> { case fulfilled(T) case rejected(Error, ErrorConsumptionToken) init(_ error: Error) { self = .rejected(error, ErrorConsumptionToken(error)) } } class State<T> { // would be a protocol, but you can't have typed variables of “generic” // protocols in Swift 2. That is, I couldn’t do var state: State<R> when // it was a protocol. There is no work around. Update: nor Swift 3 func get() -> Resolution<T>? { fatalError("Abstract Base Class") } func get(body: @escaping (Seal<T>) -> Void) { fatalError("Abstract Base Class") } final func pipe(_ body: @escaping (Resolution<T>) -> Void) { get { seal in switch seal { case .pending(let handlers): handlers.append(body) case .resolved(let resolution): body(resolution) } } } final func pipe(on q: DispatchQueue, to body: @escaping (Resolution<T>) -> Void) { pipe { resolution in contain_zalgo(q) { body(resolution) } } } final func then<U>(on q: DispatchQueue, else rejecter: @escaping (Resolution<U>) -> Void, execute body: @escaping (T) throws -> Void) { pipe { resolution in switch resolution { case .fulfilled(let value): contain_zalgo(q, rejecter: rejecter) { try body(value) } case .rejected(let error, let token): rejecter(.rejected(error, token)) } } } final func always(on q: DispatchQueue, body: @escaping (Resolution<T>) -> Void) { pipe { resolution in contain_zalgo(q) { body(resolution) } } } final func `catch`(on q: DispatchQueue, policy: CatchPolicy, else resolve: @escaping (Resolution<T>) -> Void, execute body: @escaping (Error) throws -> Void) { pipe { resolution in switch (resolution, policy) { case (.fulfilled, _): resolve(resolution) case (.rejected(let error, _), .allErrorsExceptCancellation) where error.isCancelledError: resolve(resolution) case (let .rejected(error, token), _): contain_zalgo(q, rejecter: resolve) { token.consumed = true try body(error) } } } } } class UnsealedState<T>: State<T> { private let barrier = DispatchQueue(label: "org.promisekit.barrier", attributes: .concurrent) private var seal: Seal<T> /** Quick return, but will not provide the handlers array because it could be modified while you are using it by another thread. If you need the handlers, use the second `get` variant. */ override func get() -> Resolution<T>? { var result: Resolution<T>? barrier.sync { if case .resolved(let resolution) = self.seal { result = resolution } } return result } override func get(body: @escaping (Seal<T>) -> Void) { var sealed = false barrier.sync { switch self.seal { case .resolved: sealed = true case .pending: sealed = false } } if !sealed { barrier.sync(flags: .barrier) { switch (self.seal) { case .pending: body(self.seal) case .resolved: sealed = true // welcome to race conditions } } } if sealed { body(seal) // as much as possible we do things OUTSIDE the barrier_sync } } required init(resolver: inout ((Resolution<T>) -> Void)!) { seal = .pending(Handlers<T>()) super.init() resolver = { resolution in var handlers: Handlers<T>? self.barrier.sync(flags: .barrier) { if case .pending(let hh) = self.seal { self.seal = .resolved(resolution) handlers = hh } } if let handlers = handlers { for handler in handlers { handler(resolution) } } } } #if !PMKDisableWarnings deinit { if case .pending = seal { NSLog("PromiseKit: Pending Promise deallocated! This is usually a bug") } } #endif } class SealedState<T>: State<T> { fileprivate let resolution: Resolution<T> init(resolution: Resolution<T>) { self.resolution = resolution } override func get() -> Resolution<T>? { return resolution } override func get(body: @escaping (Seal<T>) -> Void) { body(.resolved(resolution)) } } class Handlers<T>: Sequence { var bodies: [(Resolution<T>) -> Void] = [] func append(_ body: @escaping (Resolution<T>) -> Void) { bodies.append(body) } func makeIterator() -> IndexingIterator<[(Resolution<T>) -> Void]> { return bodies.makeIterator() } var count: Int { return bodies.count } } extension Resolution: CustomStringConvertible { var description: String { switch self { case .fulfilled(let value): return "Fulfilled with value: \(value)" case .rejected(let error): return "Rejected with error: \(error)" } } } extension UnsealedState: CustomStringConvertible { var description: String { var rv: String! get { seal in switch seal { case .pending(let handlers): rv = "Pending with \(handlers.count) handlers" case .resolved(let resolution): rv = "\(resolution)" } } return "UnsealedState: \(rv)" } } extension SealedState: CustomStringConvertible { var description: String { return "SealedState: \(resolution)" } }
lgpl-3.0
931e5051ea08b3532eabfe22b97fd661
27.60274
163
0.534163
4.519481
false
false
false
false
lhx931119/DouYuTest
DouYu/DouYu/Classes/Home/Controller/RecommendViewController.swift
1
5986
// // RecommendViewController.swift // DouYu // // Created by 李宏鑫 on 17/1/15. // Copyright © 2017年 hongxinli. All rights reserved. // import UIKit private let kItemMagin: CGFloat = 10 private let kItemW: CGFloat = (kScreenW - 3 * kItemMagin) / 2 private let kItemNormalH: CGFloat = kItemW * 3 / 4 private let kItemPrettyH: CGFloat = kItemW * 4 / 3 private let kHeadViewH: CGFloat = 50 private let kCycleViewH = kScreenW * 3 / 8 private let kGameViewH : CGFloat = 90 private let kNormalCellID = "kNormalCellID" private let kPrettylCellID = "kPrettylCellID" private let kHeadViewID = "kHeadViewID" class RecommendViewController: UIViewController { //懒加载属性 private lazy var gameView: RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() private lazy var cycleView: RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() private lazy var recommendVM:RecommendViewModel = RecommendViewModel() private lazy var collectionView: UICollectionView = { [unowned self] in let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemNormalH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMagin ///设置区边距 layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeadViewH) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.whiteColor() collectionView.dataSource = self collectionView.delegate = self ///全部显示 collectionView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] collectionView.registerNib(UINib(nibName: "CollectionNormalCell", bundle: nil) , forCellWithReuseIdentifier:kNormalCellID) collectionView.registerNib(UINib(nibName: "CollectionPrettyCell", bundle: nil) , forCellWithReuseIdentifier:kPrettylCellID) collectionView.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeadViewID) return collectionView }() //系统回调函数 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.purpleColor() //设置UI setUI() //请求数据 loadData() } } // Mark:-设置UI extension RecommendViewController { private func setUI(){ //添加collectionView view.addSubview(collectionView) // 添加cycleView collectionView.addSubview(cycleView) // 添加gameView collectionView.addSubview(gameView) //设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top:kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) } } // Mark:-请求数据 extension RecommendViewController{ private func loadData(){ //请求推荐数据 recommendVM.requestData { self.collectionView.reloadData() //游戏数据 self.gameView.group = self.recommendVM.anchorGroups } //请求无限轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModels = self.recommendVM.cycleModels } } } // Mark:- 遵守collectionDataSource extension RecommendViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return recommendVM.anchorGroups.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendVM.anchorGroups[section] return group.anchors.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { //取出模型 let group = recommendVM.anchorGroups[indexPath.section] let anchor = group.anchors[indexPath.item] //定义cell var cell: CollectionBaseCell! //取出cell if indexPath.section == 1 { cell = collectionView.dequeueReusableCellWithReuseIdentifier(kPrettylCellID, forIndexPath: indexPath) as! CollectionPrettyCell }else{ cell = collectionView.dequeueReusableCellWithReuseIdentifier(kNormalCellID, forIndexPath: indexPath) as! CollectionNormalCell } //给模型赋值 cell.anchor = anchor return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let headView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kHeadViewID, forIndexPath: indexPath) as! CollectionHeaderView headView.group = recommendVM.anchorGroups[indexPath.section] return headView } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ if indexPath.section == 1 { return CGSize(width: kItemW, height: kItemPrettyH) }else{ return CGSize(width: kItemW, height: kItemNormalH) } } }
mit
a43f6f1b8e23cae84f13d672a7f63f63
30.139037
187
0.679547
5.631528
false
false
false
false
dzenbot/Iconic
Vendor/SwiftGen/Pods/Stencil/Sources/Inheritence.swift
2
3199
class BlockContext { class var contextKey: String { return "block_context" } var blocks: [String:BlockNode] init(blocks: [String:BlockNode]) { self.blocks = blocks } func pop(blockName: String) -> BlockNode? { return blocks.removeValueForKey(blockName) } } extension CollectionType { func any(closure: Generator.Element -> Bool) -> Generator.Element? { for element in self { if closure(element) { return element } } return nil } } class ExtendsNode : NodeType { let templateName: Variable let blocks: [String:BlockNode] class func parse(parser: TokenParser, token: Token) throws -> NodeType { let bits = token.components() guard bits.count == 2 else { throw TemplateSyntaxError("'extends' takes one argument, the template file to be extended") } let parsedNodes = try parser.parse() guard (parsedNodes.any { $0 is ExtendsNode }) == nil else { throw TemplateSyntaxError("'extends' cannot appear more than once in the same template") } let blockNodes = parsedNodes.filter { node in node is BlockNode } let nodes = blockNodes.reduce([String:BlockNode]()) { (accumulator, node:NodeType) -> [String:BlockNode] in let node = (node as! BlockNode) var dict = accumulator dict[node.name] = node return dict } return ExtendsNode(templateName: Variable(bits[1]), blocks: nodes) } init(templateName: Variable, blocks: [String: BlockNode]) { self.templateName = templateName self.blocks = blocks } func render(context: Context) throws -> String { guard let loader = context["loader"] as? TemplateLoader else { throw TemplateSyntaxError("Template loader not in context") } guard let templateName = try self.templateName.resolve(context) as? String else { throw TemplateSyntaxError("'\(self.templateName)' could not be resolved as a string") } guard let template = loader.loadTemplate(templateName) else { let paths:String = loader.paths.map { $0.description }.joinWithSeparator(", ") throw TemplateSyntaxError("'\(templateName)' template not found in \(paths)") } let blockContext = BlockContext(blocks: blocks) context.push([BlockContext.contextKey: blockContext]) let result = try template.render(context) context.pop() return result } } class BlockNode : NodeType { let name: String let nodes: [NodeType] class func parse(parser: TokenParser, token: Token) throws -> NodeType { let bits = token.components() guard bits.count == 2 else { throw TemplateSyntaxError("'block' tag takes one argument, the template file to be included") } let blockName = bits[1] let nodes = try parser.parse(until(["endblock"])) parser.nextToken() return BlockNode(name:blockName, nodes:nodes) } init(name: String, nodes: [NodeType]) { self.name = name self.nodes = nodes } func render(context: Context) throws -> String { if let blockContext = context[BlockContext.contextKey] as? BlockContext, node = blockContext.pop(name) { return try node.render(context) } return try renderNodes(nodes, context) } }
mit
75ebf55cf5e3de5a8f5add8b20f56890
27.061404
111
0.677087
4.209211
false
false
false
false
maitruonghcmus/QuickChat
QuickChat/ViewControllers/ProfileVC.swift
1
1725
import UIKit import Firebase class ProfileVC: UIViewController { //MARK: *** Variable //MARK: *** UI Elements //MARK: *** Custom Functions //MARK: *** UI Events //MARK: *** View //MARK: *** Table View @IBOutlet weak var imgProfile: RoundedImageView! @IBOutlet weak var lblName: UILabel! @IBOutlet weak var lblEmail: UILabel! @IBOutlet weak var btnLogout: RoundedButton! func setLanguague(){ DispatchQueue.main.async { self.navigationItem.title = MultiLanguague.profileItem self.btnLogout.setTitle(MultiLanguague.profileBtnLogout, for: .normal) } //self.setLanguague(lang: MultiLanguague.languague) } override func viewDidAppear(_ animated: Bool) { self.setLanguague() } //Downloads current user credentials func fetchUserInfo() { if let id = FIRAuth.auth()?.currentUser?.uid { User.info(forUserID: id, completion: {[weak weakSelf = self] (user) in DispatchQueue.main.async { weakSelf?.lblName.text = user.name weakSelf?.lblEmail.text = user.email weakSelf?.imgProfile.image = user.profilePic weakSelf = nil } }) } } @IBAction func btnLogOut_Tapped(_ sender: Any) { User.logOutUser { (status) in if status == true { self.dismiss(animated: true, completion: nil) } } } override func viewDidLoad() { super.viewDidLoad() self.fetchUserInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
286dfbc1ebc02c6da4ea4ae82183be33
27.278689
109
0.576232
4.6875
false
false
false
false
Venkat1128/ObjCProblemSet
Problem Set/Animals_Swift/Animals_Swift/main.swift
1
958
// // main.swift // Animals_Swift // // Created by Gabrielle Miller-Messner on 4/12/16. // Copyright © 2016 Gabrielle Miller-Messner. All rights reserved. // import Foundation // Initialize some animals let babe = Pig() let snoopy = GoldenDoodle() let templeton = Rat() let sinatra = Rat() let cary = Pigeon() // Initialize my dwellings with some animals let myFarm = Farm(animals:[babe, snoopy, templeton]) let myApartment = Apartment(animals:[sinatra, cary, snoopy]) // Choose an animal to invoke a method let randomNumber = Int(arc4random_uniform(3)) let farmAnimal = myFarm?.animals![randomNumber] let cityAnimal = myApartment?.animals![randomNumber] if let farmAnimal = farmAnimal as? Rat { farmAnimal.scurry() } else if let farmAnimal = farmAnimal as? GoldenDoodle { farmAnimal.romp() } else if let farmAnimal = farmAnimal as? Pig { farmAnimal.wallow() } if let pigeon = cityAnimal as? Pigeon { pigeon.deliverMessage() }
mit
4e8b64a1d1e6871180509016cb3485b6
22.341463
67
0.721003
3.244068
false
false
false
false
loudnate/Loop
Loop/View Controllers/InsulinModelSettingsViewController.swift
1
12434
// // InsulinModelSettingsViewController.swift // Loop // // Copyright © 2017 LoopKit Authors. All rights reserved. // import UIKit import HealthKit import LoopCore import LoopKit import LoopUI protocol InsulinModelSettingsViewControllerDelegate: class { func insulinModelSettingsViewControllerDidChangeValue(_ controller: InsulinModelSettingsViewController) } class InsulinModelSettingsViewController: ChartsTableViewController, IdentifiableClass { var glucoseUnit: HKUnit { get { return insulinModelChart.glucoseUnit } set { insulinModelChart.glucoseUnit = newValue refreshContext = true if visible && active { reloadData() } } } weak var delegate: InsulinModelSettingsViewControllerDelegate? private var initialInsulinModel: InsulinModel? /// The currently-selected model. var insulinModel: InsulinModel? { didSet { if let newValue = insulinModel as? WalshInsulinModel { allModels[walshModelIndex] = newValue } refreshContext = true reloadData() } } override func glucoseUnitDidChange() { refreshContext = true } /// The sensitivity (in glucose units) to use for demonstrating the model var insulinSensitivitySchedule = InsulinSensitivitySchedule(unit: .milligramsPerDeciliter, dailyItems: [RepeatingScheduleValue<Double>(startTime: 0, value: 40)])! fileprivate let walshModelIndex = 0 private var allModels: [InsulinModel] = [ WalshInsulinModel(actionDuration: .hours(6)), ExponentialInsulinModelPreset.humalogNovologAdult, ExponentialInsulinModelPreset.humalogNovologChild, ExponentialInsulinModelPreset.fiasp ] private var selectedModelIndex: Int? { switch insulinModel { case .none: return nil case is WalshInsulinModel: return walshModelIndex case let selectedModel as ExponentialInsulinModelPreset: for index in 1..<allModels.count { if selectedModel == (allModels[index] as! ExponentialInsulinModelPreset) { return index } } default: assertionFailure("Unknown insulin model: \(String(describing: insulinModel))") } return nil } private var refreshContext = true /// The range of durations considered valid for Walsh models fileprivate let validDuration = (min: TimeInterval(hours: 2), max: TimeInterval(hours: 8)) fileprivate lazy var durationFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.collapsesLargestUnit = true formatter.unitsStyle = .short formatter.allowsFractionalUnits = true formatter.allowedUnits = [.hour, .minute] return formatter }() // MARK: - UIViewController @IBOutlet fileprivate var durationPicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 91 } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Record the configured insulinModel for change tracking initialInsulinModel = insulinModel } override func viewWillDisappear(_ animated: Bool) { // Notify observers if the model changed since viewDidAppear switch (initialInsulinModel, insulinModel) { case let (lhs, rhs) as (WalshInsulinModel, WalshInsulinModel): if lhs != rhs { delegate?.insulinModelSettingsViewControllerDidChangeValue(self) } case let (lhs, rhs) as (ExponentialInsulinModelPreset, ExponentialInsulinModelPreset): if lhs != rhs { delegate?.insulinModelSettingsViewControllerDidChangeValue(self) } default: delegate?.insulinModelSettingsViewControllerDidChangeValue(self) } super.viewWillDisappear(animated) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { refreshContext = true super.viewWillTransition(to: size, with: coordinator) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() refreshContext = true } // MARK: - ChartsTableViewController private let insulinModelChart = InsulinModelChart() override func createChartsManager() -> ChartsManager { return ChartsManager(colors: .default, settings: .default, charts: [insulinModelChart], traitCollection: traitCollection) } override func reloadData(animated: Bool = true) { if active && visible && refreshContext { refreshContext = false charts.startDate = Calendar.current.nextDate(after: Date(), matching: DateComponents(minute: 0), matchingPolicy: .strict, direction: .backward) ?? Date() let bolus = DoseEntry(type: .bolus, startDate: charts.startDate, value: 1, unit: .units) let selectedModelIndex = self.selectedModelIndex let startingGlucoseValue = insulinSensitivitySchedule.quantity(at: charts.startDate).doubleValue(for: glucoseUnit) + glucoseUnit.glucoseExampleTargetValue let startingGlucoseQuantity = HKQuantity(unit: glucoseUnit, doubleValue: startingGlucoseValue) let endingGlucoseQuantity = HKQuantity(unit: glucoseUnit, doubleValue: glucoseUnit.glucoseExampleTargetValue) let startingGlucoseSample = HKQuantitySample(type: HKQuantityType.quantityType(forIdentifier: .bloodGlucose)!, quantity: startingGlucoseQuantity, start: charts.startDate, end: charts.startDate) insulinModelChart.glucoseDisplayRange = endingGlucoseQuantity...startingGlucoseQuantity var unselectedModelValues = [[GlucoseValue]]() for (index, model) in allModels.enumerated() { let effects = [bolus].glucoseEffects(insulinModel: model, insulinSensitivity: insulinSensitivitySchedule) let values = LoopMath.predictGlucose(startingAt: startingGlucoseSample, effects: effects) if selectedModelIndex == index { insulinModelChart.setSelectedInsulinModelValues(values) } else { unselectedModelValues.append(values) } } insulinModelChart.setUnselectedInsulinModelValues(unselectedModelValues) charts.invalidateChart(atIndex: 0) // Rendering charts.prerender() for case let cell as ChartTableViewCell in self.tableView.visibleCells { cell.reloadChart() } } } // MARK: - UITableViewDataSource fileprivate enum Section: Int { case charts case models static let count = 2 } override func numberOfSections(in tableView: UITableView) -> Int { return Section.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .charts: return 1 case .models: return allModels.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .charts: let cell = tableView.dequeueReusableCell(withIdentifier: ChartTableViewCell.className, for: indexPath) as! ChartTableViewCell cell.contentView.layoutMargins.left = tableView.separatorInset.left cell.chartContentView.chartGenerator = { [weak self] (frame) in return self?.charts.chart(atIndex: 0, frame: frame)?.view } return cell case .models: let cell = tableView.dequeueReusableCell(withIdentifier: TitleSubtitleTextFieldTableViewCell.className, for: indexPath) as! TitleSubtitleTextFieldTableViewCell let isSelected = selectedModelIndex == indexPath.row cell.tintColor = isSelected ? nil : .clear cell.textField.isEnabled = isSelected switch allModels[indexPath.row] { case let model as WalshInsulinModel: configureCell(cell, duration: model.actionDuration) cell.titleLabel.text = model.title cell.subtitleLabel.text = model.subtitle case let model as ExponentialInsulinModelPreset: configureCell(cell, duration: nil) cell.titleLabel.text = model.title cell.subtitleLabel.text = model.subtitle case let model: assertionFailure("Unknown insulin model: \(model)") } return cell } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard case .models? = Section(rawValue: indexPath.section) else { return } insulinModel = allModels[indexPath.row] let selectedIndex = selectedModelIndex for index in 0..<allModels.count { guard let cell = tableView.cellForRow(at: IndexPath(row: index, section: Section.models.rawValue)) as? TitleSubtitleTextFieldTableViewCell else { continue } let isSelected = selectedIndex == index cell.tintColor = isSelected ? nil : .clear let walshModel = allModels[index] as? WalshInsulinModel configureCell(cell, duration: walshModel?.actionDuration) cell.textField.isEnabled = isSelected if walshModel != nil && isSelected && !cell.textField.isFirstResponder { cell.textField.becomeFirstResponder() } else { cell.textField.resignFirstResponder() } } tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Duration editing fileprivate extension InsulinModelSettingsViewController { func configureCell(_ cell: TitleSubtitleTextFieldTableViewCell, duration: TimeInterval?) { if let duration = duration { cell.textField.isHidden = false cell.textField.delegate = self cell.textField.tintColor = .clear // Makes the cursor invisible cell.textField.inputView = durationPicker cell.textField.text = durationFormatter.string(from: duration) self.durationPicker.countDownDuration = duration durationPicker.addTarget(self, action: #selector(durationPickerChanged(_:)), for: .valueChanged) } else { cell.textField.isHidden = true cell.textField.delegate = nil cell.textField.tintColor = nil cell.textField.inputView = nil cell.textField.text = nil } } @IBAction func durationPickerChanged(_ sender: UIDatePicker) { guard let cell = tableView.cellForRow(at: IndexPath(row: walshModelIndex, section: Section.models.rawValue)) as? TitleSubtitleTextFieldTableViewCell else { return } sender.countDownDuration = min(validDuration.max, max(validDuration.min, sender.countDownDuration)) cell.textField.text = durationFormatter.string(from: sender.countDownDuration) cell.contentView.setNeedsLayout() insulinModel = WalshInsulinModel(actionDuration: sender.countDownDuration) } } extension InsulinModelSettingsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { // Set duration again as a workaround for valueChanged actions not being triggered guard let model = insulinModel as? WalshInsulinModel else { return } DispatchQueue.main.async { self.durationPicker.countDownDuration = model.actionDuration } } } fileprivate extension HKUnit { /// An example value for the "ideal" target var glucoseExampleTargetValue: Double { if self == .milligramsPerDeciliter { return 100 } else { return 5.5 } } }
apache-2.0
96756d989ecf7363e2aceeb3eaec506b
34.829971
205
0.657685
5.560376
false
false
false
false
kevindelord/DKDBManager
Example/DBSwiftTest/Database/Baggage/Baggage.swift
1
1863
// // Baggage.swift // DBSwiftTest // // Created by kevin delord on 22/01/16. // Copyright © 2016 Smart Mobile Factory. All rights reserved. // import Foundation import CoreData import DKHelper class Baggage: NSManagedObject { // Insert code here to add functionality to your managed object subclass } // MARK: - DKDBManager extension Baggage { override var description : String { var description = "\(self.objectID.uriRepresentation().lastPathComponent)" if let w = self.weight as? Int { description += ": \(w) kg" } if let passenger = self.passenger?.objectID.uriRepresentation().lastPathComponent { description += ", passenger: \(passenger)" } return description } override func saveEntityAsNotDeprecated() { super.saveEntityAsNotDeprecated() } override func update(with dictionary: [AnyHashable: Any]?, in savingContext: NSManagedObjectContext) { super.update(with: dictionary, in: savingContext) self.weight = GET_NUMBER(dictionary, JSON.Weight) } override func invalidReason() -> String? { if let invalidReason = super.invalidReason() { return invalidReason } guard let weight = self.weight as? Int, (weight > 0) else { return "Invalid weight" } // valid baggage. return nil } override class func verbose() -> Bool { return Verbose.Model.Baggage } override func deleteEntity(withReason reason: String?, in savingContext: NSManagedObjectContext) { super.deleteEntity(withReason: reason, in: savingContext) } override class func sortingAttributeName() -> String? { return JSON.Weight } override class func primaryPredicate(with dictionary: [AnyHashable: Any]?) -> NSPredicate? { return NSPredicate(format: "FALSEPREDICATE") } override func shouldUpdateEntity(with dictionary: [AnyHashable: Any]?, in savingContext: NSManagedObjectContext) -> Bool { return true } }
mit
fcec0bdfb9bb6bc86b70ede4b19074d4
23.181818
123
0.727175
3.823409
false
false
false
false
codefellows/sea-d40-iOS
Sample Code/Week2Filtering/ParseSwiftStarterProject/ParseStarterProject/FilterService.swift
1
1163
// // FilterService.swift // ParseStarterProject // // Created by Bradley Johnson on 8/12/15. // Copyright (c) 2015 Parse. All rights reserved. // import UIKit class FilterService { class func sepiaImageFromOriginalImage(original : UIImage, context : CIContext) -> UIImage! { let image = CIImage(image: original) let filter = CIFilter(name: "CISepiaTone") filter.setValue(image, forKey: kCIInputImageKey) return filteredImageFromFilter(filter, context: context) } class func instantImageFromOriginalImage(original : UIImage,context : CIContext) -> UIImage! { let image = CIImage(image: original) let filter = CIFilter(name: "CIPhotoEffectInstant") filter.setValue(image, forKey: kCIInputImageKey) //set the vector for the colors return filteredImageFromFilter(filter, context: context) } private class func filteredImageFromFilter(filter : CIFilter, context : CIContext) -> UIImage { let outputImage = filter.outputImage let extent = outputImage.extent() let cgImage = context.createCGImage(outputImage, fromRect: extent) return UIImage(CGImage: cgImage)! } }
mit
7bfc1db1ef61f5a9e64191c27519d27b
28.820513
97
0.713672
4.490347
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/CollectionLayouts/VerticalColumnPositioningContext.swift
1
2053
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit /** * The context for computing the position of items. */ struct VerticalColumnPositioningContext { /// The width of the collection view container, minus insets. let contentWidth: CGFloat /// The number of columns that will organize the contents. let numberOfColumns: Int /// The spacing between items inside the same column. let interItemSpacing: CGFloat /// The spacing between columns. let interColumnSpacing: CGFloat /// The start position of each columns. let columns: [CGFloat] /// The width of a single column. let columnWidth: CGFloat init(contentWidth: CGFloat, numberOfColumns: Int, interItemSpacing: CGFloat, interColumnSpacing: CGFloat) { self.contentWidth = contentWidth self.numberOfColumns = numberOfColumns self.interItemSpacing = interItemSpacing self.interColumnSpacing = interColumnSpacing let totalSpacing = (CGFloat(numberOfColumns - 1) * interColumnSpacing) let columnWidth = ((contentWidth - totalSpacing) / CGFloat(numberOfColumns)) self.columns = (0 ..< numberOfColumns).map { let base = CGFloat($0) * columnWidth let precedingSpacing = CGFloat($0) * interColumnSpacing return base + precedingSpacing } self.columnWidth = columnWidth } }
gpl-3.0
89e785e793ef2834a331a3f13c1ec197
31.587302
111
0.704335
4.841981
false
false
false
false
AlasKuNull/SwiftyExcelView
AKExcelDemo/AKExcelDemo/AKExcelView/AKExcelView.swift
1
18948
// // ExcelViewSwifty.swift // YunYingSwift // // Created by AlasKu on 17/2/10. // Copyright © 2017年 innostic. All rights reserved. // import UIKit let AKCollectionViewCellIdentifier = "AKCollectionView_Cell" let AKCollectionViewHeaderIdentifier = "AKCollectionView_Header" @objc protocol AKExcelViewDelegate : NSObjectProtocol { @objc optional func excelView(_ excelView: AKExcelView, didSelectItemAt indexPath: IndexPath) @objc optional func excelView(_ excelView: AKExcelView, viewAt indexPath: IndexPath) -> UIView? @objc optional func excelView(_ excelView: AKExcelView, attributedStringAt indexPath: IndexPath) -> NSAttributedString? } class AKExcelView: UIView , UICollectionViewDelegate , UICollectionViewDataSource , UIScrollViewDelegate , UICollectionViewDelegateFlowLayout{ /// Delegate weak var delegate : AKExcelViewDelegate? /// CellTextMargin var textMargin : CGFloat = 5 /// Cell Max width var itemMaxWidth : CGFloat = 200 /// cell Min width var itemMinWidth : CGFloat = 50 /// cell heihth var itemHeight : CGFloat = 44 /// header Height var headerHeight : CGFloat = 44 /// header BackgroundColor var headerBackgroundColor : UIColor = UIColor.lightGray /// header Text Color var headerTextColor : UIColor = UIColor.black /// header Text Font var headerTextFontSize : UIFont = UIFont.systemFont(ofSize: 15) /// contenTCell TextColor var contentTextColor : UIColor = UIColor.black /// content backgroung Color var contentBackgroundColor : UIColor = UIColor.white /// content Text Font var contentTextFontSize : UIFont = UIFont.systemFont(ofSize: 13) /// letf freeze column var leftFreezeColumn : Int = 1 /// header Titles var headerTitles : Array<String>? /// content Data var contentData : Array<NSObject>? /// set Column widths var columnWidthSetting : Dictionary<Int, CGFloat>? /// CelledgeInset var itemInsets : UIEdgeInsets? /// showsProperties var properties : Array<String>? /// autoScrollItem default is false var autoScrollToNearItem : Bool = false /// showNoDataView default is false var showNoDataView : Bool = false { didSet{ self.addSubview(alertLabel) alertLabel.center = self.center } } var noDataDescription : String = " - 暂无数据 - " { didSet{ alertLabel.text = noDataDescription } } var alertLabel : UILabel = { let alertLabel = UILabel() alertLabel.text = " - 暂无数据 - " alertLabel.textColor = .lightGray alertLabel.sizeToFit() return alertLabel }() fileprivate lazy var horizontalShadow : CAShapeLayer = { let s = CAShapeLayer() s.strokeColor = UIColor.lightGray.cgColor; s.shadowColor = UIColor.black.cgColor; s.shadowOffset = CGSize.init(width: 2, height: 0) s.shadowOpacity = 1; return s }() fileprivate lazy var veritcalShadow : CAShapeLayer = { let s = CAShapeLayer() s.strokeColor = UIColor.lightGray.cgColor; s.shadowColor = UIColor.black.cgColor; s.shadowOffset = CGSize.init(width: 0, height: 3) s.shadowOpacity = 1; return s }() //MARK: - Public Method override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() setUpFrames() } func reloadData() { DispatchQueue.global().async { self.dataManager.caculateData() DispatchQueue.main.async { self.headFreezeCollectionView.reloadData() self.headMovebleCollectionView.reloadData() self.contentFreezeCollectionView.reloadData() self.contentMoveableCollectionView.reloadData() self.setUpFrames() } } } func reloadDataCompleteHandler(complete:@escaping () -> Void) { DispatchQueue.global().async { self.dataManager.caculateData() DispatchQueue.main.async { self.headFreezeCollectionView.reloadData() self.headMovebleCollectionView.reloadData() self.contentFreezeCollectionView.reloadData() self.contentMoveableCollectionView.reloadData() self.setUpFrames() complete() } } } func sizeForItem(item: Int) -> CGSize { if item < leftFreezeColumn { return CGSizeFromString(self.dataManager.freezeItemSize[item]); } else { return CGSizeFromString(self.dataManager.slideItemSize[item - leftFreezeColumn]); } } //MARK: - Private Method private func setup() { dataManager.excelView = self clipsToBounds = true addSubview(headFreezeCollectionView) addSubview(contentFreezeCollectionView) addSubview(contentScrollView) contentScrollView.addSubview(headMovebleCollectionView) contentScrollView.addSubview(contentMoveableCollectionView) contentMoveableCollectionView.contentInset = UIEdgeInsetsMake(-1, 0, 0, 0) contentFreezeCollectionView.contentInset = UIEdgeInsetsMake(-1, 0, 0, 0) layer.addSublayer(horizontalShadow) contentScrollView.layer.addSublayer(veritcalShadow) } fileprivate func showHorizontalDivideShadowLayer() { if horizontalShadow.path == nil { let path = UIBezierPath() path.move(to: CGPoint.init(x: 0, y: headerHeight)) path.addLine(to: CGPoint.init(x: min(self.bounds.size.width, self.dataManager.freezeWidth + self.dataManager.slideWidth), y: headerHeight)) path.lineWidth = 0.5 horizontalShadow.path = path.cgPath } } fileprivate func dismissHorizontalDivideShadowLayer() { horizontalShadow.path = nil } fileprivate func showVerticalDivideShadowLayer() { if veritcalShadow.path == nil { let path = UIBezierPath() let heigh = contentScrollView.contentSize.height + headFreezeCollectionView.contentSize.height path.move(to: CGPoint.init(x: 0, y:0)) path.addLine(to: CGPoint.init(x: 0, y: heigh)) path.lineWidth = 0.5 veritcalShadow.path = path.cgPath } } fileprivate func dismissVerticalDivideShadowLayer() { veritcalShadow.path = nil } fileprivate func setUpFrames() { let width = bounds.size.width let height = bounds.size.height if headerTitles != nil { headFreezeCollectionView.frame = CGRect.init(x: 0, y: 0, width: dataManager.freezeWidth, height: headerHeight) contentFreezeCollectionView.frame = CGRect.init(x: 0, y: headerHeight, width: dataManager.freezeWidth, height: height - headerHeight) contentScrollView.frame = CGRect.init(x: dataManager.freezeWidth, y: 0, width: width - dataManager.freezeWidth, height: height) contentScrollView.contentSize = CGSize.init(width: dataManager.slideWidth, height: height) headMovebleCollectionView.frame = CGRect.init(x: 0, y: 0, width: dataManager.slideWidth, height: headerHeight) contentMoveableCollectionView.frame = CGRect.init(x: 0, y: headerHeight, width: dataManager.slideWidth, height: height - headerHeight) }else{ contentFreezeCollectionView.frame = CGRect.init(x: 0, y: 0, width: dataManager.freezeWidth, height: height - headerHeight) contentScrollView.frame = CGRect.init(x: dataManager.freezeWidth, y: 0, width: width - dataManager.freezeWidth, height: height) contentScrollView.contentSize = CGSize.init(width: dataManager.slideWidth, height: height) contentMoveableCollectionView.frame = CGRect.init(x: 0, y: 0, width: dataManager.slideWidth, height: height - headerHeight) } if showNoDataView { self.alertLabel.isHidden = self.contentData?.count == 0 ? false : true } } //MARK: - 懒加载 fileprivate let dataManager : AKExcelDataManager = AKExcelDataManager() fileprivate lazy var headFreezeCollectionView : UICollectionView = { return UICollectionView.init(delelate: self, datasource: self) }() fileprivate lazy var headMovebleCollectionView : UICollectionView = { return UICollectionView.init(delelate: self, datasource: self) }() fileprivate lazy var contentFreezeCollectionView : UICollectionView = { return UICollectionView.init(delelate: self, datasource: self) }() fileprivate lazy var contentMoveableCollectionView : UICollectionView = { return UICollectionView.init(delelate: self, datasource: self) }() fileprivate lazy var contentScrollView : UIScrollView = { let slideScrollView = UIScrollView() slideScrollView.bounces = false slideScrollView.showsHorizontalScrollIndicator = true slideScrollView.delegate = self return slideScrollView }() } //MARK: - UICollectionView Delegate & DataSource & collectionPrivate extension AKExcelView { func numberOfSections(in collectionView: UICollectionView) -> Int { if collectionView == headMovebleCollectionView || collectionView == headFreezeCollectionView { return 1 } return (contentData?.count)! } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == headFreezeCollectionView || collectionView == contentFreezeCollectionView { return leftFreezeColumn } else { if let firstBodyData = self.contentData?.first { if let pros = properties { return pros.count - leftFreezeColumn } let slideColumn = (firstBodyData.propertyNames().count) - leftFreezeColumn; return slideColumn }else{ return 0 } } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AKCollectionViewCellIdentifier, for: indexPath) as! AKExcelCollectionViewCell cell.horizontalMargin = self.textMargin self.configCells(collectionView: collectionView, cell: cell, indexPath: indexPath) return cell } private func configCells(collectionView:UICollectionView ,cell:AKExcelCollectionViewCell ,indexPath: IndexPath) { var targetIndexPath = indexPath if collectionView == headFreezeCollectionView { cell.textLabel.text = headerTitles?[leftFreezeColumn - 1] cell.backgroundColor = headerBackgroundColor cell.textLabel.font = headerTextFontSize } else if collectionView == headMovebleCollectionView { if indexPath.item + leftFreezeColumn < (headerTitles?.count)! { cell.backgroundColor = headerBackgroundColor cell.textLabel.text = headerTitles?[indexPath.item + leftFreezeColumn] cell.textLabel.font = headerTextFontSize targetIndexPath = NSIndexPath.init(item: indexPath.item + leftFreezeColumn, section: indexPath.section) as IndexPath } }else if (collectionView == contentFreezeCollectionView) { let text = dataManager.contentFreezeData[indexPath.section][indexPath.item]; cell.textLabel.text = text; cell.backgroundColor = contentBackgroundColor; cell.textLabel.textColor = contentTextColor; cell.textLabel.font = contentTextFontSize; targetIndexPath = NSIndexPath.init(item: indexPath.item, section: indexPath.section + 1) as IndexPath } else { let text = dataManager.contentSlideData[indexPath.section][indexPath.item]; cell.textLabel.text = text; cell.backgroundColor = contentBackgroundColor; cell.textLabel.textColor = contentTextColor; cell.textLabel.font = contentTextFontSize; targetIndexPath = NSIndexPath.init(item: indexPath.item + leftFreezeColumn, section: indexPath.section + 1) as IndexPath } self.customViewInCell(cell: cell, indexPath: targetIndexPath) self.attributeStringInCell(cell: cell, indexPath: targetIndexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if (contentData?.count == 0) { return CGSize.zero } else { if (collectionView == headFreezeCollectionView || collectionView == contentFreezeCollectionView) { return CGSizeFromString(self.dataManager.freezeItemSize[indexPath.item]); } else { return CGSizeFromString(self.dataManager.slideItemSize[indexPath.item]); } } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var targetIndexPath = indexPath if collectionView == headFreezeCollectionView { } else if (collectionView == headMovebleCollectionView) { targetIndexPath = NSIndexPath.init(item: indexPath.item + leftFreezeColumn, section: indexPath.section) as IndexPath } else if (collectionView == contentFreezeCollectionView) { targetIndexPath = NSIndexPath.init(item: indexPath.item, section: indexPath.section + 1) as IndexPath } else { targetIndexPath = NSIndexPath.init(item: indexPath.item + leftFreezeColumn, section: indexPath.section + 1) as IndexPath } self.delegate?.excelView?(self, didSelectItemAt: targetIndexPath) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if itemInsets != nil { return itemInsets! } return UIEdgeInsets.zero } } //MARK: - UISCrollViewDelegate extension AKExcelView { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView != contentScrollView { contentFreezeCollectionView.contentOffset = scrollView.contentOffset contentMoveableCollectionView.contentOffset = scrollView.contentOffset if scrollView.contentOffset.y > 0 { showHorizontalDivideShadowLayer() } else { dismissHorizontalDivideShadowLayer() } }else{ if (scrollView.contentOffset.x > 0) { showVerticalDivideShadowLayer() } else { dismissVerticalDivideShadowLayer() } CATransaction.begin() CATransaction.setDisableActions(true) veritcalShadow.transform = CATransform3DMakeTranslation(scrollView.contentOffset.x, 0, 0) CATransaction.commit() } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if autoScrollToNearItem && scrollView == contentScrollView && !decelerate { scrollEndAnimation(scrollView: scrollView) } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == contentScrollView && autoScrollToNearItem { scrollEndAnimation(scrollView: scrollView) } } fileprivate func scrollEndAnimation(scrollView: UIScrollView) { let offSetX = scrollView.contentOffset.x let deltaOffSets = dataManager.slideItemOffSetX.flatMap({ (offset) -> CGFloat in return abs(offset - offSetX) }) var min:CGFloat = deltaOffSets[0] for i in 0..<deltaOffSets.count { if deltaOffSets[i] < min { min = deltaOffSets[i] } } let index = deltaOffSets.index(of: min) let slideToOffset = dataManager.slideItemOffSetX[index!] let scrollViewWidth = bounds.size.width - dataManager.freezeWidth if dataManager.slideWidth - slideToOffset < scrollViewWidth { return } UIView.animate(withDuration: 0.5, animations: { scrollView.contentOffset.x = slideToOffset }) } } //MARK: - CollectionView Extension extension UICollectionView { /** * 遍历构造函数 */ convenience init(delelate: UICollectionViewDelegate , datasource: UICollectionViewDataSource){ let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.headerReferenceSize = CGSize.init(width: UIScreen.main.bounds.size.width, height: 1) self.init(frame: CGRect.zero, collectionViewLayout: flowLayout) dataSource = datasource delegate = delelate register(AKExcelCollectionViewCell.self, forCellWithReuseIdentifier: AKCollectionViewCellIdentifier) backgroundColor = UIColor.clear showsVerticalScrollIndicator = false translatesAutoresizingMaskIntoConstraints = false if #available(iOS 11.0, *) { self.contentInsetAdjustmentBehavior = .never } } } //MARK: - AKExcelView Delegate Implemention extension AKExcelView { fileprivate func customViewInCell(cell : AKExcelCollectionViewCell , indexPath : IndexPath) { let customView = delegate?.excelView?(self, viewAt: indexPath) cell.customView = customView } fileprivate func attributeStringInCell(cell: AKExcelCollectionViewCell , indexPath : IndexPath) { let attributeString = delegate?.excelView?(self, attributedStringAt: indexPath) if attributeString != nil { cell.textLabel.attributedText = attributeString } } }
mit
325a5b1c5a175a63b957c5a0ea47fedb
35.720388
162
0.63931
5.369392
false
false
false
false
semonchan/LearningSwift
Project/Project - 04 - Calculator/Project - 04 - Calculator/ViewController.swift
1
3252
// // ViewController.swift // Project - 04 - Calculator // // Created by 程超 on 2017/11/24. // Copyright © 2017年 程超. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { let widthAndHeight = (UIScreen.main.bounds.size.width - 30)/4 let modelData:[String] = ["7", "8", "7", "Divide", "4", "5", "6", "Multiply", "1", "2", "3", "Minus", "c", "0", "Decimal", "Plus"] lazy var backgroundImageView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "Cal")) return imageView }() lazy var resultLabel: UILabel = { let label = UILabel() label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 100) label.text = "0" return label }() lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: widthAndHeight, height: widthAndHeight) flowLayout.minimumLineSpacing = 20 flowLayout.minimumInteritemSpacing = 10 let tempCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) tempCollectionView.register(VanCollectionViewCell.self, forCellWithReuseIdentifier: "CELL_IDENTIFIER") tempCollectionView.backgroundColor = UIColor.clear tempCollectionView.dataSource = self return tempCollectionView }() var equalsButton: UIButton = { let tempButton = UIButton(type: UIButtonType.custom) tempButton.setImage(UIImage(named: "Equals"), for: UIControlState.normal) tempButton.setImage(UIImage(named: "Equals-down"), for: UIControlState.highlighted) return tempButton }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(backgroundImageView) view.addSubview(resultLabel) view.addSubview(collectionView) view.addSubview(equalsButton) backgroundImageView.snp.makeConstraints { (make) in make.edges.equalTo(view) } resultLabel.snp.makeConstraints { (make) in make.right.equalTo(view.snp.right) make.top.equalTo(view.snp.top).offset(40) } collectionView.snp.makeConstraints { (make) in make.top.equalTo(view).offset(138) make.left.right.equalTo(view) make.height.equalTo(widthAndHeight*4 + 60) } equalsButton.snp.makeConstraints { (make) in make.top.equalTo(collectionView.snp.bottom); make.centerX.equalTo(view) make.size.equalTo(CGSize(width: widthAndHeight, height: widthAndHeight)) } } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return modelData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView .dequeueReusableCell(withReuseIdentifier: "CELL_IDENTIFIER", for: indexPath) as! VanCollectionViewCell cell.model = modelData[indexPath.row] return cell } }
mit
2778c8845cc717504b04ab3896e5f981
36.686047
136
0.663376
4.759178
false
false
false
false
semonchan/LearningSwift
语法/1.Swift基础语法.playground/Contents.swift
1
7954
//: Playground - noun: a place where people can play // 类型推导, 已经类型安全 import UIKit var str = "Hello, playground" print(str) // 可变变量 var welcomeMessage: String? var friendWelcome = "hellow!" friendWelcome = "Bonjour!" var languageName = "Swift" languageName = "C++" print(friendWelcome) // 为double类型 let anotherPi = 3 + 0.1314159 // 整数和浮点数的转换必须显示指定类型 let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine // 布尔值, 要明确知道真假, 更清晰 let i = 1 if i == 1 { print(i==1) print("my name is cc") } // 元祖 let http404Error = (404, "Not Fund") print(http404Error.0) // 将元祖的内容分解成单独的常量和变量 let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") // 可以在定义元祖的时候给单个元素命名 let http200Status = (statusCode: 200, description: "OK") print(http200Status.statusCode) // 可选类型 let possibleNumber = "123c" var convertedNumber = Int(possibleNumber) //convertedNumber = nil // nil只能给可选类型的变量赋值, 不能用于非可选的常量和变量, 如果有常量或者变量需要处理值缺失的情况, 需要声明成对应的可选类型 // 如果声明一个可选常量或者变量但是没有赋值, 会自动被设置为nil var surveyAnswer: String? // tip // Swift的nil和Objective-C中的nil并不一样, 在Objective-C中, nil是一个指向不存在对象的指针. 在Swift中, nil不是指针, 它是一个确定的值, 用来表示值缺失. 任何类型的可选状态都可以被设置为nil, 不只是对象类型 // if语句以及强制解析 if convertedNumber != nil { print(convertedNumber!) } // 可选绑定 // 使用可选绑定来判断可选类型是否包含值, 如果包含就把值赋给一个临时常量或者变量 if let actualNumber = Int(possibleNumber) { print(actualNumber) // 在if条件语句中使用常量和变量来创建一个可选绑定, 仅在if语句的句中才能获取到值 } else { print(possibleNumber) } let myName : String? myName = "cc" func printMyName(myName : String?) { guard let ccName = myName else { return } // 在guard语句中使用常量和变量来创建一个可选绑定, 仅在guard语句外且语句后才能获取到值 print("my name is \(ccName)") } printMyName(myName: myName) // 隐式解绑 // 当可选类型被第一次赋值之后就可以确定之后一直有值的时候, 可以使用隐式解绑可选类型 // 错误处理 // 一个函数可以通过在声明中添加throws关键词来抛出错误信息, 当你的函数能抛出错误信息时, 你应该在表达式中前置try关键词 // 断言 // 如果条件成立, 不报错, 否则报错 let age = -3 assert(age < 0, "A person`s age cannot be less than zero") // 空合运算符 : 当一个可选类型需要一个default值时, 可以使用 // 空合运算符(a ?? b) 将对可选类型a进行空判断, 如果a包含一个值就进行解绑, 否则就返回一个默认值b. // 空合运算符是对一下代码的简短表达方法: // a != nil ? a! : b let defaultColorName = "red" var userDefinedColorName: String? // 默认值为nil var colorNameToUse = userDefinedColorName ?? defaultColorName userDefinedColorName = "orange" colorNameToUse = userDefinedColorName ?? defaultColorName // 区间运算符 // 闭区间: 包括1, 5 for index in 1...5 { print("闭区间\(index)") } // 半开区间: 不包括 比较适合进行数组的遍历 for indexx in 1..<5 { print("半开区间\(indexx)") } let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0..<count { print("第\(i+1)个人叫\(names[i])") } // 字符串的遍历 for character in "my name is cc".characters { print(character) } let exclamationMark: NSString = "my name is" exclamationMark.appending(" cc") let greeting = "Guten Tag!" greeting[greeting.startIndex] greeting.characters.count greeting[greeting.index(before: greeting.endIndex)] // 数组 var someInts = [Int]() someInts.append(1) someInts = [] var threeDouble = Array(repeatElement(5.5, count: 5)) var shoppingList = ["Eggs", "Milk"] shoppingList.count // 判断数组是否为空 if shoppingList.isEmpty { print("This shopping list is empty") } else { print("This shopping list is not empty") } // 增加 shoppingList.append("Flour") // 插入 shoppingList.insert("Maple", at: 0) shoppingList.remove(at: 2) shoppingList for item in shoppingList { print(item) } for (index, value) in shoppingList.enumerated() { print(index, value) } // 集合(Sets): 用来存储相同类型并且没有确定顺序的值, 当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组 var letters = Set<Character>() letters.insert("a") letters = [] var favoriteGenres: Set = ["Rock", "Classical", "Rock"] favoriteGenres.count favoriteGenres.isEmpty favoriteGenres.insert("Cccc") for genre in favoriteGenres.sorted() { print(genre) } var arr = [String]() // 构造语法 var dic = [String:String]() // 字面量构造 var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] let air = airports.keys let anotnerCharacter: Character = "a" switch anotnerCharacter { case "a", "A": print(anotnerCharacter) fallthrough // 贯穿语句 case "a": print(anotnerCharacter) default: print(anotnerCharacter) } // guard let person = ["name": "cc"] func greet(person: [String: String]) { guard let name = person["name"] else { return } print(name) } greet(person: person) // 函数重载 func greet(perosnName: String) -> String { let greeting = "Hello" + perosnName + "!" return greeting } greet(perosnName: "cc") // 多重返回值函数 func minMax(_ array:[Int]) -> (min: Int, max: Int)? { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } if let cuple = minMax([1]) { cuple.min } func greet(person: String, hometown: String) -> String { return "Hello \(person)! Glad you could visit from \(hometown)." } greet(person: "cc", hometown: "xx") func arithmeticMean(numbers: Double...){ } arithmeticMean(numbers: 1, 2.2, 2) // 当要在函数内部修改参数时, 需要使用输入输出参数: inout func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 100 // 函数类型 func addTwoInts(_ a: Int, _ b: Int) -> Int { return a + b } var mathFunction:(Int, Int) -> Int = addTwoInts print(mathFunction(2, 3)) // 闭包 let names1 = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversedNames = names1.sorted { (s1: String, s2: String) -> Bool in return s1 > s2 } var callBack : ((_ str: String)->())? func loadRequst(callBack: @escaping (_ strName: String)->()) { callBack("cc is my name") } loadRequst { (str: String) in print(str) } enum CompassPoint { case north case south case east case west } var pont: CompassPoint pont = CompassPoint.south struct Resolution { var width = 0 var height = 0 } var resolution = Resolution() resolution.width = 100 class VideoMode { var resolution = Resolution() var interlaced = false var frameRate: String = "" var name: String? } // 在Swift中, 所有的结构体和枚举类型都是值类型. 这意味着它们的实例, 以及实例中所包含的任何值类型属性, 在代码中传递的时候都会被复制 let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 1000 print(hd.width) print(cinema.width)
mit
4029e65885be36dd1c6494aff164dbed
18.053571
133
0.681506
2.980447
false
false
false
false
tamershahin/iOS8Challenges
TakIt/TaskIt/TaskIt/ViewController.swift
1
2584
// // ViewController.swift // TaskIt // // Created by Tamer Shahin on 30/11/2014. // Copyright (c) 2014 Tasin. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var taskArray:[TaskModel] = [] override func viewDidLoad() { super.viewDidLoad() let date1 = Date.from(year: 2014, month: 05, day: 20) let date2 = Date.from(year: 2014, month: 03, day: 3) let date3 = Date.from(year: 2014, month: 12, day: 13) // Do any additional setup after loading the view, typically from a nib. let task1:TaskModel = TaskModel(task: "Study French", subTask: "Verbs", date: date1) let task2:TaskModel = TaskModel(task: "Eat Dinner", subTask: "Burgers", date: date2) let task3:TaskModel = TaskModel(task: "Gym", subTask: "Leg day", date: date3) taskArray = [task1, task2, task3] self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showTaskDetail" { let detailVC: TaskDetailViewController = segue.destinationViewController as TaskDetailViewController let indexPath = self.tableView.indexPathForSelectedRow() let thisTask = taskArray[indexPath!.row] detailVC.detailTaskModel = thisTask } } //UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return taskArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:TaskCell = tableView.dequeueReusableCellWithIdentifier("myCell") as TaskCell cell.taskLabel.text = taskArray[indexPath.row].task cell.descriptionLabel.text = taskArray[indexPath.row].subTask cell.dateLabel.text = Date.toString(date: taskArray[indexPath.row].date) return cell } //UITableViewDelegate func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { println(indexPath.row) performSegueWithIdentifier("showTaskDetail", sender: self) } @IBAction func addButtonTapped(sender: UIBarButtonItem) { self.performSegueWithIdentifier("showTaskAdd", sender: self) } }
apache-2.0
3d442e11a978695eb4a0d247d833bd4c
32.558442
112
0.679954
4.698182
false
false
false
false
eweill/Forge
Examples/YOLO/YOLO/BoundingBox.swift
2
1690
import Foundation import UIKit class BoundingBox { let shapeLayer: CAShapeLayer let textLayer: CATextLayer init() { shapeLayer = CAShapeLayer() shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.lineWidth = 4 shapeLayer.isHidden = true textLayer = CATextLayer() textLayer.foregroundColor = UIColor.black.cgColor textLayer.isHidden = true textLayer.contentsScale = UIScreen.main.scale textLayer.fontSize = 14 textLayer.font = UIFont(name: "Avenir", size: textLayer.fontSize) textLayer.alignmentMode = kCAAlignmentCenter } func addToLayer(_ parent: CALayer) { parent.addSublayer(shapeLayer) parent.addSublayer(textLayer) } func show(frame: CGRect, label: String, color: UIColor) { CATransaction.setDisableActions(true) let path = UIBezierPath(rect: frame) shapeLayer.path = path.cgPath shapeLayer.strokeColor = color.cgColor shapeLayer.isHidden = false textLayer.string = label textLayer.backgroundColor = color.cgColor textLayer.isHidden = false let attributes = [ NSAttributedStringKey.font: textLayer.font as Any ] let textRect = label.boundingRect(with: CGSize(width: 400, height: 100), options: .truncatesLastVisibleLine, attributes: attributes, context: nil) let textSize = CGSize(width: textRect.width + 12, height: textRect.height) let textOrigin = CGPoint(x: frame.origin.x - 2, y: frame.origin.y - textSize.height) textLayer.frame = CGRect(origin: textOrigin, size: textSize) } func hide() { shapeLayer.isHidden = true textLayer.isHidden = true } }
mit
528880acd9ba0542a13f776fe9d642f8
29.178571
88
0.686391
4.68144
false
false
false
false
willpowell8/JIRAMobileKit
JIRAMobileKit/Classes/Utils/MimeType.swift
1
4329
// // MimeType.swift // JIRAMobileKit // // Created by Will Powell on 03/10/2017. // import Foundation internal let DEFAULT_MIME_TYPE = "application/octet-stream" internal let mimeTypes = [ "html": "text/html", "htm": "text/html", "shtml": "text/html", "css": "text/css", "xml": "text/xml", "gif": "image/gif", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "application/javascript", "atom": "application/atom+xml", "rss": "application/rss+xml", "mml": "text/mathml", "txt": "text/plain", "jad": "text/vnd.sun.j2me.app-descriptor", "wml": "text/vnd.wap.wml", "htc": "text/x-component", "png": "image/png", "tif": "image/tiff", "tiff": "image/tiff", "wbmp": "image/vnd.wap.wbmp", "ico": "image/x-icon", "jng": "image/x-jng", "bmp": "image/x-ms-bmp", "svg": "image/svg+xml", "svgz": "image/svg+xml", "webp": "image/webp", "woff": "application/font-woff", "jar": "application/java-archive", "war": "application/java-archive", "ear": "application/java-archive", "json": "application/json", "hqx": "application/mac-binhex40", "doc": "application/msword", "pdf": "application/pdf", "ps": "application/postscript", "eps": "application/postscript", "ai": "application/postscript", "rtf": "application/rtf", "m3u8": "application/vnd.apple.mpegurl", "xls": "application/vnd.ms-excel", "eot": "application/vnd.ms-fontobject", "ppt": "application/vnd.ms-powerpoint", "wmlc": "application/vnd.wap.wmlc", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "7z": "application/x-7z-compressed", "cco": "application/x-cocoa", "jardiff": "application/x-java-archive-diff", "jnlp": "application/x-java-jnlp-file", "run": "application/x-makeself", "pl": "application/x-perl", "pm": "application/x-perl", "prc": "application/x-pilot", "pdb": "application/x-pilot", "rar": "application/x-rar-compressed", "rpm": "application/x-redhat-package-manager", "sea": "application/x-sea", "swf": "application/x-shockwave-flash", "sit": "application/x-stuffit", "tcl": "application/x-tcl", "tk": "application/x-tcl", "der": "application/x-x509-ca-cert", "pem": "application/x-x509-ca-cert", "crt": "application/x-x509-ca-cert", "xpi": "application/x-xpinstall", "xhtml": "application/xhtml+xml", "xspf": "application/xspf+xml", "zip": "application/zip", "bin": "application/octet-stream", "exe": "application/octet-stream", "dll": "application/octet-stream", "deb": "application/octet-stream", "dmg": "application/octet-stream", "iso": "application/octet-stream", "img": "application/octet-stream", "msi": "application/octet-stream", "msp": "application/octet-stream", "msm": "application/octet-stream", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "mid": "audio/midi", "midi": "audio/midi", "kar": "audio/midi", "mp3": "audio/mpeg", "ogg": "audio/ogg", "m4a": "audio/x-m4a", "ra": "audio/x-realaudio", "3gpp": "video/3gpp", "3gp": "video/3gpp", "ts": "video/mp2t", "mp4": "video/mp4", "mpeg": "video/mpeg", "mpg": "video/mpeg", "mov": "video/quicktime", "webm": "video/webm", "flv": "video/x-flv", "m4v": "video/x-m4v", "mng": "video/x-mng", "asx": "video/x-ms-asf", "asf": "video/x-ms-asf", "wmv": "video/x-ms-wmv", "avi": "video/x-msvideo" ] internal func MimeType(ext: String?) -> String { if ext != nil && mimeTypes.contains(where: { $0.0 == ext!.lowercased() }) { return mimeTypes[ext!.lowercased()]! } return DEFAULT_MIME_TYPE } extension NSURL { public func mimeType() -> String { return MimeType(ext: self.pathExtension) } } extension NSString { public func mimeType() -> String { return MimeType(ext: self.pathExtension) } } extension String { public func mimeType() -> String { return (self as NSString).mimeType() } }
mit
744e4ba30989e36f8c6c22eeeab99f62
29.702128
88
0.602449
3.010431
false
false
false
false
Molbie/Outlaw
Tests/OutlawTests/UInt64Tests.swift
1
4733
// // UInt64Tests.swift // Outlaw // // Created by Brian Mullen on 11/6/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import XCTest @testable import Outlaw class UInt64Tests: OutlawTestCase { static var allTests = [("testValue", testValue), ("testNestedValue", testNestedValue), ("testKeyNotFound", testKeyNotFound), ("testTypeMismatch", testTypeMismatch), ("testOptional", testOptional), ("testOptionalNestedValue", testOptionalNestedValue), ("testOptionalKeyNotFound", testOptionalKeyNotFound), ("testOptionalTypeMismatch", testOptionalTypeMismatch), ("testLowerBounds", testLowerBounds), ("testUpperBounds", testUpperBounds), ("testTransformValue", testTransformValue), ("testOptionalTransformValue", testOptionalTransformValue), ("testTransformOptionalValue", testTransformOptionalValue), ("testOptionalTransformOptionalValue", testOptionalTransformOptionalValue)] func testValue() { let value: UInt64 = try! data.value(for: "uint64") XCTAssertEqual(value, 64) } func testNestedValue() { let value: UInt64 = try! data.value(for: "object.uint64") XCTAssertEqual(value, 64) } func testKeyNotFound() { var value: UInt64 = 0 let ex = self.expectation(description: "Key not found") do { value = try data.value(for: "keyNotFound") } catch { if case OutlawError.keyNotFound = error { ex.fulfill() } } self.waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(value, 0) } func testTypeMismatch() { var value: UInt64 = 0 let ex = self.expectation(description: "Type mismatch") do { value = try data.value(for: "string") } catch { if case OutlawError.typeMismatchWithKey = error { ex.fulfill() } } self.waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(value, 0) } // MARK: - // MARK: Optionals func testOptional() { let value: UInt64? = data.optional(for: "uint64") XCTAssertEqual(value, 64) } func testOptionalNestedValue() { let value: UInt64? = data.optional(for: "object.uint64") XCTAssertEqual(value, 64) } func testOptionalKeyNotFound() { let value: UInt64? = data.optional(for: "keyNotFound") XCTAssertNil(value) } func testOptionalTypeMismatch() { let value: UInt64? = data.optional(for: "string") XCTAssertNil(value) } // MARK: - // MARK: Bounds func testLowerBounds() { let value: UInt64 = try! data.value(for: "minValue") XCTAssertEqual(value, 0) } func testUpperBounds() { let value: UInt64 = try! data.value(for: "maxValue") let maxValue: UInt64 = 18446744073709551615 XCTAssertEqual(value, maxValue) } // MARK: - // MARK: Transforms func testTransformValue() { let value: UInt64 = try! data.value(for: "transform", with: { (rawValue: String) -> UInt64 in guard let value = UInt64(rawValue) else { throw OutlawError.typeMismatchWithKey(key: "transform", expected: Int.self, actual: rawValue) } return value }) XCTAssertEqual(value, 12345) } func testOptionalTransformValue() { let value: UInt64 = try! data.value(for: "transform", with: { (rawValue: String?) -> UInt64 in guard let value = UInt64(rawValue ?? "0") else { throw OutlawError.typeMismatchWithKey(key: "transform", expected: Int.self, actual: rawValue ?? "nil") } return value }) XCTAssertEqual(value, 12345) } func testTransformOptionalValue() { let value: UInt64? = data.optional(for: "transform", with: { (rawValue: String) -> UInt64? in return UInt64(rawValue) }) XCTAssertEqual(value, 12345) } func testOptionalTransformOptionalValue() { let value: UInt64? = data.optional(for: "transform", with: { (rawValue: String?) -> UInt64? in guard let rawValue = rawValue else { return nil } return UInt64(rawValue) }) XCTAssertEqual(value, 12345) } }
mit
c1844f4b09e1de6ced0562483735913f
31.634483
118
0.561496
4.848361
false
true
false
false
bravelocation/yeltzland-ios
yeltzland/Model Extensions/Fixture+Score.swift
1
723
// // Fixture+Score.swift // Yeltzland // // Created by John Pollard on 25/06/2022. // Copyright © 2022 John Pollard. All rights reserved. // import Foundation extension Fixture { var score: String { get { guard let teamScore = teamScore, let opponentScore = opponentScore else { return "" } var result = "" if teamScore > opponentScore { result = "W" } else if teamScore < opponentScore { result = "L" } else { result = "D" } return String.init(format: "%@ %d-%d", result, teamScore, opponentScore) } } }
mit
35b607b54c4f54643f1d3371629d271a
23.066667
85
0.48338
4.56962
false
false
false
false
Shaquu/SwiftProjectsPub
YummyDesserts/YummyDesserts/DetailedViewController.swift
1
764
// // DetailedViewController.swift // YummyDesserts // // Created by Tadeusz Wyrzykowski on 11.11.2016. // Copyright © 2016 Tadeusz Wyrzykowski. All rights reserved. // import UIKit class DetailedViewController: UIViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var label: UILabel! @IBOutlet var desc: UILabel! var vImageView = "" var vLabel = "" var vDesc = "" override func viewDidLoad() { super.viewDidLoad() imageView.image = UIImage(named: vImageView) label.text = vLabel desc.text = vDesc // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
3c41dbee361fbaa35afc661b960042f6
21.441176
62
0.642202
4.624242
false
false
false
false
rudkx/swift
test/Concurrency/toplevel/async-6-top-level.swift
1
1508
// RUN: %target-swift-frontend -typecheck -disable-availability-checking -enable-experimental-async-top-level -swift-version 6 %s -verify // REQUIRES: asserts var a = 10 // expected-note@-1 2 {{var declared here}} // expected-note@-2 2 {{mutation of this var is only permitted within the actor}} func nonIsolatedSync() { //expected-note 3 {{add '@MainActor' to make global function 'nonIsolatedSync()' part of global actor 'MainActor'}} print(a) // expected-error {{var 'a' isolated to global actor 'MainActor' can not be referenced from this synchronous context}} a = a + 10 // expected-error@-1:5 {{var 'a' isolated to global actor 'MainActor' can not be mutated from this context}} // expected-error@-2:9 {{var 'a' isolated to global actor 'MainActor' can not be referenced from this synchronous context}} } @MainActor func isolatedSync() { print(a) a = a + 10 } func nonIsolatedAsync() async { await print(a) a = a + 10 // expected-error@-1:5 {{var 'a' isolated to global actor 'MainActor' can not be mutated from this context}} // expected-error@-2:9 {{expression is 'async' but is not marked with 'await'}} // expected-note@-3:9 {{property access is 'async'}} } @MainActor func isolatedAsync() async { print(a) a = a + 10 } nonIsolatedSync() isolatedSync() await nonIsolatedAsync() await isolatedAsync() print(a) if a > 10 { nonIsolatedSync() isolatedSync() await nonIsolatedAsync() await isolatedAsync() print(a) }
apache-2.0
05aa611f48b1dec2c4823f28e7b9a746
28.568627
140
0.683687
3.642512
false
false
false
false
nissivm/DemoShopPayPal
DemoShop-PayPal/Container Views/AuthenticationContainerView.swift
1
15096
// // AuthenticationContainerView.swift // DemoShop-PayPal // // Copyright © 2016 Nissi Vieira Miranda. All rights reserved. // import UIKit class AuthenticationContainerView: UIViewController, UIGestureRecognizerDelegate, UITextFieldDelegate { @IBOutlet weak var tapView: UIView! @IBOutlet weak var nameTxtField: UITextField! @IBOutlet weak var passwordTxtField: UITextField! @IBOutlet weak var emailTxtField: UITextField! @IBOutlet weak var shopName: UILabel! @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var dividerOneTopConstraint: NSLayoutConstraint! @IBOutlet weak var dividerTwoTopConstraint: NSLayoutConstraint! @IBOutlet weak var dividerThreeTopConstraint: NSLayoutConstraint! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var containerTopConstraint: NSLayoutConstraint! @IBOutlet weak var containerHeightConstraint: NSLayoutConstraint! var tappedTextField : UITextField? var multiplier: CGFloat = 1 override func viewDidLoad() { super.viewDidLoad() let tapRecognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) tapRecognizer.delegate = self tapView.addGestureRecognizer(tapRecognizer) if Device.IS_IPHONE_4 || Device.IS_IPHONE_6 || Device.IS_IPHONE_6_PLUS { containerHeightConstraint.constant = self.view.frame.size.height } if Device.IS_IPHONE_6 { multiplier = Constants.multiplier6 adjustForBiggerScreen() } else if Device.IS_IPHONE_6_PLUS { multiplier = Constants.multiplier6plus adjustForBiggerScreen() } } //-------------------------------------------------------------------------// // MARK: Firebase Sign Up //-------------------------------------------------------------------------// var signingUp = false @IBAction func signUpButtonTapped(sender: UIButton) { removeKeyboard() guard Reachability.connectedToNetwork() else { Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) return } let name = nameTxtField.text! let email = emailTxtField.text! let password = passwordTxtField.text! if name.characters.count > 0 && email.characters.count > 0 && password.characters.count > 0 { Auxiliar.showLoadingHUDWithText("Signing up...", forView: self.view) signUpWithFirebase(name, email: email, password: password) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "Please fill in all fields", forViewController: self) } } func signUpWithFirebase(name: String, email: String, password: String) { // Create user account: let ref = Firebase(url: Constants.baseURL) ref.createUser(email, password: password, withValueCompletionBlock: { [unowned self](error, result) in guard error == nil else { Auxiliar.hideLoadingHUDInView(self.view) print("Error creating user account in Firebase\n") print("Error code: \(error!.code)\n") print("Error code: \(error!.localizedDescription)") let errorInfo = self.getAuthenticationErrorInfo(error!.code) Auxiliar.presentAlertControllerWithTitle(errorInfo[0], andMessage: errorInfo[1], forViewController: self) return } self.signingUp = true self.signInWithFirebase(name, email: email, password: password) // Logging the user in }) } //-------------------------------------------------------------------------// // MARK: Firebase Sign In //-------------------------------------------------------------------------// @IBAction func signInButtonTapped(sender: UIButton) { removeKeyboard() guard Reachability.connectedToNetwork() else { Auxiliar.presentAlertControllerWithTitle("No Internet Connection", andMessage: "Make sure your device is connected to the internet.", forViewController: self) return } let email = emailTxtField.text! let password = passwordTxtField.text! if email.characters.count > 0 && password.characters.count > 0 { Auxiliar.showLoadingHUDWithText("Signing in...", forView: self.view) signInWithFirebase("", email: email, password: password) } else { Auxiliar.presentAlertControllerWithTitle("Error", andMessage: "Please insert username and password", forViewController: self) } } func signInWithFirebase(name: String, email: String, password: String) { let ref = Firebase(url: Constants.baseURL) ref.authUser(email, password: password, withCompletionBlock: { [unowned self](error, authData) in guard error == nil else { print("Error logging in the user in Firebase\n") print("Error code: \(error!.code)\n") print("Error code: \(error!.localizedDescription)") let errorInfo = self.getAuthenticationErrorInfo(error!.code) Auxiliar.presentAlertControllerWithTitle(errorInfo[0], andMessage: errorInfo[1], forViewController: self) return } if self.signingUp { self.signingUp = false self.saveNewClient(name, email: email) Auxiliar.hideLoadingHUDInView(self.view) } else { self.retrieveCurrentUser(email) } self.nameTxtField.text = "" self.passwordTxtField.text = "" self.emailTxtField.text = "" NSNotificationCenter.defaultCenter().postNotificationName("SessionStarted", object: nil) }) } //-------------------------------------------------------------------------// // MARK: Save new client //-------------------------------------------------------------------------// func saveNewClient(name: String, email: String) { let ref = Firebase(url: Constants.baseURL + "Clients") let newClientRef = ref.childByAutoId() var clientId = "\(newClientRef)" clientId = clientId.stringByReplacingOccurrencesOfString(Constants.baseURL + "Clients/", withString: "") let newClient = ["clientId": clientId, "clientName": name, "clientEmail": email] newClientRef.setValue(newClient) Auxiliar.currentUserId = newClient["clientId"]! } //-------------------------------------------------------------------------// // MARK: Retrieve current user //-------------------------------------------------------------------------// func retrieveCurrentUser(email: String) { let ref = Firebase(url: Constants.baseURL + "Clients") ref.observeEventType(.Value, withBlock: { (snapshot) in Auxiliar.hideLoadingHUDInView(self.view) if let response = snapshot.value as? [NSObject : AnyObject] { let keys = response.keys for key in keys { let item = response[key] as! [String : String] let responseItemEmail = item["clientEmail"] if responseItemEmail == email { let responseItemId = item["clientId"]! Auxiliar.currentUserId = responseItemId break } } } }) } //-------------------------------------------------------------------------// // MARK: Error Info //-------------------------------------------------------------------------// func getAuthenticationErrorInfo(errorCode: Int) -> [String] { var errorInfo = [String]() switch errorCode { case -5: errorInfo.append("INVALID EMAIL") errorInfo.append("The specified email address is invalid.") case -6: errorInfo.append("INCORRECT PASSWORD") errorInfo.append("The specified password is incorrect.") case -8: errorInfo.append("INVALID USER") errorInfo.append("The specified user does not exist.") case -9: errorInfo.append("EMAIL TAKEN") errorInfo.append("The specified email address is already in use.") default: errorInfo.append("UNKNOWN ERROR") errorInfo.append("An error occurred while authenticating, please check your authentication data and try again.") } return errorInfo } //-------------------------------------------------------------------------// // MARK: UITextFieldDelegate //-------------------------------------------------------------------------// func textFieldDidBeginEditing(textField: UITextField) { tappedTextField = textField let textFieldY = tappedTextField!.frame.origin.y let textFieldHeight = tappedTextField!.frame.size.height let total = textFieldY + textFieldHeight if total > (self.view.frame.size.height/2) { let difference = total - (self.view.frame.size.height/2) let newConstraint = containerTopConstraint.constant - difference animateConstraint(containerTopConstraint, toValue: newConstraint) } } func textFieldShouldReturn(textField: UITextField) -> Bool { removeKeyboard() return true } //-------------------------------------------------------------------------// // MARK: Tap gesture recognizer //-------------------------------------------------------------------------// func handleTap(recognizer : UITapGestureRecognizer) { removeKeyboard() } //-------------------------------------------------------------------------// // MARK: Remove keyboard //-------------------------------------------------------------------------// func removeKeyboard() { if tappedTextField != nil { tappedTextField!.resignFirstResponder() tappedTextField = nil if containerTopConstraint.constant != 0 { animateConstraint(containerTopConstraint, toValue: 0) } } } //-------------------------------------------------------------------------// // MARK: Animations //-------------------------------------------------------------------------// func animateConstraint(constraint : NSLayoutConstraint, toValue value : CGFloat) { UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: { constraint.constant = value self.view.layoutIfNeeded() }, completion: { (finished: Bool) in }) } //-------------------------------------------------------------------------// // MARK: Ajust for bigger screen //-------------------------------------------------------------------------// func adjustForBiggerScreen() { for constraint in shopName.constraints { constraint.constant *= multiplier } for constraint in nameTxtField.constraints { constraint.constant *= multiplier } for constraint in passwordTxtField.constraints { constraint.constant *= multiplier } for constraint in emailTxtField.constraints { constraint.constant *= multiplier } for constraint in signUpButton.constraints { constraint.constant *= multiplier } for constraint in signInButton.constraints { constraint.constant *= multiplier } headerHeightConstraint.constant *= multiplier dividerOneTopConstraint.constant *= multiplier dividerTwoTopConstraint.constant *= multiplier dividerThreeTopConstraint.constant *= multiplier var fontSize = 25.0 * multiplier shopName.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) fontSize = 17.0 * multiplier nameTxtField.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) passwordTxtField.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) emailTxtField.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) signUpButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) signInButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) } //-------------------------------------------------------------------------// // MARK: Memory Warning //-------------------------------------------------------------------------// override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
a4f1fefbfb460d3cec3eece80ee8e919
34.940476
128
0.473601
6.744861
false
false
false
false
BGDigital/mcwa
mcwa/mcwa/ViewController.swift
1
5736
// // ViewController.swift // mcwa // // Created by XingfuQiu on 15/10/8. // Copyright © 2015年 XingfuQiu. All rights reserved. // import UIKit class ViewController: UIViewController, PlayerDelegate { @IBOutlet weak var userAvatar: UIBarButtonItem! let manager = AFHTTPRequestOperationManager() var json: JSON! { didSet { if "ok" == self.json["state"].stringValue { if let d = self.json["dataObject", "question"].array { self.questions = d } if let users = self.json["dataObject", "user"].array { self.users = users } } } } var questions: Array<JSON>? var users: Array<JSON>? var buttonBack: UIButton! override func viewDidLoad() { super.viewDidLoad() MCUtils.checkNetWorkState(self) //背景音乐 player_bg.delegate = self player_bg.forever = true print("appMusicStatus:\(appMusicStatus)") if (appMusicStatus == 0) { player_bg.playFileAtPath(music_bg) } // Do any additional setup after loading the view, typically from a nib. self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = UIImage() //主界面背景渐变 // let background = turquoiseColor() // background.frame = self.view.bounds // self.view.layer.insertSublayer(background, atIndex: 0) //方法一 self.view.layer.contents = UIImage(named: "main_bg")!.CGImage //方法二 说的是占内存 //self.view.backgroundColor = UIColor(patternImage: UIImage(named: "main_bg")!) custom_leftbar() navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } func soundFinished(sender: AnyObject) { // delegate message from Player print("play finished") } func custom_leftbar() { buttonBack = UIButton(type: UIButtonType.Custom) buttonBack.frame = CGRectMake(5, 0, 30, 30) if let url = appUserAvatar { buttonBack.yy_setImageWithURL(NSURL(string: url), forState: .Normal, placeholder: UIImage(named: "avatar_default")) } else { buttonBack.setImage(UIImage(named: "avatar_default"), forState: .Normal) } buttonBack.addTarget(self, action: "showLogin:", forControlEvents: UIControlEvents.TouchUpInside) buttonBack.layer.masksToBounds = true buttonBack.layer.cornerRadius = 15 buttonBack.layer.borderWidth = 1.5 buttonBack.layer.borderColor = UIColor(hexString: "#675580")?.CGColor let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: buttonBack) self.navigationItem.setLeftBarButtonItem(leftBarButtonItem, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func beginWa(sender: UIButton) { self.pleaseWait() let dict = ["act":"question"] manager.GET(URL_MC, parameters: dict, success: { (operation, responseObject) -> Void in self.json = JSON(responseObject) self.clearAllNotice() //收到数据,跳转到准备页面 self.performSegueWithIdentifier("showReady", sender: self) }) { (operation, error) -> Void in self.clearAllNotice() MCUtils.showCustomHUD(self, aMsg: "获取题库失败,请重试", aType: .Error) print(error) } } //跳转Segue传值 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showReady" { let receive = segue.destinationViewController as! readyViewController receive.questions = self.questions receive.users = self.users } } override func viewWillAppear(animated: Bool) { self.navigationItem.title = "MC哇!" MobClick.beginLogPageView("viewController") self.navigationController?.navigationBarHidden = false } override func viewWillDisappear(animated: Bool) { MobClick.endLogPageView("viewController") } override func viewDidAppear(animated: Bool) { if let url = appUserAvatar { buttonBack.yy_setImageWithURL(NSURL(string: url), forState: .Normal, placeholder: UIImage(named: "avatar_default")) } else { buttonBack.setImage(UIImage(named: "avatar_default"), forState: .Normal) } } //颜色渐变 func turquoiseColor() -> CAGradientLayer { let topColor = UIColor(hexString: "#362057") let bottomColor = UIColor(hexString: "#3b3f73") let gradientColors: Array <AnyObject> = [topColor!.CGColor, bottomColor!.CGColor] let gradientLocations: Array <NSNumber> = [0.0, 1.0] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.locations = gradientLocations return gradientLayer } @IBAction func showLogin(sender: UIBarButtonItem) { mineViewController.showMineInfoPage(self.navigationController) } }
mit
f08933c8f8f0fe225b1ecaa65a7f9297
33.533742
130
0.61041
4.873593
false
false
false
false
emilstahl/swift
stdlib/public/core/LifetimeManager.swift
10
4374
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// /// Evaluate `f()` and return its result, ensuring that `x` is not /// destroyed before f returns. public func withExtendedLifetime<T, Result>( x: T, @noescape _ f: () throws -> Result ) rethrows -> Result { defer { _fixLifetime(x) } return try f() } /// Evaluate `f(x)` and return its result, ensuring that `x` is not /// destroyed before f returns. public func withExtendedLifetime<T, Result>( x: T, @noescape _ f: T throws -> Result ) rethrows -> Result { defer { _fixLifetime(x) } return try f(x) } extension String { /// Invoke `f` on the contents of this string, represented as /// a nul-terminated array of char, ensuring that the array's /// lifetime extends through the execution of `f`. public func withCString<Result>( @noescape f: UnsafePointer<Int8> throws -> Result ) rethrows -> Result { return try self.nulTerminatedUTF8.withUnsafeBufferPointer { try f(UnsafePointer($0.baseAddress)) } } } // Fix the lifetime of the given instruction so that the ARC optimizer does not // shorten the lifetime of x to be before this point. @_transparent public func _fixLifetime<T>(x: T) { Builtin.fixLifetime(x) } /// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer. public func withUnsafeMutablePointer<T, Result>( inout arg: T, @noescape _ body: UnsafeMutablePointer<T> throws -> Result ) rethrows -> Result { return try body(UnsafeMutablePointer<T>(Builtin.addressof(&arg))) } /// Like `withUnsafeMutablePointer`, but passes pointers to `arg0` and `arg1`. public func withUnsafeMutablePointers<A0, A1, Result>( inout arg0: A0, inout _ arg1: A1, @noescape _ body: ( UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) throws -> Result ) rethrows -> Result { return try body( UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)), UnsafeMutablePointer<A1>(Builtin.addressof(&arg1))) } /// Like `withUnsafeMutablePointer`, but passes pointers to `arg0`, `arg1`, /// and `arg2`. public func withUnsafeMutablePointers<A0, A1, A2, Result>( inout arg0: A0, inout _ arg1: A1, inout _ arg2: A2, @noescape _ body: ( UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>, UnsafeMutablePointer<A2> ) throws -> Result ) rethrows -> Result { return try body( UnsafeMutablePointer<A0>(Builtin.addressof(&arg0)), UnsafeMutablePointer<A1>(Builtin.addressof(&arg1)), UnsafeMutablePointer<A2>(Builtin.addressof(&arg2))) } /// Invokes `body` with an `UnsafePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer. public func withUnsafePointer<T, Result>( inout arg: T, @noescape _ body: UnsafePointer<T> throws -> Result ) rethrows -> Result { return try body(UnsafePointer<T>(Builtin.addressof(&arg))) } /// Like `withUnsafePointer`, but passes pointers to `arg0` and `arg1`. public func withUnsafePointers<A0, A1, Result>( inout arg0: A0, inout _ arg1: A1, @noescape _ body: (UnsafePointer<A0>, UnsafePointer<A1>) throws -> Result ) rethrows -> Result { return try body( UnsafePointer<A0>(Builtin.addressof(&arg0)), UnsafePointer<A1>(Builtin.addressof(&arg1))) } /// Like `withUnsafePointer`, but passes pointers to `arg0`, `arg1`, /// and `arg2`. public func withUnsafePointers<A0, A1, A2, Result>( inout arg0: A0, inout _ arg1: A1, inout _ arg2: A2, @noescape _ body: ( UnsafePointer<A0>, UnsafePointer<A1>, UnsafePointer<A2> ) throws -> Result ) rethrows -> Result { return try body( UnsafePointer<A0>(Builtin.addressof(&arg0)), UnsafePointer<A1>(Builtin.addressof(&arg1)), UnsafePointer<A2>(Builtin.addressof(&arg2))) }
apache-2.0
f0a6c01a2570002d3c096911e33d15a0
32.389313
80
0.676726
3.891459
false
false
false
false
AaronMT/firefox-ios
Storage/Rust/RustShared.swift
9
3009
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared private let log = Logger.syncLogger public class RustShared { static func moveDatabaseFileToBackupLocation(databasePath: String) { let databaseURL = URL(fileURLWithPath: databasePath) let databaseContainingDirURL = databaseURL.deletingLastPathComponent() let baseFilename = databaseURL.lastPathComponent // Attempt to make a backup as long as the database file still exists. guard FileManager.default.fileExists(atPath: databasePath) else { // No backup was attempted since the database file did not exist. Sentry.shared.sendWithStacktrace(message: "The Rust database was deleted while in use", tag: SentryTag.rustLogins) return } Sentry.shared.sendWithStacktrace(message: "Unable to open Rust database", tag: SentryTag.rustLogins, severity: .warning, description: "Attempting to move '\(baseFilename)'") // Note that a backup file might already exist! We append a counter to avoid this. var bakCounter = 0 var bakBaseFilename: String var bakDatabasePath: String repeat { bakCounter += 1 bakBaseFilename = "\(baseFilename).bak.\(bakCounter)" bakDatabasePath = databaseContainingDirURL.appendingPathComponent(bakBaseFilename).path } while FileManager.default.fileExists(atPath: bakDatabasePath) do { try FileManager.default.moveItem(atPath: databasePath, toPath: bakDatabasePath) let shmBaseFilename = baseFilename + "-shm" let walBaseFilename = baseFilename + "-wal" log.debug("Moving \(shmBaseFilename) and \(walBaseFilename)…") let shmDatabasePath = databaseContainingDirURL.appendingPathComponent(shmBaseFilename).path if FileManager.default.fileExists(atPath: shmDatabasePath) { log.debug("\(shmBaseFilename) exists.") try FileManager.default.moveItem(atPath: shmDatabasePath, toPath: "\(bakDatabasePath)-shm") } let walDatabasePath = databaseContainingDirURL.appendingPathComponent(walBaseFilename).path if FileManager.default.fileExists(atPath: walDatabasePath) { log.debug("\(walBaseFilename) exists.") try FileManager.default.moveItem(atPath: shmDatabasePath, toPath: "\(bakDatabasePath)-wal") } log.debug("Finished moving Rust database (\(baseFilename)) successfully.") } catch let error as NSError { Sentry.shared.sendWithStacktrace(message: "Unable to move Rust database to backup location", tag: SentryTag.rustLogins, severity: .error, description: "Attempted to move to '\(bakBaseFilename)'. \(error.localizedDescription)") } } }
mpl-2.0
abc2177a4018b4fc1fac4cd64d12bcae
49.966102
238
0.686066
5.140171
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Auth/AuthNavigationController.swift
1
3052
// // AuthNavigationController.swift // Rocket.Chat // // Created by Samar Sunkaria on 6/25/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit class AuthNavigationController: UINavigationController { override var shouldAutorotate: Bool { return UIDevice.current.userInterfaceIdiom == .pad } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .pad { return super.supportedInterfaceOrientations } return [.portrait] } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let navBar = self.navigationBar navBar.isTranslucent = false navBar.tintColor = .RCBlue() navBar.barTintColor = .RCNavigationBarColor() } override func popToRootViewController(animated: Bool) -> [UIViewController]? { let viewControllers = super.popToRootViewController(animated: animated) setTransparentTheme() return viewControllers } override func popViewController(animated: Bool) -> UIViewController? { let poppedViewController = super.popViewController(animated: animated) if topViewController is ConnectServerViewController { setTransparentTheme() } return poppedViewController } override func pushViewController(_ viewController: UIViewController, animated: Bool) { let pushedFromViewController = topViewController super.pushViewController(viewController, animated: animated) if viewController is LoginTableViewController || viewController is AuthTableViewController { setGrayTheme( forceRedraw: pushedFromViewController is ConnectServerViewController ) } } func setTransparentTheme(forceRedraw: Bool = false) { let navBar = self.navigationBar navBar.barStyle = .default navBar.setBackgroundImage(UIImage(), for: .default) navBar.shadowImage = UIImage() navBar.backgroundColor = UIColor.clear navBar.isTranslucent = true navBar.tintColor = .RCBlue() if forceRedraw { forceNavigationToRedraw() } setNeedsStatusBarAppearanceUpdate() } func setGrayTheme(forceRedraw: Bool = false) { let navBar = self.navigationBar navBar.barStyle = .black navBar.shadowImage = UIImage() navBar.backgroundColor = .RCNavBarGray() navBar.barTintColor = .RCNavBarGray() navBar.isTranslucent = false navBar.tintColor = .white navBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] if forceRedraw { forceNavigationToRedraw() } setNeedsStatusBarAppearanceUpdate() } func forceNavigationToRedraw() { isNavigationBarHidden = true isNavigationBarHidden = false } } // MARK: Disable Theming extension AuthNavigationController { override func applyTheme() { } }
mit
8dd6808ab902267cc789f2385b8fcd3b
30.132653
100
0.682727
5.681564
false
false
false
false
Tommy1990/swiftWibo
SwiftWibo/SwiftWibo/AppDelegate.swift
1
5035
// // AppDelegate.swift // SwiftWibo // // Created by 马继鵬 on 17/3/19. // Copyright © 2017年 7TH. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = setupRootViewController() window?.makeKeyAndVisible() window?.backgroundColor = UIColor.white NotificationCenter.default.addObserver(self, selector: #selector(switchRootController), name: NSNotification.Name(rawValue: SWITCHROOTCONTROLLERINFO), object: nil) return true } func switchRootController(noti:Notification){ if let _ = noti.object{ window?.rootViewController = EPMMainTabBarController() }else{ window?.rootViewController = EPMWelcomViewController() } } func setupRootViewController()->UIViewController{ return EPMUserAccountModelView.shared.userLogin ? EPMWelcomViewController():EPMMainTabBarController() } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { EPMEPMDAL.deleteCache() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "SwiftWibo") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
1b71e3ed135c66dbefe947d1e8909b9c
43.477876
285
0.673896
5.763761
false
false
false
false
CosmicMind/Material
Sources/iOS/Icon/Icon.swift
3
6635
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit public struct Icon { /// An internal reference to the icons bundle. private static var internalBundle: Bundle? /** A public reference to the icons bundle, that aims to detect the correct bundle to use. */ public static var bundle: Bundle { if nil == Icon.internalBundle { Icon.internalBundle = Bundle(for: View.self) let url = Icon.internalBundle!.resourceURL! let b = Bundle(url: url.appendingPathComponent("com.cosmicmind.material.icons.bundle")) if let v = b { Icon.internalBundle = v } } return Icon.internalBundle! } /// Get the icon by the file name. public static func icon(_ name: String) -> UIImage? { return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } /// Google icons. public static var add = Icon.icon("ic_add_white") public static var addCircle = Icon.icon("ic_add_circle_white") public static var addCircleOutline = Icon.icon("ic_add_circle_outline_white") public static var arrowBack = Icon.icon("ic_arrow_back_white") public static var arrowDownward = Icon.icon("ic_arrow_downward_white") public static var audio = Icon.icon("ic_audiotrack_white") public static var bell = Icon.icon("cm_bell_white") public static var cameraFront = Icon.icon("ic_camera_front_white") public static var cameraRear = Icon.icon("ic_camera_rear_white") public static var check = Icon.icon("ic_check_white") public static var clear = Icon.icon("ic_close_white") public static var close = Icon.icon("ic_close_white") public static var edit = Icon.icon("ic_edit_white") public static var email = Icon.icon("ic_email_white") public static var favorite = Icon.icon("ic_favorite_white") public static var favoriteBorder = Icon.icon("ic_favorite_border_white") public static var flashAuto = Icon.icon("ic_flash_auto_white") public static var flashOff = Icon.icon("ic_flash_off_white") public static var flashOn = Icon.icon("ic_flash_on_white") public static var history = Icon.icon("ic_history_white") public static var home = Icon.icon("ic_home_white") public static var image = Icon.icon("ic_image_white") public static var menu = Icon.icon("ic_menu_white") public static var moreHorizontal = Icon.icon("ic_more_horiz_white") public static var moreVertical = Icon.icon("ic_more_vert_white") public static var movie = Icon.icon("ic_movie_white") public static var pen = Icon.icon("ic_edit_white") public static var place = Icon.icon("ic_place_white") public static var phone = Icon.icon("ic_phone_white") public static var photoCamera = Icon.icon("ic_photo_camera_white") public static var photoLibrary = Icon.icon("ic_photo_library_white") public static var search = Icon.icon("ic_search_white") public static var settings = Icon.icon("ic_settings_white") public static var share = Icon.icon("ic_share_white") public static var star = Icon.icon("ic_star_white") public static var starBorder = Icon.icon("ic_star_border_white") public static var starHalf = Icon.icon("ic_star_half_white") public static var videocam = Icon.icon("ic_videocam_white") public static var visibility = Icon.icon("ic_visibility_white") public static var visibilityOff = Icon.icon("ic_visibility_off_white") public static var work = Icon.icon("ic_work_white") /// CosmicMind icons. public struct cm { public static var add = Icon.icon("cm_add_white") public static var arrowBack = Icon.icon("cm_arrow_back_white") public static var arrowDownward = Icon.icon("cm_arrow_downward_white") public static var audio = Icon.icon("cm_audio_white") public static var audioLibrary = Icon.icon("cm_audio_library_white") public static var bell = Icon.icon("cm_bell_white") public static var check = Icon.icon("cm_check_white") public static var clear = Icon.icon("cm_close_white") public static var close = Icon.icon("cm_close_white") public static var edit = Icon.icon("cm_pen_white") public static var image = Icon.icon("cm_image_white") public static var menu = Icon.icon("cm_menu_white") public static var microphone = Icon.icon("cm_microphone_white") public static var moreHorizontal = Icon.icon("cm_more_horiz_white") public static var moreVertical = Icon.icon("cm_more_vert_white") public static var movie = Icon.icon("cm_movie_white") public static var pause = Icon.icon("cm_pause_white") public static var pen = Icon.icon("cm_pen_white") public static var photoCamera = Icon.icon("cm_photo_camera_white") public static var photoLibrary = Icon.icon("cm_photo_library_white") public static var play = Icon.icon("cm_play_white") public static var search = Icon.icon("cm_search_white") public static var settings = Icon.icon("cm_settings_white") public static var share = Icon.icon("cm_share_white") public static var shuffle = Icon.icon("cm_shuffle_white") public static var skipBackward = Icon.icon("cm_skip_backward_white") public static var skipForward = Icon.icon("cm_skip_forward_white") public static var star = Icon.icon("cm_star_white") public static var videocam = Icon.icon("cm_videocam_white") public static var volumeHigh = Icon.icon("cm_volume_high_white") public static var volumeMedium = Icon.icon("cm_volume_medium_white") public static var volumeOff = Icon.icon("cm_volume_off_white") } }
mit
283cad214ac230f14122db8ba1fe4216
49.648855
100
0.719668
3.828621
false
false
false
false