hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
febba5c464d337293bda863c336872d69c374cad
445
// // NetworkBaseState.swift // // Created by Bauer, Robert S. on 5/12/19. // Copyright © 2019 RSB. All rights reserved. // import Foundation public class NetworkBaseState: State { // MARK: Properties let name: String // MARK: Initialization init(name: String) { self.name = name } // MARK: State overrides override func didEnter(from previousState: State?) { super.didEnter(from: previousState) } // MARK: Methods }
15.892857
53
0.678652
e0ee0aaecceaa43b8400add08346ed01d306478b
8,672
/* Copyright (c) 2014 Samsung Electronics Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation class MSFDiscoveryProvider: ServiceSearchProviderBase { private enum MSFDMessageType: String { case Up = "up" case Alive = "alive" case Dowm = "down" case Discover = "discover" } private let MULTICAST_ADDRESS = "224.0.0.7" private let MULTICAST_TTL = 1 private let MULTICAST_PORT:UInt16 = 8001 private let MAX_MESSAGE_LENGTH:UInt16 = 2000 private let TBEAT_INTERVAL = NSTimeInterval(1) private let RETRY_COUNT = 3 private let RETRY_INTERVAL = 1 private var udpSearchSocket: GCDAsyncUdpSocket! private var udpListeningSocket: GCDAsyncUdpSocket! //private var unresolvedServices = NSMutableSet(capacity: 0) private var services = NSMutableDictionary(capacity: 0) private var timer: NSTimer! private var isRestarting = false private let accessQueue = dispatch_queue_create("MSFDiscoveryProviderQueue", DISPATCH_QUEUE_SERIAL) // The intializer required init(delegate: ServiceSearchProviderDelegate, id: String?) { super.init(delegate: delegate, id: id) type = ServiceSearchDiscoveryType.LAN } /// Start the search override func search() { dispatch_async(self.accessQueue) { [unowned self] in var error: NSError? = nil self.udpListeningSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: self.accessQueue) self.udpListeningSocket.setIPv6Enabled(false) self.udpListeningSocket.setMaxReceiveIPv4BufferSize(self.MAX_MESSAGE_LENGTH) self.udpListeningSocket.bindToPort(self.MULTICAST_PORT, error: &error) if error != nil { println("udpListeningSocket bindToPort \(error)") } self.udpListeningSocket.joinMulticastGroup(self.MULTICAST_ADDRESS, error: &error) if error != nil { println("udpListeningSocket joinMulticastGroup \(error)") } self.udpListeningSocket.beginReceiving(&error) if error != nil { println("udpListeningSocket beginReceiving \(error)") } self.udpSearchSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: self.accessQueue) self.udpSearchSocket.setIPv6Enabled(false) self.udpSearchSocket.setMaxReceiveIPv4BufferSize(self.MAX_MESSAGE_LENGTH) self.udpSearchSocket.bindToPort(0, error: &error) if error != nil { println("udpSearchSocket bindToPort \(error)") } self.udpSearchSocket.beginReceiving(&error) if error != nil { println("udpSearchSocket beginReceiving \(error)") } self.udpSearchSocket.sendData(self.getMessageEnvelope(), toHost: self.MULTICAST_ADDRESS, port: self.MULTICAST_PORT, withTimeout: NSTimeInterval(-1), tag: 0) // if not searching by id if self.id == nil { dispatch_async(dispatch_get_main_queue()) { [unowned self] () -> Void in self.timer = NSTimer.scheduledTimerWithTimeInterval(self.TBEAT_INTERVAL, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } } self.isSearching = true } } func update() { dispatch_async(self.accessQueue) { [unowned self] in let now = NSDate() let keys = NSArray(array: self.services.allKeys) as! [String] for key in keys { if self.services[key]?.compare(now) == NSComparisonResult.OrderedAscending { self.services.removeObjectForKey(key) println("MSFD -> self.services \(key) \(self.services)") self.delegate?.onServiceLost(key, discoveryType: self.type) } } } } /// Stops the search override func stop() { dispatch_sync(self.accessQueue) { [unowned self] in if self.isSearching { self.isSearching = false if self.timer != nil { self.timer.invalidate() self.timer = nil } var error: NSError? = nil self.udpListeningSocket.leaveMulticastGroup(self.MULTICAST_ADDRESS, error: &error) self.udpListeningSocket = nil self.udpSearchSocket = nil self.services.removeAllObjects() //self.unresolvedServices.removeAllObjects() //delegate?.onStop(self) } } } override func serviceResolutionFaile(serviceId: String, discoveryType: ServiceSearchDiscoveryType) { if discoveryType == type { dispatch_async(self.accessQueue) { [unowned self] in self.services.removeObjectForKey(serviceId) } } } /** * Called when the datagram with the given tag has been sent. **/ func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) { } /** * Called if an error occurs while trying to send a datagram. * This could be due to a timeout, or something more serious such as the data being too large to fit in a sigle packet. **/ func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) { } /** * Called when the socket has received the requested datagram. **/ func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) { if let msg: [String:AnyObject] = JSON.parse(data: data) as? Dictionary { if let type: MSFDMessageType = MSFDMessageType(rawValue: msg["type"] as! String) { switch type { case .Up: serviceFound(msg) case .Alive: serviceFound(msg) default: () } } } } /** * Called when the socket is closed. **/ func udpSocketDidClose(sock: GCDAsyncUdpSocket!, withError error: NSError!) { if isSearching { isRestarting = true self.stop() self.delegate?.clearCacheForProvider(self) self.search() } else if !isRestarting { isSearching = false delegate?.onStop(self) } } private func serviceFound(msg: NSDictionary) { if let sid = msg["sid"] as? String { if (id != nil && id == sid) || id == nil { if let uri = msg.objectForKey("data")?.objectForKey("v2")?.objectForKey("uri") as? String { let ttl = msg["ttl"] as! Double if services[sid] == nil { println("MSFD -> serviceFound \(sid) \(uri)") services[sid] = NSDate(timeIntervalSinceNow: NSTimeInterval(ttl/1000.0)) delegate!.onServiceFound(sid, serviceURI: uri, discoveryType: ServiceSearchDiscoveryType.LAN) } else { self.services[sid] = NSDate(timeIntervalSinceNow: NSTimeInterval(ttl/1000.0)) } } } } } private func getMessageEnvelope() -> NSData { var msg: [String: AnyObject] = [ "type": MSFDMessageType.Discover.rawValue, "data": [:], "cuid": NSUUID().UUIDString ] return JSON.jsonDataForObject(msg)! } }
37.218884
168
0.613469
d61db955135d7af04d7565d3e5b752476bffb207
1,648
import Foundation import AsyncHTTPClient // 'req' variable has: // 'headers' - object with request headers // 'payload' - object with request body data // 'env' - object with environment variables // 'res' variable has: // 'send(text, status)' - function to return text response. Status code defaults to 200 // 'json(obj, status)' - function to return JSON response. Status code defaults to 200 // // If an error is thrown, a response with code 500 will be returned. func main(req: RequestValue, res: RequestResponse) async throws -> RequestResponse { let headerData = req.headers["x-test-header"] let envData = req.env["test-env"] var todoId: String = "1" var reqPayload = req.payload as! String if(reqPayload == "") { reqPayload = "{}" } if !reqPayload.isEmpty, let data = reqPayload.data(using: .utf8), let payload = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { todoId = payload["id"] as? String ?? "1" } let httpClient = HTTPClient(eventLoopGroupProvider: .createNew) let request = HTTPClientRequest(url: "https://jsonplaceholder.typicode.com/todos/\(todoId)") let response = try await httpClient.execute(request, timeout: .seconds(30)) let data = try await response.body.collect(upTo: 1024 * 1024) let todo = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] return res.json(data: [ "isTest": true, "message": "Hello Open Runtimes 👋", "todo": todo, "header": headerData, "env": envData ]) }
35.826087
100
0.63835
0e6829761f1c70388f4810481fc45a8710395d42
774
// // MenuSection.swift // import Foundation class MenuSection { var title: String var value: String? var items: [MenuItem]? var isExpanded = false var numItems: Int { return (items?.count ?? 0) } var numRows: Int { return (isExpanded ? (numItems + 1) : 1) } var isExpandable: Bool { return (numItems > 0) } init(title: String, value: String? = nil, items: [MenuItem]? = nil) { self.title = title self.value = value self.items = items } func toggle() { isExpanded = !isExpanded } func item(atIndex index: Int) -> MenuItem? { if let items = items, items.count > index { return items[index] } return nil } }
17.2
73
0.53876
76f77c75ba838232b0fc0ea80e8377cb31d4230a
426
// // PhoneCaller.swift // AptoSDK // // Created by Takeichi Kanzaki on 23/10/2018. // import AptoSDK @testable import AptoUISDK class PhoneCallerSpy: DummyPhoneCaller { private(set) var callCalled = false override func call(phoneNumberURL: URL, from module: UIModule, completion: @escaping () -> Void) { callCalled = true super.call(phoneNumberURL: phoneNumberURL, from: module, completion: completion) } }
23.666667
100
0.7277
5ddc0e04303fe952e2d7c66b2b03fc495888917e
8,360
// // MapStatusView.swift // OBAKit // // Created by Alan Chu on 7/9/20. // import UIKit import MapKit import SwiftUI import CoreLocation import OBAKitCore /// A view intended to be placed at the top of the screen, above a map view, that displays location information. /// You shouldn't manually change the visibility of this view. This view plays two roles, blurring the content behind /// the system status bar and displays location authorization, as needed. /// On iOS 13+, this will also show icons applicable to the situation. class MapStatusView: UIView { enum State { /// The user hasn't picked location services yet. case notDetermined /// Location services is unavailable system-wide. case locationServicesUnavailable /// Location services is disabled for this application. case locationServicesOff /// Location services is enabled for this appliation. case locationServicesOn /// iOS 14+ Location services is enabled, but is set to imprecise location for this application. case impreciseLocation init(_ authStatus: CLAuthorizationStatus, isImprecise: Bool = false) { switch authStatus { case .notDetermined: self = .notDetermined case .restricted: self = .locationServicesUnavailable case .denied: self = .locationServicesOff case .authorizedAlways, .authorizedWhenInUse: self = isImprecise ? .impreciseLocation : .locationServicesOn @unknown default: self = .locationServicesUnavailable } } } // MARK: - UI elements private var visualView: UIVisualEffectView! private var stackView: UIStackView! private var iconView: UIImageView! private var detailLabel: UILabel! // MARK: Large Content properties override var showsLargeContentViewer: Bool { get { return true } set { _ = newValue } } override var scalesLargeContentImage: Bool { get { return true } set { _ = newValue } } override var largeContentTitle: String? { get { detailLabel.text } set { _ = newValue } } // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { super.init(coder: coder) configure() } private func configure() { stackView = UIStackView.autolayoutNew() stackView.alignment = .center stackView.axis = .horizontal stackView.spacing = 8 // Make visual view iconView = UIImageView.autolayoutNew() iconView.tintColor = ThemeColors.shared.brand stackView.addArrangedSubview(iconView) detailLabel = UILabel.autolayoutNew() detailLabel.font = .preferredFont(forTextStyle: .headline) detailLabel.textColor = ThemeColors.shared.brand stackView.addArrangedSubview(detailLabel) visualView = UIVisualEffectView(effect: UIBlurEffect(style: .prominent)) visualView.translatesAutoresizingMaskIntoConstraints = false visualView.contentView.addSubview(stackView) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: visualView.layoutMarginsGuide.centerXAnchor), stackView.leadingAnchor.constraint(greaterThanOrEqualTo: visualView.readableContentGuide.leadingAnchor), stackView.trailingAnchor.constraint(lessThanOrEqualTo: visualView.readableContentGuide.trailingAnchor), stackView.topAnchor.constraint(equalTo: visualView.layoutMarginsGuide.topAnchor), stackView.bottomAnchor.constraint(equalTo: visualView.layoutMarginsGuide.bottomAnchor) ]) self.addSubview(visualView) visualView.pinToSuperview(.edges) } override func layoutSubviews() { super.layoutSubviews() let padding = traitCollection.verticalSizeClass == .compact ? ThemeMetrics.compactPadding : ThemeMetrics.padding visualView.layoutMargins = UIEdgeInsets(top: padding, left: 0, bottom: padding, right: 0) } // MARK: - State changes func state(for service: LocationService) -> State { if #available(iOS 14, *) { return .init(service.authorizationStatus, isImprecise: service.accuracyAuthorization == .reducedAccuracy) } else { return .init(service.authorizationStatus) } } func configure(with service: LocationService) { self.configure(for: state(for: service)) } func configure(for state: State) { var setHidden: Bool var setImage: UIImage? var setLargeImage: UIImage? var setLabel: String? switch state { case .locationServicesUnavailable, .locationServicesOff, .notDetermined: setHidden = false setImage = UIImage(systemName: "location.slash")! setLargeImage = UIImage(systemName: "location.slash.fill")! setLabel = OBALoc("map_status_view.location_services_unavailable", value: "Location services unavailable", comment: "Displayed in the map status view at the top of the map when the user has declined to give the app access to their location") case .impreciseLocation: setHidden = false setImage = UIImage(systemName: "location.circle")! setLargeImage = UIImage(systemName: "location.circle.fill")! setLabel = OBALoc("map_status_view.precise_location_unavailable", value: "Precise location unavailable", comment: "Displayed in the map status view at the top of the map when the user has declined to give the app access to their precise location") case .locationServicesOn: setHidden = true } UIView.animate(withDuration: 0.25) { self.stackView.isHidden = setHidden self.iconView.image = setImage self.detailLabel.text = setLabel self.largeContentImage = setLargeImage self.layoutIfNeeded() } } /// Provides a call-to-action alert for resolving location authorization issues. /// - important: This only returns the title and message (body) of the alert. You have to manually add applicable actions. /// - returns: In situations where the user can't modify their location services or location services is /// already enabled, this will return `nil`, meaning the user doesn't need to do anything. static func alert(for state: State) -> UIAlertController? { let title: String let message: String switch state { case .locationServicesUnavailable, .locationServicesOn: return nil case .locationServicesOff, .notDetermined: title = OBALoc("locationservices_alert_off.title", value: "OneBusAway works best with your location.", comment: "") message = OBALoc("locationservices_alert_off.message", value: "You'll get to see where you are on the map and see nearby stops, making it easier to get where you need to go.", comment: "") case .impreciseLocation: title = OBALoc("locationservices_alert_imprecise.title", value: "OneBusAway works best with your precise location", comment: "") message = OBALoc("locationservices_alert_imprecise.message", value: "You'll get to see where you are on the map and see nearby stops, making it easier to get where you need to go.", comment: "") } return UIAlertController(title: title, message: message, preferredStyle: .alert) } } // MARK: - Previews #if DEBUG extension MapStatusView.State: Identifiable, CaseIterable { var id: String { return "\(self)"} } struct MapStatusView_Previews: PreviewProvider { static func makeStatusView(for state: MapStatusView.State) -> MapStatusView { let v = MapStatusView() v.configure(for: state) return v } static var previews: some View { ForEach(MapStatusView.State.allCases) { state in UIViewPreview { makeStatusView(for: state) } .previewLayout(.fixed(width: 375, height: 64)) .previewDisplayName(state.id) } } } #endif
38.173516
259
0.664474
fef3a2d68df4880d6642b9af102bdc54fffd91b9
16,014
import Foundation import UIKit import SwiftSignalKit import AsyncDisplayKit import Display import Postbox import TelegramCore import SyncCore import TelegramPresentationData import TelegramUIPreferences import CheckNode import TextFormat import AccountContext import Markdown private let textFont = Font.regular(13.0) private let boldTextFont = Font.semibold(13.0) private func formattedText(_ text: String, color: UIColor, textAlignment: NSTextAlignment = .natural) -> NSAttributedString { return parseMarkdownIntoAttributedString(text, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: textFont, textColor: color), bold: MarkdownAttributeSet(font: boldTextFont, textColor: color), link: MarkdownAttributeSet(font: textFont, textColor: color), linkAttribute: { _ in return nil}), textAlignment: textAlignment) } private final class ChatMessageActionUrlAuthAlertContentNode: AlertContentNode { private let strings: PresentationStrings private let nameDisplayOrder: PresentationPersonNameOrder private let defaultUrl: String private let domain: String private let bot: Peer private let displayName: String private let titleNode: ASTextNode private let textNode: ASTextNode private let authorizeCheckNode: InteractiveCheckNode private let authorizeLabelNode: ASTextNode private let allowWriteCheckNode: InteractiveCheckNode private let allowWriteLabelNode: ASTextNode private let actionNodesSeparator: ASDisplayNode private let actionNodes: [TextAlertContentActionNode] private let actionVerticalSeparators: [ASDisplayNode] private var validLayout: CGSize? override var dismissOnOutsideTap: Bool { return self.isUserInteractionEnabled } var authorize: Bool = true { didSet { self.authorizeCheckNode.setSelected(self.authorize, animated: true) self.allowWriteCheckNode.isUserInteractionEnabled = self.authorize self.allowWriteCheckNode.alpha = self.authorize ? 1.0 : 0.4 self.allowWriteLabelNode.alpha = self.authorize ? 1.0 : 0.4 if !self.authorize && self.allowWriteAccess { self.allowWriteAccess = false } } } var allowWriteAccess: Bool = true { didSet { self.allowWriteCheckNode.setSelected(self.allowWriteAccess, animated: true) } } init(theme: AlertControllerTheme, ptheme: PresentationTheme, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder, defaultUrl: String, domain: String, bot: Peer, requestWriteAccess: Bool, displayName: String, actions: [TextAlertAction]) { self.strings = strings self.nameDisplayOrder = nameDisplayOrder self.defaultUrl = defaultUrl self.domain = domain self.bot = bot self.displayName = displayName self.titleNode = ASTextNode() self.titleNode.maximumNumberOfLines = 2 self.textNode = ASTextNode() self.textNode.maximumNumberOfLines = 0 self.authorizeCheckNode = InteractiveCheckNode(theme: CheckNodeTheme(backgroundColor: theme.accentColor, strokeColor: theme.contrastColor, borderColor: theme.controlBorderColor, overlayBorder: false, hasInset: false, hasShadow: false)) self.authorizeCheckNode.setSelected(true, animated: false) self.authorizeLabelNode = ASTextNode() self.authorizeLabelNode.maximumNumberOfLines = 4 self.authorizeLabelNode.isUserInteractionEnabled = true self.allowWriteCheckNode = InteractiveCheckNode(theme: CheckNodeTheme(backgroundColor: theme.accentColor, strokeColor: theme.contrastColor, borderColor: theme.controlBorderColor, overlayBorder: false, hasInset: false, hasShadow: false)) self.allowWriteCheckNode.setSelected(true, animated: false) self.allowWriteLabelNode = ASTextNode() self.allowWriteLabelNode.maximumNumberOfLines = 4 self.allowWriteLabelNode.isUserInteractionEnabled = true self.actionNodesSeparator = ASDisplayNode() self.actionNodesSeparator.isLayerBacked = true self.actionNodes = actions.map { action -> TextAlertContentActionNode in return TextAlertContentActionNode(theme: theme, action: action) } var actionVerticalSeparators: [ASDisplayNode] = [] if actions.count > 1 { for _ in 0 ..< actions.count - 1 { let separatorNode = ASDisplayNode() separatorNode.isLayerBacked = true actionVerticalSeparators.append(separatorNode) } } self.actionVerticalSeparators = actionVerticalSeparators super.init() self.addSubnode(self.titleNode) self.addSubnode(self.textNode) self.addSubnode(self.authorizeCheckNode) self.addSubnode(self.authorizeLabelNode) if requestWriteAccess { self.addSubnode(self.allowWriteCheckNode) self.addSubnode(self.allowWriteLabelNode) } self.addSubnode(self.actionNodesSeparator) for actionNode in self.actionNodes { self.addSubnode(actionNode) } for separatorNode in self.actionVerticalSeparators { self.addSubnode(separatorNode) } self.authorizeCheckNode.valueChanged = { [weak self] value in if let strongSelf = self { strongSelf.authorize = !strongSelf.authorize } } self.allowWriteCheckNode.valueChanged = { [weak self] value in if let strongSelf = self { strongSelf.allowWriteAccess = !strongSelf.allowWriteAccess } } self.updateTheme(theme) } override func didLoad() { super.didLoad() self.authorizeLabelNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.authorizeTap(_:)))) self.allowWriteLabelNode.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.allowWriteTap(_:)))) } @objc private func authorizeTap(_ gestureRecognizer: UITapGestureRecognizer) { self.authorize = !self.authorize } @objc private func allowWriteTap(_ gestureRecognizer: UITapGestureRecognizer) { if self.allowWriteCheckNode.isUserInteractionEnabled { self.allowWriteAccess = !self.allowWriteAccess } } override func updateTheme(_ theme: AlertControllerTheme) { self.titleNode.attributedText = NSAttributedString(string: strings.Conversation_OpenBotLinkTitle, font: Font.bold(17.0), textColor: theme.primaryColor, paragraphAlignment: .center) self.textNode.attributedText = formattedText(strings.Conversation_OpenBotLinkText(self.defaultUrl).0, color: theme.primaryColor, textAlignment: .center) self.authorizeLabelNode.attributedText = formattedText(strings.Conversation_OpenBotLinkLogin(self.domain, self.displayName).0, color: theme.primaryColor) self.allowWriteLabelNode.attributedText = formattedText(strings.Conversation_OpenBotLinkAllowMessages(self.bot.displayTitle(strings: self.strings, displayOrder: self.nameDisplayOrder)).0, color: theme.primaryColor) self.actionNodesSeparator.backgroundColor = theme.separatorColor for actionNode in self.actionNodes { actionNode.updateTheme(theme) } for separatorNode in self.actionVerticalSeparators { separatorNode.backgroundColor = theme.separatorColor } if let size = self.validLayout { _ = self.updateLayout(size: size, transition: .immediate) } } override func updateLayout(size: CGSize, transition: ContainedViewLayoutTransition) -> CGSize { var size = size size.width = min(size.width, 270.0) let measureSize = CGSize(width: size.width - 16.0 * 2.0, height: CGFloat.greatestFiniteMagnitude) self.validLayout = size var origin: CGPoint = CGPoint(x: 0.0, y: 20.0) let titleSize = self.titleNode.measure(measureSize) transition.updateFrame(node: self.titleNode, frame: CGRect(origin: CGPoint(x: floorToScreenPixels((size.width - titleSize.width) / 2.0), y: origin.y), size: titleSize)) origin.y += titleSize.height + 9.0 let textSize = self.textNode.measure(measureSize) transition.updateFrame(node: self.textNode, frame: CGRect(origin: CGPoint(x: floorToScreenPixels((size.width - textSize.width) / 2.0), y: origin.y), size: textSize)) origin.y += textSize.height + 16.0 let checkSize = CGSize(width: 22.0, height: 22.0) let condensedSize = CGSize(width: size.width - 76.0, height: size.height) var entriesHeight: CGFloat = 0.0 let authorizeSize = self.authorizeLabelNode.measure(condensedSize) transition.updateFrame(node: self.authorizeLabelNode, frame: CGRect(origin: CGPoint(x: 46.0, y: origin.y), size: authorizeSize)) transition.updateFrame(node: self.authorizeCheckNode, frame: CGRect(origin: CGPoint(x: 12.0, y: origin.y - 2.0), size: checkSize)) origin.y += authorizeSize.height entriesHeight += authorizeSize.height if self.allowWriteLabelNode.supernode != nil { origin.y += 16.0 entriesHeight += 16.0 let allowWriteSize = self.allowWriteLabelNode.measure(condensedSize) transition.updateFrame(node: self.allowWriteLabelNode, frame: CGRect(origin: CGPoint(x: 46.0, y: origin.y), size: allowWriteSize)) transition.updateFrame(node: self.allowWriteCheckNode, frame: CGRect(origin: CGPoint(x: 12.0, y: origin.y - 2.0), size: checkSize)) origin.y += allowWriteSize.height entriesHeight += allowWriteSize.height } let actionButtonHeight: CGFloat = 44.0 var minActionsWidth: CGFloat = 0.0 let maxActionWidth: CGFloat = floor(size.width / CGFloat(self.actionNodes.count)) let actionTitleInsets: CGFloat = 8.0 var effectiveActionLayout = TextAlertContentActionLayout.horizontal for actionNode in self.actionNodes { let actionTitleSize = actionNode.titleNode.updateLayout(CGSize(width: maxActionWidth, height: actionButtonHeight)) if case .horizontal = effectiveActionLayout, actionTitleSize.height > actionButtonHeight * 0.6667 { effectiveActionLayout = .vertical } switch effectiveActionLayout { case .horizontal: minActionsWidth += actionTitleSize.width + actionTitleInsets case .vertical: minActionsWidth = max(minActionsWidth, actionTitleSize.width + actionTitleInsets) } } let insets = UIEdgeInsets(top: 18.0, left: 18.0, bottom: 18.0, right: 18.0) var contentWidth = max(titleSize.width, minActionsWidth) contentWidth = max(contentWidth, 234.0) var actionsHeight: CGFloat = 0.0 switch effectiveActionLayout { case .horizontal: actionsHeight = actionButtonHeight case .vertical: actionsHeight = actionButtonHeight * CGFloat(self.actionNodes.count) } let resultWidth = contentWidth + insets.left + insets.right let resultSize = CGSize(width: resultWidth, height: titleSize.height + textSize.height + entriesHeight + actionsHeight + 30.0 + insets.top + insets.bottom) transition.updateFrame(node: self.actionNodesSeparator, frame: CGRect(origin: CGPoint(x: 0.0, y: resultSize.height - actionsHeight - UIScreenPixel), size: CGSize(width: resultSize.width, height: UIScreenPixel))) var actionOffset: CGFloat = 0.0 let actionWidth: CGFloat = floor(resultSize.width / CGFloat(self.actionNodes.count)) var separatorIndex = -1 var nodeIndex = 0 for actionNode in self.actionNodes { if separatorIndex >= 0 { let separatorNode = self.actionVerticalSeparators[separatorIndex] switch effectiveActionLayout { case .horizontal: transition.updateFrame(node: separatorNode, frame: CGRect(origin: CGPoint(x: actionOffset - UIScreenPixel, y: resultSize.height - actionsHeight), size: CGSize(width: UIScreenPixel, height: actionsHeight - UIScreenPixel))) case .vertical: transition.updateFrame(node: separatorNode, frame: CGRect(origin: CGPoint(x: 0.0, y: resultSize.height - actionsHeight + actionOffset - UIScreenPixel), size: CGSize(width: resultSize.width, height: UIScreenPixel))) } } separatorIndex += 1 let currentActionWidth: CGFloat switch effectiveActionLayout { case .horizontal: if nodeIndex == self.actionNodes.count - 1 { currentActionWidth = resultSize.width - actionOffset } else { currentActionWidth = actionWidth } case .vertical: currentActionWidth = resultSize.width } let actionNodeFrame: CGRect switch effectiveActionLayout { case .horizontal: actionNodeFrame = CGRect(origin: CGPoint(x: actionOffset, y: resultSize.height - actionsHeight), size: CGSize(width: currentActionWidth, height: actionButtonHeight)) actionOffset += currentActionWidth case .vertical: actionNodeFrame = CGRect(origin: CGPoint(x: 0.0, y: resultSize.height - actionsHeight + actionOffset), size: CGSize(width: currentActionWidth, height: actionButtonHeight)) actionOffset += actionButtonHeight } transition.updateFrame(node: actionNode, frame: actionNodeFrame) nodeIndex += 1 } return resultSize } } func chatMessageActionUrlAuthController(context: AccountContext, defaultUrl: String, domain: String, bot: Peer, requestWriteAccess: Bool, displayName: String, open: @escaping (Bool, Bool) -> Void) -> AlertController { let presentationData = context.sharedContext.currentPresentationData.with { $0 } let theme = presentationData.theme let strings = presentationData.strings var contentNode: ChatMessageActionUrlAuthAlertContentNode? var dismissImpl: ((Bool) -> Void)? let actions: [TextAlertAction] = [TextAlertAction(type: .genericAction, title: presentationData.strings.Common_Cancel, action: { dismissImpl?(true) }), TextAlertAction(type: .defaultAction, title: presentationData.strings.Conversation_OpenBotLinkOpen, action: { dismissImpl?(true) if let contentNode = contentNode { open(contentNode.authorize, contentNode.allowWriteAccess) } })] contentNode = ChatMessageActionUrlAuthAlertContentNode(theme: AlertControllerTheme(presentationData: presentationData), ptheme: theme, strings: strings, nameDisplayOrder: presentationData.nameDisplayOrder, defaultUrl: defaultUrl, domain: domain, bot: bot, requestWriteAccess: requestWriteAccess, displayName: displayName, actions: actions) let controller = AlertController(theme: AlertControllerTheme(presentationData: presentationData), contentNode: contentNode!) dismissImpl = { [weak controller] animated in if animated { controller?.dismissAnimated() } else { controller?.dismiss() } } return controller }
48.23494
343
0.670726
216d6f07662750d72bd561053f22d654ac6efb35
408
// // SimpleResponse.swift // Libros // // Created by Yoshihiro Tanaka on 2017/01/14. // Copyright © 2017年 Yoshihiro Tanaka. All rights reserved. // import Foundation import Himotoki struct SimpleResponse : Decodable { let status: Int static func decode(_ e: Extractor) throws -> SimpleResponse { return try SimpleResponse( status: e <| "status" ) } }
18.545455
65
0.634804
87c451757304e8e3bb0184180c18233ccba98e11
3,594
// // GameScene.swift // OralWar // // Created by MrSmall on 2015/08/26. // Copyright (c) 2015年 MrSmall. All rights reserved. // import SpriteKit let STAGELIST: String = "stagelist" class GameScene: SKScene { var uiView: UILayerView! var oralPieceMap: OralPieceMap! var user: User! override init(size: CGSize) { super.init(size: size) } // set user info func setUser(_ user: User) { self.user = user } // set ui layer func setUiLayerView(_ view: UILayerView) { uiView = view self.view!.addSubview(uiView) } // set up piece map func setUp() -> Bool { // load UserDefaults guard let user = UserDefaultsUtil.getUserInfo() else { return false } let stage = user.getStage() print("stage \(stage)") // read stagelist.json let util: JsonUtil = JsonUtil() let data = util.parseJson(STAGELIST, type: JSON_FORMAT.file) guard let stageData: NSArray = data as? NSArray else { return false } var uri = "" for elm in stageData { print(elm) guard let stageInfo: Stage = ConvertUtil.toStage(elm as? NSDictionary) else { continue } if stage == stageInfo.getId() { uri = stageInfo.getUri() } } if uri == "" { // uri empty return false } print(uri) // get stage data guard let stageMapData = util.parseJson(uri) else { return false } // convert oralpiecemap oralPieceMap = ConvertUtil.toOralPieceMap(stageMapData as! NSDictionary) // TODO set info data to ui view return true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { // show background for debug let backtooth = SKSpriteNode(imageNamed: "backtooth01.png") backtooth.size = self.size backtooth.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) self.addChild(backtooth) print("w : \(self.size.width), y : \(self.size.height)") // TODO for debug let ary = TextureUtil.loadDivImage("chip_pumpkin1.png", col: 3, row: 4) let node: SKSpriteNode = SKSpriteNode(texture: ary[0]) node.position = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2) node.name = "pumpkin" //let action: SKAction = SKAction.animateWithTextures(ary, timePerFrame: 0.2) //let forever: SKAction = SKAction.repeatActionForever(action) //node.runAction(forever) self.addChild(node) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { /* Called when a touch begins */ if let touch = touches.first as UITouch! { let location = touch.location(in: self.view) let newlocation = CGPoint(x: location.x, y: self.size.height - location.y) // TODO for debug print(location) let node = self.childNode(withName: "pumpkin") let action = SKAction.move(to: newlocation, duration: 1.0) node?.run(action) } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ } }
29.702479
97
0.562326
203e46da41059f5d77aef3caf1873b5e573db0be
599
import NIO /** SetLabelMessage - 24 Set a `Device`'s label text. */ class SetLabelMessage: LabelMessage, SetMessage { typealias CorrespondingStateMessage = StateLabelMessage override class var type: UInt16 { 24 } override class var responseTypes: [Message.Type] { super.responseTypes + [CorrespondingStateMessage.self] } required init(_ value: String, target: Target) { super.init(target: target, requestAcknowledgement: false, requestResponse: true, label: value) } }
23.038462
62
0.612688
b9c267bb7a4e649a3b15e9545b2bb2c49503b51d
5,723
// // CommentsTableViewController.swift // DNApp // // Created by Meng To on 2015-03-08. // Copyright (c) 2015 Meng To. All rights reserved. // import UIKit class CommentsTableViewController: UITableViewController, CommentTableViewCellDelegate, StoryTableViewCellDelegate, ReplyViewControllerDelegate { var story: JSON! var comments: [JSON]! var transitionManager = TransitionManager() override func viewDidLoad() { super.viewDidLoad() comments = flattenComments(story["comments"].array ?? []) refreshControl?.addTarget(self, action: "reloadStory", forControlEvents: UIControlEvents.ValueChanged) tableView.estimatedRowHeight = 140 tableView.rowHeight = UITableViewAutomaticDimension } @IBAction func shareButtonDidTouch(sender: AnyObject) { let title = story["title"].string ?? "" let url = story["url"].string ?? "" let activityViewController = UIActivityViewController(activityItems: [title, url], applicationActivities: nil) activityViewController.setValue(title, forKey: "subject") activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop] presentViewController(activityViewController, animated: true, completion: nil) } func reloadStory() { view.showLoading() DNService.storyForId(story["id"].int!, response: { (JSON) -> () in self.view.hideLoading() self.story = JSON["story"] self.comments = self.flattenComments(JSON["story"]["comments"].array ?? []) self.tableView.reloadData() self.refreshControl?.endRefreshing() }) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifer = indexPath.row == 0 ? "StoryCell" : "CommentCell" let cell = tableView.dequeueReusableCellWithIdentifier(identifer) as UITableViewCell! if let storyCell = cell as? StoryTableViewCell { storyCell.configureWithStory(story) storyCell.delegate = self } if let commentCell = cell as? CommentTableViewCell { let comment = comments[indexPath.row - 1] commentCell.configureWithComment(comment) commentCell.delegate = self } return cell } // MARK: CommentTableViewCellDelegate func commentTableViewCellDidTouchUpvote(cell: CommentTableViewCell) { if let token = LocalStore.getToken() { let indexPath = tableView.indexPathForCell(cell)! let comment = comments[indexPath.row - 1] let commentId = comment["id"].int! DNService.upvoteCommentWithId(commentId, token: token, response: { (successful) -> () in }) LocalStore.saveUpvotedComment(commentId) cell.configureWithComment(comment) } else { performSegueWithIdentifier("LoginSegue", sender: self) } } func commentTableViewCellDidTouchComment(cell: CommentTableViewCell) { if LocalStore.getToken() == nil { performSegueWithIdentifier("LoginSegue", sender: self) } else { performSegueWithIdentifier("ReplySegue", sender: cell) } } // MARK: StoryTableViewCellDelegate func storyTableViewCellDidTouchUpvote(cell: StoryTableViewCell, sender: AnyObject) { if let token = LocalStore.getToken() { let indexPath = tableView.indexPathForCell(cell)! let storyId = story["id"].int! DNService.upvoteStoryWithId(storyId, token: token, response: { (successful) -> () in }) LocalStore.saveUpvotedStory(storyId) cell.configureWithStory(story) } else { performSegueWithIdentifier("LoginSegue", sender: self) } } func storyTableViewCellDidTouchComment(cell: StoryTableViewCell, sender: AnyObject) { if LocalStore.getToken() == nil { performSegueWithIdentifier("LoginSegue", sender: self) } else { performSegueWithIdentifier("ReplySegue", sender: cell) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ReplySegue" { let toView = segue.destinationViewController as! ReplyViewController if let cell = sender as? CommentTableViewCell { let indexPath = tableView.indexPathForCell(cell)! let comment = comments[indexPath.row - 1] toView.comment = comment } if let cell = sender as? StoryTableViewCell { toView.story = story } toView.delegate = self toView.transitioningDelegate = transitionManager } } // MARK: ReplyViewControllerDelegate func replyViewControllerDidSend(controller: ReplyViewController) { reloadStory() } // Helper func flattenComments(comments: [JSON]) -> [JSON] { let flattenedComments = comments.map(commentsForComment).reduce([], combine: +) return flattenedComments } func commentsForComment(comment: JSON) -> [JSON] { let comments = comment["comments"].array ?? [] return comments.reduce([comment]) { acc, x in acc + self.commentsForComment(x) } } }
34.065476
145
0.623799
d9646a435f98f397b84063b76e76fd426527bd0e
2,080
// // Created by Eugene Kazaev on 20/01/2018. // Copyright (c) 2018 CocoaPods. All rights reserved. // import Foundation import RouteComposer import UIKit class ProductConfiguration { static func productDestination(productId: String, _ analyticParameters: ExampleAnalyticsParameters? = nil) -> ExampleDestination { let productScreen = StepAssembly( finder: ClassWithContextFinder<ProductViewController, String>(), factory: StoryboardFactory(storyboardName: "TabBar", viewControllerID: "ProductViewController", action: NavigationControllerFactory.PushToNavigation())) .add(ProductContextTask()) .add(ExampleAnalyticsInterceptor()) .add(ExampleAnalyticsPostAction()) .from(SwitchAssembly() .addCase { (destination: ExampleDestination) in // If routing requested by Universal Link - Presenting modally // Try in Mobile Safari dll://productView?product=123 guard destination.analyticParameters?.webpageURL != nil else { return nil } return ChainAssembly() .from(NavigationControllerStep(action: GeneralAction.PresentModally())) .from(CurrentViewControllerStep()) .assemble() } // If UINavigationController exists on current level - just push .addCase(when: ClassFinder<UINavigationController, Any>(options: .currentAllStack)) .assemble(default: { // Otherwise - presenting in Circle Tab return ExampleConfiguration.step(for: ExampleTarget.circle)! }) ).assemble() return ExampleDestination(finalStep: productScreen, context: productId, analyticParameters) } }
45.217391
168
0.564423
645dc5fe39d069fc57388d397cb1c093408ded4e
464
// // ScoreFive // Varun Santhanam // import FBSnapshotTestCase @testable import ScoreFive final class GameViewControllerSnapshotTests: SnapshotTestCase { override func setUp() { super.setUp() recordMode = false } func test_gameViewController() { let viewController = GameViewController() viewController.loadView() viewController.viewDidLoad() FBSnapshotVerifyViewController(viewController) } }
19.333333
63
0.693966
672ef070fd99db2bd86b73104d3778ef6fdc4747
1,589
// // Car.swift // sixtTest // // Created by Jesus Adolfo on 4/7/17. // Copyright © 2017 adolfo. All rights reserved. // import SwiftyJSON struct Car { let id: String let modelIdentifier: String let modelName: String let name: String let make: String let group: String let color: String let series: String let fuelType: String let fuelLevel: Float let transmission: String let licensePlate: String let latitude: Float let longitude: Float let innerCleanliness: String let imageUrl: String init(json: JSON) { self.id = json["id"].stringValue self.modelIdentifier = json["modelIdentifier"].stringValue self.modelName = json["modelName"].stringValue self.name = json["name"].stringValue self.make = json["make"].stringValue self.group = json["group"].stringValue self.color = json["color"].stringValue self.series = json["series"].stringValue self.fuelType = json["fuelType"].stringValue self.fuelLevel = json["fuelLevel"].floatValue self.transmission = json["transmission"].stringValue self.licensePlate = json["licensePlate"].stringValue self.latitude = json["latitude"].floatValue self.longitude = json["longitude"].floatValue self.innerCleanliness = json["innerCleanliness"].stringValue self.imageUrl = json["carImageUrl"].stringValue } }
31.78
68
0.601636
71c9365c6187b81c09fe08bc78cfad8f1bfb935f
1,466
// // HudManager.swift // CardWalletSDKTestApp // // Created by Kagan Ozupek on 13.12.2018. // Copyright © 2018 Kagan Ozupek. All rights reserved. // import Foundation import MBProgressHUD @objc class HudManager : NSObject { @objc static let shared = HudManager() var hud : MBProgressHUD! @objc public func showHud(controller : UIViewController,message : String? = nil){ self.dismissHud() if let m = message{ hud = MBProgressHUD.showAdded(to: returnCurrentView(controller: controller).view, animated: true) hud.mode = .text hud.label.numberOfLines = 0 hud.label.text = m hud.hide(animated: true, afterDelay: 5.0) }else{ hud = MBProgressHUD.showAdded(to: controller.view, animated: true) } } @objc public func dismissHud(){ if(hud != nil){ hud.hide(animated: true) hud = nil } } func returnCurrentView(controller : UIViewController) -> UIViewController { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } return controller } }
24.433333
109
0.574352
de6d5ea8c639831330b5874272fe4c8de1948516
578
// // HairProduct.swift // PerfectlyCreated // // Created by Ashli Rankin on 1/14/21. // Copyright © 2021 Ashli Rankin. All rights reserved. // import Foundation /// Represents a hair product. struct HairProduct: Codable, Hashable, Equatable { /// The item attributes. let itemAttributes: ItemAttributes /// The stores where the product can be found. let stores: [Store] let upc: String enum CodingKeys: String, CodingKey { case itemAttributes = "item_attributes" case stores = "Stores" case upc } }
20.642857
55
0.643599
fc8365da59f6a463bfef298d423fd58e035a230a
1,256
// // ViewControllerTransitionHandler.swift // Cards // // Created by Robert Nash on 14/12/2017. // Copyright © 2017 Robert Nash. All rights reserved. // import UIKit class CardViewControllerTransitionHandler: NSObject { fileprivate let animator = CardViewControllerTransitionAnimator() weak var interactionDelegate: CardViewControllerPresentationControllerDelegate? } extension CardViewControllerTransitionHandler: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let controller = CardViewControllerPresentationController(presentedViewController: presented, presenting: presenting) controller.interactionDelegate = interactionDelegate return controller } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.isPresentation = true return animator } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.isPresentation = false return animator } }
33.052632
168
0.803344
23777697ac77e2ab2ec9a1ff8edec5be0b3d2240
226
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct c import Foundation } extension NSSet { class B<f
22.6
87
0.774336
691c84242ca880cee5b27079c893a7e3eb1b7f4a
2,395
// // AppDelegate.swift // WeatherTest // // Created by Daniel Kouba on 14/02/15. // Copyright (c) 2015 Daniel Kouba. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var context = DI.context func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { context.locations.addCurrentLocationToList() context.locations.startUpdatingWeather() 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. context.save() } }
42.767857
285
0.732777
dbe29c485de622e565024d909a064f262b89802f
14,027
// swiftlint:disable file_length // swiftlint:disable force_cast // swiftlint:disable large_tuple import Foundation public class FunctionMockUnit<ReturnType> { // takes no args var mockedResult: ReturnType? var mockedResultSequence: [ReturnType]? var mockedResultFunc: (() -> ReturnType)? var thrownError: Error? public init() { } public private(set) var invocations: Int = 0 public func doReturn(result: ReturnType) { self.mockedResult = result self.mockedResultFunc = nil self.mockedResultSequence = nil self.thrownError = nil } public func doReturn(resultSequence: [ReturnType]) { self.mockedResult = nil self.mockedResultFunc = nil self.mockedResultSequence = resultSequence.reversed() self.thrownError = nil } public func doReturn(resultFunc: @escaping(() -> ReturnType)) { self.mockedResult = nil self.mockedResultFunc = resultFunc self.mockedResultSequence = nil self.thrownError = nil } public func doThrow(error: Error) { self.mockedResult = nil self.mockedResultFunc = nil self.mockedResultSequence = nil self.thrownError = error } public func verify(numberOfInvocations: Int) -> Bool { return self.invocations == numberOfInvocations } public func throwingRun() throws -> ReturnType { if let thrownError = self.thrownError { self.invocations += 1 throw thrownError } return run() } public func run() -> ReturnType { self.invocations += 1 // Don't search for a result matcher if return type is void if ReturnType.self == Void.self { return () as! ReturnType } if let mockedResult = self.mockedResult { return mockedResult } else if self.mockedResultSequence != nil && !self.mockedResultSequence!.isEmpty { return mockedResultSequence!.popLast()! } else if let mockFunc = self.mockedResultFunc { return mockFunc() } fatalError("nothing to return from mocked function") } public func clearStubs() { self.mockedResult = nil self.mockedResultFunc = nil self.mockedResultSequence = nil self.thrownError = nil } public func clearInvocations() { self.invocations = 0 } } public class FunctionMockUnitOneArg<ReturnType, Arg1T> { // takes one arg var mockedResultMatchers: [(Matcher<Arg1T>, ReturnType)] = [] var mockedResultFuncMatchers: [(Matcher<Arg1T>, () -> ReturnType)] = [] var throwingMatchers: [(Matcher<Arg1T>, Error)] = [] public init() { } public private(set) var capturedInvocations: [Arg1T] = [] public func doReturn(result: ReturnType, forArg matcher: Matcher<Arg1T>) { self.mockedResultMatchers.append((matcher, result)) } public func doReturn(resultFunc: @escaping () -> ReturnType, forArg matcher: Matcher<Arg1T>) { self.mockedResultFuncMatchers.append((matcher, resultFunc)) } public func doThrow(error: Error, forArg matcher: Matcher<Arg1T>) { self.throwingMatchers.append((matcher, error)) } public func verify(numberOfInvocations: Int, forArg matcher: Matcher<Arg1T>) -> Bool { switch matcher { case .any: return capturedInvocations.count == numberOfInvocations case .with(let condition): return capturedInvocations.count(where: { (arg) -> Bool in return condition(arg) }) == numberOfInvocations } } public func throwingRun(arg1: Arg1T) throws -> ReturnType { for throwingMatcher in self.throwingMatchers { let matcher = throwingMatcher.0 let thrownError = throwingMatcher.1 switch matcher { case .any: capturedInvocations.append(arg1) throw thrownError case .with(let condition): if condition(arg1) { capturedInvocations.append(arg1) throw thrownError } } } return self.run(arg1: arg1) } public func run(arg1: Arg1T) -> ReturnType { capturedInvocations.append(arg1) // Don't search for a result matcher if return type is void if ReturnType.self == Void.self { return () as! ReturnType } for resultMatcher in self.mockedResultMatchers { let matcher = resultMatcher.0 let mockResult = resultMatcher.1 switch matcher { case .any: return mockResult case .with(let condition): if condition(arg1) { return mockResult } } } for resultFuncMatcher in self.mockedResultFuncMatchers { let matcher = resultFuncMatcher.0 let mockResultFunc = resultFuncMatcher.1 switch matcher { case .any: return mockResultFunc() case .with(let condition): if condition(arg1) { return mockResultFunc() } } } fatalError("could not find a match to return a value from mocked function") } public func clearStubs() { self.mockedResultMatchers = [] self.throwingMatchers = [] } public func clearInvocations() { self.capturedInvocations = [] } } public class FunctionMockUnitTwoArgs<ReturnType, Arg1T, Arg2T> { // takes two args var mockedResultMatchers: [(Matcher<Arg1T>, Matcher<Arg2T>, ReturnType)] = [] var throwingMatchers: [(Matcher<Arg1T>, Matcher<Arg2T>, Error)] = [] public init() { } public private(set) var capturedInvocations: [(Arg1T, Arg2T)] = [] public func doReturn(result: ReturnType, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T>) { self.mockedResultMatchers.append((matcher1, matcher2, result)) } public func doThrow(error: Error, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T>) { self.throwingMatchers.append((matcher1, matcher2, error)) } public func verify( numberOfInvocations: Int, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T> ) -> Bool { var count: Int = 0 capturedInvocations.forEach { (argsTuple) in let (arg1, arg2) = argsTuple var matched1, matched2: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } if matched1 && matched2 { count += 1 } } return count == numberOfInvocations } public func throwingRun(arg1: Arg1T, arg2: Arg2T) throws -> ReturnType { for throwingMatcher in self.throwingMatchers { let matcher1 = throwingMatcher.0 let matcher2 = throwingMatcher.1 let thrownError = throwingMatcher.2 var matched1, matched2: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } if matched1 && matched2 { capturedInvocations.append((arg1, arg2)) throw thrownError } } return run(arg1: arg1, arg2: arg2) } public func run(arg1: Arg1T, arg2: Arg2T) -> ReturnType { capturedInvocations.append((arg1, arg2)) // Don't search for a result matcher if return type is void if ReturnType.self == Void.self { return () as! ReturnType } for resultMatcher in self.mockedResultMatchers { let matcher1 = resultMatcher.0 let matcher2 = resultMatcher.1 let mockResult = resultMatcher.2 var matched1, matched2: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } if matched1 && matched2 { return mockResult } } fatalError("could not find a match to return a value from mocked function") } public func clearStubs() { self.mockedResultMatchers = [] self.throwingMatchers = [] } public func clearInvocations() { self.capturedInvocations = [] } } public class FunctionMockUnitThreeArgs<ReturnType, Arg1T, Arg2T, Arg3T> { // takes three args var mockedResultMatchers: [(Matcher<Arg1T>, Matcher<Arg2T>, Matcher<Arg3T>, ReturnType)] = [] var throwingMatchers: [(Matcher<Arg1T>, Matcher<Arg2T>, Matcher<Arg3T>, Error)] = [] public init() { } public private(set) var capturedInvocations: [(Arg1T, Arg2T, Arg3T)] = [] public func doReturn(result: ReturnType, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T>, forArg3 matcher3: Matcher<Arg3T>) { self.mockedResultMatchers.append((matcher1, matcher2, matcher3, result)) } public func doThrow(error: Error, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T>, forArg3 matcher3: Matcher<Arg3T>) { self.throwingMatchers.append((matcher1, matcher2, matcher3, error)) } public func verify(numberOfInvocations: Int, forArg1 matcher1: Matcher<Arg1T>, forArg2 matcher2: Matcher<Arg2T>, forArg3 matcher3: Matcher<Arg3T>) -> Bool { var count: Int = 0 capturedInvocations.forEach { (argsTuple) in let (arg1, arg2, arg3) = argsTuple var matched1, matched2, matched3: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } switch matcher3 { case .any: matched3 = true case .with(let condition): matched3 = condition(arg3) } if matched1 && matched2 && matched3 { count += 1 } } return count == numberOfInvocations } public func throwingRun(arg1: Arg1T, arg2: Arg2T, arg3: Arg3T) throws -> ReturnType { for throwingMatcher in self.throwingMatchers { let matcher1 = throwingMatcher.0 let matcher2 = throwingMatcher.1 let matcher3 = throwingMatcher.2 let thrownError = throwingMatcher.3 var matched1, matched2, matched3: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } switch matcher3 { case .any: matched3 = true case .with(let condition): matched3 = condition(arg3) } if matched1 && matched2 && matched3 { capturedInvocations.append((arg1, arg2, arg3)) throw thrownError } } return run(arg1: arg1, arg2: arg2, arg3: arg3) } public func run(arg1: Arg1T, arg2: Arg2T, arg3: Arg3T) -> ReturnType { capturedInvocations.append((arg1, arg2, arg3)) // Don't search for a result matcher if return type is void if ReturnType.self == Void.self { return () as! ReturnType } for resultMatcher in self.mockedResultMatchers { let matcher1 = resultMatcher.0 let matcher2 = resultMatcher.1 let matcher3 = resultMatcher.2 let mockResult = resultMatcher.3 var matched1, matched2, matched3: Bool switch matcher1 { case .any: matched1 = true case .with(let condition): matched1 = condition(arg1) } switch matcher2 { case .any: matched2 = true case .with(let condition): matched2 = condition(arg2) } switch matcher3 { case .any: matched3 = true case .with(let condition): matched3 = condition(arg3) } if matched1 && matched2 && matched3 { return mockResult } } fatalError("could not find a match to return a value from mocked function") } public func clearStubs() { self.mockedResultMatchers = [] self.throwingMatchers = [] } public func clearInvocations() { self.capturedInvocations = [] } }
30.828571
114
0.556712
bb04823c073ffae43c6efb808c97b5e6a667e974
715
// // Created by TobyoTenma on 15/12/2017. // import Foundation open class QueueLogger: BaseLogger { internal let logQueue = OperationQueue() override init(identifier: String) { logQueue.name = "tbolog.logqueue" logQueue.maxConcurrentOperationCount = 1 super.init(identifier: identifier) } override func output(_ info: LogInfo) { if info.isAsynchronously { logQueue.addOperation { [weak self] in guard let `self` = self else { return } self.write(info) } } else { self.write(info) } } internal func write(_ info: LogInfo) { precondition(false, "This Method Must Be Override!") } }
21.666667
60
0.608392
64cd9defe2276a75d753577d66fcaf58eb5628a3
5,042
import var CommonCrypto.CC_MD5_DIGEST_LENGTH import func CommonCrypto.CC_MD5 import typealias CommonCrypto.CC_LONG extension String { public func charAt(_ pos:Int) -> Character { if(pos < 0 || pos >= count) { return Character("") } return Array(self)[pos] } public func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } public func indexOf(_ char: Character) -> Int? { return firstIndex(of: char)?.utf16Offset(in: self) } public func substring(from: Int) -> String { let fromIndex = index(from: from) return String(self[fromIndex...]) } public func substring(_ from: Int,_ until: Int) -> String? { let fromIndex = index(from: from) let untilIndex = index(from: until) return String(self[fromIndex..<untilIndex]) } public func indexOf(_ char: Character, offsetBy:Int) -> Int? { return substring(from: offsetBy).firstIndex(of: char)?.utf16Offset(in: self) } public var isDigits: Bool { let notDigits = NSCharacterSet.decimalDigits.inverted return rangeOfCharacter(from: notDigits, options: String.CompareOptions.literal, range: nil) == nil } public var isLetters: Bool { let notLetters = NSCharacterSet.letters.inverted return rangeOfCharacter(from: notLetters, options: String.CompareOptions.literal, range: nil) == nil } public var isAlphanumeric: Bool { let notAlphanumeric = NSCharacterSet.decimalDigits.union(NSCharacterSet.letters).inverted return rangeOfCharacter(from: notAlphanumeric, options: String.CompareOptions.literal, range: nil) == nil } public func matches(_ regex: String) -> Bool { let range = NSRange(location: 0, length: self.utf16.count) let regex = try! NSRegularExpression(pattern: regex, options: .caseInsensitive) return regex.firstMatch(in: self, options: [], range: range) != nil } public func matchList(_ regex: String) -> [[String]] { guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } let nsString = self as NSString let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) return results.map { result in (0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound ? nsString.substring(with: result.range(at: $0)) : "" } } } public mutating func replaceRegex(_ pattern: String, replaceWith: String = "") -> Bool { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive) let range = NSMakeRange(0, self.count) self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith) return true } catch { return false } } public func withoutHtmlTags() -> String { return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) } public func htmlToRichText() -> NSAttributedString? { guard let data = self.data(using: String.Encoding.unicode) else { return nil } guard let converted = try? NSAttributedString( data: data, options: [.documentType:NSAttributedString.DocumentType.html], documentAttributes: nil ) else { return nil } return converted } public func toDate(_ format: String = "yyyy-MM-dd HH:mm:ss", with timeZone: TimeZone = TimeZone(abbreviation: "UTC")!)-> Date?{ let dateFormatter = DateFormatter() dateFormatter.timeZone = timeZone dateFormatter.calendar = Calendar(identifier: .gregorian) dateFormatter.dateFormat = format let date = dateFormatter.date(from: self) return date } public func split(regex pattern: String) -> [String] { guard let re = try? NSRegularExpression(pattern: pattern, options: []) else { return [] } let nsString = self as NSString // needed for range compatibility let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>" let modifiedString = re.stringByReplacingMatches( in: self, options: [], range: NSRange(location: 0, length: nsString.length), withTemplate: stop) return modifiedString.components(separatedBy: stop) } var md5: String { let data = Data(self.utf8) let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash) return hash } return hash.map { String(format: "%02x", $0) }.joined() } }
37.626866
131
0.619992
c18f30b911ac2b4eeb361077dba9099cbfc41c63
4,960
import XCTest @testable import BonBon final class LockTests: AsynchronousTestCase { // MARK: Setup private static let numberOfConcurrentTasks = 1000 private static let numberOfRunsInPerformanceTest = 100_000 private var locks: [Lock]! private var unbalancedLocks: [UnbalancedLock]! private var concurrentLocks: [ConcurrentLock]! private var concurrentUnbalancedLocks: [ConcurrentUnbalancedLock]! override func setUp() { super.setUp() locks = [ MutexLock(), ReadWriteLock(), SemaphoreLock(), QueueLock(), ] if #available(OSX 10.12, *) { locks.append(UnfairLock()) } unbalancedLocks = locks.flatMap({ $0 as? UnbalancedLock }) concurrentLocks = locks.flatMap({ $0 as? ConcurrentLock }) concurrentUnbalancedLocks = locks.flatMap({ $0 as? ConcurrentUnbalancedLock }) } // MARK: Unit tests func test_whenNonConcurrentAccessesAreRequestedAtTheSameTime_thenOnlyOneAtATimeExecutes() { for lock in locks { var number = 0 queue.async { lock.sync { sleep(for: shortWaitLimit) number += 1 } } sleep(for: shortWait) lock.sync { XCTAssertEqual(number, 1, "The second access should wait for the first one to complete.") } } } func test_whenManyNonConcurrentAccessesAreRequestedAtTheSameTime_thenAllExecuteSequentially() { for lock in locks { var number = 0 for _ in 0 ..< LockTests.numberOfConcurrentTasks { queue.async(group: group) { lock.sync { number += 1 } } } group.wait() lock.sync { XCTAssertEqual(number, LockTests.numberOfConcurrentTasks, "All accesses should have completed sequentially.") } } } func test_whenConcurrentAccessesAreRequestedAtTheSameTime_thenAllExecuteTogether() { for lock in concurrentLocks { for _ in 0 ..< LockTests.numberOfConcurrentTasks { queue.async(group: group) { lock.concurrentSync { sleep(for: shortWait) } } } guard group.wait(for: shortWaitLimit) == .success else { return XCTFail("Concurrent accesses should complete within the given time.") } } } // MARK: Performance tests // - note: Performance isn't currently the best, but for the sake of // natural-looking APIs and having a ready-to-use utility, it is kept // as-is. With smarter capturing and inlining ~10x performance can be // reached, if really needed. // - seealso: [Cocoa With Love: Mutexes and closure capture in Swift] // (https://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html) func test_whenUsingAMutexLock_thenPerformanceDoesntRegress() { measureLockPerformance(MutexLock()) } func test_whenUsingAReadWriteLock_thenPerformanceDoesntRegress() { measureLockPerformance(ReadWriteLock()) } func test_whenUsingASemaphoreLock_thenPerformanceDoesntRegress() { measureLockPerformance(SemaphoreLock()) } func test_whenUsingAQueueLock_thenPerformanceDoesntRegress() { measureLockPerformance(QueueLock()) } @available(OSX 10.12, *) func test_whenUsingAnUnfairLock_thenPerformanceDoesntRegress() { measureLockPerformance(UnfairLock()) } func test_whenUsingAReadWriteLock_andAccessingConcurrently_thenPerformanceDoesntRegress() { measureConcurrentLockPerformance(ReadWriteLock()) } func test_whenUsingAQueueLock_andAccessingConcurrently_thenPerformanceDoesntRegress() { measureConcurrentLockPerformance(QueueLock()) } // MARK: Private utilities private func measureLockPerformance(_ lock: Lock) { measure(times: LockTests.numberOfRunsInPerformanceTest) { lock.sync {} } } private func measureConcurrentLockPerformance(_ lock: ConcurrentLock) { measure(times: LockTests.numberOfRunsInPerformanceTest) { lock.concurrentSync {} } } // MARK: Linux support static var allTests: [(String, (LockTests) -> () throws -> Void)] { return [ ("test_whenNonConcurrentAccessesAreRequestedAtTheSameTime_thenOnlyOneAtATimeExecutes", test_whenNonConcurrentAccessesAreRequestedAtTheSameTime_thenOnlyOneAtATimeExecutes), ("test_whenConcurrentAccessesAreRequestedAtTheSameTime_thenAllExecuteTogether", test_whenConcurrentAccessesAreRequestedAtTheSameTime_thenAllExecuteTogether), ("test_whenUsingAMutexLock_thenPerformanceDoesntRegress", test_whenUsingAMutexLock_thenPerformanceDoesntRegress), ("test_whenUsingAReadWriteLock_thenPerformanceDoesntRegress", test_whenUsingAReadWriteLock_thenPerformanceDoesntRegress), ("test_whenUsingASemaphoreLock_thenPerformanceDoesntRegress", test_whenUsingASemaphoreLock_thenPerformanceDoesntRegress), ("test_whenUsingAQueueLock_thenPerformanceDoesntRegress", test_whenUsingAQueueLock_thenPerformanceDoesntRegress), ("test_whenUsingAReadWriteLock_andAccessingConcurrently_thenPerformanceDoesntRegress", test_whenUsingAReadWriteLock_andAccessingConcurrently_thenPerformanceDoesntRegress), ("test_whenUsingAQueueLock_andAccessingConcurrently_thenPerformanceDoesntRegress", test_whenUsingAQueueLock_andAccessingConcurrently_thenPerformanceDoesntRegress), ] } }
33.972603
174
0.783669
3894faec95082184b50038d758ff4531521be69c
445
// // TestCells.swift // DataSourceTests // // Created by Aleksei Bobrov on 01/02/2019. // Copyright © 2019 Fueled. All rights reserved. // import DataSource struct TestCellModel { } final class TestTableViewCell: TableViewCell, ReusableItem { } final class TestCollectionViewCell: CollectionViewCell, ReusableItem { } struct TestHeaderFooterViewModel { } final class TestHeaderFooterView: TableViewHeaderFooterView, ReusableItem { }
22.25
77
0.773034
1121b5f121c7dbf85bfa3da7e0f49144a8a03a1e
2,356
// // SceneDelegate.swift // TableViewExperiments // // Created by リヴォーフ ユーリ on 2019/12/14. // Copyright © 2019 リヴォーフ ユーリ. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.62963
147
0.714346
bf9a50a8aace304a58b2e49a28bc39acf7edc761
912
// // SampleCodeTests.swift // SampleCode // // Created by Kazuhiro Hayashi on 2021/02/14. // // import XCTest @testable import SampleCode class SampleCodeTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.057143
111
0.663377
64b4d143d806ba6b124d49353fbfb86c7972387c
498
// // Featured.swift // Pizzaiolo // // Created by Fadion Dashi on 01/03/17. // Copyright © 2017 Fadion Dashi. All rights reserved. // import RealmSwift class Featured: Object, Model { dynamic var id = 0 dynamic var title = "" dynamic var subtitle = "" let priceWas = RealmOptional<Int>() let price = RealmOptional<Int>() dynamic var position = 0 dynamic var photo = "" override static func primaryKey() -> String? { return "id" } }
19.153846
55
0.610442
7529d9416141cfaa33b18204b82b5b5ee657f364
552
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts infix operator <*> : AdditionPrecedence func <*><A, B>(lhs: ((A) -> B)?, rhs: A?) -> B? { if let lhs1 = lhs, let rhs1 = rhs { return lhs1(rhs1) } return nil } func cons<T, U>(lhs: T) -> (U) -> (T, U) { return { rhs in (lhs, rhs) } } var str: String? = "x" if let f = cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> (cons <*> str <*> str)))))) { print("\(f)") }
27.6
147
0.528986
87f222541d89866ed492827ea7ad49c6b9ce4082
2,774
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="ParagraphListFormatResponse.swift"> * Copyright (c) 2020 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // The REST response with a list format for a paragraph. public class ParagraphListFormatResponse : WordsResponse { // Field of listFormat. The REST response with a list format for a paragraph. private var listFormat : ListFormat?; private enum CodingKeys: String, CodingKey { case listFormat = "ListFormat"; case invalidCodingKey; } public override init() { super.init(); } public required init(from decoder: Decoder) throws { try super.init(from: decoder); let container = try decoder.container(keyedBy: CodingKeys.self); self.listFormat = try container.decodeIfPresent(ListFormat.self, forKey: .listFormat); } public override func encode(to encoder: Encoder) throws { try super.encode(to: encoder); var container = encoder.container(keyedBy: CodingKeys.self); if (self.listFormat != nil) { try container.encode(self.listFormat, forKey: .listFormat); } } // Sets listFormat. Gets or sets the list format for a paragraph. public func setListFormat(listFormat : ListFormat?) { self.listFormat = listFormat; } // Gets listFormat. Gets or sets the list format for a paragraph. public func getListFormat() -> ListFormat? { return self.listFormat; } }
40.794118
94
0.663302
abf22c227e3a44f7a5a3187c1e1eef7a8a67b92a
648
// // TransactionError.swift // // // Created by Ostap Danylovych on 27.08.2021. // import Foundation public enum MalformedTransactionError: Error { case wrongValue(Any, name: String, message: String) case outOfRange(Any, expected: ClosedRange<Int>, name: String, description: String = "") } public enum TransactionBuilderError: Error { case insufficientFunds case gooseEggCheckError } public enum ExtendedAvalancheTransactionError: Error { case noSuchUtxo(TransactionID, utxoIndex: UInt32, in: [UTXO]) case noSuchSignature(Address, in: [Address: Signature]) case noSuchPath(Address, in: [Address: Bip32Path]) }
25.92
92
0.736111
4b8d6829043287635cf3e3fa56383d41703f4b54
3,841
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Logging import NIO import NIOHTTP1 import SwiftProtobuf /// Handles server-streaming calls. Calls the observer block with the request message. /// /// - The observer block is implemented by the framework user and calls `context.sendResponse` as needed. /// - To close the call and send the status, complete the status future returned by the observer block. public final class ServerStreamingCallHandler< RequestPayload, ResponsePayload >: _BaseCallHandler<RequestPayload, ResponsePayload> { public typealias EventObserver = (RequestPayload) -> EventLoopFuture<GRPCStatus> private var eventObserver: EventObserver? private var callContext: StreamingResponseCallContext<ResponsePayload>? private let eventObserverFactory: (StreamingResponseCallContext<ResponsePayload>) -> EventObserver internal init<Serializer: MessageSerializer, Deserializer: MessageDeserializer>( serializer: Serializer, deserializer: Deserializer, callHandlerContext: CallHandlerContext, eventObserverFactory: @escaping (StreamingResponseCallContext<ResponsePayload>) -> EventObserver ) where Serializer.Input == ResponsePayload, Deserializer.Output == RequestPayload { self.eventObserverFactory = eventObserverFactory super.init( callHandlerContext: callHandlerContext, codec: GRPCServerCodecHandler(serializer: serializer, deserializer: deserializer) ) } override internal func processHead(_ head: HTTPRequestHead, context: ChannelHandlerContext) { let callContext = StreamingResponseCallContextImpl<ResponsePayload>( channel: context.channel, request: head, errorDelegate: self.callHandlerContext.errorDelegate, logger: self.callHandlerContext.logger ) self.callContext = callContext self.eventObserver = self.eventObserverFactory(callContext) callContext.statusPromise.futureResult.whenComplete { _ in // When done, reset references to avoid retain cycles. self.eventObserver = nil self.callContext = nil } context.writeAndFlush(self.wrapOutboundOut(.headers([:])), promise: nil) } override internal func processMessage(_ message: RequestPayload) throws { guard let eventObserver = self.eventObserver, let callContext = self.callContext else { self.logger.error( "processMessage(_:) called before the call started or after the call completed", source: "GRPC" ) throw GRPCError.StreamCardinalityViolation.request.captureContext() } let resultFuture = eventObserver(message) resultFuture // Fulfil the status promise with whatever status the framework user has provided. .cascade(to: callContext.statusPromise) self.eventObserver = nil } override internal func endOfStreamReceived() throws { if self.eventObserver != nil { throw GRPCError.StreamCardinalityViolation.request.captureContext() } } override internal func sendErrorStatusAndMetadata(_ statusAndMetadata: GRPCStatusAndMetadata) { if let metadata = statusAndMetadata.metadata { self.callContext?.trailingMetadata.add(contentsOf: metadata) } self.callContext?.statusPromise.fail(statusAndMetadata.status) } }
39.193878
105
0.758917
dbf7b6830b858bff5ad8dbdd2843da5bc21efd65
282
import UIKit @available(iOS 4.3 ,watchOS 8.0 ,tvOS 9.0, *) public extension UIFont { public enum kailasa: String { case regular = "Kailasa" case bold = "Kailasa-Bold" public func font(size: CGFloat) -> UIFont { return UIFont(name: self.rawValue, size: size)! } } }
17.625
50
0.666667
eb7f5bfb0342eb6d2be3c7971afb8c39594b0042
1,222
// // MainViewController.swift // Created on 2021/3/12 // Description <#文件描述#> import Cocoa class MainViewController: NSViewController { var windowViewController: NSWindowController? private var subWindowController01: NSWindowController? private var subWindowController02: NSWindowController? override func viewDidLoad() { super.viewDidLoad() } @IBAction func btn01Clicked(_ sender: Any) { let sub01VC = SubViewController01(nibName: "SubViewController01", bundle: nil) let sub01Window = NSWindow(contentViewController: sub01VC) sub01Window.styleMask = [.closable, .resizable, .titled] subWindowController01 = NSWindowController(window: sub01Window) subWindowController01?.showWindow(self) } @IBAction func btn02Clicked(_ sender: Any) { let sub02VC = SubViewController02(nibName: "SubViewController02", bundle: nil) let sub02Window = NSWindow(contentViewController: sub02VC) sub02Window.styleMask = [.closable, .resizable, .titled] subWindowController02 = NSWindowController(window: sub02Window) subWindowController02?.showWindow(self) windowViewController?.close() } }
34.914286
86
0.712766
28791a5fe3d21f0dc6bbd3fcf87e43f11e368bc7
747
// // PivotBuilderTestsBase.swift // UnitTests // // Created by Luke Stringer on 22/01/2020. // Copyright © 2020 3Squared Ltd. All rights reserved. // import XCTest @testable import PeakPivot class PivotBuilderTestsBase: XCTestCase { let builder = PivotBuilder() var pivot: Pivot! var pivotRows: [PivotRow] { get { return pivot.rows } } override func setUp() { super.setUp() builder.table = TestData.people builder.percentagesEnabled = false } func runBuilder() { guard let pivot = try? builder.build() else { XCTFail("Pivot failed to build") return } self.pivot = pivot } }
19.153846
55
0.568942
d54fa01ed8423203a07a856c36aacd40ef583c4a
2,363
// // SecondViewController.swift // ValidatorSample // import UIKit import Validator class SecondViewController: UIViewController { @IBOutlet weak var userName: UITextField! @IBOutlet weak var phoneNumber: UITextField! @IBOutlet weak var userNameState: UILabel! @IBOutlet weak var phoneNumberState: UILabel! let userIdRule = ValidationRuleUserId(error: ValidationError(message: "💩")) let phoneNumberRule = ValidationRulePattern(pattern: "\\d{2,5}-\\d{1,4}-\\d{4}", error: ValidationError(message: "💩")) override func viewDidLoad() { super.viewDidLoad() enableUserIdValidation() enablePhoneNumberValidation() } private func enableUserIdValidation() { userName.validationRules = ValidationRuleSet() userName.validationRules?.add(rule: userIdRule) userName.validateOnInputChange(enabled: true) userName.validationHandler = { result in self.updateUserIdValidationState(result: result) } } private func enablePhoneNumberValidation() { phoneNumber.validationRules = ValidationRuleSet() phoneNumber.validationRules?.add(rule: phoneNumberRule) phoneNumber.validateOnInputChange(enabled: true) phoneNumber.validationHandler = { result in self.updatePhoneNumberValidationState(result: result) } } func updateUserIdValidationState(result: ValidationResult) { switch result { case .valid: userNameState.text = "😀" case .invalid(let failures): userNameState.text = (failures.first as? ValidationError)?.message } } func updatePhoneNumberValidationState(result: ValidationResult) { switch result { case .valid: phoneNumberState.text = "😀" case .invalid(let failures): phoneNumberState.text = (failures.first as? ValidationError)?.message } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.507937
122
0.687262
bb9edad0e99d80e83a82c6615ff919f45b2697bc
928
// // HeartRateMonitorCell.swift // RxHeartRateMonitors // // Created by Leandro Perez on 12/12/17. // Copyright © 2017 Leandro Perez. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxHeartRateMonitors import RxSwiftExt class HeartRateMonitorCell: UITableViewCell { @IBOutlet var nameLabel : UILabel! @IBOutlet var statusLabel : UILabel! private var monitor : HeartRateMonitor! override func awakeFromNib() { super.awakeFromNib() assert(self.nameLabel != nil) assert(self.statusLabel != nil) } func setup(with model:HeartRateMonitor){ self.monitor = model self.nameLabel.text = model.name model.monitoredState .map{$0.description} .asDriver(onErrorJustReturn: "N/A") .drive(self.statusLabel.rx.text) .disposed(by: self.rx.disposeBag) } }
22.634146
56
0.644397
75158f1815fe44f0bab9d2e8773bc7249ce815b7
1,281
// // Extensions.swift // NextPomodoro // // Created by Paul Traylor on 2018/09/09. // Copyright © 2018年 Paul Traylor. All rights reserved. // import Foundation import UIKit import SwiftMQTT extension Data { func toString() -> String? { return String(data: self, encoding: .utf8) } } extension URLRequest { func log() { print("\(httpMethod ?? "") \(self)") print("BODY \n \(httpBody?.toString())") print("HEADERS \n \(allHTTPHeaderFields)") } } extension DateFormatter { static let iso8601Full: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" formatter.calendar = Calendar(identifier: .iso8601) formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() } extension MQTTMessage { func match(_ pattern: String) -> Bool { guard let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else { return false} return regex.numberOfMatches(in: self.topic, options: .anchored, range: .init(self.topic.startIndex..., in: self.topic)) > 0 } var data: Data { return Data(bytes: payload) } }
26.6875
132
0.644809
2009dc3994adc0a4858843429a1e4fd9d41dc3ac
4,812
// // GroupNode.swift // lottie-swift // // Created by Brandon Withrow on 1/18/19. // import CoreGraphics import Foundation import QuartzCore // MARK: - GroupNodeProperties final class GroupNodeProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(transform: ShapeTransform?) { if let transform = transform { anchor = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.anchor.keyframes)) position = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.position.keyframes)) scale = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.scale.keyframes)) rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.rotation.keyframes)) opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.opacity.keyframes)) skew = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skew.keyframes)) skewAxis = NodeProperty(provider: KeyframeInterpolator(keyframes: transform.skewAxis.keyframes)) } else { /// Transform node missing. Default to empty transform. anchor = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0)))) position = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(0), y: CGFloat(0), z: CGFloat(0)))) scale = NodeProperty(provider: SingleValueProvider(Vector3D(x: CGFloat(100), y: CGFloat(100), z: CGFloat(100)))) rotation = NodeProperty(provider: SingleValueProvider(Vector1D(0))) opacity = NodeProperty(provider: SingleValueProvider(Vector1D(100))) skew = NodeProperty(provider: SingleValueProvider(Vector1D(0))) skewAxis = NodeProperty(provider: SingleValueProvider(Vector1D(0))) } keypathProperties = [ "Anchor Point" : anchor, "Position" : position, "Scale" : scale, "Rotation" : rotation, "Opacity" : opacity, "Skew" : skew, "Skew Axis" : skewAxis, ] properties = Array(keypathProperties.values) } // MARK: Internal var keypathName: String = "Transform" var childKeypaths: [KeypathSearchable] = [] let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] let anchor: NodeProperty<Vector3D> let position: NodeProperty<Vector3D> let scale: NodeProperty<Vector3D> let rotation: NodeProperty<Vector1D> let opacity: NodeProperty<Vector1D> let skew: NodeProperty<Vector1D> let skewAxis: NodeProperty<Vector1D> var caTransform: CATransform3D { CATransform3D.makeTransform( anchor: anchor.value.pointValue, position: position.value.pointValue, scale: scale.value.sizeValue, rotation: rotation.value.cgFloatValue, skew: skew.value.cgFloatValue, skewAxis: skewAxis.value.cgFloatValue) } } // MARK: - GroupNode final class GroupNode: AnimatorNode { // MARK: Lifecycle // MARK: Initializer init(name: String, parentNode: AnimatorNode?, tree: NodeTree) { self.parentNode = parentNode keypathName = name rootNode = tree.rootNode properties = GroupNodeProperties(transform: tree.transform) groupOutput = GroupOutputNode(parent: parentNode?.outputNode, rootNode: rootNode?.outputNode) var childKeypaths: [KeypathSearchable] = tree.childrenNodes childKeypaths.append(properties) self.childKeypaths = childKeypaths for childContainer in tree.renderContainers { container.insertRenderLayer(childContainer) } } // MARK: Internal // MARK: Properties let groupOutput: GroupOutputNode let properties: GroupNodeProperties let rootNode: AnimatorNode? var container = ShapeContainerLayer() // MARK: Keypath Searchable let keypathName: String let childKeypaths: [KeypathSearchable] let parentNode: AnimatorNode? var hasLocalUpdates: Bool = false var hasUpstreamUpdates: Bool = false var lastUpdateFrame: CGFloat? = nil var keypathLayer: CALayer? { container } // MARK: Animator Node Protocol var propertyMap: NodePropertyMap & KeypathSearchable { properties } var outputNode: NodeOutput { groupOutput } var isEnabled: Bool = true { didSet { container.isHidden = !isEnabled } } func performAdditionalLocalUpdates(frame: CGFloat, forceLocalUpdate: Bool) -> Bool { rootNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false } func performAdditionalOutputUpdates(_ frame: CGFloat, forceOutputUpdate: Bool) { rootNode?.updateOutputs(frame, forceOutputUpdate: forceOutputUpdate) } func rebuildOutputs(frame: CGFloat) { container.opacity = Float(properties.opacity.value.cgFloatValue) * 0.01 container.transform = properties.caTransform groupOutput.setTransform(container.transform, forFrame: frame) } }
30.846154
118
0.730673
7a9c2100e38a5de19fa8e40775e31d16398ab031
11,001
// DO NOT EDIT. // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: syft_proto/types/torch/v1/tensor.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } public struct SyftProto_Types_Torch_V1_TorchTensor { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. public var id: SyftProto_Types_Syft_V1_Id { get {return _storage._id ?? SyftProto_Types_Syft_V1_Id()} set {_uniqueStorage()._id = newValue} } /// Returns true if `id` has been explicitly set. public var hasID: Bool {return _storage._id != nil} /// Clears the value of `id`. Subsequent reads from it will return its default value. public mutating func clearID() {_uniqueStorage()._id = nil} public var contents: OneOf_Contents? { get {return _storage._contents} set {_uniqueStorage()._contents = newValue} } public var contentsData: SyftProto_Types_Torch_V1_TensorData { get { if case .contentsData(let v)? = _storage._contents {return v} return SyftProto_Types_Torch_V1_TensorData() } set {_uniqueStorage()._contents = .contentsData(newValue)} } public var contentsBin: Data { get { if case .contentsBin(let v)? = _storage._contents {return v} return SwiftProtobuf.Internal.emptyData } set {_uniqueStorage()._contents = .contentsBin(newValue)} } public var chain: SyftProto_Types_Torch_V1_TorchTensor { get {return _storage._chain ?? SyftProto_Types_Torch_V1_TorchTensor()} set {_uniqueStorage()._chain = newValue} } /// Returns true if `chain` has been explicitly set. public var hasChain: Bool {return _storage._chain != nil} /// Clears the value of `chain`. Subsequent reads from it will return its default value. public mutating func clearChain() {_uniqueStorage()._chain = nil} public var gradChain: SyftProto_Types_Torch_V1_TorchTensor { get {return _storage._gradChain ?? SyftProto_Types_Torch_V1_TorchTensor()} set {_uniqueStorage()._gradChain = newValue} } /// Returns true if `gradChain` has been explicitly set. public var hasGradChain: Bool {return _storage._gradChain != nil} /// Clears the value of `gradChain`. Subsequent reads from it will return its default value. public mutating func clearGradChain() {_uniqueStorage()._gradChain = nil} public var tags: [String] { get {return _storage._tags} set {_uniqueStorage()._tags = newValue} } public var description_p: String { get {return _storage._description_p} set {_uniqueStorage()._description_p = newValue} } public var serializer: SyftProto_Types_Torch_V1_TorchTensor.Serializer { get {return _storage._serializer} set {_uniqueStorage()._serializer = newValue} } public var unknownFields = SwiftProtobuf.UnknownStorage() public enum OneOf_Contents: Equatable { case contentsData(SyftProto_Types_Torch_V1_TensorData) case contentsBin(Data) #if !swift(>=4.1) public static func ==(lhs: SyftProto_Types_Torch_V1_TorchTensor.OneOf_Contents, rhs: SyftProto_Types_Torch_V1_TorchTensor.OneOf_Contents) -> Bool { switch (lhs, rhs) { case (.contentsData(let l), .contentsData(let r)): return l == r case (.contentsBin(let l), .contentsBin(let r)): return l == r default: return false } } #endif } public enum Serializer: SwiftProtobuf.Enum { public typealias RawValue = Int case unspecified // = 0 case torch // = 1 case numpy // = 2 case tf // = 3 case all // = 4 case UNRECOGNIZED(Int) public init() { self = .unspecified } public init?(rawValue: Int) { switch rawValue { case 0: self = .unspecified case 1: self = .torch case 2: self = .numpy case 3: self = .tf case 4: self = .all default: self = .UNRECOGNIZED(rawValue) } } public var rawValue: Int { switch self { case .unspecified: return 0 case .torch: return 1 case .numpy: return 2 case .tf: return 3 case .all: return 4 case .UNRECOGNIZED(let i): return i } } } public init() {} fileprivate var _storage = _StorageClass.defaultInstance } #if swift(>=4.2) extension SyftProto_Types_Torch_V1_TorchTensor.Serializer: CaseIterable { // The compiler won't synthesize support with the UNRECOGNIZED case. public static var allCases: [SyftProto_Types_Torch_V1_TorchTensor.Serializer] = [ .unspecified, .torch, .numpy, .tf, .all, ] } #endif // swift(>=4.2) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "syft_proto.types.torch.v1" extension SyftProto_Types_Torch_V1_TorchTensor: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".TorchTensor" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "id"), 2: .standard(proto: "contents_data"), 3: .standard(proto: "contents_bin"), 4: .same(proto: "chain"), 5: .standard(proto: "grad_chain"), 6: .same(proto: "tags"), 7: .same(proto: "description"), 8: .same(proto: "serializer"), ] fileprivate class _StorageClass { var _id: SyftProto_Types_Syft_V1_Id? = nil var _contents: SyftProto_Types_Torch_V1_TorchTensor.OneOf_Contents? var _chain: SyftProto_Types_Torch_V1_TorchTensor? = nil var _gradChain: SyftProto_Types_Torch_V1_TorchTensor? = nil var _tags: [String] = [] var _description_p: String = String() var _serializer: SyftProto_Types_Torch_V1_TorchTensor.Serializer = .unspecified static let defaultInstance = _StorageClass() private init() {} init(copying source: _StorageClass) { _id = source._id _contents = source._contents _chain = source._chain _gradChain = source._gradChain _tags = source._tags _description_p = source._description_p _serializer = source._serializer } } fileprivate mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _StorageClass(copying: _storage) } return _storage } public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { _ = _uniqueStorage() try withExtendedLifetime(_storage) { (_storage: _StorageClass) in while let fieldNumber = try decoder.nextFieldNumber() { switch fieldNumber { case 1: try decoder.decodeSingularMessageField(value: &_storage._id) case 2: var v: SyftProto_Types_Torch_V1_TensorData? if let current = _storage._contents { try decoder.handleConflictingOneOf() if case .contentsData(let m) = current {v = m} } try decoder.decodeSingularMessageField(value: &v) if let v = v {_storage._contents = .contentsData(v)} case 3: if _storage._contents != nil {try decoder.handleConflictingOneOf()} var v: Data? try decoder.decodeSingularBytesField(value: &v) if let v = v {_storage._contents = .contentsBin(v)} case 4: try decoder.decodeSingularMessageField(value: &_storage._chain) case 5: try decoder.decodeSingularMessageField(value: &_storage._gradChain) case 6: try decoder.decodeRepeatedStringField(value: &_storage._tags) case 7: try decoder.decodeSingularStringField(value: &_storage._description_p) case 8: try decoder.decodeSingularEnumField(value: &_storage._serializer) default: break } } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { try withExtendedLifetime(_storage) { (_storage: _StorageClass) in if let v = _storage._id { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } switch _storage._contents { case .contentsData(let v)?: try visitor.visitSingularMessageField(value: v, fieldNumber: 2) case .contentsBin(let v)?: try visitor.visitSingularBytesField(value: v, fieldNumber: 3) case nil: break } if let v = _storage._chain { try visitor.visitSingularMessageField(value: v, fieldNumber: 4) } if let v = _storage._gradChain { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } if !_storage._tags.isEmpty { try visitor.visitRepeatedStringField(value: _storage._tags, fieldNumber: 6) } if !_storage._description_p.isEmpty { try visitor.visitSingularStringField(value: _storage._description_p, fieldNumber: 7) } if _storage._serializer != .unspecified { try visitor.visitSingularEnumField(value: _storage._serializer, fieldNumber: 8) } } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: SyftProto_Types_Torch_V1_TorchTensor, rhs: SyftProto_Types_Torch_V1_TorchTensor) -> Bool { if lhs._storage !== rhs._storage { let storagesAreEqual: Bool = withExtendedLifetime((lhs._storage, rhs._storage)) { (_args: (_StorageClass, _StorageClass)) in let _storage = _args.0 let rhs_storage = _args.1 if _storage._id != rhs_storage._id {return false} if _storage._contents != rhs_storage._contents {return false} if _storage._chain != rhs_storage._chain {return false} if _storage._gradChain != rhs_storage._gradChain {return false} if _storage._tags != rhs_storage._tags {return false} if _storage._description_p != rhs_storage._description_p {return false} if _storage._serializer != rhs_storage._serializer {return false} return true } if !storagesAreEqual {return false} } if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension SyftProto_Types_Torch_V1_TorchTensor.Serializer: SwiftProtobuf._ProtoNameProviding { public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 0: .same(proto: "SERIALIZER_UNSPECIFIED"), 1: .same(proto: "SERIALIZER_TORCH"), 2: .same(proto: "SERIALIZER_NUMPY"), 3: .same(proto: "SERIALIZER_TF"), 4: .same(proto: "SERIALIZER_ALL"), ] }
36.306931
151
0.698846
28d76c348ead461f14c8e02372983aaf1d03ef5b
285
// // CellView.swift // CalendarTutorial // // Created by Jeron Thomas on 2016-10-15. // Copyright © 2016 OS-Tech. All rights reserved. // import JTAppleCalendar class CellView: JTAppleDayCellView { @IBOutlet var dayLabel: UILabel! @IBOutlet var selectedView: UIView! }
17.8125
50
0.708772
9ba11aa275ce4da0c4443d5844f795b450ac8878
2,469
// // FMInitialisationViewController.swift // Liste // // Created by Arash on 26/09/20. // Copyright © 2020 Apprendre. All rights reserved. // import UIKit import MSCircularSlider import Hero class FMInitialisationViewController: UIViewController, MSCircularSliderDelegate { // MARK: Outlets @IBOutlet weak var timerCircularSlider: MSCircularSlider! @IBOutlet weak var timeLabel: UILabel! // MARK: Properties var focusTime: Double = 0.0 var tasks: [Task] = [] var task: Task? var row: Int? // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() self.timerCircularSlider.delegate = self } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "start" { let destination = segue.destination as! FMPreflightViewController destination.hero.modalAnimationType = .slide(direction: .left) destination.focusTime = self.focusTime destination.tasks = self.tasks destination.task = self.task! destination.row = self.row! } } // MARK: Circular Slider Protocols func circularSlider(_ slider: MSCircularSlider, valueChangedTo value: Double, fromUser: Bool) { // Gets the value from the circular slider and updates the label's value of the time set. let time = Int(round(value)) let hours = Int(time / 60) let minutes = time - (hours * 60) var string = "" if hours > 1 { string = "\(hours) \(NSLocalizedString("hours", comment: "Plural form of hour."))" } else if hours == 1 { string = "\(hours) \(NSLocalizedString("hour", comment: "Singular form of hour."))" } else { string = "" } if minutes == 1 { string += " \(minutes) \(NSLocalizedString("minute", comment: "Singular form of minute."))" } else if minutes > 1 { string += " \(minutes) \(NSLocalizedString("minutes", comment: "Plural form of minute."))" } self.timeLabel.text = string self.focusTime = Double(time) } // MARK: Actions @IBAction func startButton(_ sender: ListeButton) { if focusTime > 0 { self.performSegue(withIdentifier: "start", sender: nil) } } @IBAction func cancelButton(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } }
30.481481
103
0.611989
67c4609f7dbdc824a1791948b3ac244286ce5968
12,969
// validation-test/Reflection/reflect_Optional_Any.swift // RUN: %empty-directory(%t) // RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Optional_Any // RUN: %target-codesign %t/reflect_Optional_Any // RUN: %target-run %target-swift-reflection-test %t/reflect_Optional_Any | %FileCheck %s --check-prefix=CHECK-%target-ptrsize %add_num_extra_inhabitants // REQUIRES: reflection_test_support // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest struct TwentyFourByteStruct { let a: Int64 let b: Int64 let c: Int64 } // ================================================================ let optionalAnyNonNil: Any? = TwentyFourByteStruct(a: 7, b: 8, c: 9) reflect(enum: optionalAnyNonNil) // CHECK-64: Reflecting an enum. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition)) // CHECK-64: Type info: // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))) // CHECK-64: (case name=none index=1)) // CHECK-64: Mangled name: $sypSg // CHECK-64: Demangled name: Swift.Optional<Any> // CHECK-64: Enum value: // CHECK-64: (enum_value name=some index=0 // CHECK-64: (protocol_composition) // CHECK-64: ) // CHECK-32: Reflecting an enum. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition)) // CHECK-32: Type info: // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (case name=none index=1)) // CHECK-32: Mangled name: $sypSg // CHECK-32: Demangled name: Swift.Optional<Any> // CHECK-32: Enum value: // CHECK-32: (enum_value name=some index=0 // CHECK-32: (protocol_composition) // CHECK-32: ) // ================================================================ let optionalAnyNil: Any? = nil reflect(enum: optionalAnyNil) // CHECK-64: Reflecting an enum. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition)) // CHECK-64: Type info: // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))) // CHECK-64: (case name=none index=1)) // CHECK-64: Mangled name: $sypSg // CHECK-64: Demangled name: Swift.Optional<Any> // CHECK-64: Enum value: // CHECK-64: (enum_value name=none index=1) // CHECK-32: Reflecting an enum. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition)) // CHECK-32: Type info: // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (case name=none index=1)) // CHECK-32: Mangled name: $sypSg // CHECK-32: Demangled name: Swift.Optional<Any> // CHECK-32: Enum value: // CHECK-32: (enum_value name=none index=1) // ================================================================ let optionalOptionalAnyNil: Any?? = nil reflect(enum: optionalOptionalAnyNil) // CHECK-64: Reflecting an enum. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition))) // CHECK-64: Type info: // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))) // CHECK-64: (case name=none index=1))) // CHECK-64: (case name=none index=1)) // CHECK-64: Mangled name: $sypSgSg // CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-64: Enum value: // CHECK-64: (enum_value name=none index=1) // CHECK-32: Reflecting an enum. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition))) // CHECK-32: Type info: // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (case name=none index=1))) // CHECK-32: (case name=none index=1)) // CHECK-32: Mangled name: $sypSgSg // CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-32: Enum value: // CHECK-32: (enum_value name=none index=1) // ================================================================ let optionalOptionalAnySomeNil: Any?? = .some(nil) reflect(enum: optionalOptionalAnySomeNil) // CHECK-64: Reflecting an enum. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition))) // CHECK-64: Type info: // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))) // CHECK-64: (case name=none index=1))) // CHECK-64: (case name=none index=1)) // CHECK-64: Mangled name: $sypSgSg // CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-64: Enum value: // CHECK-64: (enum_value name=some index=0 // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition)) // CHECK-64: ) // CHECK-32: Reflecting an enum. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition))) // CHECK-32: Type info: // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (case name=none index=1))) // CHECK-32: (case name=none index=1)) // CHECK-32: Mangled name: $sypSgSg // CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-32: Enum value: // CHECK-32: (enum_value name=some index=0 // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition)) // CHECK-32: ) // ================================================================ let optionalOptionalAnyNonNil: Any?? = .some(.some(7)) reflect(enum: optionalOptionalAnyNonNil) // CHECK-64: Reflecting an enum. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition))) // CHECK-64: Type info: // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-2]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (single_payload_enum size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit-1]] bitwise_takable=1 // CHECK-64: (case name=some index=0 offset=0 // CHECK-64: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1 // CHECK-64: (field name=metadata offset=24 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[#num_extra_inhabitants_64bit]] bitwise_takable=1)))) // CHECK-64: (case name=none index=1))) // CHECK-64: (case name=none index=1)) // CHECK-64: Mangled name: $sypSgSg // CHECK-64: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-64: Enum value: // CHECK-64: (enum_value name=some index=0 // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (protocol_composition)) // CHECK-64: ) // CHECK-32: Reflecting an enum. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition))) // CHECK-32: Type info: // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4094 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (single_payload_enum size=16 alignment=4 stride=16 num_extra_inhabitants=4095 bitwise_takable=1 // CHECK-32: (case name=some index=0 offset=0 // CHECK-32: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=4096 bitwise_takable=1 // CHECK-32: (field name=metadata offset=12 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096 bitwise_takable=1)))) // CHECK-32: (case name=none index=1))) // CHECK-32: (case name=none index=1)) // CHECK-32: Mangled name: $sypSgSg // CHECK-32: Demangled name: Swift.Optional<Swift.Optional<Any>> // CHECK-32: Enum value: // CHECK-32: (enum_value name=some index=0 // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (protocol_composition)) // CHECK-32: ) // ================================================================ doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
44.112245
153
0.698743
4a9dd809986a454cfa384408b90074f22695eb33
2,463
import Foundation import TSCBasic import TuistCore import TuistGraph import TuistGraphTesting import TuistSupport import XCTest @testable import ProjectDescription @testable import TuistLoader @testable import TuistLoaderTesting @testable import TuistSupportTesting final class DependenciesModelLoaderTests: TuistUnitTestCase { private var manifestLoader: MockManifestLoader! private var subject: DependenciesModelLoader! override func setUp() { super.setUp() manifestLoader = MockManifestLoader() subject = DependenciesModelLoader(manifestLoader: manifestLoader) } override func tearDown() { subject = nil manifestLoader = nil super.tearDown() } func test_loadDependencies() throws { // Given let temporaryPath = try self.temporaryPath() let localSwiftPackagePath = temporaryPath.appending(component: "LocalPackage") manifestLoader.loadDependenciesStub = { _ in Dependencies( carthage: .carthage( [ .github(path: "Dependency1", requirement: .exact("1.1.1")), .git(path: "Dependency1", requirement: .exact("2.3.4")), ], options: [.useXCFrameworks, .noUseBinaries] ), swiftPackageManager: .swiftPackageManager( [ .local(path: Path(localSwiftPackagePath.pathString)), .remote(url: "RemoteUrl.com", requirement: .exact("1.2.3")), ] ), platforms: [.iOS, .macOS] ) } // When let got = try subject.loadDependencies(at: temporaryPath) // Then let expected: TuistGraph.Dependencies = .init( carthage: .init( [ .github(path: "Dependency1", requirement: .exact("1.1.1")), .git(path: "Dependency1", requirement: .exact("2.3.4")), ], options: [.useXCFrameworks, .noUseBinaries] ), swiftPackageManager: .init( [ .local(path: localSwiftPackagePath), .remote(url: "RemoteUrl.com", requirement: .exact("1.2.3")), ] ), platforms: [.iOS, .macOS] ) XCTAssertEqual(got, expected) } }
30.7875
86
0.550548
092f9a3bbcbd24263400165cec08c48cefc84b25
4,333
// Automatically generated by the Fast Binary Encoding compiler, do not modify! // https://github.com/chronoxor/FastBinaryEncoding // Source: test.fbe // Version: 1.3.0.0 import Foundation import ChronoxorFbe import ChronoxorProto // Fast Binary Encoding optional FlagsSimple field model public class FieldModelOptionalFlagsSimple: FieldModel { public var _buffer: Buffer public var _offset: Int // Field size public let fbeSize: Int = 1 + 4 // Base field model value public let value: FieldModelFlagsSimple public var fbeExtra: Int { if !hasValue() { return 0 } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if (fbeOptionalOffset == 0) || ((_buffer.offset + fbeOptionalOffset + 4) > _buffer.size) { return 0 } _buffer.shift(offset: fbeOptionalOffset) let fbeResult = value.fbeSize + value.fbeExtra _buffer.unshift(offset: fbeOptionalOffset) return fbeResult } public required init() { let buffer = Buffer() let offset = 0 _buffer = buffer _offset = offset value = FieldModelFlagsSimple(buffer: buffer, offset: 0) } public required init(buffer: Buffer, offset: Int) { _buffer = buffer _offset = offset value = FieldModelFlagsSimple(buffer: buffer, offset: 0) } public func hasValue() -> Bool { if (_buffer.offset + fbeOffset + fbeSize) > _buffer.size { return false } let fbeHasValue = Int32(readInt8(offset: fbeOffset)) return fbeHasValue != 0 } public func verify() -> Bool { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { return true } let fbeHasValue = Int(readInt8(offset: fbeOffset)) if fbeHasValue == 0 { return true } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if fbeOptionalOffset == 0 { return false } _buffer.shift(offset: fbeOptionalOffset) let fbeResult = value.verify() _buffer.unshift(offset: fbeOptionalOffset) return fbeResult } // Get the optional value (being phase) func getBegin() -> Int { if !hasValue() { return 0 } let fbeOptionalOffset = Int(readUInt32(offset: fbeOffset + 1)) if fbeOptionalOffset <= 0 { assertionFailure("Model is broken!") return 0 } _buffer.shift(offset: fbeOptionalOffset) return fbeOptionalOffset } // Get the optional value (end phase) func getEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } public func get(defaults: FlagsSimple? = nil) -> FlagsSimple? { let fbeBegin = getBegin() if fbeBegin == 0 { return defaults } let optional = value.get() getEnd(fbeBegin: fbeBegin) return optional } // Set the optional value (begin phase) func setBegin(hasValue: Bool) throws -> Int { if _buffer.offset + fbeOffset + fbeSize > _buffer.size { assertionFailure("Model is broken!") return 0 } let fbeHasValue = hasValue ? 1 : 0 write(offset: fbeOffset, value: Int8(fbeHasValue)) if fbeHasValue == 0 { return 0 } let fbeOptionalSize = value.fbeSize let fbeOptionalOffset = try _buffer.allocate(size: fbeOptionalSize) - _buffer.offset if (fbeOptionalOffset <= 0) || ((_buffer.offset + fbeOptionalOffset + fbeOptionalSize) > _buffer.size) { assertionFailure("Model is broken!") return 0 } write(offset: fbeOffset + 1, value: UInt32(fbeOptionalOffset)) _buffer.shift(offset: fbeOptionalOffset) return fbeOptionalOffset } // Set the optional value (end phase) func setEnd(fbeBegin: Int) { _buffer.unshift(offset: fbeBegin) } // Set the optional value public func set(value optional: FlagsSimple?) throws { let fbeBegin = try setBegin(hasValue: optional != nil) if fbeBegin == 0 { return } try value.set(value: optional!) setEnd(fbeBegin: fbeBegin) } }
27.251572
112
0.600046
3376aab311a17c60302f6c24095a429de7f51f82
13,832
// // HalfRealTimeSceneWorker.swift // YaPlace // // Created by Rustam Shigapov on 11/09/2019. // Copyright (c) 2019 SKZ. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import ARKit import SwiftyJSON class HalfRealTimeSceneWorker { let contentOperationQueue = OperationQueue() fileprivate let image: Image = Image.sharedInstance fileprivate let point: Point = Point.sharedInstance func doImageDataRequest(image: ImageModels.Image?, completion: @escaping (ImageModels.Image?, NetModels.StatusData?) -> Swift.Void) { self.image.doImageDataRequest(image: image, completion: completion) } //MARK: calc points!!!! func calcNodesTriplePoints(maybeNodes: [StickerModels.Node]?, imageSize: CGSize, windowSize: CGSize, maybeDeviceOrientation: UIDeviceOrientation?) -> PointModels.TripleCentralPoints? { return self.point.calcNodesTriplePoints(maybeNodes: maybeNodes, imageSize: imageSize, windowSize: windowSize, maybeDeviceOrientation: maybeDeviceOrientation) } func calcAR2DCentralPoints(maybeNodes: [StickerModels.Node]?, windowSize: CGSize, maybeDeviceOrientation: UIDeviceOrientation?) -> ([Int:CGPoint]?, [Int:Int]?) { return self.point.calcAR2DCentralPoints(maybeNodes: maybeNodes, windowSize: windowSize, maybeDeviceOrientation: maybeDeviceOrientation) } func nodeInBounds(p: CGPoint, windowSize: CGSize) -> Bool { return self.point.nodeInBounds(p: p, windowSize: windowSize) } func nodesInBounds(arrP: [CGPoint], windowSize: CGSize) -> Bool { return self.point.nodesInBounds(arrP: arrP, windowSize: windowSize) } func makeStickerNodes(points: [Int : PointModels.DistantPoint], maybeStickers: [Int : StickerModels.StickerData]?) -> [StickerModels.StickerNode]? { return self.point.makeStickerNodes(points: points, maybeStickers: maybeStickers) } //MARK: ALG2 func updateStickersPosition(views: [StickerSceneView], pinViewSize: CGSize) -> [StickerSceneView] { print(views.count) let sortedViews = views.sorted { (v1, v2) -> Bool in return v2.frame.origin.x > v1.frame.origin.x } var currentPosition: StickerPosition = .up sortedViews.forEach { (view) in currentPosition = currentPosition.position(p: view.stickerCentralPoint, size: pinViewSize) view.stickerPosition = currentPosition } let upViews = sortedViews.filter { $0.stickerPosition == .up } let downViews = sortedViews.filter { $0.stickerPosition == .down } return chessStickers(views: upViews, .up) + chessStickers(views: downViews, .down) } //MARK: ALG1 func chessStickers(views: [StickerSceneView], _ stickerPosition: StickerPosition) -> [StickerSceneView] { print(views.count) let sortedViews = views.sorted { (v1, v2) -> Bool in return v2.frame.origin.x > v1.frame.origin.x } var previousIndex: Int = 0 var nextIndex: Int = 1 var heightDiff: CGFloat = 0.0 var levels: Int = 0 let internalGap: CGFloat = 8.0 while nextIndex < sortedViews.count { if sortedViews[nextIndex].leftSide < sortedViews[previousIndex].rightSide { levels += 1 heightDiff += sortedViews[nextIndex - 1].textBlockSize.height + internalGap sortedViews[nextIndex].offsetY = heightDiff nextIndex += 1 } else { previousIndex = nextIndex + levels levels = 0 heightDiff = stickerPosition.commonOffset //TODO: hard code, remove after Apple release! sortedViews[nextIndex].offsetY = heightDiff nextIndex = previousIndex + 1 } } return sortedViews } //MARK: ALG3 func levelStickers(views: [StickerSceneView], pinViewSize: CGSize) -> [StickerSceneView] { let levelSize = pinViewSize.height / 7.0 var levels: [Bool] = [false, false, false, false, false, false, false] var dU: Int = 0 var dD: Int = 0 var pos: StickerPosition = .up let checkNearestEmptyLevel: (Int) -> (CGFloat, StickerPosition) = { currentPinLevel in var dL: Int = -1 while dL < 0 { if -1 < (dU - 1), levels.count > dU { dU -= 1 if !levels[dU] { dL = dU pos = .up levels[dL] = true } } else if -1 < dD, levels.count > (dD + 1) { dD += 1 if !levels[dD] { dL = dD pos = .down levels[dL] = true } } else { break } } return (CGFloat(dL), pos) } let getLevelOffset: (CGFloat, CGFloat) -> (CGFloat, StickerPosition) = { y, vH2 in let currentPinLevel: Int = Int(floor(y / levelSize)) //to the minor side dU = currentPinLevel dD = currentPinLevel let (lvl, pos) = checkNearestEmptyLevel(currentPinLevel) switch pos { case .up: return (levelSize * (lvl + 0.5) - vH2, pos) case .down: return (pinViewSize.height - (levelSize * (lvl + 0.5) + vH2), pos) } } let placeView: (StickerSceneView) -> Void = { view in let (offset, pos) = getLevelOffset(view.stickerCentralPoint.y, view.textBlockSize.height / 2.0) view.offsetY = offset view.stickerPosition = pos } views.forEach(placeView) print("levels: ", levels) return views } func parse2DTest(completion: Task.LogicGetStickersJSON2D) { if let asset = NSDataAsset(name: "fourStickerScaleTest"), let str = String(decoding: asset.data, as: UTF8.self) as String?, let realJSON: JSON = JSON(parseJSON: str) as JSON? { let statusData = NetModels.StatusData(statusType: .GotDataFromServer) StickerService.sharedInstance.parse2D(json: realJSON, statusData: statusData, completion: completion) } } } extension HalfRealTimeSceneWorker { private func scanRect(startRect: CGRect, rects: [CGRect], validH: CGFloat, isTopDirection: Bool) -> [CGRect] { guard startRect.height > validH else { return [] } var validRects: [CGRect] = [startRect] for rect in rects { var updatedRects: [CGRect] = [] for validRect in validRects { if validRect.intersects(rect) { let result = startRect.intersection(rect) // bottom part if result.maxY < validRect.maxY, validRect.maxY - result.maxY > validH { updatedRects.append(CGRect(x: startRect.minX, y: result.maxY, width: startRect.width, height: validRect.maxY - result.maxY)) } // upper part if result.minY > validRect.minY, result.minY - validRect.minY > validH { updatedRects.append(CGRect(x: startRect.minX, y: validRect.minY, width: startRect.width, height: result.minY - validRect.minY)) } } else { updatedRects.append(validRect) } } validRects = updatedRects } return validRects } // MARK: New algorithm func alignStickers(views: [StickerSceneView], pinViewSize: CGSize) -> [StickerSceneView] { var rects: [CGRect] = [] // MARK: append pins for view in views { let center = view.stickerCentralPoint let size = StickerSceneView.distanceToScale(distance: view.distance) let rect = CGRect(x: center.x - size.width/2, y: center.y - size.height/2, width: size.width, height: size.height) rects.append(rect) } // MARK: top for view in views { let center = view.stickerCentralPoint if center.y < view.stickerCentralPoint.y, view.isHidden { continue } let gap: CGFloat = 5.0 let pinSize = StickerSceneView.distanceToScale(distance: view.distance) let width = view.frame.width let topRect = CGRect(x: center.x - width/2, y: 0, width: width, height: center.y - pinSize.height/2) let bottomRect = CGRect(x: center.x - width/2, y: center.y + pinSize.height/2, width: width, height: pinViewSize.height - (center.y + pinSize.height/2)) let validH = view.textBlockSize.height + gap let topRects = self.scanRect(startRect: topRect, rects: rects, validH: validH, isTopDirection: true).sorted(by: {$0.minY > $1.minY}) let bottomRects = self.scanRect(startRect: bottomRect, rects: rects, validH: validH, isTopDirection: false).sorted(by: {$0.minY < $1.minY}) if let top = topRects.first, let bottom = bottomRects.first { //if (center.y - top.maxY <= bottom.minY - center.y) || view.stickerPosition == .up { if view.stickerPosition == .up { view.stickerPosition = .up view.offsetY = top.maxY - validH } else { view.stickerPosition = .down view.offsetY = pinViewSize.height - (bottom.minY + validH) } } else if let top = topRects.first { view.stickerPosition = .up view.offsetY = top.maxY - validH } else if let bottom = bottomRects.first { view.stickerPosition = .down view.offsetY = pinViewSize.height - (bottom.minY + validH) } else { //print("[test] no place") continue } if view.stickerPosition == .up { rects.append( CGRect(x: center.x - width/2, y: view.offsetY, width: width, height: validH) ) } else { rects.append( CGRect(x: center.x - width/2, y: pinViewSize.height - view.offsetY - view.textBlockSize.height, width: width, height: validH) ) } } return views } } // Load video extension HalfRealTimeSceneWorker { /** https://stackoverflow.com/questions/30363502/maintaining-good-scroll-performance-when-using-avplayer */ func loadSource(url: URL, completion: @escaping (AVPlayer?) -> ()) { //self.status = .Unknown let operation = BlockOperation() operation.addExecutionBlock { () -> Void in // create the asset let asset = AVURLAsset(url: url, options: nil) // load values for track keys let keys = ["tracks", "duration"] asset.loadValuesAsynchronously(forKeys: keys) { // Loop through and check to make sure keys loaded for key in keys { var error: NSError? let keyStatus: AVKeyValueStatus = asset.statusOfValue(forKey: key, error: &error) if keyStatus == .failed { print("Failed to load key: \(key)") completion(nil) return } else if keyStatus != .loaded { print("Warning: Ignoring key status: \(keyStatus), for key: \(key), error: \(error)") completion(nil) return } } if operation.isCancelled == false, let _ = self.createCompositionFromAsset(asset: asset) { //let playerItem = AVPlayerItem(asset: asset) let playerItem = AVPlayerItem(asset: asset) // create the player let player = AVPlayer(playerItem: playerItem) completion(player) } } } // add operation to the queue self.contentOperationQueue.addOperation(operation) } func createCompositionFromAsset(asset: AVAsset, repeatCount: UInt8 = 16) -> AVMutableComposition? { let composition = AVMutableComposition() let timescale = asset.duration.timescale let duration = asset.duration.value let editRange = CMTimeRangeMake(start: CMTimeMake(value: 0, timescale: timescale), duration: CMTimeMake(value: duration, timescale: timescale)) do { try composition.insertTimeRange(editRange, of: asset, at: composition.duration) for _ in 0 ..< repeatCount - 1 { try composition.insertTimeRange(editRange, of: asset, at: composition.duration) } } catch { print("Failed createCompositionFromAsset") return nil } return composition } }
40.209302
188
0.550824
dbe6d967bc573d235a4bcd0dfc891e666e683eb6
290
// // SwiftUIiOS14OnboardingApp.swift // SwiftUIiOS14Onboarding // // Created by Luan Nguyen on 01/01/2021. // import SwiftUI @main struct SwiftUIiOS14OnboardingApp: App { // MARK: - BODY var body: some Scene { WindowGroup { ContentView() } } }
15.263158
41
0.613793
1ea3c0c0a487a55604c592923c443e06b9b82f23
3,402
// // PincodeViewController.swift // DiveLane // // Created by Anton Grigorev on 12/09/2018. // Copyright © 2018 Matter Inc. All rights reserved. // import UIKit import LocalAuthentication class PincodeViewController: BasicViewController { // MARK: - Outlets @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var firstNum: UIImageView! @IBOutlet weak var secondNum: UIImageView! @IBOutlet weak var thirdNum: UIImageView! @IBOutlet weak var fourthNum: UIImageView! @IBOutlet weak var container: UIView! @IBOutlet weak var biometricsButton: PinCodeBiometricsButton! @IBOutlet weak var deleteButton: PinCodeDeleteButton! // MARK: - Vars let animation = AnimationController() var numsIcons: [UIImageView]? // MARK: - Lifesycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) container.backgroundColor = Colors.background var image = UIImage() let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { if #available(iOS 11, *) { switch context.biometryType { case .touchID: image = UIImage(named: "touch_id") ?? UIImage() case .faceID: image = UIImage(named: "face_id") ?? UIImage() case .none: image = UIImage() } } } biometricsButton.setImage(image, for: .normal) deleteButton.setImage(UIImage(named: "delete"), for: .normal) messageLabel.textColor = Colors.mainBlue messageLabel.font = UIFont(name: Constants.Fonts.bold, size: 22) ?? UIFont.boldSystemFont(ofSize: 22) numsIcons = [firstNum, secondNum, thirdNum, fourthNum] } // MARK: - Screen status func changeNumsIcons(_ nums: Int) { switch nums { case 0: for i in 0...(numsIcons?.count)! - 1 { self.numsIcons![i].image = UIImage(named: "line") } case 4: for i in 0...nums - 1 { self.numsIcons![i].image = UIImage(named: "dot") } default: for i in 0...nums - 1 { self.numsIcons![i].image = UIImage(named: "dot") } for i in nums...(numsIcons?.count)! - 1 { self.numsIcons![i].image = UIImage(named: "line") } } } // MARK: - Button actions @IBAction func numButtonPressed(_ sender: PinCodeNumberButton) { let number = sender.currentTitle! animation.pressButtonCanceledAnimation(for: sender, color: Colors.lightBlue) numberPressedAction(number: number) } @IBAction func deletePressed(_ sender: PinCodeDeleteButton) { animation.pressButtonCanceledAnimation(for: sender, color: Colors.lightBlue) deletePressedAction() } @IBAction func biometricsPressed(_ sender: PinCodeBiometricsButton) { animation.pressButtonCanceledAnimation(for: sender, color: Colors.lightBlue) biometricsPressedAction() } func deletePressedAction() { } func numberPressedAction(number: String) { } func biometricsPressedAction() { } }
29.327586
95
0.59759
dd6318997d2564e8558e416e10103bb9f40404fd
3,729
// // TourViewController.swift // Myra // // Created by Amir Shayegh on 2018-11-08. // Copyright © 2018 Government of British Columbia. All rights reserved. // import UIKit class TourViewController: UIViewController, Theme { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var backButton: UIButton! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var skipButton: UIButton! @IBOutlet weak var descLabelHeight: NSLayoutConstraint! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var iconHeight: NSLayoutConstraint! @IBOutlet weak var titleHeight: NSLayoutConstraint! @IBOutlet weak var buttonHeights: NSLayoutConstraint! @IBOutlet weak var skipHight: NSLayoutConstraint! var backCallback: (()->Void)? var nextCallback: (()->Void)? var skipCallback: (()->Void)? var actionCallback: (()->Void)? override func viewDidLoad() { super.viewDidLoad() style() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) style() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if let callback = actionCallback { return callback() } } @IBAction func backAction(_ sender: UIButton) { back() } @IBAction func nextAction(_ sender: UIButton) { next() } @IBAction func skipAction(_ sender: UIButton) { skip() } func skip() { guard let callback = self.skipCallback else {return} actionCallback = callback self.dismiss(animated: true) } func back() { guard let callback = self.backCallback else {return} actionCallback = callback self.dismiss(animated: true) } func next() { guard let callback = self.nextCallback else {return} actionCallback = callback self.dismiss(animated: true) } func setup(header: String, desc: String, backgroundColor: UIColor, textColor: UIColor, hasPrev: Bool, hasNext: Bool, onBack: @escaping ()->Void, onNext: @escaping ()-> Void, onSkip: @escaping ()-> Void) { self.backCallback = onBack self.nextCallback = onNext self.skipCallback = onSkip self.actionCallback = onNext self.titleLabel.text = header self.descLabel.text = desc style() if !hasPrev { backButton.isHidden = true } if !hasNext { nextButton.setTitle("Done", for: .normal) } self.descLabel.textColor = textColor self.titleLabel.textColor = textColor } func style() { styleHollowButton(button: backButton) styleHollowButton(button: nextButton) self.backButton.setTitle("Back", for: .normal) self.nextButton.setTitle("Next", for: .normal) self.descLabel.textColor = UIColor.white self.titleLabel.textColor = UIColor.white self.titleLabel.font = Fonts.getPrimaryBold(size: 22) self.descLabel.font = Fonts.getPrimary(size: 17) if let descL = self.descLabel, let text = descL.text, let height = descLabelHeight { height.constant = text.height(withConstrainedWidth: descL.frame.width, font: Fonts.getPrimary(size: 17)) + 16 } backButton.isHidden = false self.view.layoutIfNeeded() } func styleButton(button: UIButton, bg: UIColor, borderColor: CGColor, titleColor: UIColor) { button.layer.cornerRadius = 5 button.backgroundColor = bg button.layer.borderWidth = 1 button.layer.borderColor = borderColor button.setTitleColor(titleColor, for: .normal) } }
29.595238
208
0.63985
084bdc25e744b42cd46da9533d4faf2b4a8bff78
5,227
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation final class KeyBackupRecoverCoordinator: KeyBackupRecoverCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private let navigationRouter: NavigationRouterType private let keyBackupVersion: MXKeyBackupVersion // MARK: Public var childCoordinators: [Coordinator] = [] weak var delegate: KeyBackupRecoverCoordinatorDelegate? // MARK: - Setup init(session: MXSession, keyBackupVersion: MXKeyBackupVersion) { self.session = session self.keyBackupVersion = keyBackupVersion self.navigationRouter = NavigationRouter(navigationController: RiotNavigationController()) } // MARK: - Public func start() { let rootCoordinator: Coordinator & Presentable // Check if a passphrase has been set for given backup if let megolmBackupAuthData = MXMegolmBackupAuthData(fromJSON: self.keyBackupVersion.authData), megolmBackupAuthData.privateKeySalt != nil { rootCoordinator = self.createRecoverFromPassphraseCoordinator() } else { rootCoordinator = self.createRecoverFromRecoveryKeyCoordinator() } rootCoordinator.start() self.add(childCoordinator: rootCoordinator) self.navigationRouter.setRootModule(rootCoordinator) } func toPresentable() -> UIViewController { return self.navigationRouter.toPresentable() } // MARK: - Private private func createRecoverFromPassphraseCoordinator() -> KeyBackupRecoverFromPassphraseCoordinator { let coordinator = KeyBackupRecoverFromPassphraseCoordinator(keyBackup: self.session.crypto.backup, keyBackupVersion: self.keyBackupVersion) coordinator.delegate = self return coordinator } private func createRecoverFromRecoveryKeyCoordinator() -> KeyBackupRecoverFromRecoveryKeyCoordinator { let coordinator = KeyBackupRecoverFromRecoveryKeyCoordinator(keyBackup: self.session.crypto.backup, keyBackupVersion: self.keyBackupVersion) coordinator.delegate = self return coordinator } private func showRecoverFromRecoveryKey() { let coordinator = self.createRecoverFromRecoveryKeyCoordinator() self.add(childCoordinator: coordinator) self.navigationRouter.push(coordinator, animated: true) { self.remove(childCoordinator: coordinator) } coordinator.start() } private func showRecoverSuccess() { let keyBackupRecoverSuccessViewController = KeyBackupRecoverSuccessViewController.instantiate() keyBackupRecoverSuccessViewController.delegate = self self.navigationRouter.push(keyBackupRecoverSuccessViewController, animated: true, popCompletion: nil) } } // MARK: - KeyBackupRecoverFromPassphraseCoordinatorDelegate extension KeyBackupRecoverCoordinator: KeyBackupRecoverFromPassphraseCoordinatorDelegate { func keyBackupRecoverFromPassphraseCoordinatorDidRecover(_ keyBackupRecoverFromPassphraseCoordinator: KeyBackupRecoverFromPassphraseCoordinatorType) { self.showRecoverSuccess() } func keyBackupRecoverFromPassphraseCoordinatorDoNotKnowPassphrase(_ keyBackupRecoverFromPassphraseCoordinator: KeyBackupRecoverFromPassphraseCoordinatorType) { self.showRecoverFromRecoveryKey() } func keyBackupRecoverFromPassphraseCoordinatorDidCancel(_ keyBackupRecoverFromPassphraseCoordinator: KeyBackupRecoverFromPassphraseCoordinatorType) { self.delegate?.keyBackupRecoverCoordinatorDidCancel(self) } } // MARK: - KeyBackupRecoverFromRecoveryKeyCoordinatorDelegate extension KeyBackupRecoverCoordinator: KeyBackupRecoverFromRecoveryKeyCoordinatorDelegate { func keyBackupRecoverFromPassphraseCoordinatorDidRecover(_ keyBackupRecoverFromRecoveryKeyCoordinator: KeyBackupRecoverFromRecoveryKeyCoordinatorType) { self.showRecoverSuccess() } func keyBackupRecoverFromPassphraseCoordinatorDidCancel(_ keyBackupRecoverFromRecoveryKeyCoordinator: KeyBackupRecoverFromRecoveryKeyCoordinatorType) { self.delegate?.keyBackupRecoverCoordinatorDidCancel(self) } } // MARK: - KeyBackupRecoverSuccessViewControllerDelegate extension KeyBackupRecoverCoordinator: KeyBackupRecoverSuccessViewControllerDelegate { func KeyBackupRecoverSuccessViewControllerDidTapDone(_ keyBackupRecoverSuccessViewController: KeyBackupRecoverSuccessViewController) { self.delegate?.keyBackupRecoverCoordinatorDidRecover(self) } }
39.300752
163
0.757796
6725d4512b5bb8704577f09dfc39673d5129dfea
1,993
// Copyright © 2017-2018 Trust. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import Foundation public extension PublicKey { /// Returns the public key address with the given prefix. public func legacyBitcoinAddress(prefix: UInt8) -> BitcoinAddress { let hash = Data([prefix]) + bitcoinKeyHash return BitcoinAddress(data: hash)! } public func compatibleBitcoinAddress(prefix: UInt8) -> BitcoinAddress { let witnessVersion = Data(bytes: [0x00, 0x14]) let redeemScript = Crypto.sha256ripemd160(witnessVersion + bitcoinKeyHash) let address = Crypto.base58Encode([prefix] + redeemScript) return BitcoinAddress(string: address)! } public func bech32Address(hrp: SLIP.HRP = .bitcoin) -> BitcoinBech32Address { let witness = WitnessProgram(version: 0x00, program: bitcoinKeyHash) let address = BitcoinBech32Address(data: witness.bech32Data!, hrp: hrp.rawValue)! return address } public func cashAddress(hrp: SLIP.HRP = .bitcoincash) -> BitcoinCashAddress { // slightly different from WitnessProgram.bech32Data let payload = Data([BitcoinCashAddress.p2khVersion]) + bitcoinKeyHash let data = convertBits(payload, from: 8, to: 5)! let address = BitcoinCashAddress(data: data, hrp: hrp.rawValue)! return address } public func cashAddress(redeemScript: BitcoinScript) -> BitcoinCashAddress { let payload = Data([BitcoinCashAddress.p2shVersion]) + Crypto.sha256ripemd160(redeemScript.data) let data = convertBits(payload, from: 8, to: 5)! return BitcoinCashAddress(data: data, hrp: SLIP.HRP.bitcoincash.rawValue)! } /// Returns the public key hash. public var bitcoinKeyHash: Data { return Crypto.sha256ripemd160(data) } }
41.520833
104
0.700953
3af45bfb1fd0bd96564a49e421247f6f01cef466
3,933
#if canImport(UIKit) import UIKit #else import Cocoa #endif import MetalKit public class PictureInput: ImageSource { public let targets = TargetContainer() var internalTexture:Texture? var hasProcessedImage:Bool = false var internalImage:CGImage? public init(image:CGImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { internalImage = image } #if canImport(UIKit) public convenience init(image:UIImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { self.init(image: image.cgImage!, smoothlyScaleOutput: smoothlyScaleOutput, orientation: orientation) } public convenience init(imageName:String, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { guard let image = UIImage(named:imageName) else { fatalError("No such image named: \(imageName) in your application bundle") } self.init(image:image, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation) } #else public convenience init(image:NSImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { self.init(image:image.cgImage(forProposedRect:nil, context:nil, hints:nil)!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation) } public convenience init(imageName:String, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { let imageName = NSImage.Name(rawValue: imageName) guard let image = NSImage(named:imageName) else { fatalError("No such image named: \(imageName) in your application bundle") } self.init(image:image.cgImage(forProposedRect:nil, context:nil, hints:nil)!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation) } #endif public func processImage(synchronously:Bool = false) { if let texture = internalTexture { if synchronously { self.updateTargetsWithTexture(texture) self.hasProcessedImage = true } else { DispatchQueue.global().async{ self.updateTargetsWithTexture(texture) self.hasProcessedImage = true } } } else { let textureLoader = MTKTextureLoader(device: sharedMetalRenderingDevice.device) if synchronously { do { let imageTexture = try textureLoader.newTexture(cgImage:internalImage!, options: [MTKTextureLoader.Option.SRGB : false]) internalImage = nil self.internalTexture = Texture(orientation: .portrait, texture: imageTexture) self.updateTargetsWithTexture(self.internalTexture!) self.hasProcessedImage = true } catch { fatalError("Failed loading image texture") } } else { textureLoader.newTexture(cgImage: internalImage!, options: [MTKTextureLoader.Option.SRGB : false], completionHandler: { (possibleTexture, error) in guard (error == nil) else { fatalError("Error in loading texture: \(error!)") } guard let texture = possibleTexture else { fatalError("Nil texture received") } self.internalImage = nil self.internalTexture = Texture(orientation: .portrait, texture: texture) DispatchQueue.global().async{ self.updateTargetsWithTexture(self.internalTexture!) self.hasProcessedImage = true } }) } } } public func transmitPreviousImage(to target:ImageConsumer, atIndex:UInt) { if hasProcessedImage { target.newTextureAvailable(self.internalTexture!, fromSourceIndex:atIndex) } } }
47.385542
163
0.6448
d5885be16604b33554f13e7ce1a77100605c8050
848
// // CEFNavigationEntryVisitor.swift // CEF.swift // // Created by Tamas Lustyik on 2015. 07. 30.. // Copyright © 2015. Tamas Lustyik. All rights reserved. // import Foundation func CEFNavigationEntryVisitor_visit(ptr: UnsafeMutablePointer<cef_navigation_entry_visitor_t>, entry: UnsafeMutablePointer<cef_navigation_entry_t>, isCurrent: Int32, index: Int32, totalCount: Int32) -> Int32 { guard let obj = CEFNavigationEntryVisitorMarshaller.get(ptr) else { return 0 } return obj.visit(CEFNavigationEntry.fromCEF(entry)!, isCurrent: isCurrent != 0, index: Int(index), totalCount: Int(totalCount)) ? 1 : 0 }
33.92
95
0.554245
7170cc4bd5d8da1989548858d792733074196214
2,069
// // AppDelegate.swift // SimpleXIB // // Created by Don Mag on 8/7/17. // Copyright © 2017 DonMag. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 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:. } }
44.021277
279
0.788304
b94368516bd18c988ef3dbd62a76e1828dbfc193
1,403
// // PositionFullyConnectedTextView.swift // SwiftQuantumComputing // // Created by Enrique de la Torre on 31/08/2020. // Copyright © 2020 Enrique de la Torre. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // MARK: - Main body class PositionFullyConnectedTextView: PositionView { // MARK: - PositionViewFullyConnectable outlets @IBOutlet weak var connectionUp: SQCView! @IBOutlet weak var conenctionDown: SQCView! // MARK: - PositionViewTextShowable outlets #if os(macOS) @IBOutlet weak var label: NSTextField! #else @IBOutlet weak var label: UILabel! #endif } // MARK: - PositionViewFullyConnectable methods extension PositionFullyConnectedTextView: PositionViewFullyConnectable {} // MARK: - PositionViewTextShowable methods extension PositionFullyConnectedTextView: PositionViewTextShowable {}
29.229167
75
0.749822
f49bffb408c6612338b7119f60e4d45c4ffe2626
5,694
// // CircleGestureRecognizer.swift // GameOfRunes // // Created by Andy on 18/3/20. // Copyright © 2020 TeamHoWan. All rights reserved. // import UIKit class CircleGestureRecognizer { private static let tolerance: CGFloat = 0.25 // circle wiggle room private static let maxIteration = 8 static func isCircle(touchedPoints: [CGPoint]) -> CircleResult? { let fitResult = fitCircle(points: touchedPoints) let hasInside = anyPointsInTheMiddle(touchedPoints: touchedPoints, fitResult: fitResult) let path = CGMutablePath() guard let first = touchedPoints.first else { return nil } path.move(to: first) for i in 1..<touchedPoints.count { path.addLine(to: touchedPoints[i]) } let percentOverlap = calculateBoundingOverlap(fitResult: fitResult, path: path) if fitResult.error <= tolerance && !hasInside && percentOverlap > (1 - tolerance) { return fitResult } return nil } private static func anyPointsInTheMiddle(touchedPoints: [CGPoint], fitResult: CircleResult) -> Bool { let fitInnerRadius = fitResult.radius / sqrt(2) * tolerance let innerBox = CGRect( x: fitResult.center.x - fitInnerRadius, y: fitResult.center.y - fitInnerRadius, width: 2 * fitInnerRadius, height: 2 * fitInnerRadius) var hasInside = false for point in touchedPoints { if innerBox.contains(point) { hasInside = true break } } return hasInside } private static func calculateBoundingOverlap(fitResult: CircleResult, path: CGPath) -> CGFloat { let fitBoundingBox = CGRect( x: fitResult.center.x - fitResult.radius, y: fitResult.center.y - fitResult.radius, width: 2 * fitResult.radius, height: 2 * fitResult.radius) let pathBoundingBox = path.boundingBox let overlapRect = fitBoundingBox.intersection(pathBoundingBox) let overlapRectArea = overlapRect.width * overlapRect.height let circleBoxArea = fitBoundingBox.height * fitBoundingBox.width let percentOverlap = overlapRectArea / circleBoxArea return percentOverlap } private static func fitCircle(points: [CGPoint]) -> CircleResult { let dataLength = CGFloat(points.count) var mean = CGPoint(x: 0, y: 0) for p in points { mean.x += p.x mean.y += p.y } mean.x /= dataLength mean.y /= dataLength // computing moments var Mxx = 0.0 as CGFloat var Myy = 0.0 as CGFloat var Mxy = 0.0 as CGFloat var Mxz = 0.0 as CGFloat var Myz = 0.0 as CGFloat var Mzz = 0.0 as CGFloat for p in points { let Xi = p.x - mean.x let Yi = p.y - mean.y let Zi = Xi * Xi + Yi + Yi Mxy += Xi * Yi Mxx += Xi * Xi Myy += Yi * Yi Mxz += Xi * Zi Myz += Yi * Zi Mzz += Zi * Zi } Mxx /= dataLength Myy /= dataLength Mxy /= dataLength Mxz /= dataLength Myz /= dataLength Mzz /= dataLength // computing coefficients of the characteristic polynomial let Mz = Mxx + Myy let Cov_xy = Mxx * Myy - Mxy * Mxy let Var_z = Mzz - Mz * Mz let A3 = 4 * Mz let A2 = -3 * Mz * Mz - Mzz let A1 = Var_z * Mz + 4 * Cov_xy * Mz - Mxz * Mxz - Myz * Myz let A0 = Mxz * (Mxz * Myy - Myz * Mxy) + Myz * (Myz * Mxx - Mxz * Mxy) - Var_z * Cov_xy let A22 = A2 + A2 let A33 = A3 + A3 + A3 // finding the root of the characteristic polynomial // using Newton's method starting at x=0 // (it is guaranteed to converge to the right root) var x: CGFloat = 0 var y = A0 let iter = 0 for _ in 0..<maxIteration { let Dy = A1 + x * (A22 + A33 * x) let xnew = x - y / Dy if (xnew == x) || (!xnew.isFinite) { break } let ynew = A0 + xnew * (A1 + xnew * (A2 + xnew * A3)) if abs(ynew) >= abs(y) { break } x = xnew; y = ynew } // computing paramters of the fitting circle let DET = x * x - x * Mz + Cov_xy let Xcenter = (Mxz * (Myy - x) - Myz * Mxy) / DET / 2.0 let Ycenter = (Myz * (Mxx - x) - Mxz * Mxy) / DET / 2.0 // assembling the output var circle = CircleResult() circle.center.x = Xcenter + mean.x circle.center.y = Ycenter + mean.y circle.radius = sqrt(Xcenter * Xcenter + Ycenter * Ycenter + Mz) circle.error = Sigma(data: points, circle: circle) circle.j = iter // return the number of iterations, too return circle } // Estimate of Sigma = square root of RSS divided by N // Gives the root-mean-square error of the geometric circle fit static func Sigma(data: [CGPoint], circle: CircleResult) -> CGFloat { var sum: CGFloat = 0.0 for p in data { let dx = p.x - circle.center.x let dy = p.y - circle.center.y let s = (sqrt(dx * dx + dy * dy) - circle.radius) / circle.radius //<- added / c.r to give normalized result sum += s * s } return sqrt(sum / CGFloat(data.count)) } }
34.719512
120
0.534422
d54832cd6098af15a7d7b2b0d13235f935a6b701
8,918
// // PDFPageView.swift // PDFReader // // Created by ALUA KINZHEBAYEVA on 4/23/15. // Copyright (c) 2015 AK. All rights reserved. // import UIKit /// Delegate that is informed of important interaction events with the current `PDFPageView` protocol PDFPageViewDelegate: class { /// User has tapped on the page view func handleSingleTap(_ pdfPageView: PDFPageView) } /// An interactable page of a document internal final class PDFPageView: UIScrollView { /// The TiledPDFView that is currently front most. private var tiledPDFView: TiledView /// Current scale of the scrolling view fileprivate var scale: CGFloat /// Number of zoom levels possible when double tapping private let zoomLevels: CGFloat = 2 /// View which contains all of our content fileprivate var contentView: UIView /// A low resolution image of the PDF page that is displayed until the TiledPDFView renders its content. private let backgroundImageView: UIImageView /// Page reference being displayed private let pdfPage: CGPDFPage /// Current amount being zoomed private var zoomAmount: CGFloat? /// Delegate that is informed of important interaction events private weak var pageViewDelegate: PDFPageViewDelegate? /// Instantiates a scrollable page view /// /// - parameter frame: frame of the view /// - parameter document: document to be displayed /// - parameter pageNumber: specific page number of the document to display /// - parameter backgroundImage: background image of the page to display while rendering /// - parameter pageViewDelegate: delegate notified of any important interaction events /// /// - returns: a freshly initialized page view init(frame: CGRect, document: PDFDocument, pageNumber: Int, backgroundImage: UIImage?, pageViewDelegate: PDFPageViewDelegate?) { guard let pageRef = document.coreDocument.page(at: pageNumber + 1) else { fatalError() } pdfPage = pageRef self.pageViewDelegate = pageViewDelegate let originalPageRect = pageRef.originalPageRect scale = min(frame.width/originalPageRect.width, frame.height/originalPageRect.height) let scaledPageRectSize = CGSize(width: originalPageRect.width * scale, height: originalPageRect.height * scale) let scaledPageRect = CGRect(origin: originalPageRect.origin, size: scaledPageRectSize) guard !scaledPageRect.isEmpty else { fatalError() } // Create our content view based on the size of the PDF page contentView = UIView(frame: scaledPageRect) backgroundImageView = UIImageView(image: backgroundImage) backgroundImageView.frame = contentView.bounds // Create the TiledPDFView and scale it to fit the content view. tiledPDFView = TiledView(frame: contentView.bounds, scale: scale, newPage: pdfPage) super.init(frame: frame) let targetRect = bounds.insetBy(dx: 0, dy: 0) var zoomScale = zoomScaleThatFits(targetRect.size, source: bounds.size) minimumZoomScale = zoomScale // Set the minimum and maximum zoom scales maximumZoomScale = zoomScale * (zoomLevels * zoomLevels) // Max number of zoom levels zoomAmount = (maximumZoomScale - minimumZoomScale) / zoomLevels scale = 1 if zoomScale > minimumZoomScale { zoomScale = minimumZoomScale } contentView.addSubview(backgroundImageView) contentView.sendSubview(toBack: backgroundImageView) contentView.addSubview(tiledPDFView) addSubview(contentView) let doubleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleDoubleTap)) doubleTapOne.numberOfTapsRequired = 2 doubleTapOne.cancelsTouchesInView = false addGestureRecognizer(doubleTapOne) let singleTapOne = UITapGestureRecognizer(target: self, action:#selector(handleSingleTap)) singleTapOne.numberOfTapsRequired = 1 singleTapOne.cancelsTouchesInView = false addGestureRecognizer(singleTapOne) singleTapOne.require(toFail: doubleTapOne) bouncesZoom = false decelerationRate = UIScrollView.DecelerationRate.hash delegate = self autoresizesSubviews = true autoresizingMask = [.flexibleHeight, .flexibleWidth] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Use layoutSubviews to center the PDF page in the view. override func layoutSubviews() { super.layoutSubviews() // Center the image as it becomes smaller than the size of the screen. let contentViewSize = contentView.frame.size // Center horizontally. let xOffset: CGFloat if contentViewSize.width < bounds.width { xOffset = (bounds.width - contentViewSize.width) / 2 } else { xOffset = 0 } // Center vertically. let yOffset: CGFloat if contentViewSize.height < bounds.height { yOffset = (bounds.height - contentViewSize.height) / 2 } else { yOffset = 0 } contentView.frame = CGRect(origin: CGPoint(x: xOffset, y: yOffset), size: contentViewSize) // To handle the interaction between CATiledLayer and high resolution screens, set the // tiling view's contentScaleFactor to 1.0. If this step were omitted, the content scale factor // would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale. tiledPDFView.contentScaleFactor = 1 } /// Notifies the delegate that a single tap was performed @objc func handleSingleTap(_ tapRecognizer: UITapGestureRecognizer) { pageViewDelegate?.handleSingleTap(self) } /// Zooms in and out accordingly, based on the current zoom level @objc func handleDoubleTap(_ tapRecognizer: UITapGestureRecognizer) { var newScale = zoomScale * zoomLevels if newScale >= maximumZoomScale { newScale = minimumZoomScale } let zoomRect = zoomRectForScale(newScale, zoomPoint: tapRecognizer.location(in: tapRecognizer.view)) zoom(to: zoomRect, animated: true) } /// Calculates the zoom scale given a target size and a source size /// /// - parameter target: size of the target rect /// - parameter source: size of the source rect /// /// - returns: the zoom scale of the target in relation to the source private func zoomScaleThatFits(_ target: CGSize, source: CGSize) -> CGFloat { let widthScale = target.width / source.width let heightScale = target.height / source.height return (widthScale < heightScale) ? widthScale : heightScale } /// Calculates the new zoom rect given a desired scale and a point to zoom on /// /// - parameter scale: desired scale to zoom to /// - parameter zoomPoint: the reference point to zoom on /// /// - returns: a new zoom rect private func zoomRectForScale(_ scale: CGFloat, zoomPoint: CGPoint) -> CGRect { // Normalize current content size back to content scale of 1.0f let updatedContentSize = CGSize(width: contentSize.width/zoomScale, height: contentSize.height/zoomScale) let translatedZoomPoint = CGPoint(x: (zoomPoint.x / bounds.width) * updatedContentSize.width, y: (zoomPoint.y / bounds.height) * updatedContentSize.height) // derive the size of the region to zoom to let zoomSize = CGSize(width: bounds.width / scale, height: bounds.height / scale) // offset the zoom rect so the actual zoom point is in the middle of the rectangle return CGRect(x: translatedZoomPoint.x - zoomSize.width / 2.0, y: translatedZoomPoint.y - zoomSize.height / 2.0, width: zoomSize.width, height: zoomSize.height) } } extension PDFPageView: UIScrollViewDelegate { /// A UIScrollView delegate callback, called when the user starts zooming. /// Return the content view func viewForZooming(in scrollView: UIScrollView) -> UIView? { return contentView } /// A UIScrollView delegate callback, called when the user stops zooming. /// When the user stops zooming, create a new Tiled /// PDFView based on the new zoom level and draw it on top of the old TiledPDFView. func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { self.scale = scale } }
41.672897
132
0.664947
f5e2a8056e7b4836a3a5cf57344d9f6922c2abcf
934
// // Country.swift // Corona Virus Tracker // // Created by Tarokh on 9/13/20. // Copyright © 2020 Tarokh. All rights reserved. // import Foundation // MARK: - Country struct Country: Codable { var updated: Int? var country: String? var countryInfo: CountryInfo? var cases, todayCases, deaths, todayDeaths: Int? var recovered, todayRecovered, active, critical: Int? var casesPerOneMillion: Int? var deathsPerOneMillion: Double? var tests, testsPerOneMillion, population: Int? var oneCasePerPeople, oneDeathPerPeople, oneTestPerPeople: Int? var activePerOneMillion, recoveredPerOneMillion, criticalPerOneMillion: Double? } // MARK: - CountryInfo struct CountryInfo: Codable { var _id: Int? var iso2, iso3: String? var lat, long: Double? var flag: String? enum CodingKeys: String, CodingKey { case _id = "_id" case iso2, iso3, lat, long, flag } }
25.243243
83
0.688437
e4d55e77f00c8e762d2a4312df20aad3a10efa42
2,594
// // Observable+ModelMapper.swift // Pods // // Created by sunshinejr on 03.02.2016. // Copyright © 2016 sunshinejr. All rights reserved. // import Foundation import RxSwift import Moya import Mapper #if !COCOAPODS import Moya_ModelMapper #endif /// Extension for processing Responses into Mappable objects through ObjectMapper public extension ObservableType where E == Response { /// Maps data received from the signal into an object which implement /// the Mappable protocol and returns the result back. If the conversion fails, /// error event is sent. public func map<T: Mappable>(to type: T.Type, keyPath: String? = nil) -> Observable<T> { return flatMap { response -> Observable<T> in return Observable.just(try response.map(to: type, keyPath: keyPath)) } } /// Maps data received from the signal into an array of objects which implement /// the Mappable protocol and returns the result back. If the conversion fails, /// error event is sent. public func map<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in return Observable.just(try response.map(to: type, keyPath: keyPath)) } } /// Maps data received from the signal into an object which implement /// the Mappable protocol and returns the result back. If the conversion fails, /// the nil is returned instead of error signal. public func mapOptional<T: Mappable>(to type: T.Type, keyPath: String? = nil) -> Observable<T?> { return flatMap { response -> Observable<T?> in do { let object = try response.map(to: type, keyPath: keyPath) return Observable.just(object) } catch { return Observable.just(nil) } } } /// Maps data received from the signal into an array of objects which implement /// the Mappable protocol and returns the result back. If the conversion fails, /// the nil is returned instead of error signal. public func mapOptional<T: Mappable>(to type: [T].Type, keyPath: String? = nil) -> Observable<[T]?> { return flatMap { response -> Observable<[T]?> in do { let object = try response.map(to: type, keyPath: keyPath) return Observable.just(object) } catch { return Observable.just(nil) } } } }
39.30303
105
0.611411
e8ae6ffd979d6cd2344bdf4e1cc5ca5e973476aa
1,829
import TBADataTesting import XCTest @testable import TBAData @testable import The_Blue_Alliance class EventAllianceCellViewModelTestCase: TBADataTestCase { func test_init() { let alliance = EventAlliance.init(entity: EventAlliance.entity(), insertInto: persistentContainer.viewContext) alliance.picksRaw = NSOrderedSet(array: [ Team.insert("frc1", in: persistentContainer.viewContext), Team.insert("frc3", in: persistentContainer.viewContext), Team.insert("frc2", in: persistentContainer.viewContext), Team.insert("frc4", in: persistentContainer.viewContext) ]) let first = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2) XCTAssertEqual(first.picks, ["frc1", "frc3", "frc2", "frc4"]) XCTAssertEqual(first.allianceName, "Alliance 2") XCTAssertNil(first.allianceLevel) XCTAssertFalse(first.hasAllianceLevel) alliance.nameRaw = "Alliance 3" let second = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2) XCTAssertEqual(second.picks, ["frc1", "frc3", "frc2", "frc4"]) XCTAssertEqual(second.allianceName, "Alliance 3") XCTAssertNil(first.allianceLevel) XCTAssertFalse(first.hasAllianceLevel) let status = EventStatusPlayoff.init(entity: EventStatusPlayoff.entity(), insertInto: persistentContainer.viewContext) status.levelRaw = "f" status.statusRaw = "won" alliance.statusRaw = status let third = EventAllianceCellViewModel(alliance: alliance, allianceNumber: 2) XCTAssertEqual(third.picks, ["frc1", "frc3", "frc2", "frc4"]) XCTAssertEqual(third.allianceName, "Alliance 3") XCTAssertEqual(third.allianceLevel, "W") XCTAssert(third.hasAllianceLevel) } }
43.547619
126
0.696009
71cdce6b1b76953bffdbcc9e21fa56192aa02184
7,262
// // NotesListViewController.swift // Mooskine // // Created by Josh Svatek on 2017-05-31. // Copyright © 2017 Udacity. All rights reserved. // import UIKit import CoreData class NotesListViewController: UIViewController, UITableViewDataSource { /// A table view that displays a list of notes for a notebook @IBOutlet weak var tableView: UITableView! /// The notebook whose notes are being displayed var notebook: Notebook! var dataController:DataController! var fetchedResultsController:NSFetchedResultsController<Note>! /// A date formatter for date text in note cells let dateFormatter: DateFormatter = { let df = DateFormatter() df.dateStyle = .medium return df }() fileprivate func setupFetchedResultsController() { let fetchRequest:NSFetchRequest<Note> = Note.fetchRequest() let predicate = NSPredicate(format: "notebook == %@", notebook) fetchRequest.predicate = predicate let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: dataController.viewContext, sectionNameKeyPath: nil, cacheName: "\(notebook)-notes") fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { fatalError("The fetch could not be performed: \(error.localizedDescription)") } } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = notebook.name navigationItem.rightBarButtonItem = editButtonItem setupFetchedResultsController() updateEditButtonState() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupFetchedResultsController() if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRow(at: indexPath, animated: false) tableView.reloadRows(at: [indexPath], with: .fade) } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) fetchedResultsController = nil } // ------------------------------------------------------------------------- // MARK: - Actions @IBAction func addTapped(sender: Any) { addNote() } // ------------------------------------------------------------------------- // MARK: - Editing // Adds a new `Note` to the end of the `notebook`'s `notes` array func addNote() { let note = Note(context: dataController.viewContext) note.creationDate = Date() note.notebook = notebook try? dataController.viewContext.save() } // Deletes the `Note` at the specified index path func deleteNote(at indexPath: IndexPath) { let noteToDelete = fetchedResultsController.object(at: indexPath) dataController.viewContext.delete(noteToDelete) try? dataController.viewContext.save() } func updateEditButtonState() { navigationItem.rightBarButtonItem?.isEnabled = fetchedResultsController.sections![0].numberOfObjects > 0 } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) } // ------------------------------------------------------------------------- // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[0].numberOfObjects ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let aNote = fetchedResultsController.object(at: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: NoteCell.defaultReuseIdentifier, for: indexPath) as! NoteCell // Configure cell cell.textPreviewLabel.attributedText = aNote.attributedText if let creationDate = aNote.creationDate { cell.dateLabel.text = dateFormatter.string(from: creationDate) } return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: deleteNote(at: indexPath) default: () // Unsupported } } // ------------------------------------------------------------------------- // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // If this is a NoteDetailsViewController, we'll configure its `Note` // and its delete action if let vc = segue.destination as? NoteDetailsViewController { if let indexPath = tableView.indexPathForSelectedRow { vc.note = fetchedResultsController.object(at: indexPath) vc.dataController = dataController vc.onDelete = { [weak self] in if let indexPath = self?.tableView.indexPathForSelectedRow { self?.deleteNote(at: indexPath) self?.navigationController?.popViewController(animated: true) } } } } } } extension NotesListViewController:NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) break case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) break case .update: tableView.reloadRows(at: [indexPath!], with: .fade) case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let indexSet = IndexSet(integer: sectionIndex) switch type { case .insert: tableView.insertSections(indexSet, with: .fade) case .delete: tableView.deleteSections(indexSet, with: .fade) case .update, .move: fatalError("Invalid change type in controller(_:didChange:atSectionIndex:for:). Only .insert or .delete should be possible.") } } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() } }
36.862944
209
0.636188
ebd61818d9d7c79f6fe471553c8ea439c7bcca02
18,101
// // DOFavoriteButton.swift // DOFavoriteButton // // Created by Daiki Okumura on 2015/07/09. // Copyright (c) 2015 Daiki Okumura. All rights reserved. // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // import UIKit let defaultSelectedColor = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) let defaultUnSelectedColor = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) let defaultLineColor = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) /// Custom lại UIButton @IBDesignable open class DOFavoriteButton: UIButton { /// Setting 4 color cho Selected, UnSelected, màu hình tròn bung ra, màu các tia bắn ra nhỏ nhỏ @IBInspectable open var selectedColor: UIColor! = defaultSelectedColor { didSet { if (isSelected) { imageShapeLayer.fillColor = selectedColor.cgColor } } } @IBInspectable open var unselectedColor: UIColor! = defaultUnSelectedColor { didSet { if (isSelected == false) { imageShapeLayer.fillColor = unselectedColor.cgColor } } } @IBInspectable open var circleColor: UIColor! = defaultSelectedColor { didSet { circleShape.fillColor = circleColor.cgColor } } @IBInspectable open var lineColor: UIColor! = defaultLineColor { didSet { for line in lines { line.strokeColor = lineColor.cgColor } } } @IBInspectable open var image: UIImage! { didSet { createLayers(image: image) } } fileprivate var imageShapeLayer: CAShapeLayer! fileprivate var circleShape: CAShapeLayer! fileprivate var circleMask: CAShapeLayer! fileprivate var lines: [CAShapeLayer]! fileprivate let circleTransform = CAKeyframeAnimation(keyPath: "transform") fileprivate let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform") fileprivate let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart") fileprivate let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd") fileprivate let lineOpacity = CAKeyframeAnimation(keyPath: "opacity") fileprivate let imageTransform = CAKeyframeAnimation(keyPath: "transform") /// Animation duration @IBInspectable open var duration: Double = 1.0 { didSet { circleTransform.duration = 0.333 * duration // 0.0333 * 10 circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10 lineStrokeStart.duration = 0.6 * duration //0.0333 * 18 lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18 lineOpacity.duration = 1.0 * duration //0.0333 * 30 imageTransform.duration = 1.0 * duration //0.0333 * 30 } } override open var isSelected : Bool { didSet { if (isSelected != oldValue) { if isSelected { imageShapeLayer.fillColor = selectedColor.cgColor } else { animateToDeselectedState() } } } } // MARK: Initialize public convenience init() { self.init(frame: CGRect.zero) } public override convenience init(frame: CGRect) { self.init(frame: frame, image: UIImage()) } public init(frame: CGRect, image: UIImage!) { super.init(frame: frame) self.image = image createLayers(image: image) addTargets() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! createLayers(image: UIImage()) addTargets() } // MARK: Public open func select() { select(animated: true) } open func select(animated: Bool = true) { isSelected = true imageShapeLayer.fillColor = selectedColor.cgColor if !animated { return } CATransaction.begin() circleShape.add(circleTransform, forKey: "transform") circleMask.add(circleMaskTransform, forKey: "transform") imageShapeLayer.add(imageTransform, forKey: "transform") for i in 0 ..< 5 { lines[i].add(lineStrokeStart, forKey: "strokeStart") lines[i].add(lineStrokeEnd, forKey: "strokeEnd") lines[i].add(lineOpacity, forKey: "opacity") } CATransaction.commit() } open func deselect() { animateToDeselectedState() } open func animateToSelectedState() { isSelected = true imageShapeLayer.fillColor = selectedColor.cgColor CATransaction.begin() circleShape.add(circleTransform, forKey: "transform") circleMask.add(circleMaskTransform, forKey: "transform") imageShapeLayer.add(imageTransform, forKey: "transform") for i in 0 ..< 5 { lines[i].add(lineStrokeStart, forKey: "strokeStart") lines[i].add(lineStrokeEnd, forKey: "strokeEnd") lines[i].add(lineOpacity, forKey: "opacity") } CATransaction.commit() } open func animateToDeselectedState() { isSelected = false imageShapeLayer.fillColor = unselectedColor.cgColor // remove all animations circleShape.removeAllAnimations() circleMask.removeAllAnimations() imageShapeLayer.removeAllAnimations() lines[0].removeAllAnimations() lines[1].removeAllAnimations() lines[2].removeAllAnimations() lines[3].removeAllAnimations() lines[4].removeAllAnimations() } // MARK: Private fileprivate func createLayers(image: UIImage!) { self.layer.sublayers = nil /// Calculate ImageFrame and LineFrame let buttonWidth = frame.size.width let buttonHeight = frame.size.height let imageFrame = CGRect(x: buttonWidth/4, y: buttonHeight/4, width: buttonWidth/2, height: buttonHeight/2) let imgCenterPoint = CGPoint(x: imageFrame.midX, y: imageFrame.midY) /// CircleLayer là 1 hình tròn (nó cũng chứa 1 UIBezierPath đó) /// Hình tròn này có kích thước to bằng MAIN-IMAGE /// Tạm thời scale về 0.0 circleShape = OvalLayer(fillColor: circleColor.cgColor) circleShape.bounds = imageFrame circleShape.position = imgCenterPoint circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0) /// scale width, height về 0 self.layer.addSublayer(circleShape) /// /// Read more about FillRule /// https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html#//apple_ref/doc/uid/TP40003290-CH206-BAJIJJGD /// CircleMask là 1 CAShapLayer chịu trách nhiệm draw 1 UIBezierPath (là hình tròn nhỏ xíu nằm ngay giữa MAIN-IMAGE) circleMask = CAShapeLayer() circleMask.bounds = imageFrame circleMask.position = imgCenterPoint circleMask.fillRule = CAShapeLayerFillRule.evenOdd circleShape.mask = circleMask /// Tạo 1 path object là hình tròn bán kính 0.1 nằm chính giữa MAIN-IMAGE /// Gán path vào CAShapeLayer (circleMask) let maskPath = UIBezierPath(rect: imageFrame) maskPath.addArc(withCenter: imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(Double.pi*2), clockwise: true) circleMask.path = maskPath.cgPath /// Lines là list của các CAShapeLayer (~ CALayer) let lineFrame = CGRect(x: imageFrame.origin.x - imageFrame.width/4, y: imageFrame.origin.y - imageFrame.height / 4 , width: imageFrame.width * 1.5, height: imageFrame.height * 1.5) lines = [] for i in 0 ..< 5 { let line = CAShapeLayer() line.bounds = lineFrame line.position = imgCenterPoint line.masksToBounds = true line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()] line.strokeColor = lineColor.cgColor line.lineWidth = 1.25 line.miterLimit = 1.25 line.path = { let path = CGMutablePath() path.move(to: CGPoint(x: lineFrame.midX, y: lineFrame.midY)) path.addLine(to: CGPoint(x: lineFrame.origin.x + lineFrame.width / 2, y: lineFrame.origin.y)) return path }() line.lineCap = CAShapeLayerLineCap.round line.lineJoin = CAShapeLayerLineJoin.round line.strokeStart = 0.0 line.strokeEnd = 0.0 line.opacity = 0.0 line.transform = CATransform3DMakeRotation(CGFloat(Double.pi) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0) self.layer.addSublayer(line) lines.append(line) } //=============== // image layer //=============== imageShapeLayer = CAShapeLayer() imageShapeLayer.bounds = imageFrame imageShapeLayer.position = imgCenterPoint imageShapeLayer.path = UIBezierPath(rect: imageFrame).cgPath imageShapeLayer.fillColor = unselectedColor.cgColor imageShapeLayer.actions = ["fillColor": NSNull()] self.layer.addSublayer(imageShapeLayer) imageShapeLayer.mask = CALayer() imageShapeLayer.mask!.contents = image.cgImage imageShapeLayer.mask!.bounds = imageFrame imageShapeLayer.mask!.position = imgCenterPoint //============================== // circle transform animation //============================== circleTransform.duration = 0.333 // 0.0333 * 10 circleTransform.values = [ NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10 NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10 NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10 NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10 NSValue(caTransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10 NSValue(caTransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10 NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10 NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10 ] circleTransform.keyTimes = [ 0.0, // 0/10 0.1, // 1/10 0.2, // 2/10 0.3, // 3/10 0.4, // 4/10 0.5, // 5/10 0.6, // 6/10 1.0 // 10/10 ] circleMaskTransform.duration = 0.333 // 0.0333 * 10 circleMaskTransform.values = [ NSValue(caTransform3D: CATransform3DIdentity), // 0/10 NSValue(caTransform3D: CATransform3DIdentity), // 2/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10 NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10 ] circleMaskTransform.keyTimes = [ 0.0, // 0/10 0.2, // 2/10 0.3, // 3/10 0.4, // 4/10 0.5, // 5/10 0.6, // 6/10 0.7, // 7/10 0.9, // 9/10 1.0 // 10/10 ] //============================== // line stroke animation //============================== lineStrokeStart.duration = 0.6 //0.0333 * 18 lineStrokeStart.values = [ 0.0, // 0/18 0.0, // 1/18 0.18, // 2/18 0.2, // 3/18 0.26, // 4/18 0.32, // 5/18 0.4, // 6/18 0.6, // 7/18 0.71, // 8/18 0.89, // 17/18 0.92 // 18/18 ] lineStrokeStart.keyTimes = [ 0.0, // 0/18 0.056, // 1/18 0.111, // 2/18 0.167, // 3/18 0.222, // 4/18 0.278, // 5/18 0.333, // 6/18 0.389, // 7/18 0.444, // 8/18 0.944, // 17/18 1.0, // 18/18 ] lineStrokeEnd.duration = 0.6 //0.0333 * 18 lineStrokeEnd.values = [ 0.0, // 0/18 0.0, // 1/18 0.32, // 2/18 0.48, // 3/18 0.64, // 4/18 0.68, // 5/18 0.92, // 17/18 0.92 // 18/18 ] lineStrokeEnd.keyTimes = [ 0.0, // 0/18 0.056, // 1/18 0.111, // 2/18 0.167, // 3/18 0.222, // 4/18 0.278, // 5/18 0.944, // 17/18 1.0, // 18/18 ] lineOpacity.duration = 1.0 //0.0333 * 30 lineOpacity.values = [ 1.0, // 0/30 1.0, // 12/30 0.0 // 17/30 ] lineOpacity.keyTimes = [ 0.0, // 0/30 0.4, // 12/30 0.567 // 17/30 ] //============================== // image transform animation //============================== imageTransform.duration = 1.0 //0.0333 * 30 imageTransform.values = [ NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30 NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30 NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30 NSValue(caTransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30 NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30 NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30 NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30 NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30 NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30 NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30 NSValue(caTransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30 NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30 NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30 NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30 NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30 NSValue(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30 NSValue(caTransform3D: CATransform3DIdentity) // 30/30 ] imageTransform.keyTimes = [ 0.0, // 0/30 0.1, // 3/30 0.3, // 9/30 0.333, // 10/30 0.367, // 11/30 0.467, // 14/30 0.5, // 15/30 0.533, // 16/30 0.567, // 17/30 0.667, // 20/30 0.7, // 21/30 0.733, // 22/30 0.833, // 25/30 0.867, // 26/30 0.9, // 27/30 0.967, // 29/30 1.0 // 30/30 ] } fileprivate func addTargets() { //=============== // add target //=============== self.addTarget(self, action: #selector(DOFavoriteButton.touchDown(_:)), for: UIControl.Event.touchDown) self.addTarget(self, action: #selector(DOFavoriteButton.touchUpInside(_:)), for: UIControl.Event.touchUpInside) self.addTarget(self, action: #selector(DOFavoriteButton.touchDragExit(_:)), for: UIControl.Event.touchDragExit) self.addTarget(self, action: #selector(DOFavoriteButton.touchDragEnter(_:)), for: UIControl.Event.touchDragEnter) self.addTarget(self, action: #selector(DOFavoriteButton.touchCancel(_:)), for: UIControl.Event.touchCancel) } @objc func touchDown(_ sender: DOFavoriteButton) { self.layer.opacity = 0.4 } @objc func touchUpInside(_ sender: DOFavoriteButton) { self.layer.opacity = 1.0 } @objc func touchDragExit(_ sender: DOFavoriteButton) { self.layer.opacity = 1.0 } @objc func touchDragEnter(_ sender: DOFavoriteButton) { self.layer.opacity = 0.4 } @objc func touchCancel(_ sender: DOFavoriteButton) { self.layer.opacity = 1.0 } }
39.521834
167
0.537097
5019c423521d0c51ee01bb237171d9602ff696b1
6,171
// // Geom.swift // TaboDemo // // Created by Michiyasu Wada on 2016/01/13. // Copyright © 2016年 Michiyasu Wada. All rights reserved. // import UIKit import QuartzCore import SceneKit class Geom { // 3つの点(三角形)から外心点(外接円の中心)を求める static func circumcircle(a:CGPoint, b:CGPoint, c:CGPoint) -> CGPoint { let x1:CGFloat = (a.y-c.y)*(a.y*a.y-b.y*b.y+a.x*a.x-b.x*b.x) let x2:CGFloat = (a.y-b.y)*(a.y*a.y-c.y*c.y+a.x*a.x-c.x*c.x) let x3:CGFloat = 2*(a.y-c.y)*(a.x-b.x)-2*(a.y-b.y)*(a.x-c.x) let y1:CGFloat = (a.x-c.x)*(a.x*a.x-b.x*b.x+a.y*a.y-b.y*b.y) let y2:CGFloat = (a.x-b.x)*(a.x*a.x-c.x*c.x+a.y*a.y-c.y*c.y) let y3:CGFloat = 2*(a.x-c.x)*(a.y-b.y)-2*(a.x-b.x)*(a.y-c.y) let px:CGFloat = (x1-x2)/x3 let py:CGFloat = (y1-y2)/y3 return CGPoint(x:px, y:py) } // 2点間の距離を調べる static func length(a:CGPoint, b:CGPoint) -> CGFloat { let x:CGFloat = a.x - b.x let y:CGFloat = a.y - b.y return sqrt(x * x + y * y) } // 2点の角度を調べる static func angle(a:CGPoint, b:CGPoint) -> CGFloat { let x:CGFloat = a.x - b.x let y:CGFloat = a.y - b.y return atan2(y, x) } // 点が線B→Aの右にあるか左にあるか(1=右、-1=左、0=線上) static func lineSide(pt:CGPoint, a:CGPoint, b:CGPoint) -> Int { let n:CGFloat = pt.x * (a.y - b.y) + a.x * (b.y - pt.y) + b.x * (pt.y - a.y) if n > 0 { return 1 } if n < 0 { return -1 } return 0 } // 線分の範囲内にあるか判定 static func line_overlaps(pt:CGPoint, a:CGPoint, b:CGPoint) -> Bool { if (((a.x >= pt.x && b.x <= pt.x) || (b.x >= pt.x && a.x <= pt.x)) && ((a.y >= pt.y && b.y <= pt.y) || (b.y >= pt.y && a.y <= pt.y))) { return true } return false } // 線ABと線CDの角度を調べる static func lineAngle(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint) -> CGFloat { let abX:CGFloat = b.x - a.x let abY:CGFloat = b.y - a.y let cdX:CGFloat = d.x - c.x let cdY:CGFloat = d.y - c.y let r1:CGFloat = abX * cdX + abY * cdY let r2:CGFloat = abX * cdY - abY * cdX return atan2(r2, r1) } // 線分ABと線分CDが交差するか調べる static func intersection(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint) -> Bool { if (((a.x-b.x)*(c.y-a.y)+(a.y-b.y)*(a.x-c.x)) * ((a.x-b.x)*(d.y-a.y)+(a.y-b.y)*(a.x-d.x)) < 0) { return (((c.x-d.x)*(a.y-c.y)+(c.y-d.y) * (c.x-a.x))*((c.x-d.x)*(b.y-c.y)+(c.y-d.y)*(c.x-b.x)) < 0) } return false } // 直線ABと直線CDの交点を調べる static func cross(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint) -> CGPoint { var t1:CGFloat = a.x-b.x var t2:CGFloat = c.x-d.x if t1 == 0 { t1 = 0.0000001 } if t2 == 0 { t2 = 0.0000001 } let ta:CGFloat = (a.y-b.y) / t1 let tb:CGFloat = (a.x*b.y - a.y*b.x) / t1 let tc:CGFloat = (c.y-d.y) / t2 let td:CGFloat = (c.x*d.y - c.y*d.x) / t2 let px:CGFloat = (td-tb) / (ta-tc) let py:CGFloat = ta * px + tb return CGPoint(x:px, y:py) } //直線ABが直線CDに衝突したときの反射角度 static func refrect(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint) -> CGFloat { let aX:CGFloat = b.x-a.x let aY:CGFloat = b.y-a.y let bX:CGFloat = d.x-c.x let bY:CGFloat = d.y-c.y return atan2(aY, aX) + CGFloat(PI) + atan2(aX*bY-aY*bX, aX*bX+aY*bY) * 2 } //点ptを線分ABに対して垂直に移動した時に交差する点を調べる static func perpPoint(pt:CGPoint, a:CGPoint, b:CGPoint, outside:Bool=false) -> CGPoint? { var dest:CGPoint = CGPoint() if(a.x == b.x) { dest.x = a.x; dest.y = pt.y; } else if(a.y == b.y) { dest.x = pt.x dest.y = a.y } else { let m1:CGFloat = (b.y - a.y) / (b.x - a.x) let b1:CGFloat = a.y - (m1 * a.x); let m2:CGFloat = -1.0 / m1 let b2:CGFloat = pt.y - (m2 * pt.x) dest.x = (b2 - b1) / (m1 - m2) dest.y = (b2 * m1 - b1 * m2) / (m1 - m2) } if (outside) { return dest } // 線分の範囲内にあるか判定 if ((a.x >= dest.x && b.x <= dest.x && a.y >= dest.y && b.y <= dest.y) || (b.x >= dest.x && a.x <= dest.x && b.y >= dest.y && a.y <= dest.y)) { return dest } return nil } // 3次ベジェ曲線の座標を取得する (a=anchorA, b=controlA, c=controlB, d=anchorB, t=[0.0 <= 1.0]) static func bezierCurve(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint, t:CGFloat) -> CGPoint { let s:CGFloat = 1-t let nx:CGFloat = s*s*s*a.x + 3*s*s*t*b.x + 3*s*t*t*c.x + t*t*t*d.x let ny:CGFloat = s*s*s*a.y + 3*s*s*t*b.y + 3*s*t*t*c.y + t*t*t*d.y return CGPoint(x:nx, y:ny) } // 3次ベジェ曲線の座標を取得する (a=anchorA, b=controlA, c=controlB, d=anchorB, t=[0.0 <= 1.0]) static func bezierCurve(a:CGFloat, b:CGFloat, c:CGFloat, d:CGFloat, t:CGFloat) -> CGFloat { let s:CGFloat = 1-t return s*s*s*a + 3*s*s*t*b + 3*s*t*t*c + t*t*t*d } // CatmullRom補間(スプライン曲線)の座標を取得する (a → b → c → d, t=[0.0 <= 1.0]) static func catmullRom(a:CGPoint, b:CGPoint, c:CGPoint, d:CGPoint, t:CGFloat) -> CGPoint { let px:CGFloat = _catmullRom(a:a.x, b:b.x, c:c.x, d:d.x, t:t) let py:CGFloat = _catmullRom(a:a.y, b:b.y, c:c.y, d:d.y, t:t) return CGPoint(x:px, y:py) } // CatmullRom補間(スプライン曲線)の座標を取得する (a → b → c → d, t=[0.0 <= 1.0]) static func catmullRom(a:CGFloat, b:CGFloat, c:CGFloat, d:CGFloat, t:CGFloat) -> CGFloat { return _catmullRom(a:a, b:b, c:c, d:d, t:t) } private static func _catmullRom(a:CGFloat, b:CGFloat, c:CGFloat, d:CGFloat, t:CGFloat) -> CGFloat { let v0:CGFloat = (c - a) * 0.5 let v1:CGFloat = (d - b) * 0.5 let t2:CGFloat = t * t let t3:CGFloat = t2 * t return (2*b-2*c+v0+v1) * t3+(-3*b+3*c-2*v0-v1) * t2+v0*t+b } }
31.324873
149
0.482094
f77855e22faad006431aa77f17e1b2788fda14f2
313
// // EmployeeService.swift // birthday-tracker-ios // // Created by Darvin on 18.03.2022. // import Foundation protocol EmployeeService { func edit(employee: Employee, completion: @escaping (Result<Void, Error>) -> Void) func load(id: Int, completion: @escaping (Result<Employee, Error>) -> Void) }
22.357143
86
0.693291
e0c573ca411cc4c1a2d23a8ee9baba0f0271c726
8,526
// // Checker.swift // LocalizationChecker // // Created by Adrian Ziemecki on 09/11/2017. // Copyright © 2017 Cybercom. All rights reserved. // import Foundation class Checker { static let quotationMark = "\"" static let commentMark = "//" static let localizedMark = "localizedString(\"" private let configuration: Configuration private var usedStringVars = [String]() private var localizations = [StringsLocalization]() private var output: String = "" private var inputFilename: String { return "\(configuration.inputFilename).\(Configuration.inputExtension)" } private var stringsFilename: String { return "\(configuration.localizableFilename).\(Configuration.localizableExtension)" } private var outputFilename: String { return "\(configuration.outputFilename).\(Configuration.outputExtension)" } init(configuration: Configuration) { self.configuration = configuration } func check() { guard let inputFile = inputFileUrl(forPath: configuration.inputFolder) else { return } guard let inputData = stringFromFile(inputFile) else { return } usedStringVars = getUsedStrings(from: inputData) let localizableStrings = stringsUrls(forPath: configuration.inputFolder) localizations = getLocalizations(from: localizableStrings) lookForMissingStrings() saveOutput() } } // Load files extension Checker { private func inputFileUrl(forPath path: String) -> URL? { let pathUrl = URL(fileURLWithPath: path, isDirectory: true) let fileManager = FileManager.default let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles] let enumerator = fileManager.enumerator(at: pathUrl, includingPropertiesForKeys: nil, options: options, errorHandler: {(url, error) -> Bool in return true }) if let enumerator = enumerator { while let path = enumerator.nextObject() as? URL { if path.lastPathComponent == inputFilename { return path } } } print("Could not find input file: \(inputFilename)") return nil } private func stringsUrls(forPath path: String) -> [URL] { var urls: [URL] = [] let pathUrl = URL(fileURLWithPath: path, isDirectory: true) let fileManager = FileManager.default let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles] let enumerator = fileManager.enumerator(at: pathUrl, includingPropertiesForKeys: nil, options: options, errorHandler: {(url, error) -> Bool in return true }) if let enumerator = enumerator { while let path = enumerator.nextObject() as? URL { if path.lastPathComponent == stringsFilename { urls.append(path) } } } return urls } // Read file as String private func stringFromFile(_ filePath: URL) -> String? { guard let data = try? String(contentsOf: filePath) else { print("Could not load file \(filePath)") return nil } return data } // Split multiline String into an array of single line Strings private func splitStringByNewLines(_ data: String) -> [String] { var lines = [String]() data.enumerateLines { (line, _) in lines.append(line) } return lines } } // Get localization vars used in input file extension Checker { private func getUsedStrings(from data: String) -> [String] { var usedStrings = [String]() let dataLines = splitStringByNewLines(data) for line in dataLines { guard let string = usedStringsGetQuotation(from: line as NSString) else { continue } usedStrings.append(string) } return usedStrings } private func usedStringsGetQuotation(from text: NSString) -> String? { let rangeForFirstQM = NSMakeRange(0, text.length) let firstQMRange = text.range(of: Checker.localizedMark, options: [], range: rangeForFirstQM, locale: nil) guard firstQMRange.location < Int.max else { return nil } let firstQMRangeEnd = firstQMRange.location + firstQMRange.length let rangeForSecondQM = NSMakeRange(firstQMRangeEnd, text.length - firstQMRangeEnd) let secondQMRange = text.range(of: Checker.quotationMark, options: [], range: rangeForSecondQM, locale: nil) guard secondQMRange.location < Int.max else { return nil } let quotation = text.substring(with: NSMakeRange(firstQMRangeEnd, secondQMRange.location - firstQMRangeEnd)) return quotation } } // Get localizations from .strings files extension Checker { private func getLocalizations(from urls: [URL]) -> [StringsLocalization] { var localizations = [StringsLocalization]() for url in urls { guard let data = stringFromFile(url) else { continue } let dataLines = splitStringByNewLines(data) let localizables = getLocalizables(from: dataLines) let stringsLocalization = StringsLocalization(filePath: url, strings: localizables) localizations.append(stringsLocalization) } return localizations } //TODO: Basic looking for vars, might need updating in the future. private func getLocalizables(from data: [String]) -> [String] { var parsedLocalizables = [String]() for line in data where !localizablesIsCommentLineOnly(line: line as NSString) { guard let variable = localizablesGetQuotation(from: line as NSString) else { continue } parsedLocalizables.append(variable) } return parsedLocalizables } private func localizablesGetQuotation(from text: NSString) -> String? { let rangeForFirstQM = NSMakeRange(0, text.length) let firstQMRange = text.range(of: Checker.quotationMark, options: [], range: rangeForFirstQM, locale: nil) guard firstQMRange.location < Int.max else { return nil } let firstQMRangeEnd = firstQMRange.location + firstQMRange.length let rangeForSecondQM = NSMakeRange(firstQMRangeEnd, text.length - firstQMRangeEnd) let secondQMRange = text.range(of: Checker.quotationMark, options: [], range: rangeForSecondQM, locale: nil) guard secondQMRange.location < Int.max else { return nil } let quotation = text.substring(with: NSMakeRange(firstQMRangeEnd, secondQMRange.location - firstQMRangeEnd)) return quotation } private func localizablesIsCommentLineOnly(line: NSString) -> Bool { guard line.contains(Checker.commentMark) else { return false } let commentRange = line.range(of: Checker.commentMark) let quotationRange = line.range(of: Checker.quotationMark) return commentRange.location < quotationRange.location } } // Look for missing vars in .strings file extension Checker { func lookForMissingStrings() { for (index, localization) in localizations.enumerated() { for usedStringVar in usedStringVars where !localization.strings.contains(usedStringVar) { localizations[index].missingStrings.append(usedStringVar) } } } } // Save missing vars to output file extension Checker { private func saveOutput() { var outputString = "" for localization in localizations where !localization.missingStrings.isEmpty { let missingVars = localization.missingStrings.reduce("") { return $0+"\n"+$1 } let missingOutput = "File:\n\(localization.filePath.path)\n\nMissing vars:\(missingVars)\n=====\n\n" outputString.append(missingOutput) } let directoryUrl = URL(fileURLWithPath: configuration.outputFolder) try? FileManager.default.createDirectory(at: directoryUrl, withIntermediateDirectories: true, attributes: nil) let outputFileUrl = directoryUrl.appendingPathComponent(configuration.outputFilename).appendingPathExtension(Configuration.outputExtension) if configuration.verboseFlag { print(outputString) } do { try outputString.write(to: outputFileUrl, atomically: true, encoding: .utf8) print("Output saved to: \(outputFileUrl)") } catch { print("Failed to save output to: \(outputFileUrl)") } } }
41.188406
150
0.663148
e415ae69e6a1a89a1ea1ade59391a0e8390fb04d
8,073
// // XLCrossLineLayer.swift // behoo // // Created by 夏磊 on 2018/8/24. // Copyright © 2018年 behoo. All rights reserved. // import UIKit /// 十字线layer class XLCrossLineLayer: CAShapeLayer { var theme = XLKLineStyle() var topChartHeight: CGFloat { get { return frame.height - theme.topTextHeight - theme.midTextHeight - theme.bottomChartHeight - theme.timeTextHeight } } /// 十字线 lazy var corssLineLayer: XLCAShapeLayer = { let line = XLCAShapeLayer() line.lineWidth = self.theme.corssLineWidth line.strokeColor = UIColor(red:1, green:1, blue:1, alpha:0.6).cgColor line.fillColor = UIColor(red:1, green:1, blue:1, alpha:0.6).cgColor return line }() /// Y轴标签 lazy var yMarkLayer: XLCAShapeLayer = { let yMarkLayer = XLCAShapeLayer() yMarkLayer.backgroundColor = self.theme.crossBgColor.cgColor yMarkLayer.borderColor = self.theme.crossBorderColor yMarkLayer.borderWidth = self.theme.frameWidth yMarkLayer.cornerRadius = 2 yMarkLayer.contentsScale = UIScreen.main.scale yMarkLayer.addSublayer(self.yMarkTextLayer) return yMarkLayer }() /// Y轴文字 lazy var yMarkTextLayer: XLCATextLayer = { let yMarkTextLayer = XLCATextLayer() yMarkTextLayer.fontSize = 10 yMarkTextLayer.foregroundColor = UIColor.white.cgColor yMarkTextLayer.backgroundColor = UIColor.clear.cgColor yMarkTextLayer.alignmentMode = .center yMarkTextLayer.contentsScale = UIScreen.main.scale return yMarkTextLayer }() /// time标签 lazy var timeMarkLayer: XLCAShapeLayer = { let timeMarkLayer = XLCAShapeLayer() timeMarkLayer.backgroundColor = self.theme.crossBgColor.cgColor timeMarkLayer.borderColor = self.theme.crossBorderColor timeMarkLayer.borderWidth = self.theme.frameWidth timeMarkLayer.cornerRadius = 2 timeMarkLayer.contentsScale = UIScreen.main.scale timeMarkLayer.addSublayer(self.timeMarkTextLayer) return timeMarkLayer }() /// time文字 lazy var timeMarkTextLayer: XLCATextLayer = { let timeMarkTextLayer = XLCATextLayer() timeMarkTextLayer.fontSize = 10 timeMarkTextLayer.foregroundColor = UIColor.white.cgColor timeMarkTextLayer.backgroundColor = UIColor.clear.cgColor timeMarkTextLayer.alignmentMode = .center timeMarkTextLayer.contentsScale = UIScreen.main.scale return timeMarkTextLayer }() /// 中心圆点 lazy var circleBigLayer: XLCAShapeLayer = { let circleBigLayer = XLCAShapeLayer() circleBigLayer.cornerRadius = self.theme.crossCircleWidth * 0.5 circleBigLayer.backgroundColor = UIColor.white.cgColor return circleBigLayer }() lazy var circleMidLayer: XLCAShapeLayer = { let circleMidLayer = XLCAShapeLayer() circleMidLayer.cornerRadius = (self.theme.crossCircleWidth - 2) * 0.5 circleMidLayer.backgroundColor = UIColor.xlChart.color(rgba: "#243245").cgColor return circleMidLayer }() lazy var circleSmallLayer: XLCAShapeLayer = { let circleSmallLayer = XLCAShapeLayer() circleSmallLayer.cornerRadius = (self.theme.crossCircleWidth - 4) * 0.5 circleSmallLayer.backgroundColor = UIColor.white.cgColor return circleSmallLayer }() override init() { super.init() isHidden = true addSublayer(corssLineLayer) addSublayer(circleBigLayer) addSublayer(circleMidLayer) addSublayer(circleSmallLayer) addSublayer(yMarkLayer) addSublayer(timeMarkLayer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func moveCrossLineLayer(touchNum: CGFloat?, touchPoint: CGPoint, pricePoint: CGPoint, volumePoint: CGPoint, model: XLKLineModel?, secondString: String?, dateType: XLKLineDateType) { guard let model = model else { return } let linePath = UIBezierPath() // 竖线 linePath.move(to: CGPoint(x: pricePoint.x, y: theme.topTextHeight)) linePath.addLine(to: CGPoint(x: pricePoint.x, y: theme.topTextHeight + topChartHeight)) linePath.move(to: CGPoint(x: pricePoint.x, y: theme.topTextHeight + topChartHeight + theme.midTextHeight)) linePath.addLine(to: CGPoint(x: pricePoint.x, y: frame.height - theme.timeTextHeight)) let xlineTop = touchPoint.y // 横线 if touchNum != nil { linePath.move(to: CGPoint(x: 0, y: xlineTop)) linePath.addLine(to: CGPoint(x: frame.width, y: xlineTop)) // 圆 var circleWidth: CGFloat = theme.crossCircleWidth circleBigLayer.frame = CGRect(x: pricePoint.x - circleWidth*0.5, y: xlineTop - circleWidth*0.5, width: circleWidth, height: circleWidth) circleWidth = circleWidth - 2 circleMidLayer.frame = CGRect(x: pricePoint.x - circleWidth*0.5, y: xlineTop - circleWidth*0.5, width: circleWidth, height: circleWidth) circleWidth = circleWidth - 2 circleSmallLayer.frame = CGRect(x: pricePoint.x - circleWidth*0.5, y: xlineTop - circleWidth*0.5, width: circleWidth, height: circleWidth) circleBigLayer.isHidden = false circleMidLayer.isHidden = false circleSmallLayer.isHidden = false }else { circleBigLayer.isHidden = true circleMidLayer.isHidden = true circleSmallLayer.isHidden = true } corssLineLayer.path = linePath.cgPath // Y轴标签 var labelX: CGFloat = 0 var labelY: CGFloat = 0 if let touchNum = touchNum { var yMarkString = "" if secondString == KLINEVOL { yMarkString = touchNum.xlChart.kLineVolNumber() }else { yMarkString = touchNum.xlChart.kLinePriceNumber() } let yMarkStringSize = theme.getCrossTextSize(text: yMarkString) labelX = 0 + 2 labelY = xlineTop - yMarkStringSize.height * 0.5 if labelY <= theme.topTextHeight { labelY = theme.topTextHeight } let maxY = frame.height - theme.timeTextHeight - yMarkStringSize.height if labelY >= maxY { labelY = maxY } yMarkTextLayer.string = yMarkString yMarkTextLayer.frame = CGRect(x: 6, y: 6, width: yMarkStringSize.width - 12, height: yMarkStringSize.height - 12) yMarkLayer.frame = CGRect(x: labelX, y: labelY, width: yMarkStringSize.width, height: yMarkStringSize.height) yMarkLayer.isHidden = false }else { yMarkLayer.isHidden = true } // time标签 var timeMarkString = "" if dateType == .min { timeMarkString = model.time.xlChart.toTimeString("MM/dd HH:mm") }else { timeMarkString = model.time.xlChart.toTimeString("YY/MM/dd") } let timeMarkStringSize = theme.getCrossTextSize(text: timeMarkString) let maxX = UIScreen.main.bounds.width - timeMarkStringSize.width labelX = pricePoint.x - timeMarkStringSize.width * 0.5 labelY = frame.height - theme.timeTextHeight if labelX > maxX { labelX = maxX } else if labelX < 0 { labelX = 0 } timeMarkTextLayer.string = timeMarkString timeMarkTextLayer.frame = CGRect(x: 6, y: 5.5, width: timeMarkStringSize.width - 12, height: timeMarkStringSize.height - 12) timeMarkLayer.frame = CGRect(x: labelX, y: labelY, width: timeMarkStringSize.width, height: timeMarkStringSize.height) isHidden = false } }
38.080189
192
0.627028
fb6631fd42671b2fdceee94e589461970ec97a89
345
// // Constants.swift // lakes // // Created by Vadim K on 12.09.2018. // Copyright © 2018 Vadim K. All rights reserved. // let GOOGLE_MAP_API_KEY = "YOUR API KEY" let STORYBOARD_NAME = "Main" let MAP_VIEW_CONTROLLER_ID = "MapViewController" let LAKE_VIEW_CONTROLLER_ID = "LakeViewController" let ASSEMBLY_LAKE_SPECIFICATION = "LakeById"
21.5625
50
0.744928
abf8b88bfb441d7009fb1fcc4d02321917444350
3,536
// // ImageDownloadRedirectHandler.swift // Longinus // // Created by Qitao Yang on 2020/8/30. // // Copyright (c) 2020 KittenYang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents and wraps a method for modifying request during an image download request redirection. public protocol ImageDownloadRedirectHandler { /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirection. You can modify the /// request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or /// something like url mapping. /// /// Usually, you pass an `ImageDownloadRedirectHandler` as the associated value of /// `LonginusImageOptionItem.redirectHandler` and use it as the `options` parameter in related methods. /// /// If you do nothing with the input `request` and return it as is, a downloading process will redirect with it. /// /// - Parameters: /// - operation: The current `ImageDownloadOperation` which triggers this redirect. /// - response: The response received during redirection. /// - newRequest: The request for redirection which can be modified. /// - completionHandler: A closure for being called with modified request. func handleHTTPRedirection( for operation: ImageDownloadOperation, response: HTTPURLResponse, newRequest: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) } /// A wrapper for creating an `ImageDownloadRedirectHandler` easier. /// This type conforms to `ImageDownloadRedirectHandler` and wraps a redirect request modify block. public struct AnyRedirectHandler: ImageDownloadRedirectHandler { let block: (ImageDownloadOperation, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void public func handleHTTPRedirection( for operation: ImageDownloadOperation, response: HTTPURLResponse, newRequest: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { block(operation, response, newRequest, completionHandler) } /// Creates a value of `ImageDownloadRedirectHandler` which runs `modify` block. public init(handle: @escaping (ImageDownloadOperation, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void) { block = handle } }
47.783784
121
0.730769
abcc38699483423b15f363097799c565d180ff00
1,010
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftGCM", products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SwiftGCM", targets: ["SwiftGCM"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "SwiftGCM", dependencies: []), .testTarget( name: "SwiftGCMTests", dependencies: ["SwiftGCM"]), ] )
34.827586
117
0.616832
4b7c11bdf89169622643737ee403ab8a05f70cbc
998
// // ViewController.swift // YourStory // // Created by Minna on 08/04/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var storyLabel: UILabel! @IBOutlet weak var choice1Button: UIButton! @IBOutlet weak var choice2Button: UIButton! override func viewDidLoad() { super.viewDidLoad() updateUI() } var storyBrain = StoryBrain() @IBAction func choiceButtonPressed(_ sender: UIButton) { let choiceSelected = sender.currentTitle! storyBrain.nextStoryline(for: choiceSelected) Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false) } @objc func updateUI() { storyLabel.text = storyBrain.getStoryText() choice1Button.setTitle(storyBrain.getChoiceText()[0], for: .normal) choice2Button.setTitle(storyBrain.getChoiceText()[1], for: .normal) } }
23.209302
123
0.642285
fb1bcd9437ac79ba8a5fb06c00c217d0434c23d1
8,695
// // MagicianEntity.swift // glide Demo // // Copyright (c) 2019 cocoatoucher user on github.com (https://github.com/cocoatoucher/) // // 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 GlideEngine import CoreGraphics import Foundation class MagicianEntity: GlideEntity { let colliderSize = CGSize(width: 24, height: 28) var couldShoot: Bool = false init(initialNodePosition: CGPoint) { super.init(initialNodePosition: initialNodePosition, positionOffset: CGPoint(size: colliderSize / 2)) } override func setup() { name = "Magician" let spriteNodeComponent = SpriteNodeComponent(nodeSize: colliderSize) spriteNodeComponent.zPositionContainer = DemoZPositionContainer.npcs addComponent(spriteNodeComponent) let colliderComponent = ColliderComponent(categoryMask: DemoCategoryMask.npc, size: colliderSize, offset: .zero, leftHitPointsOffsets: (10, 10), rightHitPointsOffsets: (10, 10), topHitPointsOffsets: (5, 5), bottomHitPointsOffsets: (5, 5)) addComponent(colliderComponent) var kinematicsBodyConfiguration = KinematicsBodyComponent.sharedConfiguration kinematicsBodyConfiguration.maximumHorizontalVelocity = 3.0 let kinematicsBodyComponent = KinematicsBodyComponent(configuration: kinematicsBodyConfiguration) addComponent(kinematicsBodyComponent) var horizontalMovementConfiguration = HorizontalMovementComponent.sharedConfiguration horizontalMovementConfiguration.acceleration = 3.0 horizontalMovementConfiguration.deceleration = 5.0 let horizontalMovementComponent = HorizontalMovementComponent(movementStyle: .accelerated, configuration: horizontalMovementConfiguration) addComponent(horizontalMovementComponent) let moveComponent = SelfMoveComponent(movementAxes: .horizontal) addComponent(moveComponent) let colliderTileHolderComponent = ColliderTileHolderComponent() addComponent(colliderTileHolderComponent) setupShooterComponents() setupTextureAnimations() } func setupShooterComponents() { let shootOnObserve = SelfShootOnObserveComponent(entityTagsToShoot: ["Player"]) addComponent(shootOnObserve) let projectileShooterComponent = ProjectileShooterComponent(projectileTemplate: BulletEntity.self, projectilePropertiesCallback: { [weak self, weak shootOnObserve] in guard let self = self else { return nil } guard let shootsAtEntity = shootOnObserve?.shootsAtEntity else { return nil } guard let scene = self.scene else { return nil } let angle = self.transform.currentPosition.angleOfLine(to: shootsAtEntity.transform.currentPosition) if angle > -90 && angle < 90 { self.transform.headingDirection = .left } else { self.transform.headingDirection = .right } guard angle < 0 else { return nil } self.couldShoot = true let properties = ProjectileShootingProperties(position: self.transform.node.convert(.zero, to: scene), sourceAngle: angle) return properties }) addComponent(projectileShooterComponent) } func setupTextureAnimations() { let timePerFrame: TimeInterval = 0.1 let animationSize = CGSize(width: 64, height: 64) let animationOffset = CGPoint(x: 0, y: 2) // Idle let idleAction = TextureAnimation.Action(textureFormat: "shooter_idle_%d", numberOfFrames: 12, timePerFrame: timePerFrame, shouldGenerateNormalMaps: false) let idleAnimation = TextureAnimation(triggerName: "Idle", offset: animationOffset, size: animationSize, action: idleAction, loops: true) let animatorComponent = TextureAnimatorComponent(entryAnimation: idleAnimation) addComponent(animatorComponent) // Walk let walkAction = TextureAnimation.Action(textureFormat: "shooter_walk_%d", numberOfFrames: 12, timePerFrame: timePerFrame, shouldGenerateNormalMaps: false) let walkAnimation = TextureAnimation(triggerName: "Walk", offset: animationOffset, size: animationSize, action: walkAction, loops: true) animatorComponent.addAnimation(walkAnimation) // Shoot let attackAction = TextureAnimation.Action(textureFormat: "shooter_attack_%d", numberOfFrames: 12, timePerFrame: 0.05, shouldGenerateNormalMaps: false) let attackAnimation = TextureAnimation(triggerName: "Attack", offset: animationOffset, size: animationSize, action: attackAction, loops: false) attackAnimation.addTriggerToInterruptNonLoopingAnimation("Attack") animatorComponent.addAnimation(attackAnimation) } override func didUpdateComponents(currentTime: TimeInterval, deltaTime: TimeInterval) { let textureAnimator = component(ofType: TextureAnimatorComponent.self) if component(ofType: ProjectileShooterComponent.self)?.shoots == true { if couldShoot { textureAnimator?.enableAnimation(with: "Attack") } else { textureAnimator?.enableAnimation(with: "Idle") } return } else if component(ofType: SelfSpawnEntitiesComponent.self)?.didSpawn == true { textureAnimator?.enableAnimation(with: "Attack") return } guard let kinematicsBody = component(ofType: KinematicsBodyComponent.self) else { return } if kinematicsBody.velocity.dx < 0 { transform.headingDirection = .left textureAnimator?.enableAnimation(with: "Walk") } else if kinematicsBody.velocity.dx > 0 { transform.headingDirection = .right textureAnimator?.enableAnimation(with: "Walk") } else { textureAnimator?.enableAnimation(with: "Idle") } } override func resetStates(currentTime: TimeInterval, deltaTime: TimeInterval) { couldShoot = false } }
46.005291
174
0.579643
71496b760139601694f17830863c38a38818c93e
825
// // Macropad_ToolboxUITestsLaunchTests.swift // Macropad ToolboxUITests // // Created by Danilo Campos on 12/18/21. // import XCTest class Macropad_ToolboxUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
25
88
0.682424
4b9292e1bfa9821f98f40b5a0fa86c14516f8438
331
// // ARComparisonScene.swift // MegaHack2018 // // Created by Vlad Bonta on 10/11/2018. // Copyright © 2018 Vlad Bonta. All rights reserved. // import Foundation import ARKit class ARComparisonScene: NSObject { var phones: [ARPhoneModel] = [] var phoneScenes: [String] = [] var comparisonSceneNode = SCNNode() }
19.470588
53
0.688822
2143353681b3ec24b094ae5b0d198e7f8f4d1049
265
// // FirebirdDatabaseInformation.swift // // // Created by ugo cottin on 26/03/2022. // import fbclient public protocol FirebirdDatabaseInformation: CustomStringConvertible { typealias RawValue = db_info_types.RawValue var rawValue: RawValue { get } }
16.5625
70
0.74717
0a645db4a501dfc30a679ebb4bc1f90e41ddbc47
131,162
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %gyb %s -o %t/main.swift // RUN: if [ %target-runtime == "objc" ]; then \ // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: else \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Dictionary -Xfrontend -disable-access-control; \ // RUN: fi // // RUN: %line-directive %t/main.swift -- %target-run %t/Dictionary // REQUIRES: executable_test #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) import Darwin #else import Glibc #endif import StdlibUnittest import StdlibCollectionUnittest #if _runtime(_ObjC) import Foundation import StdlibUnittestFoundationExtras #endif extension Dictionary { func _rawIdentifier() -> Int { return unsafeBitCast(self, to: Int.self) } } // Check that the generic parameters are called 'Key' and 'Value'. protocol TestProtocol1 {} extension Dictionary where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIndex where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } extension DictionaryIterator where Key : TestProtocol1, Value : TestProtocol1 { var _keyValueAreTestProtocol1: Bool { fatalError("not implemented") } } var DictionaryTestSuite = TestSuite("Dictionary") DictionaryTestSuite.test("AssociatedTypes") { typealias Collection = Dictionary<MinimalHashableValue, OpaqueValue<Int>> expectCollectionAssociatedTypes( collectionType: Collection.self, iteratorType: DictionaryIterator<MinimalHashableValue, OpaqueValue<Int>>.self, subSequenceType: Slice<Collection>.self, indexType: DictionaryIndex<MinimalHashableValue, OpaqueValue<Int>>.self, indexDistanceType: Int.self, indicesType: DefaultIndices<Collection>.self) } DictionaryTestSuite.test("sizeof") { var dict = [1: "meow", 2: "meow"] #if arch(i386) || arch(arm) expectEqual(4, MemoryLayout.size(ofValue: dict)) #else expectEqual(8, MemoryLayout.size(ofValue: dict)) #endif } DictionaryTestSuite.test("valueDestruction") { var d1 = Dictionary<Int, TestValueTy>() for i in 100...110 { d1[i] = TestValueTy(i) } var d2 = Dictionary<TestKeyTy, TestValueTy>() for i in 100...110 { d2[TestKeyTy(i)] = TestValueTy(i) } } DictionaryTestSuite.test("COW.Smoke") { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) var identity1 = d1._rawIdentifier() d1[TestKeyTy(10)] = TestValueTy(1010) d1[TestKeyTy(20)] = TestValueTy(1020) d1[TestKeyTy(30)] = TestValueTy(1030) var d2 = d1 _fixLifetime(d2) assert(identity1 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 != d2._rawIdentifier()) d1[TestKeyTy(50)] = TestValueTy(1050) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } func getCOWFastDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } func getCOWSlowDictionary() -> Dictionary<TestKeyTy, TestValueTy> { var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestValueTy(1010) d[TestKeyTy(20)] = TestValueTy(1020) d[TestKeyTy(30)] = TestValueTy(1030) return d } func getCOWSlowEquatableDictionary() -> Dictionary<TestKeyTy, TestEquatableValueTy> { var d = Dictionary<TestKeyTy, TestEquatableValueTy>(minimumCapacity: 10) d[TestKeyTy(10)] = TestEquatableValueTy(1010) d[TestKeyTy(20)] = TestEquatableValueTy(1020) d[TestKeyTy(30)] = TestEquatableValueTy(1030) return d } DictionaryTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[40] = 2040 assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1 != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var startIndex = d.startIndex let empty = startIndex == d.endIndex assert((d.startIndex < d.endIndex) == !empty) assert(d.startIndex <= d.endIndex) assert((d.startIndex >= d.endIndex) == empty) assert(!(d.startIndex > d.endIndex)) assert(identity1 == d._rawIdentifier()) assert(d[startIndex].1.value != 0) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.SubscriptWithKeyDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() assert(d[10]! == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[40] = 2040 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Overwrite a value in existing binding. d[10] = 2010 assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[10]! == 2010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Delete an existing key. d[10] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) // Try to delete a key that does not exist. d[42] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 2040) do { var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectNil(d2[MinimalHashableValue(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Slow.SubscriptWithKeyDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() assert(d[TestKeyTy(10)]!.value == 1010) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestKeyTy(40)] = TestValueTy(2040) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 1010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. d[TestKeyTy(10)] = TestValueTy(2010) assert(identity1 == d._rawIdentifier()) assert(d.count == 4) assert(d[TestKeyTy(10)]!.value == 2010) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Delete an existing key. d[TestKeyTy(10)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) // Try to delete a key that does not exist. d[TestKeyTy(42)] = nil assert(identity1 == d._rawIdentifier()) assert(d.count == 3) assert(d[TestKeyTy(20)]!.value == 1020) assert(d[TestKeyTy(30)]!.value == 1030) assert(d[TestKeyTy(40)]!.value == 2040) do { var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectNil(d2[MinimalHashableClass(42)]) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Fast.UpdateValueForKeyDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(2040, forKey: 40) == .none) assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(2010, forKey: 10)! == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 2010) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(2040, forKey: 40) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == .none) assert(d2.count == 4) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(2010, forKey: 10) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.AddDoesNotReallocate") { do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() // Insert a new key-value pair. assert(d1.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) == nil) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(40)]!.value == 2040) // Overwrite a value in existing binding. assert(d1.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(d1.count == 4) assert(d1[TestKeyTy(10)]!.value == 2010) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Insert a new key-value pair. d2.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d1[TestKeyTy(40)] == nil) assert(d2.count == 4) assert(d2[TestKeyTy(10)]!.value == 1010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) assert(d2[TestKeyTy(40)]!.value == 2040) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Overwrite a value in existing binding. d2.updateValue(TestValueTy(2010), forKey: TestKeyTy(10)) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d1[TestKeyTy(20)]!.value == 1020) assert(d1[TestKeyTy(30)]!.value == 1030) assert(d2.count == 3) assert(d2[TestKeyTy(10)]!.value == 2010) assert(d2[TestKeyTy(20)]!.value == 1020) assert(d2[TestKeyTy(30)]!.value == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeSequenceDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([(10, 2010), (60, 2060)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([(30, 2030), (70, 2070)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([(40, 3040), (80, 3080)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([(40, 2040), (50, 2050)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([(10, 2010)]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([(10, 2010)]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.MergeDictionaryDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // Merge some new values. d1.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 5) assert(d1[50]! == 2050) // Merge and overwrite some existing values. d1.merge([10: 2010, 60: 2060]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 6) assert(d1[10]! == 2010) assert(d1[60]! == 2060) // Merge, keeping existing values. d1.merge([30: 2030, 70: 2070]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(d1.count == 7) assert(d1[30]! == 1030) assert(d1[70]! == 2070) let d2 = d1.merging([40: 3040, 80: 3080]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.count == 8) assert(d2[40]! == 3040) assert(d2[80]! == 3080) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge some new values. d2.merge([40: 2040, 50: 2050]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d1[40] == nil) assert(d2.count == 5) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) assert(d2[40]! == 2040) assert(d2[50]! == 2050) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge and overwrite some existing values. d2.merge([10: 2010]) { _, y in y } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 2010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Merge, keeping existing values. d2.merge([10: 2010]) { x, _ in x } assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d1[20]! == 1020) assert(d1[30]! == 1030) assert(d2.count == 3) assert(d2[10]! == 1010) assert(d2[20]! == 1020) assert(d2[30]! == 1030) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() // No mutation on access. assert(d1[10, default: 0] + 1 == 1011) assert(d1[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1010) // Increment existing in place. d1[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[10]! == 1011) // Add incremented default value. d1[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(d1[40]! == 1) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // No mutation on access. assert(d2[10, default: 0] + 1 == 1011) assert(d2[40, default: 0] + 1 == 1) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Increment existing in place. d2[10, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[10]! == 1010) assert(d2[10]! == 1011) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) // Add incremented default value. d2[40, default: 0] += 1 assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d1[40] == nil) assert(d2[40]! == 1) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.IndexForKeyDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) var foundIndex2 = d.index(forKey: 10)! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = d.index(forKey: 1111) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableValue(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Slow.IndexForKeyDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() // Find an existing key. do { var foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) var foundIndex2 = d.index(forKey: TestKeyTy(10))! assert(foundIndex1 == foundIndex2) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = d.index(forKey: TestKeyTy(1111)) assert(foundIndex1 == nil) assert(identity1 == d._rawIdentifier()) } do { var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectNil(d2.index(forKey: MinimalHashableClass(42))) // If the dictionary is empty, we shouldn't be computing the hash value of // the provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } DictionaryTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") { do { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() let foundIndex1 = d.index(forKey: 10)! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == 10) assert(d[foundIndex1].1 == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: 10) == nil) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var foundIndex1 = d2.index(forKey: 10)! assert(d2[foundIndex1].0 == 10) assert(d2[foundIndex1].1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) let removed = d2.remove(at: foundIndex1) assert(removed.0 == 10) assert(removed.1 == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: 10) == nil) } } DictionaryTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") { do { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var foundIndex1 = d.index(forKey: TestKeyTy(10))! assert(identity1 == d._rawIdentifier()) assert(d[foundIndex1].0 == TestKeyTy(10)) assert(d[foundIndex1].1.value == 1010) let removed = d.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d._rawIdentifier()) assert(d.index(forKey: TestKeyTy(10)) == nil) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) var foundIndex1 = d2.index(forKey: TestKeyTy(10))! assert(d2[foundIndex1].0 == TestKeyTy(10)) assert(d2[foundIndex1].1.value == 1010) let removed = d2.remove(at: foundIndex1) assert(removed.0 == TestKeyTy(10)) assert(removed.1.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) assert(d2.index(forKey: TestKeyTy(10)) == nil) } } DictionaryTestSuite.test("COW.Fast.RemoveValueForKeyDoesNotReallocate") { do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: 0) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: 10) assert(deleted! == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveValueForKeyDoesNotReallocate") { do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var deleted = d1.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) deleted = d1.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 var deleted = d2.removeValue(forKey: TestKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) deleted = d2.removeValue(forKey: TestKeyTy(10)) assert(deleted!.value == 1010) assert(identity1 == d1._rawIdentifier()) assert(identity1 != d2._rawIdentifier()) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") { do { var d = getCOWFastDictionary() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. var identity1 = d._rawIdentifier() assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[10] == nil) } do { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[10]! == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[10] == nil) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[10]! == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() let originalCapacity = d1._variantBuffer.asNative.capacity assert(d1.count == 3) assert(d1[10] == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[10]! == 1010) assert(d2._variantBuffer.asNative.capacity == originalCapacity) assert(d2.count == 0) assert(d2[10] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") { do { var d = getCOWSlowDictionary() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll() // We cannot assert that identity changed, since the new buffer of smaller // size can be allocated at the same address as the old one. var identity1 = d._rawIdentifier() assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() let originalCapacity = d._variantBuffer.asNative.capacity assert(d.count == 3) assert(d[TestKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity == originalCapacity) assert(d.count == 0) assert(d[TestKeyTy(10)] == nil) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } do { var d1 = getCOWSlowDictionary() var identity1 = d1._rawIdentifier() let originalCapacity = d1._variantBuffer.asNative.capacity assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity == originalCapacity) assert(d2.count == 0) assert(d2[TestKeyTy(10)] == nil) // Keep variables alive. _fixLifetime(d1) _fixLifetime(d2) } } DictionaryTestSuite.test("COW.Fast.CountDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") { var d = getCOWFastDictionary() var identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { pairs += [(key, value)] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.GenerateDoesNotReallocate") { var d = getCOWSlowDictionary() var identity1 = d._rawIdentifier() var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { // FIXME: This doesn't work (<rdar://problem/17751308> Can't += // with array literal of pairs) // pairs += [(key.value, value.value)] // FIXME: This doesn't work (<rdar://problem/17750582> generics over tuples) // pairs.append((key.value, value.value)) // FIXME: This doesn't work (<rdar://problem/17751359>) // pairs.append(key.value, value.value) let kv = (key.value, value.value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWFastDictionary() var identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[40] = 2040 assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") { var d1 = getCOWSlowEquatableDictionary() var identity1 = d1._rawIdentifier() var d2 = getCOWSlowEquatableDictionary() var identity2 = d2._rawIdentifier() assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestKeyTy(40)] = TestEquatableValueTy(2040) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } //===--- // Keys and Values collection tests. //===--- DictionaryTestSuite.test("COW.Fast.ValuesAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert([1010, 1020, 1030] == d1.values.sorted()) assert(identity1 == d1._rawIdentifier()) var d2 = d1 assert(identity1 == d2._rawIdentifier()) let i = d2.index(forKey: 10)! assert(d1.values[i] == 1010) assert(d1[i] == (10, 1010)) #if swift(>=4.0) d2.values[i] += 1 assert(d2.values[i] == 1011) assert(d2[10]! == 1011) assert(identity1 != d2._rawIdentifier()) #endif assert(d1[10]! == 1010) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.values), d1.values, stackTrace: SourceLocStack()) { $0 == $1 } } DictionaryTestSuite.test("COW.Fast.KeysAccessDoesNotReallocate") { var d1 = getCOWFastDictionary() var identity1 = d1._rawIdentifier() assert([10, 20, 30] == d1.keys.sorted()) let i = d1.index(forKey: 10)! assert(d1.keys[i] == 10) assert(d1[i] == (10, 1010)) assert(identity1 == d1._rawIdentifier()) checkCollection( Array(d1.keys), d1.keys, stackTrace: SourceLocStack()) { $0 == $1 } do { var d2: [MinimalHashableValue : Int] = [ MinimalHashableValue(10): 1010, MinimalHashableValue(20): 1020, MinimalHashableValue(30): 1030, MinimalHashableValue(40): 1040, MinimalHashableValue(50): 1050, MinimalHashableValue(60): 1060, MinimalHashableValue(70): 1070, MinimalHashableValue(80): 1080, MinimalHashableValue(90): 1090, ] // Find the last key in the dictionary var lastKey: MinimalHashableValue = d2.first!.key for i in d2.indices { lastKey = d2[i].key } // index(where:) - linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let j = d2.index(where: { (k, _) in k == lastKey })! expectGE(MinimalHashableValue.timesEqualEqualWasCalled, 8) // index(forKey:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let k = d2.index(forKey: lastKey)! expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) // keys.index(of:) - O(1) bucket + linear search MinimalHashableValue.timesEqualEqualWasCalled = 0 let l = d2.keys.index(of: lastKey)! #if swift(>=4.0) expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4) #endif expectEqual(j, k) expectEqual(k, l) } } //===--- // Native dictionary tests. //===--- func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) { var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d1[k1] = TestValueTy(1010) d1[k2] = TestValueTy(1020) d1[k3] = TestValueTy(1030) assert(d1[k1]!.value == 1010) assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k1] = nil assert(d1[k2]!.value == 1020) assert(d1[k3]!.value == 1030) d1[k2] = nil assert(d1[k3]!.value == 1030) d1[k3] = nil assert(d1.count == 0) } DictionaryTestSuite.test("deleteChainCollision") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 0) var k3 = TestKeyTy(value: 30, hashValue: 0) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainNoCollision") { var k1 = TestKeyTy(value: 10, hashValue: 0) var k2 = TestKeyTy(value: 20, hashValue: 1) var k3 = TestKeyTy(value: 30, hashValue: 2) helperDeleteThree(k1, k2, k3) } DictionaryTestSuite.test("deleteChainCollision2") { var k1_0 = TestKeyTy(value: 10, hashValue: 0) var k2_0 = TestKeyTy(value: 20, hashValue: 0) var k3_2 = TestKeyTy(value: 30, hashValue: 2) var k4_0 = TestKeyTy(value: 40, hashValue: 0) var k5_2 = TestKeyTy(value: 50, hashValue: 2) var k6_0 = TestKeyTy(value: 60, hashValue: 0) var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10) d[k1_0] = TestValueTy(1010) // in bucket 0 d[k2_0] = TestValueTy(1020) // in bucket 1 d[k3_2] = TestValueTy(1030) // in bucket 2 d[k4_0] = TestValueTy(1040) // in bucket 3 d[k5_2] = TestValueTy(1050) // in bucket 4 d[k6_0] = TestValueTy(1060) // in bucket 5 d[k3_2] = nil assert(d[k1_0]!.value == 1010) assert(d[k2_0]!.value == 1020) assert(d[k3_2] == nil) assert(d[k4_0]!.value == 1040) assert(d[k5_2]!.value == 1050) assert(d[k6_0]!.value == 1060) } func uniformRandom(_ max: Int) -> Int { #if os(Linux) // SR-685: Can't use arc4random on Linux return Int(random() % (max + 1)) #else return Int(arc4random_uniform(UInt32(max))) #endif } func pickRandom<T>(_ a: [T]) -> T { return a[uniformRandom(a.count)] } func product<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result } DictionaryTestSuite.test("deleteChainCollisionRandomized") .forEach(in: product(1...8, 0...5)) { (collisionChains, chainOverlap) in func check(_ d: Dictionary<TestKeyTy, TestValueTy>) { var keys = Array(d.keys) for i in 0..<keys.count { for j in 0..<i { assert(keys[i] != keys[j]) } } for k in keys { assert(d[k] != nil) } } let chainLength = 7 var knownKeys: [TestKeyTy] = [] func getKey(_ value: Int) -> TestKeyTy { for k in knownKeys { if k.value == value { return k } } let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains let k = TestKeyTy(value: value, hashValue: hashValue) knownKeys += [k] return k } var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 30) for i in 1..<300 { let key = getKey(uniformRandom(collisionChains * chainLength)) if uniformRandom(chainLength * 2) == 0 { d[key] = nil } else { d[key] = TestValueTy(key.value * 10) } check(d) } } DictionaryTestSuite.test("init(dictionaryLiteral:)") { do { var empty = Dictionary<Int, Int>() assert(empty.count == 0) assert(empty[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010)) assert(d.count == 1) assert(d[10]! == 1010) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020)) assert(d.count == 2) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030)) assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[1111] == nil) } do { var d = Dictionary(dictionaryLiteral: (10, 1010), (20, 1020), (30, 1030), (40, 1040)) assert(d.count == 4) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) assert(d[40]! == 1040) assert(d[1111] == nil) } do { var d: Dictionary<Int, Int> = [ 10: 1010, 20: 1020, 30: 1030 ] assert(d.count == 3) assert(d[10]! == 1010) assert(d[20]! == 1020) assert(d[30]! == 1030) } } DictionaryTestSuite.test("init(uniqueKeysWithValues:)") { do { var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (30, 1030)]) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary<Int, Int>(uniqueKeysWithValues: EmptyCollection<(Int, Int)>()) expectEqual(d.count, 0) expectNil(d[1111]) } do { expectCrashLater() var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (10, 2010)]) } } DictionaryTestSuite.test("init(_:uniquingKeysWith:)") { do { var d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)], uniquingKeysWith: min) expectEqual(d.count, 3) expectEqual(d[10]!, 1010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary( [(10, 1010), (20, 1020), (30, 1030), (10, 2010)] as [(Int, Int)], uniquingKeysWith: +) expectEqual(d.count, 3) expectEqual(d[10]!, 3020) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary([(10, 1010), (20, 1020), (30, 1030), (10, 2010)]) { (a, b) in Int("\(a)\(b)")! } expectEqual(d.count, 3) expectEqual(d[10]!, 10102010) expectEqual(d[20]!, 1020) expectEqual(d[30]!, 1030) expectNil(d[1111]) } do { var d = Dictionary([(10, 1010), (10, 2010), (10, 3010), (10, 4010)]) { $1 } expectEqual(d.count, 1) expectEqual(d[10]!, 4010) expectNil(d[1111]) } do { var d = Dictionary(EmptyCollection<(Int, Int)>(), uniquingKeysWith: min) expectEqual(d.count, 0) expectNil(d[1111]) } struct TE: Error {} do { // No duplicate keys, so no error thrown. var d1 = try Dictionary([(10, 1), (20, 2), (30, 3)]) { _ in throw TE() } expectEqual(d1.count, 3) // Duplicate keys, should throw error. var d2 = try Dictionary([(10, 1), (10, 2)]) { _ in throw TE() } assertionFailure() } catch { assert(error is TE) } } DictionaryTestSuite.test("init(grouping:by:)") { let r = 0..<10 let d1 = Dictionary(grouping: r, by: { $0 % 3 }) expectEqual(3, d1.count) expectEqual([0, 3, 6, 9], d1[0]!) expectEqual([1, 4, 7], d1[1]!) expectEqual([2, 5, 8], d1[2]!) let d2 = Dictionary(grouping: r, by: { $0 }) expectEqual(10, d2.count) let d3 = Dictionary(grouping: 0..<0, by: { $0 }) expectEqual(0, d3.count) } DictionaryTestSuite.test("mapValues(_:)") { let d1 = [10: 1010, 20: 1020, 30: 1030] let d2 = d1.mapValues(String.init) expectEqual(d1.count, d2.count) expectEqual(d1.keys.first, d2.keys.first) for (key, value) in d1 { expectEqual(String(d1[key]!), d2[key]!) } do { var d3: [MinimalHashableValue : Int] = Dictionary( uniqueKeysWithValues: d1.lazy.map { (MinimalHashableValue($0), $1) }) expectEqual(d3.count, 3) MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 // Calling mapValues shouldn't ever recalculate any hashes. let d4 = d3.mapValues(String.init) expectEqual(d4.count, d3.count) expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } DictionaryTestSuite.test("capacity/reserveCapacity(_:)") { var d1 = [10: 1010, 20: 1020, 30: 1030] expectEqual(3, d1.capacity) d1[40] = 1040 expectEqual(6, d1.capacity) // Reserving new capacity jumps up to next limit. d1.reserveCapacity(7) expectEqual(12, d1.capacity) // Can reserve right up to a limit. d1.reserveCapacity(24) expectEqual(24, d1.capacity) // Fill up to the limit, no reallocation. d1.merge(stride(from: 50, through: 240, by: 10).lazy.map { ($0, 1000 + $0) }, uniquingKeysWith: { _ in fatalError() }) expectEqual(24, d1.count) expectEqual(24, d1.capacity) d1[250] = 1250 expectEqual(48, d1.capacity) } #if _runtime(_ObjC) //===--- // NSDictionary -> Dictionary bridging tests. //===--- func getAsNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsEquatableNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCEquatableValueTy($0) }) // Return an `NSMutableDictionary` to make sure that it has a unique // pointer identity. return NSMutableDictionary(objects: values, forKeys: keys) } func getAsNSMutableDictionary(_ d: Dictionary<Int, Int>) -> NSMutableDictionary { let keys = Array(d.keys.map { TestObjCKeyTy($0) }) let values = Array(d.values.map { TestObjCValueTy($0) }) return NSMutableDictionary(objects: values, forKeys: keys) } func getBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, AnyObject> { let nsd = getAsNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedVerbatimDictionaryAndNSMutableDictionary() -> (Dictionary<NSObject, AnyObject>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (convertNSDictionaryToDictionary(nsd), nsd) } func getBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030 ]) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getAsNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getBridgedNonverbatimDictionaryAndNSMutableDictionary() -> (Dictionary<TestBridgedKeyTy, TestBridgedValueTy>, NSMutableDictionary) { let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030]) return (Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self), nsd) } func getBridgedVerbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, TestObjCEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return convertNSDictionaryToDictionary(nsd) } func getBridgedNonverbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedEquatableValueTy> { let nsd = getAsEquatableNSDictionary(d) return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } func getHugeBridgedVerbatimDictionaryHelper() -> NSDictionary { let keys = (1...32).map { TestObjCKeyTy($0) } let values = (1...32).map { TestObjCValueTy(1000 + $0) } return NSMutableDictionary(objects: values, forKeys: keys) } func getHugeBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return convertNSDictionaryToDictionary(nsd) } func getHugeBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd = getHugeBridgedVerbatimDictionaryHelper() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } /// A mock dictionary that stores its keys and values in parallel arrays, which /// allows it to return inner pointers to the keys array in fast enumeration. @objc class ParallelArrayDictionary : NSDictionary { struct Keys { var key0: AnyObject = TestObjCKeyTy(10) var key1: AnyObject = TestObjCKeyTy(20) var key2: AnyObject = TestObjCKeyTy(30) var key3: AnyObject = TestObjCKeyTy(40) } var keys = [ Keys() ] var value: AnyObject = TestObjCValueTy(1111) override init() { super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by ParallelArrayDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary does not produce a CoreFoundation // object. return self } override func countByEnumerating( with state: UnsafeMutablePointer<NSFastEnumerationState>, objects: AutoreleasingUnsafeMutablePointer<AnyObject?>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 theState.itemsPtr = AutoreleasingUnsafeMutablePointer(keys._baseAddressIfContiguous) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr state.pointee = theState return 4 } return 0 } override func object(forKey aKey: Any) -> Any? { return value } override var count: Int { return 4 } } func getParallelArrayBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> { let nsd: NSDictionary = ParallelArrayDictionary() return convertNSDictionaryToDictionary(nsd) } func getParallelArrayBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { let nsd: NSDictionary = ParallelArrayDictionary() return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self) } @objc class CustomImmutableNSDictionary : NSDictionary { init(_privateInit: ()) { super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by CustomImmutableNSDictionary") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { CustomImmutableNSDictionary.timesCopyWithZoneWasCalled += 1 return self } override func object(forKey aKey: Any) -> Any? { CustomImmutableNSDictionary.timesObjectForKeyWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).object(forKey: aKey) } override func keyEnumerator() -> NSEnumerator { CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled += 1 return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).keyEnumerator() } override var count: Int { CustomImmutableNSDictionary.timesCountWasCalled += 1 return 3 } static var timesCopyWithZoneWasCalled = 0 static var timesObjectForKeyWasCalled = 0 static var timesKeyEnumeratorWasCalled = 0 static var timesCountWasCalled = 0 } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DictionaryIsCopied") { var (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestObjCKeyTy(10)] != nil) nsd.removeObject(forKey: TestObjCKeyTy(10)) assert(nsd[TestObjCKeyTy(10)] == nil) // Find an existing key, again. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") { var (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } // Delete the key from the NSMutableDictionary. assert(nsd[TestBridgedKeyTy(10) as NSCopying] != nil) nsd.removeObject(forKey: TestBridgedKeyTy(10) as NSCopying) assert(nsd[TestBridgedKeyTy(10) as NSCopying] == nil) // Find an existing key, again. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") { var nsd: NSDictionary = autoreleasepool { NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) } var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.NSDictionaryIsCopied") { var nsd: NSDictionary = autoreleasepool { NSDictionary(dictionary: getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])) } var d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ImmutableDictionaryIsRetained") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 var d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd) expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableDictionaryIsCopied") { var nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ()) CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0 CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0 CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0 CustomImmutableNSDictionary.timesCountWasCalled = 0 TestBridgedValueTy.bridgeOperations = 0 var d: [TestBridgedKeyTy : TestBridgedValueTy] = convertNSDictionaryToDictionary(nsd) expectEqual(0, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled) expectEqual(3, CustomImmutableNSDictionary.timesObjectForKeyWasCalled) expectEqual(1, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled) expectNotEqual(0, CustomImmutableNSDictionary.timesCountWasCalled) expectEqual(3, TestBridgedValueTy.bridgeOperations) var bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d) expectNotEqual( unsafeBitCast(nsd, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nsd) _fixLifetime(d) _fixLifetime(bridgedBack) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.IndexForKey") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestObjCKeyTy(10))!] assert(kv.0 == TestObjCKeyTy(10)) assert((kv.1 as! TestObjCValueTy).value == 1010) kv = d[d.index(forKey: TestObjCKeyTy(20))!] assert(kv.0 == TestObjCKeyTy(20)) assert((kv.1 as! TestObjCValueTy).value == 1020) kv = d[d.index(forKey: TestObjCKeyTy(30))!] assert(kv.0 == TestObjCKeyTy(30)) assert((kv.1 as! TestObjCValueTy).value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestObjCKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForKey") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Find an existing key. do { var kv = d[d.index(forKey: TestBridgedKeyTy(10))!] assert(kv.0 == TestBridgedKeyTy(10)) assert(kv.1.value == 1010) kv = d[d.index(forKey: TestBridgedKeyTy(20))!] assert(kv.0 == TestBridgedKeyTy(20)) assert(kv.1.value == 1020) kv = d[d.index(forKey: TestBridgedKeyTy(30))!] assert(kv.0 == TestBridgedKeyTy(30)) assert(kv.1.value == 1030) } // Try to find a key that does not exist. assert(d.index(forKey: TestBridgedKeyTy(40)) == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { var (key, value) = d[i] let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex != endIndex) assert(startIndex < endIndex) assert(startIndex <= endIndex) assert(!(startIndex >= endIndex)) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) var pairs = Array<(Int, Int)>() for i in d.indices { var (key, value) = d[i] let kv = (key.value, value.value) pairs += [kv] } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var startIndex = d.startIndex var endIndex = d.endIndex assert(startIndex == endIndex) assert(!(startIndex < endIndex)) assert(startIndex <= endIndex) assert(startIndex >= endIndex) assert(!(startIndex > endIndex)) assert(identity1 == d._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithKey") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) // Read existing key-value pairs. var v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestObjCKeyTy(40)] = TestObjCValueTy(2040) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 1010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) // Overwrite value in existing binding. d[TestObjCKeyTy(10)] = TestObjCValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestObjCKeyTy(10)] as! TestObjCValueTy assert(v.value == 2010) v = d[TestObjCKeyTy(20)] as! TestObjCValueTy assert(v.value == 1020) v = d[TestObjCKeyTy(30)] as! TestObjCValueTy assert(v.value == 1030) v = d[TestObjCKeyTy(40)] as! TestObjCValueTy assert(v.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithKey") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) // Read existing key-value pairs. var v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) assert(identity1 == d._rawIdentifier()) // Insert a new key-value pair. d[TestBridgedKeyTy(40)] = TestBridgedValueTy(2040) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) // Overwrite value in existing binding. d[TestBridgedKeyTy(10)] = TestBridgedValueTy(2010) assert(identity2 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(d.count == 4) v = d[TestBridgedKeyTy(10)] assert(v!.value == 2010) v = d[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = d[TestBridgedKeyTy(30)] assert(v!.value == 1030) v = d[TestBridgedKeyTy(40)] assert(v!.value == 2040) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40)) assert(oldValue == nil) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert((d[TestObjCKeyTy(40)] as! TestObjCValueTy).value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var oldValue: AnyObject? = d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10)) assert((oldValue as! TestObjCValueTy).value == 1010) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 2010) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.UpdateValueForKey") { // Insert a new key-value pair. do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40)) assert(oldValue == nil) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 4) assert(d[TestBridgedKeyTy(10)]!.value == 1010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(d[TestBridgedKeyTy(40)]!.value == 2040) } // Overwrite a value in existing binding. do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var oldValue = d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))! assert(oldValue.value == 1010) var identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 2010) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let foundIndex1 = d.index(forKey: TestObjCKeyTy(10))! assert(d[foundIndex1].0 == TestObjCKeyTy(10)) assert((d[foundIndex1].1 as! TestObjCValueTy).value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 != d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10)) assert((removedElement.1 as! TestObjCValueTy).value == 1010) assert(d.count == 2) assert(d.index(forKey: TestObjCKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let foundIndex1 = d.index(forKey: TestBridgedKeyTy(10))! assert(d[foundIndex1].0 == TestBridgedKeyTy(10)) assert(d[foundIndex1].1.value == 1010) assert(identity1 == d._rawIdentifier()) let removedElement = d.remove(at: foundIndex1) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) assert(removedElement.0 == TestObjCKeyTy(10) as TestBridgedKeyTy) assert(removedElement.1.value == 1010) assert(d.count == 2) assert(d.index(forKey: TestBridgedKeyTy(10)) == nil) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveValueForKey") { do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var deleted: AnyObject? = d.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isCocoaDictionary(d)) deleted = d.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) var identity2 = d._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestObjCKeyTy(10)] == nil) assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) var deleted: AnyObject? = d2.removeValue(forKey: TestObjCKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isCocoaDictionary(d1)) assert(isCocoaDictionary(d2)) deleted = d2.removeValue(forKey: TestObjCKeyTy(10)) assert((deleted as! TestObjCValueTy).value == 1010) var identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isCocoaDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert((d1[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d1[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestObjCKeyTy(10)] == nil) assert((d2[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020) assert((d2[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveValueForKey") { do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var deleted = d.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d._rawIdentifier()) assert(isNativeDictionary(d)) deleted = d.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) var identity2 = d._rawIdentifier() assert(identity1 == identity2) assert(isNativeDictionary(d)) assert(d.count == 2) assert(d[TestBridgedKeyTy(10)] == nil) assert(d[TestBridgedKeyTy(20)]!.value == 1020) assert(d[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d._rawIdentifier()) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() var d2 = d1 assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) var deleted = d2.removeValue(forKey: TestBridgedKeyTy(0)) assert(deleted == nil) assert(identity1 == d1._rawIdentifier()) assert(identity1 == d2._rawIdentifier()) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) deleted = d2.removeValue(forKey: TestBridgedKeyTy(10)) assert(deleted!.value == 1010) var identity2 = d2._rawIdentifier() assert(identity1 != identity2) assert(isNativeDictionary(d1)) assert(isNativeDictionary(d2)) assert(d2.count == 2) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d1[TestBridgedKeyTy(20)]!.value == 1020) assert(d1[TestBridgedKeyTy(30)]!.value == 1030) assert(identity1 == d1._rawIdentifier()) assert(d2[TestBridgedKeyTy(10)] == nil) assert(d2[TestBridgedKeyTy(20)]!.value == 1020) assert(d2[TestBridgedKeyTy(30)]!.value == 1030) assert(identity2 == d2._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") { do { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2._variantBuffer.asNative.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } do { var d1 = getBridgedVerbatimDictionary() var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010) assert(d2._variantBuffer.asNative.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestObjCKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") { do { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 0) d.removeAll() assert(identity1 == d._rawIdentifier()) assert(d.count == 0) } do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll() assert(identity1 != d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity < originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) let originalCapacity = d.count assert(d.count == 3) assert(d[TestBridgedKeyTy(10)]!.value == 1010) d.removeAll(keepingCapacity: true) assert(identity1 == d._rawIdentifier()) assert(d._variantBuffer.asNative.capacity >= originalCapacity) assert(d.count == 0) assert(d[TestBridgedKeyTy(10)] == nil) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll() var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity < originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } do { var d1 = getBridgedNonverbatimDictionary() var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) let originalCapacity = d1.count assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) var d2 = d1 d2.removeAll(keepingCapacity: true) var identity2 = d2._rawIdentifier() assert(identity1 == d1._rawIdentifier()) assert(identity2 != identity1) assert(d1.count == 3) assert(d1[TestBridgedKeyTy(10)]!.value == 1010) assert(d2._variantBuffer.asNative.capacity >= originalCapacity) assert(d2.count == 0) assert(d2[TestBridgedKeyTy(10)] == nil) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Count") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) assert(d.count == 3) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") { var d = getBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") { var d = getBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") { var d = getBridgedVerbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") { var d = getBridgedNonverbatimDictionary([:]) var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() // Cannot write code below because of // <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison // assert(iter.next() == .none) assert(iter.next() == nil) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") { var d = getHugeBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") { var d = getHugeBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = Array<(Int, Int)>() for i in 1...32 { expectedPairs += [(i, 1000 + i)] } assert(equalsUnordered(pairs, expectedPairs)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. var d = getParallelArrayBridgedVerbatimDictionary() var identity1 = d._rawIdentifier() assert(isCocoaDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_ParallelArray") { autoreleasepoolIfUnoptimizedReturnAutoreleased { // Add an autorelease pool because ParallelArrayDictionary autoreleases // values in objectForKey. var d = getParallelArrayBridgedNonverbatimDictionary() var identity1 = d._rawIdentifier() assert(isNativeDictionary(d)) var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ] assert(equalsUnordered(pairs, expectedPairs)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. assert(iter.next() == nil) assert(iter.next() == nil) assert(iter.next() == nil) assert(identity1 == d._rawIdentifier()) } } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") { var d1 = getBridgedVerbatimEquatableDictionary([:]) var identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary([:]) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) // We can't check that `identity1 != identity2` because Foundation might be // returning the same singleton NSDictionary for empty dictionaries. assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(10)] = TestObjCEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") { var d1 = getBridgedNonverbatimEquatableDictionary([:]) var identity1 = d1._rawIdentifier() assert(isNativeDictionary(d1)) var d2 = getBridgedNonverbatimEquatableDictionary([:]) var identity2 = d2._rawIdentifier() assert(isNativeDictionary(d2)) assert(identity1 != identity2) assert(d1 == d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestBridgedKeyTy(10)] = TestBridgedEquatableValueTy(2010) assert(isNativeDictionary(d2)) assert(identity2 == d2._rawIdentifier()) assert(d1 != d2) assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") { func helper(_ nd1: Dictionary<Int, Int>, _ nd2: Dictionary<Int, Int>, _ expectedEq: Bool) { let d1 = getBridgedVerbatimEquatableDictionary(nd1) let identity1 = d1._rawIdentifier() assert(isCocoaDictionary(d1)) var d2 = getBridgedVerbatimEquatableDictionary(nd2) var identity2 = d2._rawIdentifier() assert(isCocoaDictionary(d2)) do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) d2[TestObjCKeyTy(1111)] = TestObjCEquatableValueTy(1111) d2[TestObjCKeyTy(1111)] = nil assert(isNativeDictionary(d2)) assert(identity2 != d2._rawIdentifier()) identity2 = d2._rawIdentifier() do { let eq1 = (d1 == d2) assert(eq1 == expectedEq) let eq2 = (d2 == d1) assert(eq2 == expectedEq) let neq1 = (d1 != d2) assert(neq1 != expectedEq) let neq2 = (d2 != d1) assert(neq2 != expectedEq) } assert(identity1 == d1._rawIdentifier()) assert(identity2 == d2._rawIdentifier()) } helper([:], [:], true) helper([10: 1010], [10: 1010], true) helper([10: 1010, 20: 1020], [10: 1010, 20: 1020], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030], true) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 1111: 1030], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1111], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010], false) helper([10: 1010, 20: 1020, 30: 1030], [:], false) helper([10: 1010, 20: 1020, 30: 1030], [10: 1010, 20: 1020, 30: 1030, 40: 1040], false) } DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfDictionaries") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<NSObject, AnyObject>] for i in 0..<3 { var d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i])) } var a = nsa as [AnyObject] as! [Dictionary<TestBridgedKeyTy, TestBridgedValueTy>] for i in 0..<3 { var d = a[i] var iter = d.makeIterator() var pairs = Array<(Int, Int)>() while let (key, value) = iter.next() { let kv = (key.value, value.value) pairs.append(kv) } var expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ] assert(equalsUnordered(pairs, expectedPairs)) } } //===--- // Dictionary -> NSDictionary bridging tests. // // Key and Value are bridged verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.Verbatim.Count") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() assert(d.count == 3) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.ObjectForKey") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var v: AnyObject? = d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject } expectEqual(1010, (v as! TestObjCValueTy).value) let idValue10 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject } expectEqual(1020, (v as! TestObjCValueTy).value) let idValue20 = unsafeBitCast(v, to: UInt.self) v = d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject } expectEqual(1030, (v as! TestObjCValueTy).value) let idValue30 = unsafeBitCast(v, to: UInt.self) expectNil(d.object(forKey: TestObjCKeyTy(40))) // NSDictionary can store mixed key types. Swift's Dictionary is typed, but // when bridged to NSDictionary, it should behave like one, and allow queries // for mismatched key types. expectNil(d.object(forKey: TestObjCInvalidKeyTy())) for i in 0..<3 { expectEqual(idValue10, unsafeBitCast( d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue20, unsafeBitCast( d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue30, unsafeBitCast( d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject }, to: UInt.self)) } expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() var capturedIdentityPairs = Array<(UInt, UInt)>() for i in 0..<3 { let enumerator = d.keyEnumerator() var dataPairs = Array<(Int, Int)>() var identityPairs = Array<(UInt, UInt)>() while let key = enumerator.nextObject() { let keyObj = key as AnyObject let value: AnyObject = d.object(forKey: keyObj)! as AnyObject let dataPair = ((keyObj as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) dataPairs.append(dataPair) let identityPair = (unsafeBitCast(keyObj, to: UInt.self), unsafeBitCast(value, to: UInt.self)) identityPairs.append(identityPair) } expectTrue( equalsUnordered(dataPairs, [ (10, 1010), (20, 1020), (30, 1030) ])) if capturedIdentityPairs.isEmpty { capturedIdentityPairs = identityPairs } else { expectTrue(equalsUnordered(capturedIdentityPairs, identityPairs)) } assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject_Empty") { let d = getBridgedEmptyNSDictionary() let enumerator = d.keyEnumerator() assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) assert(enumerator.nextObject() == nil) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") { let d = getBridgedEmptyNSDictionary() checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } //===--- // Dictionary -> NSDictionary bridging tests. // // Key type and value type are bridged non-verbatim. //===--- DictionaryTestSuite.test("BridgedToObjC.KeyValue_ValueTypesCustomBridged") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift.Partial") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 9) checkDictionaryEnumeratorPartialFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030), (40, 1040), (50, 1050), (60, 1060), (70, 1070), (80, 1080), (90, 1090) ], d, maxFastEnumerationItems: 5, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (9, 9)) } DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d.keyEnumerator() }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged() checkDictionaryFastEnumerationFromObjC( [ (10, 1010), (20, 1020), (30, 1030) ], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") { let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged( numElements: 0) checkDictionaryFastEnumerationFromSwift( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) checkDictionaryFastEnumerationFromObjC( [], d, { d }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) } func getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() -> NSDictionary { assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self)) var d = Dictionary<TestBridgedKeyTy, TestObjCValueTy>() d[TestBridgedKeyTy(10)] = TestObjCValueTy(1010) d[TestBridgedKeyTy(20)] = TestObjCValueTy(1020) d[TestBridgedKeyTy(30)] = TestObjCValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Key_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } func getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() -> NSDictionary { assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self)) assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self)) var d = Dictionary<TestObjCKeyTy, TestBridgedValueTy>() d[TestObjCKeyTy(10)] = TestBridgedValueTy(1010) d[TestObjCKeyTy(20)] = TestBridgedValueTy(1020) d[TestObjCKeyTy(30)] = TestBridgedValueTy(1030) let bridged = convertDictionaryToNSDictionary(d) assert(isNativeNSDictionary(bridged)) return bridged } DictionaryTestSuite.test("BridgedToObjC.Value_ValueTypeCustomBridged") { let d = getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() let enumerator = d.keyEnumerator() var pairs = Array<(Int, Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) expectAutoreleasedKeysAndValues(unopt: (3, 3)) } //===--- // NSDictionary -> Dictionary -> NSDictionary bridging tests. //===--- func getRoundtripBridgedNSDictionary() -> NSDictionary { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary<NSObject, AnyObject> = convertNSDictionaryToDictionary(nsd) let bridgedBack = convertDictionaryToNSDictionary(d) assert(isCocoaNSDictionary(bridgedBack)) // FIXME: this should be true. //assert(unsafeBitCast(nsd, Int.self) == unsafeBitCast(bridgedBack, Int.self)) return bridgedBack } DictionaryTestSuite.test("BridgingRoundtrip") { let d = getRoundtripBridgedNSDictionary() let enumerator = d.keyEnumerator() var pairs = Array<(key: Int, value: Int)>() while let key = enumerator.nextObject() { let value: AnyObject = d.object(forKey: key)! as AnyObject let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } expectEqualsUnordered([ (10, 1010), (20, 1020), (30, 1030) ], pairs) } //===--- // NSDictionary -> Dictionary implicit conversion. //===--- DictionaryTestSuite.test("NSDictionaryToDictionaryConversion") { let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) } let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) } let nsd = NSDictionary(objects: values, forKeys: keys) let d: Dictionary = nsd as Dictionary var pairs = Array<(Int, Int)>() for (key, value) in d { let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value) pairs.append(kv) } assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ])) } DictionaryTestSuite.test("DictionaryToNSDictionaryConversion") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) let nsd: NSDictionary = d as NSDictionary checkDictionaryFastEnumerationFromSwift( [ (10, 1010), (20, 1020), (30, 1030) ], d as NSDictionary, { d as NSDictionary }, { ($0 as! TestObjCKeyTy).value }, { ($0 as! TestObjCValueTy).value }) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } //===--- // Dictionary upcasts //===--- DictionaryTestSuite.test("DictionaryUpcastEntryPoint") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = _dictionaryUpCast(d) assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcast") { var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) var dAsAnyObject: Dictionary<NSObject, AnyObject> = d assert(dAsAnyObject.count == 3) var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)] assert((v! as! TestObjCValueTy).value == 1010) v = dAsAnyObject[TestObjCKeyTy(20)] assert((v! as! TestObjCValueTy).value == 1020) v = dAsAnyObject[TestObjCKeyTy(30)] assert((v! as! TestObjCValueTy).value == 1030) } DictionaryTestSuite.test("DictionaryUpcastBridgedEntryPoint") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO: Dictionary<NSObject, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV: Dictionary<NSObject, TestBridgedValueTy> = _dictionaryBridgeToObjectiveC(d) assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO: Dictionary<TestBridgedKeyTy, AnyObject> = _dictionaryBridgeToObjectiveC(d) assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } DictionaryTestSuite.test("DictionaryUpcastBridged") { var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32) d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010) d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020) d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030) do { var dOO = d as! Dictionary<NSObject, AnyObject> assert(dOO.count == 3) var v: AnyObject? = dOO[TestObjCKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dOO[TestObjCKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dOO[TestObjCKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } do { var dOV = d as! Dictionary<NSObject, TestBridgedValueTy> assert(dOV.count == 3) var v = dOV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dOV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dOV[TestObjCKeyTy(30)] assert(v!.value == 1030) } do { var dVO = d as Dictionary<TestBridgedKeyTy, AnyObject> assert(dVO.count == 3) var v: AnyObject? = dVO[TestBridgedKeyTy(10)] assert((v! as! TestBridgedValueTy).value == 1010) v = dVO[TestBridgedKeyTy(20)] assert((v! as! TestBridgedValueTy).value == 1020) v = dVO[TestBridgedKeyTy(30)] assert((v! as! TestBridgedValueTy).value == 1030) } } //===--- // Dictionary downcasts //===--- DictionaryTestSuite.test("DictionaryDowncastEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC: Dictionary<TestObjCKeyTy, TestObjCValueTy> = _dictionaryDownCast(d) assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncast") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCC = d as! Dictionary<TestObjCKeyTy, TestObjCValueTy> assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) expectAutoreleasedKeysAndValues(unopt: (0, 3)) } DictionaryTestSuite.test("DictionaryDowncastConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if let dCC = _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? { assert(false) } } DictionaryTestSuite.test("DictionaryDowncastConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(dCC.count == 3) var v = dCC[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCC[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCC[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcast d["hello" as NSString] = 17 as NSNumber if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> { assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV: Dictionary<TestObjCKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC: Dictionary<TestBridgedKeyTy, TestObjCValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV: Dictionary<TestBridgedKeyTy, TestBridgedValueTy> = _dictionaryBridgeFromObjectiveC(d) do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveC") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy> do { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy> do { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } // Successful downcast. let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy> do { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditionalEntryPoint") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>? { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>? { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>? { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if let dCV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestObjCKeyTy, TestBridgedValueTy>?{ assert(false) } if let dVC = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestObjCValueTy>?{ assert(false) } if let dVV = _dictionaryBridgeFromObjectiveCConditional(d) as Dictionary<TestBridgedKeyTy, TestBridgedValueTy>?{ assert(false) } } DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditional") { var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32) d[TestObjCKeyTy(10)] = TestObjCValueTy(1010) d[TestObjCKeyTy(20)] = TestObjCValueTy(1020) d[TestObjCKeyTy(30)] = TestObjCValueTy(1030) // Successful downcast. if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(dCV.count == 3) var v = dCV[TestObjCKeyTy(10)] assert(v!.value == 1010) v = dCV[TestObjCKeyTy(20)] assert(v!.value == 1020) v = dCV[TestObjCKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(dVC.count == 3) var v = dVC[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVC[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVC[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Successful downcast. if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(dVV.count == 3) var v = dVV[TestBridgedKeyTy(10)] assert(v!.value == 1010) v = dVV[TestBridgedKeyTy(20)] assert(v!.value == 1020) v = dVV[TestBridgedKeyTy(30)] assert(v!.value == 1030) } else { assert(false) } // Unsuccessful downcasts d["hello" as NSString] = 17 as NSNumber if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> { assert(false) } if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> { assert(false) } if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> { assert(false) } } #endif // _runtime(_ObjC) //===--- // Tests for APIs implemented strictly based on public interface. We only need // to test them once, not for every storage type. //===--- func getDerivedAPIsDictionary() -> Dictionary<Int, Int> { var d = Dictionary<Int, Int>(minimumCapacity: 10) d[10] = 1010 d[20] = 1020 d[30] = 1030 return d } var DictionaryDerivedAPIs = TestSuite("DictionaryDerivedAPIs") DictionaryDerivedAPIs.test("isEmpty") { do { var empty = Dictionary<Int, Int>() expectTrue(empty.isEmpty) } do { var d = getDerivedAPIsDictionary() expectFalse(d.isEmpty) } } #if _runtime(_ObjC) @objc class MockDictionaryWithCustomCount : NSDictionary { init(count: Int) { self._count = count super.init() } override init() { expectUnreachable() super.init() } override init( objects: UnsafePointer<AnyObject>?, forKeys keys: UnsafePointer<NSCopying>?, count: Int) { expectUnreachable() super.init(objects: objects, forKeys: keys, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by MockDictionaryWithCustomCount") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this dictionary produces an object of the same // dynamic type. return self } override func object(forKey aKey: Any) -> Any? { expectUnreachable() return NSObject() } override var count: Int { MockDictionaryWithCustomCount.timesCountWasCalled += 1 return _count } var _count: Int = 0 static var timesCountWasCalled = 0 } func getMockDictionaryWithCustomCount(count: Int) -> Dictionary<NSObject, AnyObject> { return MockDictionaryWithCustomCount(count: count) as Dictionary } func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool { return collection.isEmpty } DictionaryDerivedAPIs.test("isEmpty/ImplementationIsCustomized") { do { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 0) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectTrue(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(d.isEmpty) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } do { var d = getMockDictionaryWithCustomCount(count: 4) MockDictionaryWithCustomCount.timesCountWasCalled = 0 expectFalse(callGenericIsEmpty(d)) expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled) } } #endif // _runtime(_ObjC) DictionaryDerivedAPIs.test("keys") { do { var empty = Dictionary<Int, Int>() var keys = Array(empty.keys) expectTrue(equalsUnordered(keys, [])) } do { var d = getDerivedAPIsDictionary() var keys = Array(d.keys) expectTrue(equalsUnordered(keys, [ 10, 20, 30 ])) } } DictionaryDerivedAPIs.test("values") { do { var empty = Dictionary<Int, Int>() var values = Array(empty.values) expectTrue(equalsUnordered(values, [])) } do { var d = getDerivedAPIsDictionary() var values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1020, 1030 ])) d[11] = 1010 values = Array(d.values) expectTrue(equalsUnordered(values, [ 1010, 1010, 1020, 1030 ])) } } #if _runtime(_ObjC) var ObjCThunks = TestSuite("ObjCThunks") class ObjCThunksHelper : NSObject { dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) { expectEqual(10, array[0].value) expectEqual(20, array[1].value) expectEqual(30, array[2].value) } dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) { // Cannot check elements because doing so would bridge them. expectEqual(3, array.count) } dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] { return [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ] } dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] { return [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ] } dynamic func acceptDictionaryBridgedVerbatim( _ d: [TestObjCKeyTy : TestObjCValueTy]) { expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } dynamic func acceptDictionaryBridgedNonverbatim( _ d: [TestBridgedKeyTy : TestBridgedValueTy]) { expectEqual(3, d.count) // Cannot check elements because doing so would bridge them. } dynamic func returnDictionaryBridgedVerbatim() -> [TestObjCKeyTy : TestObjCValueTy] { return [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030), ] } dynamic func returnDictionaryBridgedNonverbatim() -> [TestBridgedKeyTy : TestBridgedValueTy] { return [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030), ] } } ObjCThunks.test("Array/Accept") { var helper = ObjCThunksHelper() do { helper.acceptArrayBridgedVerbatim( [ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ]) } do { TestBridgedValueTy.bridgeOperations = 0 helper.acceptArrayBridgedNonverbatim( [ TestBridgedValueTy(10), TestBridgedValueTy(20), TestBridgedValueTy(30) ]) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Array/Return") { var helper = ObjCThunksHelper() do { let a = helper.returnArrayBridgedVerbatim() expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) } do { TestBridgedValueTy.bridgeOperations = 0 let a = helper.returnArrayBridgedNonverbatim() expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedValueTy.bridgeOperations = 0 expectEqual(10, a[0].value) expectEqual(20, a[1].value) expectEqual(30, a[2].value) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Accept") { var helper = ObjCThunksHelper() do { helper.acceptDictionaryBridgedVerbatim( [ TestObjCKeyTy(10): TestObjCValueTy(1010), TestObjCKeyTy(20): TestObjCValueTy(1020), TestObjCKeyTy(30): TestObjCValueTy(1030) ]) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 helper.acceptDictionaryBridgedNonverbatim( [ TestBridgedKeyTy(10): TestBridgedValueTy(1010), TestBridgedKeyTy(20): TestBridgedValueTy(1020), TestBridgedKeyTy(30): TestBridgedValueTy(1030) ]) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } ObjCThunks.test("Dictionary/Return") { var helper = ObjCThunksHelper() do { let d = helper.returnDictionaryBridgedVerbatim() expectEqual(3, d.count) expectEqual(1010, d[TestObjCKeyTy(10)]!.value) expectEqual(1020, d[TestObjCKeyTy(20)]!.value) expectEqual(1030, d[TestObjCKeyTy(30)]!.value) } do { TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 let d = helper.returnDictionaryBridgedNonverbatim() expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) TestBridgedKeyTy.bridgeOperations = 0 TestBridgedValueTy.bridgeOperations = 0 expectEqual(3, d.count) expectEqual(1010, d[TestBridgedKeyTy(10)]!.value) expectEqual(1020, d[TestBridgedKeyTy(20)]!.value) expectEqual(1030, d[TestBridgedKeyTy(30)]!.value) expectEqual(0, TestBridgedKeyTy.bridgeOperations) expectEqual(0, TestBridgedValueTy.bridgeOperations) } } #endif // _runtime(_ObjC) //===--- // Check that iterators traverse a snapshot of the collection. //===--- DictionaryTestSuite.test("mutationDoesNotAffectIterator/subscript/store") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict[10] = 1011 expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,all") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() expectOptionalEqual(1010, dict.removeValue(forKey: 10)) expectOptionalEqual(1020, dict.removeValue(forKey: 20)) expectOptionalEqual(1030, dict.removeValue(forKey: 30)) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict.removeAll(keepingCapacity: false) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } DictionaryTestSuite.test( "mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") { var dict = getDerivedAPIsDictionary() var iter = dict.makeIterator() dict.removeAll(keepingCapacity: true) expectEqualsUnordered( [ (10, 1010), (20, 1020), (30, 1030) ], Array(IteratorSequence(iter))) } //===--- // Misc tests. //===--- DictionaryTestSuite.test("misc") { do { // Dictionary literal var dict = ["Hello": 1, "World": 2] // Insertion dict["Swift"] = 3 // Access expectOptionalEqual(1, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) // Overwriting existing value dict["Hello"] = 0 expectOptionalEqual(0, dict["Hello"]) expectOptionalEqual(2, dict["World"]) expectOptionalEqual(3, dict["Swift"]) expectNil(dict["Universe"]) } do { // Dictionaries with other types var d = [ 1.2: 1, 2.6: 2 ] d[3.3] = 3 expectOptionalEqual(1, d[1.2]) expectOptionalEqual(2, d[2.6]) expectOptionalEqual(3, d[3.3]) } do { var d = Dictionary<String, Int>(minimumCapacity: 13) d["one"] = 1 d["two"] = 2 d["three"] = 3 d["four"] = 4 d["five"] = 5 expectOptionalEqual(1, d["one"]) expectOptionalEqual(2, d["two"]) expectOptionalEqual(3, d["three"]) expectOptionalEqual(4, d["four"]) expectOptionalEqual(5, d["five"]) // Iterate over (key, value) tuples as a silly copy var d3 = Dictionary<String,Int>(minimumCapacity: 13) for (k, v) in d { d3[k] = v } expectOptionalEqual(1, d3["one"]) expectOptionalEqual(2, d3["two"]) expectOptionalEqual(3, d3["three"]) expectOptionalEqual(4, d3["four"]) expectOptionalEqual(5, d3["five"]) expectEqual(3, d.values[d.keys.index(of: "three")!]) expectEqual(4, d.values[d.keys.index(of: "four")!]) expectEqual(3, d3.values[d3.keys.index(of: "three")!]) expectEqual(4, d3.values[d3.keys.index(of: "four")!]) } } #if _runtime(_ObjC) DictionaryTestSuite.test("dropsBridgedCache") { // rdar://problem/18544533 // Previously this code would segfault due to a double free in the Dictionary // implementation. // This test will only fail in address sanitizer. var dict = [0:10] do { var bridged: NSDictionary = dict as NSDictionary expectEqual(10, bridged[0 as NSNumber] as! Int) } dict[0] = 11 do { var bridged: NSDictionary = dict as NSDictionary expectEqual(11, bridged[0 as NSNumber] as! Int) } } DictionaryTestSuite.test("getObjects:andKeys:") { let d = ([1: "one", 2: "two"] as Dictionary<Int, String>) as NSDictionary var keys = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSNumber>.allocate(capacity: 2), count: 2) var values = UnsafeMutableBufferPointer( start: UnsafeMutablePointer<NSString>.allocate(capacity: 2), count: 2) var kp = AutoreleasingUnsafeMutablePointer<AnyObject?>(keys.baseAddress!) var vp = AutoreleasingUnsafeMutablePointer<AnyObject?>(values.baseAddress!) var null: AutoreleasingUnsafeMutablePointer<AnyObject?>? d.available_getObjects(null, andKeys: null) // don't segfault d.available_getObjects(null, andKeys: kp) expectEqual([2, 1] as [NSNumber], Array(keys)) d.available_getObjects(vp, andKeys: null) expectEqual(["two", "one"] as [NSString], Array(values)) d.available_getObjects(vp, andKeys: kp) expectEqual([2, 1] as [NSNumber], Array(keys)) expectEqual(["two", "one"] as [NSString], Array(values)) } #endif DictionaryTestSuite.test("popFirst") { // Empty do { var d = [Int: Int]() let popped = d.popFirst() expectNil(popped) } do { var popped = [(Int, Int)]() var d: [Int: Int] = [ 1010: 1010, 2020: 2020, 3030: 3030, ] let expected = Array(d.map{($0.0, $0.1)}) while let element = d.popFirst() { popped.append(element) } expectEqualSequence(expected, Array(popped)) { (lhs: (Int, Int), rhs: (Int, Int)) -> Bool in lhs.0 == rhs.0 && lhs.1 == rhs.1 } expectTrue(d.isEmpty) } } DictionaryTestSuite.test("removeAt") { // Test removing from the startIndex, the middle, and the end of a dictionary. for i in 1...3 { var d: [Int: Int] = [ 10: 1010, 20: 2020, 30: 3030, ] let removed = d.remove(at: d.index(forKey: i*10)!) expectEqual(i*10, removed.0) expectEqual(i*1010, removed.1) expectEqual(2, d.count) expectNil(d.index(forKey: i)) let origKeys: [Int] = [10, 20, 30] expectEqual(origKeys.filter { $0 != (i*10) }, d.keys.sorted()) } } DictionaryTestSuite.setUp { resetLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) resetLeaksOfObjCDictionaryKeysValues() #endif } DictionaryTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) expectNoLeaksOfObjCDictionaryKeysValues() #endif } runAllTests()
29.101842
285
0.680921
9b55f5ac794c25835ac12e8c7b00ae9c61d13dce
500
// // ViewController.swift // learnGenericTable // // Created by 王智刚 on 2017/8/31. // Copyright © 2017年 王智刚. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
19.230769
80
0.668
1e094a0f308902aa249eba8b45ffc853be25ef6a
3,671
// // ChatRoomsController.swift // Blind-Chat // // Created by Mikael Mukhsikaroyan on 10/14/16. // Copyright © 2016 MSquaredmm. All rights reserved. // import UIKit import ChameleonFramework class ChatRoomsController: UIViewController { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 2 layout.minimumInteritemSpacing = 0 let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.translatesAutoresizingMaskIntoConstraints = false cv.register(RoomsCell.self, forCellWithReuseIdentifier: "rooms") cv.backgroundColor = FlatBlue() cv.delegate = self cv.dataSource = self cv.bounces = true return cv }() var rooms = ["Swift", "Python", "C++", "Brainfuck", "JavaScript", "Ruby", "Java", "C", "C#", "PHP", "Objective-C", "R", "Haskell", "Erlang"] var user: String! override func viewDidLoad() { super.viewDidLoad() title = "Rooms" navigationController?.navigationBar.tintColor = FlatWhite() navigationController?.navigationBar.barTintColor = FlatMint() navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: FlatWhite()] setupViews() addLogoutButton() } func addLogoutButton() { let btn = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logoutButtonPressed(sender:))) navigationItem.rightBarButtonItem = btn } func setupViews() { view.addSubview(collectionView) collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true } func gotoChat(room: String) { let vc = MessagesViewController() vc.user = user vc.room = room let backButton = UIBarButtonItem() backButton.title = "" navigationItem.backBarButtonItem = backButton navigationController?.pushViewController(vc, animated: true) } // MARK: - Actions func logoutButtonPressed(sender: UIBarButtonItem) { let vc = RegisterViewController() present(vc, animated: true, completion: nil) } } extension ChatRoomsController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return rooms.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "rooms", for: indexPath) as! RoomsCell let room = rooms[indexPath.item] cell.configureCell(forRoom: room) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: 50) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let room = rooms[indexPath.item] gotoChat(room: room) } }
36.346535
160
0.678017
defc1d8ed68d898d970a115e7f77c53d37fc5e93
2,191
// // AppDelegate.swift // ParentChildStoryboard // // Created by Ciprian Rarau on 2017-05-30. // Copyright © 2017 Ciprian Rarau. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 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:. } }
46.617021
285
0.757188
bb659dbc878ef42d8008b55dd91d4e3a56519262
1,281
// // PopUpViewController.swift // RoutingExample // // Created by Cassius Pacheco on 7/3/20. // Copyright © 2020 Cassius Pacheco. All rights reserved. // import UIKit final class PopUpViewController: UIViewController { private let viewModel: PopUpViewModel init(viewModel: PopUpViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white print("👶 \(self) Created") let dismissButton = DefaultButton(title: "Dismiss", target: self, selector: #selector(dismissButtonTouchUpInside)) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = viewModel.message let vStack = UIStackView(arrangedSubviews: [label, dismissButton]) vStack.axis = .vertical vStack.spacing = 8.0 view.addSubview(vStack) vStack.layout.center(in: view) } @objc private func dismissButtonTouchUpInside() { viewModel.dismissButtonTouchUpInside() } deinit { print("♻️ \(self) Deallocated") } }
25.117647
122
0.653396
bfebc9b5525f2ddfd44831952064d68038a16dec
2,171
// // AppDelegate.swift // ContextObserver // // Created by datinc on 09/19/2018. // Copyright (c) 2018 datinc. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.191489
285
0.754491
8ff24cd248abe10d3dc41c4c24ca4d601901e63e
28,065
// // EduVPN_UITests_macOS.swift // EduVPN-UITests-macOS // // Copyright © 2020-2021 The Commons Conservancy. All rights reserved. // import XCTest struct DemoInstituteAccessServerCredentials { let username: String let password: String } struct CustomServerCredentials { let host: String let username: String let password: String } struct TestServerCredentials { let demoInstituteAccessServerCredentials: DemoInstituteAccessServerCredentials? let customServerCredentials: CustomServerCredentials? } class EduVPNUITestsmacOS: XCTestCase { var interruptionMonitor: NSObjectProtocol! var alertButtonToClick: String? override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. interruptionMonitor = addUIInterruptionMonitor(withDescription: "“APP_NAME” Wants to Use “example.com” to Sign In") { (alert) -> Bool in if let alertButtonToClick = self.alertButtonToClick, alert.buttons[alertButtonToClick].exists { alert.buttons[alertButtonToClick].click() return true } return false } } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. removeUIInterruptionMonitor(interruptionMonitor) } func testFreshLaunch() throws { // Scenario: A fresh launch should open with the "Find your institute" search page // Given I launched a freshly installed app let app = givenILaunchedAFreshlyInstalledApp() // Then I should see "Find your institute" label thenIShouldSeeLabel(app, label: "Find your institute") // Then I should see search field with "Search for your institute" placeholder thenIShouldSeeSearchFieldWithPlaceholder(app, placeholder: "Search for your institute...") } func testSearching() { // Scenario: A fresh launch should open with the "Find your institute" search page // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // Then I should see "Add" button thenIShouldSeeButton(app, label: "Add") // When I click "Add" button whenIClickButton(app, label: "Add") // Then I should see "Find your institute" label thenIShouldSeeLabel(app, label: "Find your institute") // Then I should see search field with "Search for your institute" placeholder thenIShouldSeeSearchFieldWithPlaceholder(app, placeholder: "Search for your institute...") // When I start typing in the search field whenIStartTypingInTheSearchField(app) // Then I should see "Institute Access" label thenIShouldSeeLabel(app, label: "Institute Access") // Then I should see "Secure Internet" label thenIShouldSeeLabel(app, label: "Secure Internet") // When I search for "vsvsdkfb" whenISearchFor(app, query: "vsvsdkfb") // Then I should see "No results. Please check your search query." label thenIShouldSeeLabel(app, label: "No results. Please check your search query.") // When I clear the search field whenIClearTheSearchField(app) // Then I should see "Institute Access" label thenIShouldSeeLabel(app, label: "Institute Access") // When I search for "konijn" whenISearchFor(app, query: "konijn") // Then I should see "Secure Internet" label thenIShouldSeeLabel(app, label: "Secure Internet") // Then I should see "SURFnet bv" cell thenIShouldSeeCell(app, label: "SURFnet bv") // When I clear the search field whenIClearTheSearchField(app) // When I search for "Dem" whenISearchFor(app, query: "Dem") // Then I should see "Institute Access" label thenIShouldSeeLabel(app, label: "Institute Access") // Then I should see "Demo" cell thenIShouldSeeCell(app, label: "Demo") } func testAddInstituteAccess() throws { // Scenario: Adding a provider for institute access guard let demoCredentials = testServerCredentialsmacOS.demoInstituteAccessServerCredentials else { throw XCTSkip("No credentials provided for Demo Institute Access server") } // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // When I click "Add" button whenIClickButton(app, label: "Add") // Then I should see search field with "Search for your institute" placeholder thenIShouldSeeSearchFieldWithPlaceholder(app, placeholder: "Search for your institute...") // When I search for "Demo" whenISearchFor(app, query: "Demo") // Then I should see "Institute Access" label thenIShouldSeeLabel(app, label: "Institute Access") // Then I should see "Demo" cell thenIShouldSeeCell(app, label: "Demo") // When I click "Demo" cell whenIClickCell(app, label: "Demo") // When I authenticate with Demo whenIAuthenticateWithDemo(app, credentials: demoCredentials) // Then I should see "Demo" cell thenIShouldSeeCell(app, label: "Demo") } func testAddSecureInternet() { // Scenarion: Adding a provider for secure internet // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // When I click "Add" button whenIClickButton(app, label: "Add") // Then I should see search field with "Search for your institute" placeholder thenIShouldSeeSearchFieldWithPlaceholder(app, placeholder: "Search for your institute...") // When I search for "Surf" whenISearchFor(app, query: "Surf") // Then I should see "Secure Internet" label thenIShouldSeeLabel(app, label: "Secure Internet") // Then I should see "SURFnet bv" cell thenIShouldSeeCell(app, label: "SURFnet bv") // When I click "SURFnet bv" cell whenIClickCell(app, label: "SURFnet bv") // When I wait 3 seconds whenIWait(time: 3) // Then I should see webpage with host "idp.surfnet.nl" thenIShouldSeeWebpageWithHost(host: "idp.surfnet.nl") // When I click "Cancel" button whenIClickButton(app, label: "Cancel") // Then I should see "Secure Internet" label thenIShouldSeeLabel(app, label: "Secure Internet") // Then I should see "SURFnet bv" cell thenIShouldSeeCell(app, label: "SURFnet bv") } func testAddCustomServer() throws { // Scenario: A custom server can be added and connected to guard let customCredentials = testServerCredentialsmacOS.customServerCredentials else { throw XCTSkip("No credentials provided for custom server") } // Given I launched a freshly installed app let app = givenILaunchedAFreshlyInstalledApp() // Then I should see search field with "Search for your institute" placeholder thenIShouldSeeSearchFieldWithPlaceholder(app, placeholder: "Search for your institute...") // When I search for host whenISearchFor(app, query: customCredentials.host) // Then I should see "Add your own server" label thenIShouldSeeLabel(app, label: "Add your own server") // Then I should see "https:// + host" cell thenIShouldSeeCell(app, label: "https://" + customCredentials.host + "/") // When I click "https:// + host" cell whenIClickCell(app, label: "https://" + customCredentials.host + "/") // Then I might see webpage with host "host" let (_, safari) = thenIMightSeeWebpageWithHost(host: customCredentials.host) // Then I might see "Sign In" label let needLogin = thenIMightSeeLabel(safari, label: "Sign In") if needLogin { // When I start typing in the "Username" textfield whenIStartTypingInTheTextfield(safari, label: "Username") // When I type "********" whenIType(safari, text: customCredentials.username) // When I start typing in the secure "Password" textfield whenIStartTypingInTheSecureTextfield(safari, label: "Password") // When I type "********" whenIType(safari, text: customCredentials.password) // When I click "Sign In" button whenIClickButton(safari, label: "Sign In") // When I wait 10 seconds whenIWait(time: 10) } // Then I might see "Approve Application" label let needApproval = thenIMightSeeLabel(safari, label: "Approve Application") if needApproval { // Then I should see webpage with host "host" thenIShouldSeeWebpageWithHost(host: customCredentials.host) // Then I should see "Approve Application" label thenIShouldSeeLabel(safari, label: "Approve Application") // When I click "Approve" button whenIClickButton(safari, label: "Approve") // When I wait 10 seconds whenIWait(time: 10) } // Then I should see "https:// + host" cell thenIShouldSeeCell(app, label: "https://" + customCredentials.host + "/") // When I click "https:// + host" cell whenIClickCell(app, label: "https://" + customCredentials.host + "/") // When I click "Allow" button in system alert whenIClickButtonInSystemAlert(app, label: "Allow") // Then I should see "host" label thenIShouldSeeLabel(app, label: customCredentials.host) // Then I should see "Connected" label thenIShouldSeeLabel(app, label: "Connected", timeout: 10) // Then I should see connection switch on thenIShouldSeeConnectionSwitch(app, isOn: true) // Then I should see "Connection info" label thenIShouldSeeLabel(app, label: "Connection info") // FIXME: iOS capitalizes "info" // When I click "Connection info" label whenIClickLabel(app, label: "Connection info") // Then I should see "DURATION" label thenIShouldSeeLabel(app, label: "DURATION") // Then I should see "DATA TRANSFERRED" label thenIShouldSeeLabel(app, label: "DATA TRANSFERRED") // Then I should see "ADDRESS" label thenIShouldSeeLabel(app, label: "ADDRESS") // Then I should see "PROFILE" label thenIShouldSeeLabel(app, label: "PROFILE") // Then I should see "Hide connection info" button thenIShouldSeeButton(app, label: "Hide connection info") // When I click "Close" button whenIClickButton(app, label: "Hide connection info") // When I wait 1 second whenIWait(time: 1) // Then I should not see "DURATION" label thenIShouldNotSeeLabel(app, label: "DURATION") // Then I should see connection switch on thenIShouldSeeConnectionSwitch(app, isOn: true) // When I toggle connection switch whenIToggleConnectionSwitch(app) // Then I should see connection switch off thenIShouldSeeConnectionSwitch(app, isOn: false) // Then I should see "Not connected" label thenIShouldSeeLabel(app, label: "Not connected", timeout: 10) } func testRemovingProvider() { // Scenario: A provider can be removed // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // Then I should see "Demo" cell thenIShouldSeeCell(app, label: "Demo") // When I show contextual menu for "Demo" cell whenIShowContextualMenuForCell(app, label: "Demo") // Then I should see "Delete" contextual menu item thenIShouldSeeContextualMenuItem(app, label: "Delete") // When I choose "Delete" contextual menu item whenIChooseContextualMenuItem(app, label: "Delete") // Then I should not see "Demo" cell thenIShouldNotSeeCell(app, label: "Demo") } func testConnectVPN() throws { // Scenario: Should be able to setup connection guard let demoCredentials = testServerCredentialsmacOS.demoInstituteAccessServerCredentials else { throw XCTSkip("No credentials provided for Demo Institute Access server") } // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // When I click "Demo" cell whenIClickCell(app, label: "Demo") // Then I should see "Demo" label thenIShouldSeeLabel(app, label: "Demo") // Then I might see "Not connected" label let needAuthentication = !thenIMightSeeLabel(app, label: "Not connected") if needAuthentication { // When I authenticate with Demo whenIAuthenticateWithDemo(app, credentials: demoCredentials) } // Then I should see "Not connected" label thenIShouldSeeLabel(app, label: "Not connected", timeout: 30) // Then I should see connection switch off thenIShouldSeeConnectionSwitch(app, isOn: false) // When I wait 3 seconds whenIWait(time: 3) // When I toggle the connection switch whenIToggleConnectionSwitch(app) // Then I should see "Demo" label thenIShouldSeeLabel(app, label: "Demo") // Then I should see "Connected" label thenIShouldSeeLabel(app, label: "Connected", timeout: 30) // Then I should see connection switch on thenIShouldSeeConnectionSwitch(app, isOn: true) // When I toggle the connection switch whenIToggleConnectionSwitch(app) // Then I should see "Not connected" label thenIShouldSeeLabel(app, label: "Not connected", timeout: 30) // Then I should see connection switch off thenIShouldSeeConnectionSwitch(app, isOn: false) } func testConnectionLog() { // Scenario: Should be able to see connection log // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // When I click "Preferences" button whenIClickButton(app, label: "Preferences") // Then I should see "Connection log" label thenIShouldSeeLabel(app, label: "Connection log") // FIXME: iOS capitalizes Log, should this be the same? // Then I should see "View Log" button thenIShouldSeeButton(app, label: "View Log") // When I click "View Log" button whenIClickButton(app, label: "View Log") // Then I should see "com.apple.Console" app active thenIShouldSeeAppActive(bundleIdentifier: "com.apple.Console") } func testPreferences() { // Scenario: Preferences should be available // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // When I click "Preferences" button whenIClickButton(app, label: "Preferences") // Then I should see "Preferences" label thenIShouldSeeLabel(app, label: "Preferences") // Then I should see "Connect using TCP only" checkbox thenIShouldSeeCheckbox(app, label: "Connect using TCP only") // Then I should see "Connection log" label thenIShouldSeeLabel(app, label: "Connection log") // FIXME: iOS capitalizes Log, should this be the same? // Then I should see "View Log" button thenIShouldSeeButton(app, label: "View Log") // Then I should see "Show in menu bar" checkbox thenIShouldSeeCheckbox(app, label: "Show in menu bar") // Then I should see "Show in Dock" checkbox thenIShouldSeeCheckbox(app, label: "Show in Dock") // When I click "Done" button whenIClickButton(app, label: "Done") // Then I should see "Preferences" button thenIShouldSeeButton(app, label: "Preferences") } func testHelp() { // Scenario: Help should be available // Given I launched a configured app let app = givenILaunchedAConfiguredApp() // Then I should see "Help" button thenIShouldSeeButton(app, label: "Help") // When I click "Help" button whenIClickButton(app, label: "Help") // Then I should see webpage with host "eduvpn.org" thenIShouldSeeWebpageWithHost(host: "eduvpn.org") } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } } private extension EduVPNUITestsmacOS { // MARK: - Given private func givenILaunchedTheApp() -> XCUIApplication { let app = XCUIApplication() app.launchArguments.append("isUITesting") app.launch() return app } private func givenILaunchedAFreshlyInstalledApp() -> XCUIApplication { let app = XCUIApplication() app.launchArguments.append("isUITesting") app.launchArguments.append("isUITestingFreshInstall") app.launch() return app } private func givenILaunchedAConfiguredApp() -> XCUIApplication { let app = XCUIApplication() app.launchArguments.append("isUITesting") app.launchArguments.append("isUITestingConfigured") app.launch() return app } // MARK: - Then private func thenIShouldSeeLabel(_ app: XCUIApplication, label: String, timeout: TimeInterval = 3) { let labelElement = app.staticTexts[label] _ = labelElement.waitForExistence(timeout: timeout) XCTAssert(labelElement.exists) } private func thenIShouldNotSeeLabel(_ app: XCUIApplication, label: String) { let labelElement = app.staticTexts[label] XCTAssert(labelElement.exists == false || labelElement.isHittable == false) } private func thenIMightSeeLabel(_ app: XCUIApplication, label: String) -> Bool { let labelElement = app.staticTexts[label] _ = labelElement.waitForExistence(timeout: 3) return labelElement.exists } private func thenIShouldSeeSearchFieldWithPlaceholder(_ app: XCUIApplication, placeholder: String) { let searchField = app.searchFields.firstMatch XCTAssert(searchField.exists) XCTAssert(searchField.placeholderValue == placeholder) } private func thenIShouldSeeButton(_ app: XCUIApplication, label: String) { let buttonElement = app.buttons[label] XCTAssert(buttonElement.exists) } private func thenIShouldSeeCell(_ app: XCUIApplication, label: String) { let cellElement = app.cells[label] XCTAssert(cellElement.exists) } private func thenIShouldSeeHeader(_ app: XCUIApplication, label: String) { let otherElement = app.otherElements[label] XCTAssert(otherElement.exists) } private func thenIShouldNotSeeCell(_ app: XCUIApplication, label: String) { let cellElement = app.cells[label] XCTAssert(cellElement.exists == false) } private func thenIShouldSeeAlert(_ app: XCUIApplication, title: String) { let alertElement = app.alerts[title] XCTAssert(alertElement.exists) } @discardableResult private func thenIShouldSeeWebpageWithHost(_ safari: XCUIApplication = XCUIApplication(bundleIdentifier: "com.apple.Safari"), host: String) -> XCUIApplication { let textFieldElement = safari.textFields["WEB_BROWSER_ADDRESS_AND_SEARCH_FIELD"] _ = textFieldElement.waitForExistence(timeout: 3) XCTAssert((textFieldElement.value as? String)?.contains(host) ?? false) return safari } @discardableResult private func thenIMightSeeWebpageWithHost(_ safari: XCUIApplication = XCUIApplication(bundleIdentifier: "com.apple.Safari"), host: String) -> (Bool, XCUIApplication) { let textFieldElement = safari.textFields["WEB_BROWSER_ADDRESS_AND_SEARCH_FIELD"] _ = textFieldElement.waitForExistence(timeout: 3) let webpageSeen = (textFieldElement.value as? String)?.contains(host) ?? false return (webpageSeen, safari) } private func thenIShouldSeeConnectionSwitch(_ app: XCUIApplication, isOn: Bool) { let switchElement = app.checkBoxes["Connection"] XCTAssert(switchElement.exists) if let value = switchElement.value as? Bool { XCTAssert(value == isOn) } else { XCTFail("Checkbox value is not a boolean") } } private func thenIShouldSeeCheckbox(_ app: XCUIApplication, label: String, isOn: Bool? = nil) { let checkboxElement = app.checkBoxes[label] XCTAssert(checkboxElement.exists) if let isOn = isOn { XCTAssert(checkboxElement.isSelected == isOn) } } private func thenIShouldSeeContextualMenuItem(_ app: XCUIApplication, label: String) { let menuItemElement = app.menuItems[label] XCTAssert(menuItemElement.exists) } private func thenIShouldSeeAppActive(bundleIdentifier: String) { let app = XCUIApplication(bundleIdentifier: bundleIdentifier) XCTAssert(app.state == .runningForeground) } // MARK: - When private func whenIStartTypingInTheSearchField(_ app: XCUIApplication) { app.searchFields.firstMatch.click() } private func whenIStartTypingInTheTextfield(_ app: XCUIApplication, label: String) { let textFieldElement = app.textFields[label] _ = textFieldElement.waitForExistence(timeout: 3) textFieldElement.click() } private func whenIStartTypingInTheSecureTextfield(_ app: XCUIApplication, label: String) { let textFieldElement = app.secureTextFields[label] _ = textFieldElement.waitForExistence(timeout: 3) textFieldElement.click() } private func whenISearchFor(_ app: XCUIApplication, query: String) { app.searchFields.firstMatch.click() app.typeText(query) } private func whenIClearTheSearchField(_ app: XCUIApplication) { app.searchFields.firstMatch.buttons["cancel"].click() } private func whenIClickCell(_ app: XCUIApplication, label: String) { let cellElement = app.cells[label].firstMatch cellElement.click() } private func whenIClickButton(_ app: XCUIApplication, label: String) { let buttonElement = app.buttons[label].firstMatch buttonElement.click() } private func whenIClickLabel(_ app: XCUIApplication, label: String) { let labelElement = app.staticTexts[label].firstMatch labelElement.click() } private func whenIClickLink(_ app: XCUIApplication, label: String) { let linkElement = app.links[label].firstMatch _ = linkElement.waitForExistence(timeout: 3) if linkElement.exists { linkElement.click() } } private func whenIType(_ app: XCUIApplication, text: String) { app.typeText(text) } private func whenIToggleConnectionSwitch(_ app: XCUIApplication) { let switchElement = app.checkBoxes["Connection"] switchElement.click() } private func whenIShowContextualMenuForCell(_ app: XCUIApplication, label: String) { let cellElement = app.cells[label].firstMatch cellElement.rightClick() } private func whenIChooseContextualMenuItem(_ app: XCUIApplication, label: String) { let menuItemElement = app.windows.menuItems[label] menuItemElement.click() } private func whenIWait(time: TimeInterval) { Thread.sleep(forTimeInterval: time) } private func whenIClickButtonInSystemAlert(_ app: XCUIApplication, label: String) { alertButtonToClick = label Thread.sleep(forTimeInterval: 3) app.activate() // Interaction with app needed for some reasone } private func whenIAuthenticateWithDemo( _ app: XCUIApplication, credentials: DemoInstituteAccessServerCredentials) { // When I wait 3 seconds whenIWait(time: 3) // Then I might see webpage with host "engine.surfconext.nl" let (needChoice, safari) = thenIMightSeeWebpageWithHost(host: "engine.surfconext.nl") if needChoice { // When I click "eduID (NL)" link whenIClickLink(safari, label: "eduID (NL)") // When I wait 3 seconds whenIWait(time: 3) } // Then I might see webpage with host "login.eduid.nl" let (needLogin, _) = thenIMightSeeWebpageWithHost(safari, host: "login.eduid.nl") if needLogin { // When I click "Login!" link (if it exists) whenIClickLink(safari, label: "Login!") // When I wait 3 seconds whenIWait(time: 3) // When I click "Type a password." link whenIClickLink(safari, label: "type a password.") // When I start typing in the "e.g. [email protected]" textfield whenIStartTypingInTheTextfield(safari, label: "e.g. [email protected]") // When I type "********" whenIType(safari, text: credentials.username) // When I start typing in the secure "Password" textfield whenIStartTypingInTheSecureTextfield(safari, label: "Password") // When I type "********" whenIType(safari, text: credentials.password) // When I click "Login" link whenIClickLink(safari, label: "Login") // When I wait 10 seconds whenIWait(time: 10) } // Then I might see "Approve Application" label let needApproval = thenIMightSeeLabel(safari, label: "Approve Application") if needApproval { // Then I should see webpage with host "host" thenIShouldSeeWebpageWithHost(safari, host: "demo.eduvpn.nl") // When I click "Approve" button whenIClickButton(safari, label: "Approve") // When I wait 10 seconds whenIWait(time: 10) } } } // swiftlint:disable:this file_length
36.879106
182
0.621343
698b0626bc5501ddadd7825ff6087a8dbdb71fa6
3,181
// // CSVBaseImporter.swift // SwiftBeanCountImporter // // Created by Steffen Kötte on 2020-05-10. // Copyright © 2020 Steffen Kötte. All rights reserved. // import CSV import Foundation import SwiftBeanCountModel class CSVBaseImporter: BaseImporter { let csvReader: CSVReader let fileName: String override var importName: String { fileName } private var loaded = false private var lines = [CSVLine]() required init(ledger: Ledger?, csvReader: CSVReader, fileName: String) { self.csvReader = csvReader self.fileName = fileName super.init(ledger: ledger) } override func load() { guard !loaded else { return } while csvReader.next() != nil { lines.append(parseLine()) } lines.sort { $0.date > $1.date } loaded = true } override func nextTransaction() -> ImportedTransaction? { guard loaded, let data = lines.popLast() else { return nil } var description = sanitize(description: data.description) var categoryAccountName = try! AccountName(Settings.defaultAccountName) // swiftlint:disable:this force_try var payee = data.payee let originalPayee = payee let originalDescription = description let (savedDescription, savedPayee) = savedDescriptionAndPayeeFor(description: description) if let savedPayee = savedPayee { payee = savedPayee } if let savedDescription = savedDescription { description = savedDescription } if let accountName = savedAccountNameFor(payee: payee) { categoryAccountName = accountName } let categoryAmount = Amount(number: -data.amount, commoditySymbol: commoditySymbol, decimalDigits: 2) let flag: Flag = description == originalDescription && payee == originalPayee ? .incomplete : .complete let posting = Posting(accountName: configuredAccountName, amount: Amount(number: data.amount, commoditySymbol: commoditySymbol, decimalDigits: 2)) var posting2: Posting if let price = data.price { let pricePer = Amount(number: categoryAmount.number / price.number, commoditySymbol: commoditySymbol, decimalDigits: 7) posting2 = Posting(accountName: categoryAccountName, amount: price, price: pricePer, cost: nil) } else { posting2 = Posting(accountName: categoryAccountName, amount: categoryAmount) } let transaction = Transaction(metaData: TransactionMetaData(date: data.date, payee: payee, narration: description, flag: flag), postings: [posting, posting2]) return ImportedTransaction(transaction, originalDescription: originalDescription, possibleDuplicate: getPossibleDuplicateFor(transaction), shouldAllowUserToEdit: true, accountName: configuredAccountName) } func parseLine() -> CSVLine { // swiftlint:disable:this unavailable_function fatalError("Must Override") } }
36.563218
166
0.64288
bf163f35f419498c31fcf64664c9a9db40a0bb7c
130
import Foundation extension APIXU { enum Constants { static let baseURL: String = "https://api.apixu.com/v1" } }
16.25
63
0.638462
d66a72cac31c1389d42d6ffbb5f662f0e02a2dab
739
// // HostTableViewCell.swift // DataSafer // // Created by Fellipe Thufik Costa Gomes Hoashi on 10/1/16. // Copyright © 2016 Fellipe Thufik Costa Gomes Hoashi. All rights reserved. // import UIKit class HostTableViewCell: UITableViewCell { @IBOutlet weak var hostName: UILabel! @IBOutlet weak var hostIP: UILabel! @IBOutlet weak var backupStatus: UILabel! @IBOutlet weak var computerImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
22.393939
76
0.669824
0e6aa521ffdaaafa7c31a94af3193068eabc222c
5,872
// // TUIOServer.swift // TUIOSwift // // Created by Mirko Fetter on 28.02.17. // Copyright © 2017 grugru. All rights reserved. // import Foundation class TUIOServer { private let oscClient:F53OSCClient private var currentFrame = 0; private var lastFrameTime = -1; private var session_id = -1; var lastX = -1; var lastY = -1; var clickX = 0; var clickY = 0; var windowWidth = 1920; var windowHeight = 1080; var table_width:Int var table_height:Int var border_width:Int var border_height:Int static let pi = Float.pi; private let halfPi = (Float)(Float.pi/2.0); private let doublePi = (Float)(Float.pi*2.0); var sourceString:String; var selectedObject:Tangible?; var selectedCursor:Finger?; init(){ oscClient = F53OSCClient.init() oscClient.host = "127.0.0.1" oscClient.port = 3333 table_width = (Int)(Float(windowWidth)/1.25); table_height = (Int)(Float(windowHeight)/1.25); border_width = (Int)(windowWidth)/2; border_height = (Int)(windowHeight-table_height)/2; sourceString = "tuioSift@" + Host.current().address!; } private func sendOSC(bundle:F53OSCBundle) { oscClient.send(bundle) } private func setMessage( tangible:Tangible) -> F53OSCMessage{ let xpos = Float(tangible.getPosition().x - Float(border_width)/Float(table_width)); let ypos = Float(tangible.getPosition().y - Float(border_height)/Float(table_height)); var angle = tangible.getAngle() - Float.pi; if (angle<0) { angle += doublePi } var arguments = ["set"] as [Any] arguments.append(tangible.session_id); arguments.append(tangible.fiducial_id); arguments.append(xpos); arguments.append(ypos); arguments.append(angle); arguments.append(tangible.xspeed); arguments.append(tangible.yspeed); arguments.append(tangible.rspeed); arguments.append(tangible.maccel); arguments.append(tangible.raccel); let setMessage = F53OSCMessage(addressPattern: "/tuio/2Dobj", arguments: arguments) return setMessage!; } private func cursorDelete() { let sourceArguments = ["source", sourceString]; let sourceMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: sourceArguments) let aliveArguments = ["alive"]; // Enumeration<Integer> cursorList = manager.cursorList.keys(); // while (cursorList.hasMoreElements()) { // Integer s_id = cursorList.nextElement(); // aliveArguments.append(s_id); // } let aliveMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: aliveArguments) currentFrame += 1; let frameArguments = ["fseq", currentFrame] as [Any]; let frameMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: frameArguments) let elements: [Any] = [sourceMessage!.packetData(),aliveMessage!.packetData(),frameMessage!.packetData()] let cursorBundle = F53OSCBundle(timeTag: F53OSCTimeTag.immediate(), elements: elements) oscClient.send(cursorBundle) } private func cursorMessage() { let sourceArguments = ["source", sourceString]; let sourceMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: sourceArguments) let aliveArguments = ["alive"]; // Enumeration<Integer> cursorList = manager.cursorList.keys(); // while (cursorList.hasMoreElements()) { // Integer s_id = cursorList.nextElement(); // aliveArguments.append(s_id); // } let aliveMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: aliveArguments) let cursor = selectedCursor; let point = cursor?.getPosition(); // float xpos = (point.x-border_width)/(float)table_width; // if (manager.invertx) xpos = 1 - xpos; // float ypos = (point.y-border_height)/(float)table_height; // if (manager.inverty) ypos = 1 - ypos; // OSCMessage setMessage = new OSCMessage("/tuio/2Dcur"); // setMessage.addArgument("set"); // setMessage.addArgument(cursor.session_id); // setMessage.addArgument(xpos); // setMessage.addArgument(ypos); // setMessage.addArgument(cursor.xspeed); // setMessage.addArgument(cursor.yspeed); // setMessage.addArgument(cursor.maccel); var setArguments = ["set"] as [Any] // setArguments.append(cursor.session_id); // setArguments.append(xpos); // setArguments.append(ypos); // setArguments.append(cursor.xspeed); // setArguments.append(cursor.yspeed); // setArguments.append(cursor.maccel); let setMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: setArguments) currentFrame += 1; let frameArguments = ["fseq", currentFrame] as [Any]; let frameMessage = F53OSCMessage(addressPattern: "/tuio/2Dcur", arguments: frameArguments) // if (manager.verbose) { // System.out.println("set cur "+cursor.session_id+" "+xpos+" "+ypos+" "+cursor.xspeed+" "+cursor.yspeed+" "+cursor.maccel); // } let elements: [Any] = [sourceMessage!.packetData(),aliveMessage!.packetData(),setMessage!.packetData(),frameMessage!.packetData()] let cursorBundle = F53OSCBundle(timeTag: F53OSCTimeTag.immediate(), elements: elements) oscClient.send(cursorBundle) } }
31.40107
138
0.60814
5b89623456e33d480984b8df56500a9cf2f0cb93
680
// // AutoNotifyReenabledScenario.swift // iOSTestApp // // Created by Jamie Lynch on 13/05/2021. // Copyright © 2021 Bugsnag. All rights reserved. // /** * Raises an unhandled NSException with autoNotify set to false then true, * which should be reported by Bugsnag */ internal class AutoNotifyReenabledScenario: Scenario { override func startBugsnag() { self.config.autoTrackSessions = false super.startBugsnag() } override func run() { Bugsnag.client.autoNotify = false Bugsnag.client.autoNotify = true NSException.init(name: NSExceptionName("SomeError"), reason: "Something went wrnog", userInfo: nil).raise() } }
26.153846
115
0.694118
cc24999f8789b16b4f8b8dcb92ac2f4b58151e54
584
// // ViewController.swift // aroundME // // Created by Michael Flowers on 5/8/18. // Copyright © 2018 Michael Flowers. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } @IBAction func aroundMeButtonPressed(_ sender: UIButton) { } }
20.857143
80
0.669521
ebe57db7500d664d50dd0eeeb4d24a0aefce8114
2,182
// // AppDelegate.swift // PodGerarLeroLero // // Created by lgdomingues on 01/17/2018. // Copyright (c) 2018 lgdomingues. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.425532
285
0.755729
e8004747f742a9e6fc8ecb1f4f8322acc8ec0277
4,943
import Foundation import Core public final class CloudConfigs: Command { public let id = "configs" public let signature: [Argument] = [] public let help: [String] = [ "Interact with your cloud configurations" ] public let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } public func run(arguments: [String]) throws { let arguments = arguments.dropFirst().array let token = try Token.global(with: console) let repo = try getRepo( arguments, console: console, with: token ) let env: String if let name = arguments.option("env") { env = name } else { let e = try selectEnvironment( args: arguments, forRepo: repo, queryTitle: "Which Environment?", using: console, with: token ) env = e.name } let values = arguments.values let input = values.first ?? "" let options = [ (id: "", runner: getConfigs), (id: "add", runner: addConfigs), (id: "replace", runner: replaceConfigs), (id: "delete", runner: deleteConfigs), ] let selection = options.lazy.filter { id, _ in return id.lowercased().hasPrefix(input.lowercased()) }.first let runner = selection?.runner ?? getConfigs try runner(values, repo, env, token) } func getConfigs(args: [String], forRepo repo: String, envName env: String, with token: Token) throws { let configs = try applicationApi .hosting .environments .configs .get(forRepo: repo, envName: env, with: token) console.success("App: ", newLine: false) console.print("\(repo).vapor.cloud") console.success("Env: ", newLine: false) console.print(env) console.print() configs.forEach { config in console.info(config.key + ": ", newLine: false) console.print(config.value) } } func addConfigs(args: [String], forRepo repo: String, envName env: String, with token: Token) throws { // drop 'add' let configs = args.values.dropFirst() guard !configs.isEmpty else { throw "No configs found to add" } var keyVal = [String: String]() try configs.forEach { config in let comps = config.makeBytes().split( separator: .equals, maxSplits: 1, omittingEmptySubsequences: true ) guard comps.count == 2 else { throw "Invalid config argument \(config)" } let key = comps[0].makeString() let val = comps[1].makeString() keyVal[key] = val } _ = try applicationApi.hosting.environments.configs.add( keyVal, forRepo: repo, envName: env, with: token ) } func replaceConfigs(args: [String], forRepo repo: String, envName env: String, with token: Token) throws { // drop 'replace' let configs = args.values.dropFirst() guard !configs.isEmpty else { throw "No configs found to add" } guard console.confirm("This will overwrite any existing configurations, are you sure?") else { return } var keyVal = [String: String]() try configs.forEach { config in let comps = config.makeBytes().split( separator: .equals, maxSplits: 1, omittingEmptySubsequences: true ) guard comps.count == 2 else { throw "Invalid config argument \(config)" } let key = comps[0].makeString() let val = comps[1].makeString() keyVal[key] = val } _ = try applicationApi.hosting.environments.configs.replace( keyVal, forRepo: repo, envName: env, with: token ) } func deleteConfigs(args: [String], forRepo repo: String, envName env: String, with token: Token) throws { // drop 'delete' let configs = args.values.dropFirst().array if configs.isEmpty { console.warning("Are you sure you want to delete all configurations?") } else { console.warning("Are you sure you want to delete these configurations?") } guard console.confirm("There is no undo.", style: .warning) else { return } _ = try applicationApi.hosting.environments.configs.delete( keys: configs, forRepo: repo, envName: env, with: token ) } }
29.777108
110
0.533886
908954011d039959273a8d613607185770595967
2,013
// // OBOtherProductType1.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation /** Other product type details associated with the account. */ public struct OBOtherProductType1: Codable { /** Long name associated with the product */ public var name: String /** Description of the Product associated with the account */ public var _description: String public var productDetails: OBOtherProductDetails1? public var creditInterest: OBCreditInterest1? public var overdraft: OBOverdraft1? public var loanInterest: OBLoanInterest1? public var repayment: OBRepayment1? /** Contains details of fees and charges which are not associated with either Overdraft or features/benefits */ public var otherFeesCharges: [OBOtherFeesAndCharges1]? public var supplementaryData: OBSupplementaryData1? public init(name: String, _description: String, productDetails: OBOtherProductDetails1?, creditInterest: OBCreditInterest1?, overdraft: OBOverdraft1?, loanInterest: OBLoanInterest1?, repayment: OBRepayment1?, otherFeesCharges: [OBOtherFeesAndCharges1]?, supplementaryData: OBSupplementaryData1?) { self.name = name self._description = _description self.productDetails = productDetails self.creditInterest = creditInterest self.overdraft = overdraft self.loanInterest = loanInterest self.repayment = repayment self.otherFeesCharges = otherFeesCharges self.supplementaryData = supplementaryData } public enum CodingKeys: String, CodingKey { case name = "Name" case _description = "Description" case productDetails = "ProductDetails" case creditInterest = "CreditInterest" case overdraft = "Overdraft" case loanInterest = "LoanInterest" case repayment = "Repayment" case otherFeesCharges = "OtherFeesCharges" case supplementaryData = "SupplementaryData" } }
36.6
301
0.724789
ac6530c790bf19d2653b7b9af7db443b6c56c535
1,054
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency) | %FileCheck %s --dump-input always // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: OS=macosx // REQUIRES: CPU=x86_64 import Dispatch #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #endif func asyncEcho(_ value: Int) async -> Int { value } func test_taskGroup_isEmpty() async { _ = try! await Task.withGroup(resultType: Int.self) { (group) async -> Int in // CHECK: before add: isEmpty=true print("before add: isEmpty=\(group.isEmpty)") await group.add { sleep(2) return await asyncEcho(1) } // CHECK: while add running, outside: isEmpty=false print("while add running, outside: isEmpty=\(group.isEmpty)") // CHECK: next: 1 while let value = try! await group.next() { print("next: \(value)") } // CHECK: after draining tasks: isEmpty=true print("after draining tasks: isEmpty=\(group.isEmpty)") return 0 } } runAsyncAndBlock(test_taskGroup_isEmpty)
23.954545
113
0.681214
11f306e79c9a9b01c90d54c865f45a38212c1175
6,396
// // EMSInputView.swift // // Created on 24/02/2020. // Copyright © 2020 WildAid. All rights reserved. // import SwiftUI struct VesselInformationInputView: View { @ObservedObject var vessel: BoatViewModel let reportId: String @Binding var activeEditableComponentId: String @Binding var informationComplete: Bool @Binding var showingWarningState: Bool @State private var showingNationalityPicker = false @Binding private var showingNameWarning: Bool @Binding private var showingPermitNumberWarning: Bool @Binding private var showingHomePortWarning: Bool @Binding private var showingNationalityWarning: Bool private enum Dimensions { static let spacing: CGFloat = 16.0 static let bottomPadding: CGFloat = 24.0 static let noSpacing: CGFloat = 0.0 } init(vessel: BoatViewModel, reportId: String, activeEditableComponentId: Binding<String>, informationComplete: Binding<Bool>, showingWarningState: Binding<Bool>) { self.vessel = vessel self.reportId = reportId _activeEditableComponentId = activeEditableComponentId _informationComplete = informationComplete _showingWarningState = showingWarningState _showingNameWarning = .constant(showingWarningState.wrappedValue && vessel.name.isEmpty) _showingPermitNumberWarning = .constant(showingWarningState.wrappedValue && vessel.permitNumber.isEmpty) _showingHomePortWarning = .constant(showingWarningState.wrappedValue && vessel.homePort.isEmpty) _showingNationalityWarning = .constant(showingWarningState.wrappedValue && vessel.nationality.isEmpty) } var body: some View { VStack(spacing: Dimensions.spacing) { HStack(alignment: .center) { TitleLabel(title: "Vessel Information") AddAttachmentsButton(attachments: vessel.attachments, reportId: reportId) } .padding(.top, Dimensions.spacing) InputField(title: "Vessel Name", text: $vessel.name, showingWarning: showingNameWarning, inputChanged: inputChanged) InputField(title: "Permit Number", text: Binding<String>( get: { self.vessel.permitNumber.uppercased() }, set: { self.vessel.permitNumber = $0} ), showingWarning: showingPermitNumberWarning, inputChanged: inputChanged) .autocapitalization(.allCharacters) InputField(title: "Home Port", text: $vessel.homePort, showingWarning: showingHomePortWarning, inputChanged: inputChanged) Group { if hasNationality { VStack(spacing: Dimensions.noSpacing) { CaptionLabel(title: "Flag State") Button(action: { self.showingNationalityPicker.toggle() }) { CountryPickerDataView(item: displayedNationality) } Divider() } } else { ButtonField(title: "Flag State", text: vessel.nationality, showingWarning: showingNationalityWarning, fieldButtonClicked: { self.showingNationalityPicker.toggle() }) } } .sheet(isPresented: $showingNationalityPicker) { ChooseNationalityView(selectedItem: Binding<CountryPickerData>( get: { self.displayedNationality }, set: { self.vessel.nationality = $0.title self.checkAllInput() } )) } AttachmentsView(attachments: vessel.attachments) } .padding(.bottom, Dimensions.bottomPadding) .contentShape(Rectangle()) .onTapGesture { self.activeEditableComponentId = self.vessel.id } } /// Actions private func inputChanged(_ value: String) { self.checkAllInput() } /// Logic private var hasNationality: Bool { !vessel.nationality.isEmpty } private var displayedNationality: CountryPickerData { CountryPickerData(image: "\(transformCountryName(from: vessel.nationality))", title: vessel.nationality) } private func transformCountryName(from country: String) -> String { for code in Locale.isoRegionCodes as [String] { if let name = Locale.autoupdatingCurrent.localizedString(forRegionCode: code), name == country { return code } } return "" } private func checkAllInput() { showingNameWarning = showingWarningState && vessel.name.isEmpty showingPermitNumberWarning = showingWarningState && vessel.permitNumber.isEmpty showingHomePortWarning = showingWarningState && vessel.homePort.isEmpty showingNationalityWarning = showingWarningState && vessel.nationality.isEmpty informationComplete = !vessel.name.isEmpty && !vessel.permitNumber.isEmpty && !vessel.homePort.isEmpty && !vessel.nationality.isEmpty } } struct VesselInformationInputView_Previews: PreviewProvider { static var previews: some View { VStack { VesselInformationInputView( vessel: .sample, reportId: "TestId", activeEditableComponentId: .constant(""), informationComplete: .constant(false), showingWarningState: .constant(false)) .environment(\.locale, .init(identifier: "uk")) VesselInformationInputView( vessel: .sample, reportId: "TestId", activeEditableComponentId: .constant(""), informationComplete: .constant(false), showingWarningState: .constant(true)) } } }
37.623529
112
0.578956
56ec414e3a11af4be851e206a7b359c3a070de4d
904
// // ViewBController.swift // ContainerView // // Created by Shridhar Mali on 12/22/16. // Copyright © 2016 TIS. All rights reserved. // import UIKit class ViewBController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.red // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
25.111111
106
0.670354
090aca23c7f21b7d5be5297929ef7f3105c33e64
360
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { class B<T where T : P { let a : a { { if true { } if true { class b> { } } func b<1 { protocol c : a { println(x: d { } let g = 1) } let f = compose(x: a { init<1 { class case c, in
13.846154
87
0.647222
e57bc1f6ab0b3e4ad83d8501dc48f4eeebc8da1f
1,312
import Cocoa enum ShapeDimensions { // Point has no associated value - it is dimensionless case Point // Square's associated value is the length of one side case Square(Double) // Rectangle's associated value defines its width and height case Rectangle(width: Double, height: Double) func area() -> Double { switch self { case .Point: return 0 case let .Square(side): return side * side case let .Rectangle(width: w, height: h): return w * h } } // BRONZE CHALLENGE func perimeter() -> Double { switch self { case .Point: return 0 case let .Square(side): return 4 * side case let .Rectangle(width: w, height: h): return 2 * ( w + h ) } } } // Examples using the perimeter() method var squareShape = ShapeDimensions.Square(10.0) var rectShape = ShapeDimensions.Rectangle(width: 5.0, height: 10.0) var pointShape = ShapeDimensions.Point print("square's perimeter = \(squareShape.perimeter())") print("rectangle's perimeter = \(rectShape.perimeter())") print("point's perimeter = \(pointShape.perimeter())")
24.296296
69
0.559451
c15ace4394fb3129a26916de9dd1c3929ea3390e
253
// // Entities.swift // Decred Wallet // // Copyright (c) 2018, The Decred developers // See LICENSE for details. // import Foundation import RealmSwift class WalletEntity : Object { @objc dynamic var id = "" @objc dynamic var seed = "" }
14.882353
44
0.660079
1d31bd84b3ccadfce6e13ca0adeaf55dede5e169
1,024
import Foundation /// This should really be private, see https://github.com/zoul/typed-forms/issues/1. public protocol _Bindable: AnyObject { associatedtype Model var bindings: [(Model) -> Void] { get set } } extension _Bindable { public func bind<T>( _ viewPath: WritableKeyPath<Self, T>, to modelPath: KeyPath<Model, T>) { bindings.append { [weak self] model in self?[keyPath: viewPath] = model[keyPath: modelPath] } } public func bind<T>( _ viewPath: WritableKeyPath<Self, T?>, to modelPath: KeyPath<Model, T>) { bindings.append { [weak self] model in self?[keyPath: viewPath] = model[keyPath: modelPath] } } public func bind<T, U>( _ viewPath: WritableKeyPath<Self, T>, to modelPath: KeyPath<Model, U>, through map: @escaping (U) -> T) { bindings.append { [weak self] model in self?[keyPath: viewPath] = map(model[keyPath: modelPath]) } } }
26.947368
84
0.594727
64003d162fd446a757a5c3bb13c6a53f4484fc0c
1,830
// // CATiledLayer+Chain.swift // CocoaChain // // Created by Nelo on 2020/7/6. // import Foundation public extension CocoaChain where ObjectType: CATiledLayer{ @discardableResult func levelsOfDetail(_ levelsOfDetail: Int) -> CocoaChain { self.chain.levelsOfDetail = levelsOfDetail return self } /* The number of levels of detail maintained by this layer. Defaults to * one. Each LOD is half the resolution of the previous level. If too * many levels are specified for the current size of the layer, then * the number of levels is clamped to the maximum value (the bottom * most LOD must contain at least a single pixel in each dimension). */ @discardableResult func levelsOfDetailBias(_ levelsOfDetailBias: Int) -> CocoaChain { self.chain.levelsOfDetailBias = levelsOfDetailBias return self } /* The number of magnified levels of detail for this layer. Defaults to * zero. Each previous level of detail is twice the resolution of the * later. E.g. specifying 'levelsOfDetailBias' of two means that the * layer devotes two of its specified levels of detail to * magnification, i.e. 2x and 4x. */ @discardableResult func tileSize(_ tileSize: CGSize) -> CocoaChain { self.chain.tileSize = tileSize return self } /* The maximum size of each tile used to create the layer's content. * Defaults to (256, 256). Note that there is a maximum tile size, and * requests for tiles larger than that limit will cause a suitable * value to be substituted. */ @discardableResult func tileSize(_ width: CGFloat,_ height: CGFloat) -> CocoaChain { self.chain.tileSize = CGSize(width: width, height: height) return self } }
33.272727
75
0.67541
0880fb5c723b0069a4f90c83bad6e7584334e3d5
6,339
// // FilterControlView.swift // MetalFilters // // Created by xu.shuifeng on 2018/6/12. // Copyright © 2018 shuifeng.me. All rights reserved. // import UIKit public protocol FilterControlViewDelegate { func filterControlViewDidPressCancel(filterTool: FilterToolItem) func filterControlViewDidPressDone(filterTool: FilterToolItem) func filterControlViewDidStartDragging() func filterControlView(_ controlView: FilterControlView, didChangeValue value: Float, filterTool: FilterToolItem) func filterControlViewDidEndDragging() func filterControlView(_ controlView: FilterControlView, borderSelectionChangeTo isSelected: Bool) } public class FilterControlView: UIView { public var delegate: FilterControlViewDelegate? public var value: Float = 0 private let cancelButton: UIButton private let doneButton: UIButton private let titleLabel: UILabel private let borderButton: UIButton private let sliderView: HorizontalSliderView private let filterTool: FilterToolItem public init(frame: CGRect, filterTool: FilterToolItem, value: Float = 1.0, borderSeleted: Bool = false) { self.filterTool = filterTool let textColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1) cancelButton = UIButton(type: .system) cancelButton.tintColor = .clear cancelButton.titleLabel?.font = UIFont.systemFont(ofSize: 16) cancelButton.setTitleColor(textColor, for: .normal) cancelButton.setTitle("Cancel", for: .normal) doneButton = UIButton(type: .system) doneButton.tintColor = .clear doneButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .semibold) doneButton.setTitleColor(textColor, for: .normal) doneButton.setTitle("Done", for: .normal) titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) titleLabel.textAlignment = .center titleLabel.textColor = textColor titleLabel.text = "\(Int(value * 100))" sliderView = HorizontalSliderView(frame: CGRect(x: 30, y: frame.height/2 - 50, width: frame.width - 60, height: 70)) borderButton = UIButton(type: .system) borderButton.frame.size = CGSize(width: 22, height: 22) borderButton.setBackgroundImage(UIImage(named: "filter-border", in: Bundle(for: ToolPickerCell.self), compatibleWith: nil), for: .normal) borderButton.setBackgroundImage(UIImage(named: "filter-border-active", in: Bundle(for: ToolPickerCell.self), compatibleWith: nil), for: .selected) borderButton.tintColor = .clear borderButton.isSelected = borderSeleted super.init(frame: frame) sliderView.valueRange = filterTool.slider sliderView.slider.value = value if filterTool.type == .adjustStrength { addSubview(borderButton) borderButton.addTarget(self, action: #selector(borderButtonTapped(_:)), for: .touchUpInside) } backgroundColor = .white isUserInteractionEnabled = true addSubview(titleLabel) addSubview(sliderView) addSubview(cancelButton) addSubview(doneButton) let buttonHeight: CGFloat = 52 cancelButton.frame = CGRect(x: 0, y: frame.height - buttonHeight, width: frame.width/2, height: buttonHeight) doneButton.frame = CGRect(x: frame.width/2, y: frame.height - buttonHeight, width: frame.width/2, height: buttonHeight) cancelButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside) doneButton.addTarget(self, action: #selector(doneButtonTapped), for: .touchUpInside) sliderView.slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged) if filterTool.type == .color { //let colorControlView = FilterTintColorControl(frame: frame) } else if filterTool.type == .adjust { sliderView.isHidden = true } else { } updateSlider(value: value) } public override func layoutSubviews() { super.layoutSubviews() let buttonY = frame.height - cancelButton.frame.height - keyWindowSafeAreaInsets.bottom cancelButton.frame.origin = CGPoint(x: 0, y: buttonY) doneButton.frame.origin = CGPoint(x: frame.width/2, y: buttonY) if filterTool.type == .adjustStrength { sliderView.frame.size = CGSize(width: frame.width - 100, height: 70) borderButton.center = CGPoint(x: sliderView.frame.maxX + 30, y: sliderView.center.y) } } @objc private func borderButtonTapped(_ sender: UIButton) { sender.isSelected = !sender.isSelected delegate?.filterControlView(self, borderSelectionChangeTo: sender.isSelected) } @objc private func cancelButtonTapped() { delegate?.filterControlViewDidPressCancel(filterTool: filterTool) } @objc private func doneButtonTapped() { delegate?.filterControlViewDidPressDone(filterTool: filterTool) } @objc private func sliderValueChanged(_ sender: UISlider) { updateSlider(value: sender.value) delegate?.filterControlView(self, didChangeValue: sender.value, filterTool: filterTool) } private func updateSlider(value: Float) { titleLabel.text = "\(Int(value * 100))" guard let sender = sliderView.slider else {return} let trackRect = sender.trackRect(forBounds: sender.bounds) let thumbRect = sender.thumbRect(forBounds: sender.bounds, trackRect: trackRect, value: sender.value) let x = thumbRect.origin.x + sender.frame.origin.x + 44 titleLabel.center = CGPoint(x: x, y: frame.height/2 - 60) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func setPosition(offScreen isOffScreen: Bool) { if isOffScreen { frame.origin = CGPoint(x: frame.origin.x, y: frame.origin.y + 44) alpha = 0 } else { frame.origin = CGPoint(x: frame.origin.x, y: frame.origin.y - 44) alpha = 1 } } }
40.375796
154
0.659883
d9fe8feae0626639bc8ce049718a03a7e495b331
1,570
// // CustomScrollViewController.swift // ShoppingApp // // Created by Christian Slanzi on 10.08.20. // Copyright © 2020 Christian Slanzi. All rights reserved. // import UIKit /// A generic adapter to act as convenient DataSource and Delegate for UICollectionView public final class Adapter<T, Cell: UICollectionViewCell>: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { public var items: [T] = [] public var configure: ((T, Cell) -> Void)? public var select: ((T) -> Void)? public var cellWidth: CGFloat = 60 public var cellHeight: CGFloat = 60 public var numberOfSections: Int = 1 public func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfSections } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = items[indexPath.item] let cell: Cell = collectionView.dequeue(indexPath: indexPath) configure?(item, cell) return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let item = items[indexPath.item] select?(item) } public func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: cellWidth, height: cellHeight) } }
32.040816
128
0.742675
f972aef2d7a37ec67bfe3089a5652e566002c8a9
1,509
// // CircleButton.swift // CaptureTheMoment // // Created by Doyoung Song on 6/21/20. // Copyright © 2020 Doyoung Song. All rights reserved. // import UIKit class CircleButton: UIButton { // MARK: - Properties let btnIcon = UIImage(systemName: "camera.fill")! // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func configureUI() { // Colors backgroundColor = colorPalette.circleButtonColor tintColor = colorPalette.circleBtnCameraColor layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor layer.shadowOffset = CGSize(width: 0.0, height: 2.0) layer.shadowOpacity = 1.0 layer.shadowRadius = 0.0 layer.masksToBounds = false layer.cornerRadius = 4.0 // Add an icon imageView?.image = btnIcon imageView?.contentMode = .scaleAspectFill setImage(btnIcon, for: .normal) // AutoLayout addSubview(imageView!) imageView?.translatesAutoresizingMaskIntoConstraints = false [ imageView?.widthAnchor.constraint(equalToConstant: frame.width / 3.5), imageView?.heightAnchor.constraint(equalToConstant: frame.width / 3.5), ].forEach { $0?.isActive = true } } }
27.944444
83
0.607687