label
int64
0
1
text
stringlengths
0
2.8M
0
import Foundation extension PasswordGeneratorView.PasswordView { enum Action { case generatePassword case updateFlow(Flow) case updateCopyableContentView(CopyableContentView.Action) } }
0
// // ColumnNavigationViewState.swift // Construct // // Created by Thomas Visser on 28/09/2020. // Copyright © 2020 Thomas Visser. All rights reserved. // import Foundation import ComposableArchitecture import DiceRollerFeature import Dice import GameModels struct ColumnNavigationViewState: Equatable { var campaignBrowse = CampaignBrowseViewState(node: CampaignNode.root, mode: .browse, items: .initial, showSettingsButton: true) var referenceView = ReferenceViewState.defaultInstance var diceCalculator = FloatingDiceRollerViewState(diceCalculator: DiceCalculatorState( displayOutcomeExternally: false, rollOnAppear: false, expression: .dice(count: 1, die: Die(sides: 20)), mode: .rollingExpression )) var topNavigationItems: [Any] { var res = campaignBrowse.topNavigationItems() if let ref = referenceView.selectedItemNavigationNode?.topNavigationItems() { res.append(ref) } return res } } enum ColumnNavigationViewAction: Equatable { case diceCalculator(FloatingDiceRollerViewAction) case campaignBrowse(CampaignBrowseViewAction) case referenceView(ReferenceViewAction) } extension ColumnNavigationViewState { static let reducer: Reducer<Self, ColumnNavigationViewAction, Environment> = Reducer.combine( FloatingDiceRollerViewState.reducer.pullback(state: \.diceCalculator, action: /ColumnNavigationViewAction.diceCalculator), CampaignBrowseViewState.reducer.pullback(state: \.campaignBrowse, action: /ColumnNavigationViewAction.campaignBrowse), ReferenceViewState.reducer.pullback(state: \.referenceView, action: /ColumnNavigationViewAction.referenceView), Reducer { state, action, env in switch action { case .campaignBrowse, .referenceView: if state.diceCalculator.canCollapse { return Effect(value: .diceCalculator(.collapse)) .receive(on: env.mainQueue.animation()) .eraseToEffect() } default: break } return .none }, // manages interactions between the left column and reference view Reducer { state, action, env in var actions: [ColumnNavigationViewAction] = [] let encounterContext = state.campaignBrowse.referenceContext if encounterContext != state.referenceView.encounterReferenceContext { state.referenceView.encounterReferenceContext = encounterContext } let itemRequests = state.campaignBrowse.referenceItemRequests + state.referenceView.referenceItemRequests if itemRequests != state.referenceView.itemRequests { actions.append(.referenceView(.itemRequests(itemRequests))) } if case .referenceView(.item(_, .inEncounterDetailContext(let action))) = action { // forward to context if let toContext = state.campaignBrowse.toReferenceContextAction { actions.append(.campaignBrowse(toContext(action))) } } if case .referenceView(.removeTab(let id)) = action, state.referenceView.itemRequests.contains(where: { $0.id == id }) { // inform context of removal if let toContext = state.campaignBrowse.toReferenceContextAction { actions.append(.campaignBrowse(toContext(.didDismiss(id)))) } } return actions.publisher.eraseToEffect() } ) static let nullInstance = ColumnNavigationViewState() }
0
// // ChatLayout // EditNotifierDelegate.swift // https://github.com/ekazaev/ChatLayout // // Created by Eugene Kazaev in 2020-2022. // Distributed under the MIT license. // import Foundation import UIKit public enum ActionDuration { case notAnimated case animated(duration: TimeInterval) } public protocol EditNotifierDelegate: AnyObject { func setIsEditing(_ isEditing: Bool, duration: ActionDuration) } public extension EditNotifierDelegate { func setIsEditing(_ isEditing: Bool, duration: ActionDuration) {} }
0
/// Protocol for matrices that support transposition. /// /// [square matrices]: https://en.wikipedia.org/wiki/Square_matrix public protocol TransposableMatrixType: MatrixType { /// The resulting type of a transposition of this matrix. associatedtype Transpose: MatrixType /// Returns a new matrix that is a [transposition] of this matrix. /// /// [transposition]: https://en.wikipedia.org/wiki/Transpose func transposed() -> Transpose }
0
// // CacherTestHelper.swift // CacherTests // // Created by Prajwal Lobo on 20/03/18. // Copyright © 2018 Prajwal Lobo. All rights reserved. // import Foundation import UIKit @testable import Cacher let imageString = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIQEBAPDxAPDw8QEA8PDw8QDw8ODw0PFREWFhURFRUYHSggGBolGxUVITEhJikrLi4uFx8zOzMwNygtLisBCgoKDg0OFxAQGC0lHyUtLS0rLS0tKy0tLS0tLS0tLS0tLS8vKystLS0tLSstLS4tLS0tLSsrKy0tLSsrLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAcAAACAwEBAQEAAAAAAAAAAAACAwEEBQAGBwj/xAA9EAACAgEDAgQEBAQEAwkAAAABAgARAwQSIQUxEyJBUTJhcYEGFCORQlKhsWJywdEzgpIHFRYkU2Oy4fD/xAAaAQADAQEBAQAAAAAAAAAAAAABAgMABAUG/8QAJxEAAgICAgICAQQDAAAAAAAAAAECEQMhEjEEQRMiUUJhobEFFIH/2gAMAwEAAhEDEQA/APKnHB8OW9kgpOM8rkVRjhBI8JJ2wmsrlYtllorAKxkayoySAktFJGyMLYkJDCxgWEBMDkKCyCkbJqEDYrbO2x22dtmBZX2yCksFYJWMCyvtnBY4rI2zBAqRUYVgsJkCTAIg7YVTjHItgkThJqQBMD2EBJqQIUVjxZwEOoKmEDJM6InARggRiiAayZBEmcYDWLIkERlQGhDYFSZFzoaMaREipNzgYiRIGpxWHU6oTWJIkERxEErCaxJWQVjdsEiEDF1AJhtAIjCkAxggARgEzYTjOk1O2wWaiJFQtsmpuRqI2TtkYIVRHIZISccU2OWysWwhUgSRW2TtkeRBqU5EWhOyCySxUhlm5GoqkSAY5kgbZrGSIAhCSBCIk2zoiiIamCIUFhDkSJIms1HVAYQ4DGFM1AVOkXOjGovXCWAhjVk2yYQEmoQnQWCganbYdTpuQaFFYphLDCKYQ8jUIIkVGEQYeRqBAhATpIEDZqOAkwp0WwkTqkgQts3I1AQxJCwtsFmAYxdRpEEiFMDAqRth1J2x7EaFVJ2xuyQVmsWiuywdseywamsZCtkgrHhZDLEbLIr7YQjNsEiaxiJIkTrhMSRFvDZol2hRgC0mKJnRzGmhjlldDHKZJsWhwMIRQMMGICgxOgiEJrMdFusZIIgsBWIg1HssjbDyDQnbJqM2zqmsNAVCUSahKIGzUcFhATT0nRcjhWfZhxsAVyZWCBwe20d2+wmzj/D2mUVkz5GYqGGwIgr6G7/cQ02Vh4+SW0jyoE4ieh6t+H0RDl0+XxUX4kahkHuRXB4PbiefIiu0LPHKDqSAIgMI0xZEZMkxYjRAAhiNYtBgSCskGTcWzUJZYG2PMWYeQUgQJxWTJuLZRCysBkjpIS4bCVSsAiaA01yG0Jm5oNGY0W8030hHpA/JX6QLLEbiZJE6aZ0JkSnyxBxFo0crSqrRqtFFosBoxTK6mNVorBQ8QotWhXFAFcEmCxnCYFEgQts5RGAQNjUKIgVHkSNs1mFhZtfhrpa58jFxuTGASoO3exNKpPt3/aVNBpA5JYlca8uwFmvRV9Nx+fHc+k9Fj6piVHw4sKjCocOylmbJQFncK3Gj3sfKwLjwje2dXj4HN8n0drdCrsS7o+2tqq+yiD8AW6rg/Sp5bH0R/wA1ny5c2Rg5fZjK4mONWcEkspt9o8oJA7mbb4sKIpxZHzITTrkN+KwsLuH8I4Pxc+USgdcVY41wBQQzM3inUDKQCK4UVQHtXFR1NtNHqcVovdP0QRicLMuQK5GbJkZ2REUliqLS+lc3MfU6l3sPkyOL3U7bgD7gdh9gJs9MLPi1QQEbNOQH2EAivOLI9dhF8f1mCZLlKqOHzpu1FdAwGhSDMmedQudcgmCWjijlMOIUxlwMxJgGEYJgswMiFUiAdEqJbwY5Wxy/pxBJjofiwy7j04qBgWaenwzlyyZWMTMyaK/Scmh+U3hpp35ecM5tbKqBhHQidNw6eRJ/O/yHgfKwY1WioQn0JytFhXjFaVlMapisWiyrQw0rK0YDFBQ24SxQMNTAah6mGIpTDBihoKSogSTnGNS5Fn4UHHLHj/8Afv6QD48bnJRQWo61jRRgxgcDzu1Nuc9+DwF7f9IlbFqWznbx4eFTkLMOz2WQAAWfML9e3auB5zVEEhFUNl3WQPKvFizzwPX7T2nQtBtQWDuss5LCiKKg7SwCgWK4Pp8p0t0kexCCSpFpczMCfzCjyNuzKMbnK25wSAvNbie9VfeVMOs8NTkLlyCqAn4f5uNvcFtov5H50xgQzZAuO3VgNqfpFcbU3Nct8VAfeJy407MjrbkFHbKxohaRUv229xXp6RB6L3R9cyt4bMtFCrg0CCdwJKgcgi+x77ftjmaOnw+GMrqDjUiyrbdxLCgPL2FhT/yn05lAiSb2ef53cUKkNGVBIhs4aEtF1GsIBjpitErGKYoQhMwUNuTUEGEDEMkRthDFG4kltMUlPLRVRKIxS3pxHjDDXTn2k1nTYyiaGkTtNfTpMfSEibGneaSKxLipJOOTjaGTOLLAshOydGTpx0OfGanQqk7J9OcLQIMNTI2SQJgUGpjN0Woh1FFoINGYzExmMxWYtAybgLNHSaUBVyP/ABWVHHYGr547j1/aIVxYnkdIVh05NE2oPbjcz/5V9fr2+cz+qDdkVEVi1FUThjxy7NXpYI+g47z1C7MYZsjBDVhB5suU1x9vmeJ5rQ4viyk279z8iOw/2/xCPFVcj0Vjx4Itrb9ljoXS18MPlQrmdubKlQosc/ej25muucq20rxW07QSpBbttPpO0HUsaD9cAVYGSt20NQ9vl3+ct6bQYs3iNizI4JpnxupKMOwNE0RCpt7L45RnG0N6e3/F2gItADhV8OrNUL5v5/vKmn0NsWB8z8Oa7qaoD2qgPoJeweF5kOdGKUMnmFijfIHqZV1+uUqVxXzYZiK8vsPYHiLLIzZMmPErb3+DO1hAAxqbVbtv5m/tQ+Xz95TIjmEW0kmeNObnJyYhhAMcwnJgJj9CUViJBSaePRw/ycSWZI3EyCsiaeTSyllxVDHKpAcRUJZCqY5cRjNmSLmmWX8eKK0GLtNnBgnnZ5Oy0YlTFglxcHEtY9PHDFFgPRQXDLeIQjjhKJ3J2gDsbQ98qnJUW+ac+Rjplw5J0zvzEmcfEbkfNykkJNnrPRn077W5U/C3v8pnjHPddrTINUV9kjZLYxyfCmsUqKsYFjxihDFA2AqlJKrLfhSVwQWChKiNAlnHp5ZTSXFZjPCe/Y96jUUAKqilUfUk+rE+/b7AS4+iI7RQxEd4rbqhuTqiMWLdamqIN2L4HP8ApOw4wg2qAFsmh2J/mPuZb0ePzH/Jk/8AgYpUmk/ohnJ8FEnR6VVx5dgFnIMzcc0RtIv2BIP/ADfKQRLOkfYwJ+E2GHupFEfsZGr0+xyvcDlT/Mp5B/aB7Vhm3Opf8KbCKYSyywNkCJ0BjxXNHTaWdpsM1tPihn0MkIxaaG2lmimOM8GcM0OkYOXSyll0c9LmwShnxTzX5Usc6GcLRgflQDGeBLuXHCTFPQx5nLZPiBpMc29KnEp4cU0ME2R2UiqLSpJ8OHjMYY0B6KTrEtLWaUsjS/OkLQjK9SpkzQ9VkmVnzRF9hWWTqZEym1E6H4QWey/EfTcmYcD58zxuTRlSVYURPrGLVLkHaYHW+mBvMB9/UT2c2Fy+yL5IJ9Hhxghfl5o+BRo9xDXBfFTz+RyNGX+XhjTy7lKJ8bon+dlX+87V58OAr4+RcYYblPDbhdWKPIvjv6H14hXJ+ho45S6RUGnjcemlxUUi0ZHHHKMD37cdx29Zc0WifIduNGc/IXX1Pp94tu6Bxd00UsWmlpMEdrx+WQvnTLjQd28HKyj6lVIH3i+k6jLqFGTHodU+Fq25Q2Bb55NOwO2qIIBuMozeki8PGnJXWv3C8ERGbSAz0Gn6NkYWynGwYDw2bGxK8ea1YgDv3547Szj6Mqj9Vhk2m7BGMqKrzbKv3Pp8hGXi5pd6CsD9nlNHgCuN17aYHaNzEMpHA9fU/aV3wbdxcqioSGd2CY9w/h3NQs+gmxqfwdixZG1OPLqPEKBUxtn8RQNykbQ3mulq7JIdu8r9b/CmmzM65cYDugZlfITlFmgVCOaA3ivKeTV83OmPiLilJlP9eOtmJqOpadKF52O8qGXEhTL5SQcVMS4sN6X5Dx2vabCMirjdNRjyIBsOTTsPFxMLG3bu3UbscMObHM1uidK2pp2GHHiYYuQvnTGwB3FW3EgggAmySD6jiegykqSwDEc2AwHsbs/tH+CFPRX4oR1R4HVdKdBdMa4Nij6egJI7jvKASezwYczl2/Uxr5vh2Fwb4ryjn181wdX0pHC34jGqLt4e9T7ttA9gOxAk5+L7iRyYF+k89pRNPAITdJVGKh2Hb41HPAs2PS7+kBDtFtVCrIJbk+na7kpYJ10R+OSL2MRyrKuHOpqiOewNqW+YB5I+csb55uZOPYarsjKspZcUuM0S08bMrZRGfl09yEwS8VkbZTDka0BxF4scsosBDHrOtOwJBLJLQGaJfJKJhOzvKGV4/K8o5nlUBlXVvMfUvNPPMzULOjFEmygz8zpJWTOukA+v6BVqlj3xXYMy+g5rwpkKuFatpKkel+vp85c6l1fFixnIz+QA8oA7M3bavoWsjyizfpPVOumzK6n0SzadyQAPczL13QsxWmvGo5dfEAxuoBN5WKgovpSFjzzwLlzqn4jz/lny6fD4L0dn5kBWUngZHHcIOLG2+PSYo65pSCOqa7JrWdVb8riwZMWiYivKFRd2YX/PYPBqcS+Dm2nstHxpRalxGf8AcufUsqvj0uoXGmNjmxDeMzFSBZzV5CB6X/D8zLzfgtWsOMPhYV2YkTxrZhzbuSqjub4bv8pt9L/E2PMqLh0+YKQApCHEi12BsDaP6/KXMZytmAyk7FFsAuzAv8qqW8zuDzu4HHbnh1wlvZZqcdOkY2h6dpyi48OEeIOGXc5CN/i8IsOfewPnxU1tN0nNhT9HJgw2QchGNszOovhWZhtPPej9L5mnny+EhKqdqi1RAPMPlQ+XYTM6f1svZbTauwf/AE8e1R/hsgn19z/aBY8cWr7JuPK5Riv4LOLo/mDNmzN2YjxXFt6WAaI+RvvLjaQIoXGfD5BtVVjVgsTu9+eTzzM3H13GS36Os4am26VxzXrXPauYrW9Y0uXGwObEjKSwXOwA3gUpfGTbDn4SP61LxjFbQknNumaZ1uNx+nmxng2we0A+bDyj7yi2lfNbXsxc7VVmD5ef+IWB9a7dqPPPYOndR0+Rt6uzPtAvwnx4+D6BgCT7X7/OWCGG13cOVBbtsSjzyPXj14+kVv2Mo+kebRMAy5CmmyjJpmxv42TFvR3aqdMj9wKILem495p4Me/HuxagK2QgvXhv4uQfEGZgSRxQAogCr44PFrsmUUuLFzwW3uVxc2CAV8371GHp4whfDO0nzF6Xhr/YHtxVVxEvdos1Wn2FmxK6qqL6+ICF43oa2kdu9+Xjv9wjxwFVcvl3KMb2o4Y+hPpfFHntLmPUKFUPQIPJPK2xr0JoG+/p9Jn64K5Z8QJdH8+JuTYuiw+tj7/SOqdE6e0zkzJ5kxtTBgWFgFbRX7enlYGXtCSTTFybNBhVetA1TTzmu0v66uG8Nmwo/lRz4i4jyhNkk25X37zUTXMmJXONjQ8+LHuXMo5rZ2DN8uP6UUU/tTNLH9bRtviXKWVlHl2nzclrHcAencfYynqfw+psqSho8KAePv6fKW9Pq1yDcjhivfvvWx8LD/Qy3jy+lc1YU8Ej3FytkaPEa3oT4V42up2gqVO1RXm7cjtfH7esrYNFqkBZN+T/ANrIy7V4oUe4F129jwZ9C8PdyRyPvUoavpoexyLBujwSfUj0+oqJPFHIqkrF0eaVmI8yMh9Qw/sexHPcSbk59DlxvRJy4N27ZwXXjjYSe/8AcE/ORlxle9i+wYFWr6H/AEsfOfO+d/jXjfOG4/0I41tAkyJBM4NOOGOidkiNDxO6RcvGALHM8r5GklooqW7AmXjjDYrK8p5DNROmu3pK2v0LYxZ7S6wy7oZwlXRlZTKWYTQZLiMmKPF0RaMs450veDOlOQD1HSxlx4/DxqwdaoZP/MZWY0RudnIFC/LuofSHp8DebN5tRldgGV9aQEIFUpCbUHc0gq7njutLgw4WVcmsGPxKyJj1JHhs92VAFfbtVzxGqZcOTxcLZvCZiiurbWugQDVc0Z2xhfcm/wCj1pZK6ikfam6baEYtPp3ZACq5tbnzYlBv+Hw6HbsAO0tdIwZMSk6nF0/ACLAwM27v3Jcc8T4r0rqKsR42q1Yc3tZCf0iPh+ZH0mr03qrrlGsx6jJqDhXZWZiy0wA2/IXz9o/DHH9P8C/JN+/5PrC/iDB4hvW6cKAKxopcKOed6kWTx6S7ptWjOpxsc/fu7KP+iuf69p8e65lOqHijDpcTguHfC5Znu+TjIoe/v2mdpNJnxbMwIzKCCnDjIjXR2IfX5ijCpRWgPkz9AvnybqZBjxerE73PtwPh/rB1ufULZworigRvybTfqNoX29zPiul/HzaTMX1WnyZMyp5MmdsjMq3Q2Kex57z12g/7X9Myrak5DQ2AbRdfzMff3jpWuxG0n0b3WulvmXE+XwyS6rkVcG4BSefiJJH0H7S10/8AC2lxN4w0+FG967H17qKlDRfj/HlGMMjYmYkN5kPNgLs581/6TS0nUWcsx1Ix40tTjYYywr+Jr5H7xXCP4sopzrui9i0/iE7ihxWypjxqQlAjl2qyePkKJHPeTrdSUZaQlmPoRQFev7TM1/XtLiKFMeTPmyX4YxpsOUgclWagf3j+m6psql8+FMC76CFg7VXxk+/P/wBma10ZJpWaKaYEAkVd/W/lI1CVwBv45HYm+Lrt7x6dQxL5TkTgWSXXj6xu1WAZTuB5BBBBB9ozSZNSa7MkafxOM2AjGpBQh96DvTVQN/WUNZo1w/rI2bGd6/CjZfF28hWRQTXHpXE3HyKGClmQn4W52hu9X7/WdjLi9/6ovuQFIHvxwYiVLspy9mDr1bxCFUm8aBuCFU82ykcjsLu/7w9RoztJx03lIoMxI96vg8+tXNLqOpVUpMb5OQGTGLYC9u4D1onkVEppXTheRXC+oPzB9PvEb9Dpasxn6k+LHudG8gcFgKYUxHf61/tI6Z+Ja3nPjybVIpthIAPYWti+fcfSdrkVi+PUBvHoHG2nwZCCliuQpFe9/OeV1/T9VjbJk0x1DeGG4zLkyFsbgblx7VC+/Ffw+vaaNxfeguCktn0nRdex5cbZMLeMoBO3Gd+Rq9Avf9xL2LWhgB2YgNtPxAHtxPnvTeilcTZsq48TFGY/pPbMSTRUDcK7ccetew6fq+THkTxMyHHmVcKBn+DOTwVcEuAe1duI6yq6JPA6PoGswjIpFX7g9jMo6PEbVj4bHgElQbr4hfH2/pKOm62UbI2MNqsW7zHCzZmxvyCpXbYA+Z+0r678ZIQa0uY2KByY2xU5HlBsGvr713jOUWmmT+OX4B1eMo1Ej+vb0P0MreJGafEWdcjYcjHKoG6xSp4jUSrEGx/KD2PvOz6cK7puUMjlNrOhZjYqq9SCvcDvxc8bL4jtygtE8uFxegA8nfOGna6KkH5gia+k6WCBcGLx5T6Ixg2UdJpGyHtxPQ6Xp6qO0dgxqgoCMLz08HirHt9nTFKKpEeGAO0zepYhkUiaDvxUqttF3LtWUTPEarT+GaANRQFzc6xlUg1PP6fLTEn3nFmgpdGyYOUbD8KdLa0eZ04tnn8TxubRh8LXdl181m+5/wBzMYdHXaqUTWRyCTwQODYnTp6kXR6kkhPTNAm9rBDLuoAj0PofpLOg0Qxt4a35zuJPw7QeLE6dGbYiSO12k3OqK211tiwsGi3AE3tJ1LU4C25xl2KpBcAldx9u06dA+hktjz0TBqnbLqWKjKpphfmyEfDtHZRXaI/8A6amO4sfMd6k4wSR5aSj7e86dIyk0tMqopvaKem/BG1xkVjeHZlFkElkawO9dxPXdJ6kq4i+oPjaos7vuQcc8AHtQUCdOlvHk5LZPNFRejH6h1r8ziz5nz5EOM7URFAAVeeD6Gx34njh+M84yknNkHlUbizHt6kA80PTtJnSke5Epvo9X0X8dFk8DKoyjlRnIosleq97+8970XraYsKUKQhNmIA0gJqgfb5ek6dKJWgfsbup6mtUVtz8KtVE/USvhy5mwMcmDErKeQGUpkUG+w7H/WdOknuVfsUVKPQQ6orLhy7CEeiFG20Pt85eyIzrW41V7gdpInTo8VaJz0zO6tqFVbBYHGN/l79iPX95mZdWzUwII5VhtCuzAWabsOK7g+s6dOHK+GRNezuxLlB2Fh1b5DSBH2DcVL5Q1Htz8PoeK9InqnS9K+3JmRBl+JW2HaHU2ppavn3uROnRbaJtJS0Vup6DUY1DFsa4xTBsLZdxJrynGxC7fXg/aO0PWWd/y2Zy2QA1uxFd/rYK5D27c88XOnQv69CL7J2Mx/iPH4j4xkO9D8JxsDsAHO7kEcMD6+3vK2qyK2TG5Z/GyrmXHlx3sD4vOrFSQaUbjzyWr5EROmcnSCoLZs6HrS58jYsoVXFeGBbMwFAsTVdyPX1mwq0J06Vh1ZCaqWiCYnNmHYTp0ZioQ+oCgnm6mLk1hYmROiSKLooa48WZh63UgA16Tp0hkWykG6OwdQ8okzp0nwRJ442f/9k=" let imageData = Data(base64Encoded: imageString) let testImage = UIImage(data: imageData!) let testCacheKey = ["https://medium.com/@shahabejaz/create-and-distribute-private-libraries-with-cocoapods-5b6507b57a03","http://base64.wutils.com/encoding-online/image-to-base64/"] func clearCache(cache : ImageCache){ cache.clearCache(type: .memory) }
0
// Copyright © 2018 Stormbird PTE. LTD. import UIKit import PromiseKit protocol AccountsViewControllerDelegate: class { func didSelectAccount(account: Wallet, in viewController: AccountsViewController) func didDeleteAccount(account: Wallet, in viewController: AccountsViewController) func didSelectInfoForAccount(account: Wallet, sender: UIView, in viewController: AccountsViewController) } class AccountsViewController: UIViewController { private let roundedBackground = RoundedBackground() private let tableView = UITableView(frame: .zero, style: .plain) private var viewModel: AccountsViewModel private var balances: [AlphaWallet.Address: Balance?] = [:] private let config: Config private let keystore: Keystore private let balanceCoordinator: GetNativeCryptoCurrencyBalanceCoordinator weak var delegate: AccountsViewControllerDelegate? var allowsAccountDeletion: Bool = false var hasWallets: Bool { return !keystore.wallets.isEmpty } init(config: Config, keystore: Keystore, balanceCoordinator: GetNativeCryptoCurrencyBalanceCoordinator, viewModel: AccountsViewModel) { self.config = config self.keystore = keystore self.balanceCoordinator = balanceCoordinator self.viewModel = viewModel super.init(nibName: nil, bundle: nil) view.backgroundColor = Colors.appBackground roundedBackground.translatesAutoresizingMaskIntoConstraints = false view.addSubview(roundedBackground) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .singleLine tableView.backgroundColor = GroupedTable.Color.background tableView.tableFooterView = UIView() tableView.register(AccountViewCell.self) tableView.register(WalletSummaryTableViewCell.self) roundedBackground.addSubview(tableView) NSLayoutConstraint.activate([ tableView.leadingAnchor.constraint(equalTo: roundedBackground.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: roundedBackground.trailingAnchor), tableView.topAnchor.constraint(equalTo: roundedBackground.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ] + roundedBackground.createConstraintsWithContainer(view: view)) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configure(viewModel: .init(keystore: keystore, config: config, configuration: viewModel.configuration)) refreshWalletBalances() } func configure(viewModel: AccountsViewModel) { self.viewModel = viewModel title = viewModel.title tableView.reloadData() } private func confirmDelete(account: Wallet) { confirm( title: R.string.localizable.accountsConfirmDeleteTitle(), message: R.string.localizable.accountsConfirmDeleteMessage(), okTitle: R.string.localizable.accountsConfirmDeleteOkTitle(), okStyle: .destructive ) { [weak self] result in guard let strongSelf = self else { return } switch result { case .success: strongSelf.delete(account: account) case .failure: break } } } private func delete(account: Wallet) { navigationController?.displayLoading(text: R.string.localizable.deleting()) let result = keystore.delete(wallet: account) DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in guard let strongSelf = self else { return } strongSelf.navigationController?.hideLoading() switch result { case .success: strongSelf.configure(viewModel: .init(keystore: strongSelf.keystore, config: strongSelf.config, configuration: strongSelf.viewModel.configuration)) strongSelf.delegate?.didDeleteAccount(account: account, in: strongSelf) case .failure(let error): strongSelf.displayError(error: error) } } } private func refreshWalletBalances() { let group = DispatchGroup() for address in viewModel.addresses { group.enter() balanceCoordinator.getBalance(for: address) { [weak self] result in self?.balances[address] = result.value group.leave() } } group.notify(queue: .main) { [weak self] in self?.tableView.reloadData() } } private func getAccountViewModels(for path: IndexPath) -> AccountViewModel? { guard let account = viewModel.account(for: path) else { return nil } let walletName = viewModel.walletName(forAccount: account) let balance = self.balances[account.address].flatMap { $0 } return AccountViewModel(wallet: account, current: keystore.currentWallet, walletBalance: balance, server: balanceCoordinator.server, walletName: walletName) } required init?(coder aDecoder: NSCoder) { return nil } } extension AccountsViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return viewModel.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfItems(section: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch viewModel.sections[indexPath.section] { case .hdWallet, .keystoreWallet, .watchedWallet: let cell: AccountViewCell = tableView.dequeueReusableCell(for: indexPath) guard var cellViewModel = getAccountViewModels(for: indexPath) else { //NOTE: this should never happen here return UITableViewCell() } cell.configure(viewModel: cellViewModel) cell.account = cellViewModel.wallet let gesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress)) gesture.minimumPressDuration = 0.6 cell.addGestureRecognizer(gesture) let address = cellViewModel.address ENSReverseLookupCoordinator(server: .forResolvingEns).getENSNameFromResolver(forAddress: address) { result in guard let ensName = result.value else { return } //Cell might have been reused. Check guard let cellAddress = cell.viewModel?.address, cellAddress.sameContract(as: address) else { return } cellViewModel.ensName = ensName cell.configure(viewModel: cellViewModel) } return cell case .summary: let cell: WalletSummaryTableViewCell = tableView.dequeueReusableCell(for: indexPath) cell.configure(viewModel: .init(walletBalance: nil, server: balanceCoordinator.server)) return cell } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard allowsAccountDeletion else { return false } return viewModel.canEditCell(indexPath: indexPath) } @objc private func didLongPress(_ recognizer: UILongPressGestureRecognizer) { guard let cell = recognizer.view as? AccountViewCell, let account = cell.account, recognizer.state == .began else { return } delegate?.didSelectInfoForAccount(account: account, sender: cell, in: self) } } extension AccountsViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let value = viewModel.shouldHideHeader(in: section) let headerView = AccountViewTableSectionHeader() headerView.configure(type: value.section, shouldHide: value.shouldHide) return headerView } //Hide the footer func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { .leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { nil } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let copyAction = UIContextualAction(style: .normal, title: R.string.localizable.copyAddress()) { _, _, complete in guard let account = self.viewModel.account(for: indexPath) else { return } UIPasteboard.general.string = account.address.eip55String complete(true) } copyAction.image = R.image.copy()?.withRenderingMode(.alwaysTemplate) copyAction.backgroundColor = R.color.azure() let deleteAction = UIContextualAction(style: .normal, title: R.string.localizable.accountsConfirmDeleteAction()) { _, _, complete in guard let account = self.viewModel.account(for: indexPath) else { return } self.confirmDelete(account: account) complete(true) } deleteAction.image = R.image.close()?.withRenderingMode(.alwaysTemplate) deleteAction.backgroundColor = R.color.danger() let configuration = UISwipeActionsConfiguration(actions: [copyAction, deleteAction]) configuration.performsFirstActionWithFullSwipe = true return configuration } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let account = viewModel.account(for: indexPath) else { return } delegate?.didSelectAccount(account: account, in: self) } }
0
// // MaskedTextContainerView.swift // demo // // Created by Johan Halin on 26/02/2019. // Copyright © 2019 Dekadence. All rights reserved. // import UIKit class MaskedTextContainerView: UIView { private let labelCount: Int private let contentView1 = UIView() private let contentView2 = UIView() private let contentView3 = UIView() private let contentView4 = UIView() private var label1: UILabel? = nil private var label2: UILabel? = nil private var label3: UILabel? = nil private var label4: UILabel? = nil init(frame: CGRect, labelCount: Int) { assert(labelCount >= 2 && labelCount <= 4) self.labelCount = labelCount super.init(frame: frame) self.backgroundColor = UIColor(white: 0.1, alpha: 1) self.contentView1.frame = self.bounds self.contentView2.frame = self.bounds self.contentView1.mask = MaskView(frame: self.bounds, offset: 2, count: labelCount) self.contentView2.mask = MaskView(frame: self.bounds, offset: 6, count: labelCount) self.label1 = addLabel(toView: self.contentView1) self.label1?.clipsToBounds = false self.label1?.textColor = UIColor(white: 1.0, alpha: 1.0) self.label2 = addLabel(toView: self.contentView2) self.label2?.textColor = UIColor(white: 0.6, alpha: 1.0) self.label2?.clipsToBounds = false self.addSubview(self.contentView1) self.addSubview(self.contentView2) if labelCount >= 3 { self.addSubview(self.contentView3) self.contentView3.frame = self.bounds self.contentView3.mask = MaskView(frame: self.bounds, offset: 10, count: labelCount) self.label3 = addLabel(toView: self.contentView3) self.label3?.textColor = UIColor(white: 0.4, alpha: 1.0) self.label3?.clipsToBounds = false } if labelCount >= 4 { self.addSubview(self.contentView4) self.contentView4.frame = self.bounds self.contentView4.mask = MaskView(frame: self.bounds, offset: 14, count: labelCount) self.label4 = addLabel(toView: self.contentView4) self.label4?.textColor = UIColor(white: 0.8, alpha: 1.0) self.label4?.clipsToBounds = false } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addLabel(toView parent: UIView) -> UILabel { let label = UILabel(frame: parent.bounds) label.font = UIFont.boldSystemFont(ofSize: self.bounds.size.height) label.lineBreakMode = .byClipping label.textColor = UIColor(white: 0.7, alpha: 1.0) parent.addSubview(label) return label } func setText(text1: String, text2: String) { assert(self.labelCount == 2) updateLabels(text1: text1, text2: text2) } func setText(text1: String, text2: String, text3: String) { assert(self.labelCount == 3) updateLabels(text1: text1, text2: text2, text3: text3) } func setText(text1: String, text2: String, text3: String, text4: String) { assert(self.labelCount == 4) updateLabels(text1: text1, text2: text2, text3: text3, text4: text4) } private func updateLabels(text1: String, text2: String, text3: String? = nil, text4: String? = nil) { let angle1: CGFloat let angle2: CGFloat let angle3: CGFloat let angle4: CGFloat switch RotationOption.random() { case .none: angle1 = CGFloat.random(in: -0.2...0.2) angle2 = angle1 angle3 = angle1 angle4 = angle1 case .some: angle1 = CGFloat.random(in: -0.2...0.2) angle2 = angle1 + CGFloat.random(in: -0.2...0.2) angle3 = angle1 + CGFloat.random(in: -0.2...0.2) angle4 = angle1 + CGFloat.random(in: -0.2...0.2) default: angle1 = CGFloat.random(in: -1...1) angle2 = CGFloat.random(in: -1...1) angle3 = CGFloat.random(in: -1...1) angle4 = CGFloat.random(in: -1...1) } setTextAndCenter(label: self.label1, text: text1, rotationAngle: angle1) setTextAndCenter(label: self.label2, text: text2, rotationAngle: angle2) if let text3 = text3 { setTextAndCenter(label: self.label3, text: text3, rotationAngle: angle3) } if let text4 = text4 { setTextAndCenter(label: self.label4, text: text4, rotationAngle: angle4) } if Int.random(in: 0...3) == 0 { self.label2?.textColor = ModernPicturesConstants.redColor } else { self.label2?.textColor = UIColor(white: 0.6, alpha: 1.0) } } private func setTextAndCenter(label: UILabel?, text: String, rotationAngle: CGFloat) { if let label = label { label.transform = CGAffineTransform.identity label.bounds = self.bounds label.text = text label.bounds.size.width = label.intrinsicContentSize.width label.transform = CGAffineTransform.init(rotationAngle: rotationAngle) UIView.animate(withDuration: 2, delay: 0, options: [.curveLinear], animations: { label.transform = label.transform.translatedBy(x: CGFloat.random(in: -20...20), y: CGFloat.random(in: -20...20)) }, completion: nil) } } enum RotationOption { case none case some case lots static func random() -> RotationOption { switch arc4random_uniform(3) { case 0: return RotationOption.none case 1: return RotationOption.some default: return RotationOption.lots } } } }
1
// RUN: not %target-swift-frontend %s -typecheck ""[{class a{enum S:S<n>{class case,
0
// Copyright 2016 The Tulsi 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 /// Handles fetching of interesting paths for a Bazel workspace. class BazelWorkspacePathInfoFetcher { /// The Bazel package_path as defined by the target workspace. private var packagePath: String? = nil /// The Bazel execution_root as defined by the target workspace. private var executionRoot: String? = nil /// Optional path to the directory in which bazel-* symlinks will be created. private var bazelSymlinkParentPathOverride: String? = nil /// The location of the bazel binary. private let bazelURL: NSURL /// The location of the Bazel workspace to be examined. private let workspaceRootURL: NSURL private let localizedMessageLogger: LocalizedMessageLogger private let semaphore: dispatch_semaphore_t private var fetchCompleted = false init(bazelURL: NSURL, workspaceRootURL: NSURL, localizedMessageLogger: LocalizedMessageLogger) { self.bazelURL = bazelURL self.workspaceRootURL = workspaceRootURL self.localizedMessageLogger = localizedMessageLogger semaphore = dispatch_semaphore_create(0) fetchWorkspaceInfo() } /// Returns the package_path for this fetcher's workspace, blocking until it is available. func getPackagePath() -> String { if fetchCompleted { return packagePath! } waitForCompletion() return packagePath! } /// Returns the execution_root for this fetcher's workspace, blocking until it is available. func getExecutionRoot() -> String { if fetchCompleted { return executionRoot! } waitForCompletion() return executionRoot! } /// Returns the tulsi_bazel_symlink_parent_path for this workspace (if it exists), blocking until /// the fetch is completed. func getBazelSymlinkParentPathOverride() -> String? { if fetchCompleted { return bazelSymlinkParentPathOverride } waitForCompletion() return bazelSymlinkParentPathOverride } /// Returns the bazel-bin path for this workspace, blocking until the fetch is completed. func getBazelBinPath() -> String { let bazelBin = "bazel-bin" if let parentPathOverride = getBazelSymlinkParentPathOverride() { return (parentPathOverride as NSString).stringByAppendingPathComponent(bazelBin) } return bazelBin } // MARK: - Private methods // Waits for the workspace fetcher to signal the private func waitForCompletion() { dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) dispatch_semaphore_signal(semaphore) } // Fetches Bazel package_path info from the registered workspace URL. private func fetchWorkspaceInfo() { let profilingStart = localizedMessageLogger.startProfiling("get_package_path", message: "Fetching bazel path info") guard let bazelPath = bazelURL.path where NSFileManager.defaultManager().fileExistsAtPath(bazelPath) else { localizedMessageLogger.error("BazelBinaryNotFound", comment: "Error to show when the bazel binary cannot be found at the previously saved location %1$@.", values: bazelURL) return } let task = TulsiTaskRunner.createTask(bazelPath, arguments: ["info"]) { completionInfo in defer { self.localizedMessageLogger.logProfilingEnd(profilingStart) self.fetchCompleted = true dispatch_semaphore_signal(self.semaphore) } if completionInfo.task.terminationStatus == 0 { if let stdout = NSString(data: completionInfo.stdout, encoding: NSUTF8StringEncoding) { self.extractWorkspaceInfo(stdout) return } } self.packagePath = "" self.executionRoot = "" let stderr = NSString(data: completionInfo.stderr, encoding: NSUTF8StringEncoding) let debugInfoFormatString = NSLocalizedString("DebugInfoForBazelCommand", bundle: NSBundle(forClass: self.dynamicType), comment: "Provides general information about a Bazel failure; a more detailed error may be reported elsewhere. The Bazel command is %1$@, exit code is %2$d, stderr %3$@.") let debugInfo = String(format: debugInfoFormatString, completionInfo.commandlineString, completionInfo.terminationStatus, stderr ?? "<No STDERR>") self.localizedMessageLogger.infoMessage(debugInfo) self.localizedMessageLogger.error("BazelWorkspaceInfoQueryFailed", comment: "Extracting path info from bazel failed. The exit code is %1$d.", details: stderr as String?, values: completionInfo.task.terminationStatus) } task.currentDirectoryPath = workspaceRootURL.path! task.launch() } private func extractWorkspaceInfo(output: NSString) { let lines = output.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) for line in lines { let components = line.componentsSeparatedByString(": ") guard let key = components.first where !key.isEmpty else { continue } let valueComponents = components.dropFirst() let value = valueComponents.joinWithSeparator(": ") switch key { case "execution_root": executionRoot = value case "package_path": packagePath = value case "tulsi_bazel_symlink_parent_path": bazelSymlinkParentPathOverride = value default: break } } } }
0
// // NotificationTableViewController.swift // CoreDataNotification // // Created by HocTran on 12/1/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import CoreData import CoreDataNotification class NotificationTableViewController: TableViewController { override func viewDidLoad() { super.viewDidLoad() //notification let moc = DataController.default.managedObjectContext let fetchRequest = NSFetchRequest<City>(entityName: "City") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] notificationToken = moc.addNotificationBlock(fetchRequest: fetchRequest) { change in switch change { case .initial(let list): self.cities = list self.tableView.reloadData() case .insert(let list, let insertion): self.cities = list self.tableView.insertRows(at: [insertion], with: .automatic) case .delete(let list, let deletion): self.cities = list self.tableView.deleteRows(at: [deletion], with: .automatic) case .update(let list, let modification): self.cities = list self.tableView.reloadRows(at: [modification], with: .automatic) case .move(let list, let from, let to): self.cities = list self.tableView.moveRow(at: from, to: to) case .error(let error): print("++++++++ ERROR ++++++++") print(error) print("+++++++++++++++++++++++++") } } } }
0
// // RepositoriesViewController.swift // GitHubFeed // // Created by Alex Salom on 23/04/2019. // Copyright © 2019 Alex Salom. All rights reserved. // import UIKit import IGListKit import RxSwift import RxCocoa protocol RepositoriesView: class { func update() } final class RepositoriesViewController: UIViewController, RepositoriesView, ListAdapterDataSource { @IBOutlet private weak var searchBar: UISearchBar! @IBOutlet private weak var collectionView: UICollectionView! private let presenter: RepositoriesPresenter private var adapter: ListAdapter? private let disposeBag = DisposeBag() init(presenter: RepositoriesPresenter = RepositoriesPresenterImpl()) { self.presenter = presenter super.init(nibName: "RepositoriesViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() presenter.viewDidLoad(view: self) let updater = ListAdapterUpdater() let adapter = ListAdapter(updater: updater, viewController: self, workingRangeSize: 0) adapter.collectionView = collectionView adapter.dataSource = self self.adapter = adapter searchBar.rx.text .orEmpty .debounce(0.5, scheduler: MainScheduler.instance) .distinctUntilChanged() .subscribe(onNext: { [weak self] query in self?.presenter.search(query: query) }) .disposed(by: disposeBag) } func update() { //adapter?.reloadData(completion: nil) adapter?.performUpdates(animated: true) } func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return presenter.repositories } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { return RepositorySectionController() } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } } class RepositorySectionController: ListSectionController { private var repository: Repository? override func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } override func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(withNibName: "RepositoryCell", bundle: nil, for: self, at: index) as! RepositoryCell cell.nameLabel.text = repository?.name return cell } override func didUpdate(to object: Any) { self.repository = (object as? DiffableRepository)?.repository } }
0
// // Response.swift // GrapheneInspector // // Created by Ilya Kharlamov on 7/18/22. // import Foundation import Graphene public extension GrapheneInspector { struct Response: Decodable { public let errors: [GraphQLError] public let deprecated: [GraphQLError] private enum CodingKeys: String, CodingKey { case errors case deprecated } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.errors = (try? container.decodeIfPresent([GraphQLError].self, forKey: .errors)) ?? [] self.deprecated = (try? container.decodeIfPresent([GraphQLError].self, forKey: .deprecated)) ?? [] } } }
0
import Quick import Nimble @testable import Artsy var socket: Test_Socket! class LiveAuctionSocketCommunicatorSpec: QuickSpec { override func spec() { let host = "squiggly host" let jwt = StubbedCredentials.Registered.jwt let saleID = "honest ed's bargain basement" beforeEach { socket = Test_Socket() } it("configures the socket with the correct host") { _ = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) expect(socket.host) == host } it("connects the socket on initialization") { let subject = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) expect(socket.connected) == true _ = subject // Keep a reference around until after expect() } it("disconnects the socket when deallocated") { do { _ = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) } expect(socket.connected) == false } it("sends authentication once connected") { let subject = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) socket.onConnect?() let authCalls = socket.writes.filter { $0 == "{\"type\":\"Authorize\",\"jwt\":\"\(jwt.string)\"}" } expect(authCalls).to( haveCount(1) ) _ = subject // Keep a reference around until after expect() } it("listens for updated auction state") { _ = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) expect(socket.onText).toNot( beNil() ) } it("sends its updatedAuctionState observable its updated auction state") { let subject = LiveAuctionSocketCommunicator(host: host, causalitySaleID: saleID, jwt: jwt, socketCreator: test_SocketCreator()) // "emit" the socket event from the server let state = "{\"type\":\"InitialFullSaleState\",\"currentLotId\":\"54c7ecc27261692b5e420600\",\"fullLotStateById\":{}}" socket.onText?(state) expect(subject.updatedAuctionState.peek() ).toNot( beNil() ) } } } func test_SocketCreator() -> LiveAuctionSocketCommunicator.SocketCreator { return { host, causalitySaleID in socket.host = host return socket } } class Test_Socket: SocketType { var onText: ((String) -> Void)? var onConnect: ((Void) -> Void)? var onDisconnect: ((NSError?) -> Void)? var writes = [String]() var datas = [NSData]() var connected = false var host = "" init() { } func writeString(str: String) { writes += [str] } func writeData(data: NSData) { datas += [data] } func writePing() { } func connect() { connected = true } func disconnect() { connected = false } }
0
// // UIImageTests.swift // // Created by Giorgi Iashvili on 24.09.16. // Copyright (c) 2016 Giorgi Iashvili // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest import RDExtensionsSwift open class UIImageTests : XCTestCase { func testMethods() { let size1 = CGSize(width: 100, height: 100) let size2 = CGSize(width: 50, height: 50) let size3 = CGSize(width: 20, height: 20) let color = UIColor.green let image = UIImage(color: color, size: size1) XCTAssertEqual(image.color(CGPoint.zero), color) XCTAssertEqual(image.rescale(0.5)?.size, size2) XCTAssertEqual(image.resize(size3)?.size, size3) XCTAssertEqual(image.changeOrientation(UIImage.Orientation.down)?.imageOrientation, UIImage.Orientation.down) } func testDownload() { let expectation = self.expectation(description: "UIImage.testDownload") let url = URL(string: "https://avatars3.githubusercontent.com/u/5988751?v=3&s=466")! var uuid : String = "" uuid = UIImage.download(url, completion: { (image, id) in expectation.fulfill() XCTAssertEqual(uuid, id) XCTAssertNotNil(image) }) self.waitForExpectations(timeout: 30) { (error) in if(error != nil) { XCTAssert(false, "Request Timeout for URL: " + url.absoluteString) } } } }
0
// // ForgotAlertViewModel.swift // loafwallet // // Created by Kerry Washington on 4/1/21. // Copyright © 2021 Sumcoin Wallet. All rights reserved. // import Foundation import SwiftUI import Sumcoin WalletPartnerAPI class ForgotAlertViewModel: ObservableObject { //MARK: - Combine Variables @Published var emailString: String = "" @Published var detailMessage: String = S.SumcoinCard.resetPasswordDetail init() { } func resetPassword(completion: @escaping () -> Void) { PartnerAPI.shared.forgotPassword(email: emailString) { (responseMessage, code) in DispatchQueue.main.async { self.detailMessage = "\(code): " + responseMessage completion() } } } func shouldDismissView(completion: @escaping () -> Void) { completion() } }
0
// // ViewController.swift // DateTimeTest // // Created by lcx on 2021/11/6. // import UIKit import Amplify class ViewController: UIViewController { @IBOutlet weak var dateTime: UITextField! private let datePicker = UIDatePicker() override func viewDidLoad() { super.viewDidLoad() datePicker.preferredDatePickerStyle = .wheels let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem( barButtonSystemItem: .done, target: nil, action: #selector(doneButtonPressed) ) toolBar.setItems([doneButton], animated: true) dateTime.inputAccessoryView = toolBar dateTime.inputView = datePicker } @objc private func doneButtonPressed() { let date = datePicker.date let formatter = DateFormatter() formatter.timeZone = .current formatter.locale = .current // https://nsdateformatter.com/ formatter.dateFormat = "MM-dd-yyyy HH:mm:ss a" dateTime.text = formatter.string(from: date) view.endEditing(true) DispatchQueue.global().async { // let now = Temporal.DateTime.now() // above is how to get current time let dateTime = Temporal.DateTime(date) let item = DateTimeTest(dateTime: dateTime) Amplify.DataStore.save(item) { result in switch(result) { case .success(let savedItem): print("Saved item: \(savedItem.id)") case .failure(let error): print("Could not save item to DataStore: \(error)") } } } } }
0
// // NetworkVader.swift // Creeper // // Created by Deepti Pandey on 10/04/18. // Copyright © 2018 Tapzo. All rights reserved. // import UIKit class NetworkVader: NSObject { static let sharedVader = NetworkVader() fileprivate var eventConfig: EventConfigData? internal func fetchConfigData(_ deviceId: String){ if let url = URL(string: "\(Creeper.shared.baseUrl)\(CreeperNetworkRequestType.Config.rawValue)?did=\(deviceId)"){ var request = URLRequest(url: url) request.addValue(Creeper.shared.segmentKey, forHTTPHeaderField: NetworkConstants.EventKey.rawValue) request.addValue(NetworkConstants.ApplicationJSON.rawValue, forHTTPHeaderField: NetworkConstants.ContentType.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") return } print("\n\nconfig api=", request) print("\n config api time =", Date()) if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] print("\n\nconfig response JSON: \(json)") self.parseConfigData(json) } catch let error as NSError { print(error) } } task.resume() } } internal func sendEventsSync(_ params: [String: AnyObject], messageIDs: [String]) { if let url = URL(string: "\(Creeper.shared.baseUrl)\(CreeperNetworkRequestType.EventsPush.rawValue)"){ var request = URLRequest(url: url) request.addValue(Creeper.shared.segmentKey, forHTTPHeaderField: NetworkConstants.EventKey.rawValue) request.addValue(NetworkConstants.ApplicationJSON.rawValue, forHTTPHeaderField: NetworkConstants.ContentType.rawValue) request.httpMethod = "POST" do { if JSONSerialization.isValidJSONObject(params) { let body = try JSONSerialization.data(withJSONObject: params, options:[.prettyPrinted]) request.httpBody = body } } catch { print("unable to serialise") return } let semaphore = DispatchSemaphore(value: 1) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") semaphore.signal() return } print("\n\n push api=", request) Creeper.sharedUserDefaults.setValue(Date(), forKey: Creeper.shared.kLastDatePushAttempted) if let events = params["events"] as? [[String: AnyObject]]{ print("\n number of items =", events.count) } if let str = params.prettyPrintedJSON{ print("\n push params=\n", str) } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:AnyObject] print("\n\npush JSON response : \(String(describing: json))") self.parseEventsPushData(json, messageIDs: messageIDs) } catch let error as NSError { print(error) } semaphore.signal() } task.resume() _ = semaphore.wait(wallTimeout: DispatchWallTime.distantFuture) } } internal func fetchSavedConfig() -> EventConfigData?{ if let defaultsConfig = Creeper.sharedUserDefaults.object(forKey: "configKey") as? [String: AnyObject] { let config = EventConfigData(defaultsConfig, isDataFromAPI: false) self.eventConfig = config return config }else{ if let deviceId = Creeper.sharedUserDefaults.object(forKey: Creeper.shared.kDeviceId) as? String{ Creeper.shared.fetchConfigData(deviceId) } } return nil } //MARK: - Parsing internal func parseConfigData(_ dict: [String: AnyObject]?){ if let dict = dict{ self.eventConfig = EventConfigData(dict, isDataFromAPI: true) } } internal func parseEventsPushData(_ dict: [String: AnyObject]?, messageIDs: [String]){ if let dict = dict{ if let status = dict["status"] as? String{ if status == "success"{ CreeperDataVader.sharedInstance().updateSentEvents(messageIDs) } } } } } internal class EventConfigData: NSObject{ var timestamp: Date = Date() var batchSize: Int = 20 var exclusionEvents: [EventDescription] = [] var interval: Int64 = 30000 var selfAnalytics: Bool = false init(_ dict: [String: AnyObject], isDataFromAPI: Bool){ var dictWithTimeStamp = dict if isDataFromAPI{ dictWithTimeStamp["timestamp"] = timestamp as AnyObject }else if let timeS = dict["timestamp"] as? Date{ timestamp = timeS if let batchSizeString = dict["batch_size"] as? String, let batchsize = Int(batchSizeString){ batchSize = batchsize } if let exclusionEventArray = dict["exclusion_events"] as? [[String: AnyObject]] { for exclusionEventDict in exclusionEventArray{ if let event = EventDescription(exclusionEventDict){ exclusionEvents.append(event) } } } if let intervalString = dict["interval"] as? String, let intrval = Int64(intervalString){ interval = intrval } if let selfAn = dict["self_analytics"] as? Bool{ selfAnalytics = selfAn } } Creeper.sharedUserDefaults.set(dictWithTimeStamp, forKey: "configKey") } } internal class EventDescription: NSObject{ var desc: String var name: String init?(_ dict: [String: AnyObject]){ guard let descripton = dict["event_desc"] as? String, let nam = dict["event_name"] as? String else{ return nil } desc = descripton name = nam return nil } } extension Dictionary { var prettyPrintedJSON: String? { do { let data: Data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) return String(data: data, encoding: .utf8) } catch _ { return nil } } }
0
// // TootView.swift // StarPteranoMac // // Created by takayoshi on 2018/10/28. // Copyright © 2018 pgostation. All rights reserved. // import Cocoa final class TootView: NSView { // 下書き保存 static var inReplyToId: String? = nil static var inReplyToContent: String? = nil static var scheduledDate: Date? //---- var protectMode = SettingsData.protectMode // トゥート let spoilerTextField = TootTextView() let textField = TootTextView() let textCountLabel = MyTextField() let inReplyToLabel = NSButton() weak var target: TootViewController? // 入力バー let inputBar = NSView() let imagesButton = NSButton() let imagesCountButton = NSButton() let protectButton = NSButton() let cwButton = NSButton() let emojiButton = NSButton() // 画像チェック画面 let imageCheckView = ImageCheckView() override var tag: Int { return 8364 } init() { super.init(frame: NSRect(x: 0, y: 0, width: 0, height: 0)) self.addSubview(spoilerTextField) self.addSubview(textField) self.addSubview(inputBar) inputBar.addSubview(textCountLabel) inputBar.addSubview(imagesButton) inputBar.addSubview(imagesCountButton) inputBar.addSubview(protectButton) inputBar.addSubview(cwButton) inputBar.addSubview(emojiButton) spoilerTextField.isHidden = true refresh() } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func refresh() { if !SettingsData.isTransparentWindow { self.wantsLayer = true self.layer?.backgroundColor = ThemeColor.viewBgColor.cgColor } textCountLabel.stringValue = "0 / 500" textCountLabel.textColor = ThemeColor.contrastColor textCountLabel.font = NSFont.systemFont(ofSize: 12) textCountLabel.backgroundColor = ThemeColor.viewBgColor.withAlphaComponent(0.3) textCountLabel.alignment = .center textCountLabel.layer?.cornerRadius = 10 textCountLabel.isBezeled = false textCountLabel.isEditable = false textCountLabel.isSelectable = false textCountLabel.sizeToFit() if SettingsData.isTransparentWindow { spoilerTextField.backgroundColor = NSColor.clear } else { spoilerTextField.backgroundColor = ThemeColor.viewBgColor } spoilerTextField.textColor = ThemeColor.messageColor spoilerTextField.font = NSFont.systemFont(ofSize: SettingsData.fontSize + 5) spoilerTextField.isEditable = true spoilerTextField.layer?.borderColor = ThemeColor.messageColor.cgColor spoilerTextField.layer?.borderWidth = 1 / (NSScreen.main?.backingScaleFactor ?? 1) spoilerTextField.font = NSFont.systemFont(ofSize: SettingsData.fontSize) spoilerTextField.textContainerInset = NSSize.init(width: 1, height: 5) spoilerTextField.insertionPointColor = ThemeColor.contrastColor if imageCheckView.isHidden { DispatchQueue.main.async { self.textField.becomeFirstResponder() } } if SettingsData.isTransparentWindow { textField.backgroundColor = NSColor.clear } else { textField.backgroundColor = ThemeColor.viewBgColor } textField.textColor = ThemeColor.messageColor textField.font = NSFont.systemFont(ofSize: SettingsData.fontSize + 5) textField.isEditable = true textField.layer?.borderColor = ThemeColor.messageColor.cgColor textField.layer?.borderWidth = 1 / (NSScreen.main?.backingScaleFactor ?? 1) textField.font = NSFont.systemFont(ofSize: SettingsData.fontSize) textField.textContainerInset = NSSize.init(width: 1, height: 5) textField.insertionPointColor = ThemeColor.contrastColor if !SettingsData.isTransparentWindow { inputBar.layer?.backgroundColor = ThemeColor.cellBgColor.withAlphaComponent(0.9).cgColor } imagesButton.title = "🏞" imagesButton.isBordered = false if imageCheckView.urls.count == 0 { imagesCountButton.isHidden = true } else { imagesCountButton.isHidden = false let attributedTitle = NSMutableAttributedString(string: "[\(imageCheckView.urls.count)]") attributedTitle.addAttributes([NSAttributedString.Key.foregroundColor : ThemeColor.contrastColor], range: NSRange.init(location: 0, length: attributedTitle.length)) imagesCountButton.attributedTitle = attributedTitle } imagesCountButton.isBordered = false switch self.protectMode { case .publicMode: protectButton.title = "🌐" case .unlisted: protectButton.title = "🔓" case .privateMode: protectButton.title = "🔐" case .direct: protectButton.title = "✉️" } protectButton.isBordered = false let attributedTitle = NSMutableAttributedString(string: "CW") attributedTitle.addAttributes([NSAttributedString.Key.foregroundColor : ThemeColor.contrastColor], range: NSRange.init(location: 0, length: attributedTitle.length)) cwButton.attributedTitle = attributedTitle cwButton.isBordered = false emojiButton.title = "😀" emojiButton.isBordered = false } override func layout() { let spoilerTextFieldHeight = spoilerTextField.isHidden ? 0 : max(25, spoilerTextField.frame.height) let oldHeight = self.frame.size.height self.frame.size.height = spoilerTextFieldHeight + textField.frame.height + 25 if oldHeight != self.frame.size.height { self.superview?.needsLayout = true } spoilerTextField.frame = CGRect(x: 0, y: 25 + textField.frame.height, width: self.frame.width, height: spoilerTextFieldHeight) textField.frame = CGRect(x: 0, y: 25, width: self.frame.width, height: textField.frame.height) inputBar.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 25) imagesButton.frame = CGRect(x: 0, y: 0, width: 30, height: 25) imagesCountButton.frame = CGRect(x: 30, y: 0, width: 30, height: 25) protectButton.frame = CGRect(x: 60, y: 0, width: 30, height: 25) cwButton.frame = CGRect(x: 90, y: 0, width: 30, height: 25) emojiButton.frame = CGRect(x: 120, y: 0, width: 30, height: 25) textCountLabel.frame = CGRect(x: 150, y: (25 - textCountLabel.frame.height) / 2, width: 75, height: textCountLabel.frame.height) } class MyTextView: NSTextView { override func layout() { super.layout() superview?.needsLayout = true } } override func updateLayer() { refresh() } class TootTextView: MyTextView { override func keyDown(with event: NSEvent) { if self.hasMarkedText() { // 変換中の場合 super.keyDown(with: event) return } switch event.keyCode { case 36, 52, 76: // return, enter if event.modifierFlags.contains(.command) { // cmd + return // トゥート (self.superview as? TootView)?.target?.tootAction() return } else { if HelperViewManager.select() { return } } case 48: // tab // タイムラインを選択 self.window?.makeFirstResponder(nil) if let tabView = self.superview?.superview?.superview?.viewWithTag(5823) as? PgoTabView { tabView.selectLeft() tabView.selectRight() } return case 123: // <- if HelperViewManager.left() { return } case 124: // -> if HelperViewManager.right() { return } default: break } super.keyDown(with: event) } } }
0
// // NetworkResponse.swift // Networking // // Created by Sudo Dev OSS on 14/2/21. // import Foundation public struct NetworkResponse<T>: Decodable where T: Decodable { public let success: Bool public let data: T public init(success: Bool, data: T){ self.success = success self.data = data } fileprivate enum CodingKeys: String, CodingKey { case success case data } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.success = try container.decode(Bool.self, forKey: .success) self.data = try container.decode(T.self, forKey: .data) } }
0
// // GeneralNavigationTransitionControl.swift // LMFloatingKeeper // // Created by 刘明 on 2019/3/19. // Copyright © 2019 ming.liu. All rights reserved. // import UIKit open class GeneralTransitionControl: NSObject, UINavigationControllerDelegate, NavigationInteractiveControlType { // MARK: - NavigationInteractiveControlType /// NavigationInteractiveControlType properties open var interactiveProducer: InteractiveProducerType open var aniTransitionProducer: AniTransitionProducerType open var interactiveEnabled: Bool = true open var draggingGesture: UIPanGestureRecognizer? = nil open var draggingEdge: InteractiveDraggingEdge? = nil /// 清除手势,该方法必须将 draggingGesture 设置为nil public func clearDraggingGesture() { draggingGesture = nil } // MARK: - init public init( aniTransitionProducer: AniTransitionProducerType, interactiveProducer: InteractiveProducerType) { self.aniTransitionProducer = aniTransitionProducer self.interactiveProducer = interactiveProducer super.init() } public override convenience init() { self.init(aniTransitionProducer:FrameAniTransitionProducer(), interactiveProducer: GeneralInteractiveProducer()) } // MARK: - UINavigationControllerDelegate /// UI的各种delegate扩展真的麻烦, 这么写只为消除警告 open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return noobj_naviController(navigationController, operation, fromVC, toVC) } open func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return noobj_naviController(navigationController, animationController) } }
0
// // ChatsService.swift // Messenger // // Created by Sergei Meza on 2018/06/26. // Copyright © 2018 Sergei Meza. All rights reserved. // import Foundation import Firebase import ObjectMapper import SwiftyJSON import Moya import GameKit struct ChatsService { func getChats(paginate: Bool, lastValue: Any? = nil, completion: @escaping ((Result<(chats: [RealmChat], lastValue: Any?)>)->Void)) { #if DEBUG // generateRandomChatsWithFirebaseDatabase() #endif let path = DeviceConst.firebaseDatabaseRootURL.appendingPathComponent("CHATS/me_id") Service.queryDatabase(path: path, paginate: paginate, child: "reverse_timestamp", lastValue: lastValue) { result in switch result { case .success(let snapshot): guard let value = snapshot?.value as? [String: Any] else { snapshot == nil ? completion(Result.success(([], nil))) : completion(Result.error(NetworkError(statusCode: 404))) return } var chats = Mapper<RealmChat>().mapArray(JSONArray: value.compactMap({ $0.value as? [String:Any] })) chats.sort { $0.reverseTimestamp < $1.reverseTimestamp } completion(Result.success((chats, chats.last?.reverseTimestamp))) case .error(let error): completion(Result.error(error)) } } } func generateRandomChatsWithFirebaseDatabase() { let randomGenerator = GKRandomDistribution.init(lowestValue: 0, highestValue: 4) for index in 1...50 { let chat = FirebaseObject.init(path: "CHATS/me_id") chat[DeviceConst.object_id] = FirebaseObject.autoId() let timestamp = Date().timeIntervalSinceReferenceDate chat["timestamp"] = timestamp + Double(index) chat["reverse_timestamp"] = -(timestamp + Double(index)) chat["name"] = ["David", "Rose", "Mary", "John", "Paul"][randomGenerator.nextInt()] chat.saveInBackground() } } }
0
// // AddWalletCellCollectionViewCell.swift // cryptolin // // Created by Olayemi Abimbola on 26/10/2021. // import UIKit class AddWalletCellCollectionViewCell: UICollectionViewCell { static let reuseIdentifier = String(describing: AddWalletCellCollectionViewCell.self) @IBOutlet weak var containerView: UIView! @IBOutlet weak var plusButton: UIButton! override func awakeFromNib() { super.awakeFromNib() containerView.layer.cornerRadius = 8 plusButton.layer.cornerRadius = plusButton.layer.frame.height / 2 } }
0
// // KeySize.swift // // // Created by Joseph Hinkle on 5/10/21. // enum KeySize: Int, CaseIterable, Identifiable { var id: Int { self.rawValue } case _2048 = 2048 case _4096 = 4096 }
0
// // ColorPickerView.swift // color_picker // // Created by Jimmy Tai on 2020/4/13. // import UIKit protocol WhitePickerViewDelegate { func onInitialized() func colorSelected(whiteSelectedColor color: UIColor) } @IBDesignable @objc open class WhitePickerView: UIControl { @objc var onInit: RCTBubblingEventBlock? @objc var onColorChange: RCTBubblingEventBlock? private let contentInsetX: CGFloat = 0 private let contentInsetY: CGFloat = 0 private let indicatorSizeInactive: CGFloat = 45 private let indicatorSizeActive: CGFloat = 55 var initialized: Bool = false var delegate: WhitePickerViewDelegate? var tempColor: UIColor? private lazy var colorSquareView: ColorSquareView = { return ColorSquareView() }() open lazy var indicator: ColorIndicatorView = { let size = CGSize(width: self.indicatorSizeInactive, height: self.indicatorSizeInactive) let indicatorRect = CGRect(origin: .zero, size: size) return ColorIndicatorView(frame: indicatorRect) }() public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.clipsToBounds = true } public override init(frame: CGRect) { super.init(frame: frame) self.clipsToBounds = true } open override func layoutSubviews() { if initialized { return } self.isUserInteractionEnabled = true if colorSquareView.superview == nil { print("ColorSquareView superview is nil") let image = UIImage.gradientImageWithBounds( bounds: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height), colors: [ UIColor.hexColor(str: "#C1EAF9").cgColor, UIColor.hexColor(str: "#F3F3F3").cgColor, UIColor.hexColor(str: "#EEC348").cgColor ], startPoint: CGPoint(x: 1, y: 0), endPoint: CGPoint(x: 0, y: 1)) colorSquareView.image = image colorSquareView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(colorSquareView) colorSquareView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: contentInsetX).isActive = true colorSquareView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -contentInsetX).isActive = true colorSquareView.topAnchor.constraint(equalTo: self.topAnchor, constant: contentInsetY).isActive = true colorSquareView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -contentInsetY).isActive = true } if indicator.superview == nil { print("Indicator superview is nil") self.addSubview(indicator) } if let color = tempColor { setColor(color: color) } else { indicator.center = self.center } setIndicatorColor() if initialized == false { // send event back to js if let callback = self.onInit { let params: [String : Any] = [:] callback(params) } if let d = delegate { d.onInitialized() } } initialized = true } public func setColor(color: UIColor) { var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0 color.getRed(&r, green: &g, blue: &b, alpha: &a) setColor(red: Int(r * 255), green: Int(g * 255), blue: Int(b * 255)) } public func setColor(red: Int, green: Int, blue: Int) { let rgb = RGB(r: CGFloat(red) / 255.0, g: CGFloat(green) / 255, b: CGFloat(blue) / 255) tempColor = UIColor(red: rgb.r, green: rgb.g, blue: rgb.b, alpha: 1.0) print("setColor: \((tempColor != nil) ? "not nil" : "nil")") let hsv = rgb.toHSV(preserveHS: true) var hue = CGFloat(hsv.h) * 360 if hue > 196 { hue = 196 } else if hue < 44 { hue = 44 } var x: CGFloat = 0.0, y: CGFloat = 0.0; if hue <= 60 { x = abs(CGFloat(blue) - 150) / 99 * (self.bounds.width / 2) y = self.bounds.height - (self.bounds.height / self.bounds.width * x) } else { x = self.bounds.width / 2 + abs(CGFloat(red) - 249) / 56 * (self.bounds.width / 2) y = self.bounds.height - (self.bounds.height / self.bounds.width * x) } indicator.center = CGPoint(x: x, y: y) setIndicatorColor() } public func getColor() -> UIColor { return indicator.color } private func setIndicatorColor() { let color = colorSquareView.getPixelColorAtPoint(point: indicator.center) indicator.color = color } // MARK: - Tracking private func trackIndicator(with touch: UITouch) { var position = touch.location(in: self) if position.x > self.bounds.width - 2 { position.x = self.bounds.width - 2 } else if position.x < 2 { position.x = 2 } if position.y > self.bounds.height - 2 { position.y = self.bounds.height - 2 } else if position.y < 2 { position.y = 2 } indicator.center = position setIndicatorColor() } open override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.trackIndicator(with: touch) growIndicator() return true } open override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { self.trackIndicator(with: touch) return true } open override func endTracking(_ touch: UITouch?, with event: UIEvent?) { super.endTracking(touch, with: event) shrinkIndicator() if let callback = self.onColorChange { let params: [String : Any] = ["color": indicator.color.toHexString()] callback(params) } if let d = delegate { d.colorSelected(whiteSelectedColor: indicator.color) } } open override func cancelTracking(with event: UIEvent?) { super.cancelTracking(with: event) shrinkIndicator() if let callback = self.onColorChange { let params: [String : Any] = ["color": indicator.color.toHexString()] callback(params) } if let d = delegate { d.colorSelected(whiteSelectedColor: indicator.color) } } private func changeIndicatorSize(to size: CGFloat) { let center = self.indicator.center let size = CGSize(width: size, height: size) let indicatorRect = CGRect(origin: .zero, size: size) self.indicator.frame = indicatorRect self.indicator.center = center } private func growIndicator() { UIView.animate(withDuration: 0.15, delay: 0.0, options: [.curveEaseIn], animations: { self.changeIndicatorSize(to: self.indicatorSizeActive) }) { (finished) in } } private func shrinkIndicator() { UIView.animate(withDuration: 0.15, delay: 0.0, options: [.curveEaseOut], animations: { self.changeIndicatorSize(to: self.indicatorSizeInactive) self.indicator.setNeedsDisplay() }) { (finished) in self.indicator.setNeedsDisplay() } } } extension UIColor { static func hexColor(str: String) -> UIColor { let hex = str.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: (a, r, g, b) = (255, 0, 0, 0) } return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255) } func toHexString() -> String { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return String(format:"#%06x", rgb) } }
0
// // DetailTableViewCell.swift // XCoordinator_Example // // Created by Paul Kraft on 20.11.18. // Copyright © 2018 QuickBird Studios. All rights reserved. // import UIKit class DetailTableViewCell: UITableViewCell { // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Overrides override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) UIView.animate(withDuration: animated ? 0.35 : 0) { self.backgroundColor = highlighted ? .lightGray : .white } } }
0
// // UIButton.swift // ImagePosition // // Created by Bohdan Savych on 10/1/16. // Copyright © 2016 BBB. All rights reserved. // import Foundation import UIKit typealias ContentPosition = (horizontal: HorizontalPosition, vertical: VerticalPosition) typealias ContentOffset = (horizontal: Double, vertical: Double) enum HorizontalPosition { case left, right, center } enum VerticalPosition { case top, bottom, center } extension UIButton { func setupImageInButton(imagePosition: ContentPosition = (.center, .center), imageOffset: ContentOffset = (0, 0), textPosition: ContentPosition = (.center, .center), textOffset: ContentOffset = (0, 0)) { guard let imageViewFrame = imageView?.frame, let labelFrame = titleLabel?.frame else { return } contentHorizontalAlignment = .left contentVerticalAlignment = .top let buttonWidth = bounds.width let buttonHeight = bounds.height switch imagePosition.horizontal { case .left: imageEdgeInsets = UIEdgeInsets.init(top: 0, left: CGFloat(imageOffset.horizontal), bottom: 0, right: 0) case .right: let imageViewXOrigin = buttonWidth - imageViewFrame.width imageEdgeInsets = UIEdgeInsets.init(top: 0, left: imageViewXOrigin - CGFloat(imageOffset.horizontal), bottom: 0, right: 0) case .center: let imageViewXOrigin = (buttonWidth - imageViewFrame.width) / 2.0 imageEdgeInsets = UIEdgeInsets.init(top: 0, left: imageViewXOrigin, bottom: 0, right: 0) } switch imagePosition.vertical { case .top: imageEdgeInsets = UIEdgeInsets.init(top: CGFloat(imageOffset.vertical),left: imageEdgeInsets.left, bottom: 0, right: imageEdgeInsets.right) case .bottom: let imageViewYOrigin = buttonHeight - imageViewFrame.height imageEdgeInsets = UIEdgeInsets.init(top: imageViewYOrigin - CGFloat(imageOffset.vertical), left: imageEdgeInsets.left, bottom: 0, right: imageEdgeInsets.right) case .center: let imageViewYOrigin = (buttonHeight - imageViewFrame.height) / 2.0 imageEdgeInsets = UIEdgeInsets.init(top: imageViewYOrigin, left: imageEdgeInsets.left, bottom: 0, right: imageEdgeInsets.right) } switch textPosition.horizontal { case .left: let textXOrigin = -imageViewFrame.width + CGFloat(textOffset.horizontal) titleEdgeInsets = UIEdgeInsets.init(top: 0, left: textXOrigin, bottom: 0, right: 0) case .center: let textXOrigin = ((buttonWidth - labelFrame.width) / 2.0) - imageViewFrame.width titleEdgeInsets = UIEdgeInsets.init(top: 0, left: textXOrigin, bottom: 0, right: 0) case .right: let textXOrigin = (buttonWidth - labelFrame.width - CGFloat(textOffset.horizontal) - imageViewFrame.width) titleEdgeInsets = UIEdgeInsets.init(top: 0, left: textXOrigin, bottom: 0, right: 0) } switch textPosition.vertical { case .top: titleEdgeInsets = UIEdgeInsets.init(top: CGFloat(textOffset.vertical), left: titleEdgeInsets.left, bottom: 0, right: titleEdgeInsets.right) case .center: let textYOrigin = (buttonHeight - labelFrame.height) / 2.0 titleEdgeInsets = UIEdgeInsets.init(top: textYOrigin, left: titleEdgeInsets.left, bottom: 0, right: titleEdgeInsets.right) case .bottom: let textYOrigin = buttonHeight - labelFrame.height - CGFloat(textOffset.vertical) titleEdgeInsets = UIEdgeInsets.init(top: textYOrigin, left: titleEdgeInsets.left, bottom: 0, right: titleEdgeInsets.right) } } }
0
// // MyClass.swift // weak // // Created by Jon Hoffman on 5/6/19. // Copyright © 2019 Jon Hoffman. All rights reserved. // import Foundation class MyClass1_Weak { var name = "" var class2: MyClass2_Weak? init(name: String) { self.name = name print("Initializing class1_Weak with name \(self.name)") } deinit { print("Releasing class1_Weak with name \(self.name)") } } class MyClass2_Weak { var name = "" weak var class1: MyClass1_Weak? init(name: String) { self.name = name print("Initializing class2_Weak with name \(self.name)") } deinit { print("Releasing class2_Weak with name \(self.name)") } } func myFunc() { let class1: MyClass1_Weak? = MyClass1_Weak(name: "Class1_Weak") let class2: MyClass2_Weak? = MyClass2_Weak(name: "Class2_Weak") class1?.class2 = class2 class2?.class1 = class1 print("Classes going out of scope") }
0
// // MIT License // // Copyright (c) 2018 Wojciech Nagrodzki // // 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 protocol SizeLimitedFileFactory { /// Returns newly initialized SizeLimitedFile instance. /// /// - Parameters: /// - fileURL: URL of the file. /// - fileSizeLimit: Maximum size the file can reach in bytes. /// - Throws: An error that may occur while the file is being opened for writing. func makeInstance(fileURL: URL, fileSizeLimit: UInt64) throws -> SizeLimitedFile } protocol LogrotateFactory { /// Returns newly initialized Logrotate instance. /// /// - Parameters: /// - fileURL: URL of the log file. /// - rotations: Number of times log files are rotated before being removed. func makeInstance(fileURL: URL, rotations: Int) -> Logrotate } /// Logger that writes messages into the file at specified URL with log rotation support. @available(OSX 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public final class DiskLogger: Logger { private let fileURL: URL private let fileSizeLimit: UInt64 private let rotations: Int private let fileManager: OSFileManager private let sizeLimitedFileFactory: SizeLimitedFileFactory private let logrotateFactory: LogrotateFactory private let formatter: DateFormatter private let queue = DispatchQueue(label: "com.wnagrodzki.DiskLogger", qos: .background, attributes: [], autoreleaseFrequency: .workItem, target: nil) private var buffer = Data() private var sizeLimitedFile: SizeLimitedFile! /// Initializes new DiskLogger instance. /// /// - Parameters: /// - fileURL: URL of the log file. /// - fileSizeLimit: Maximum size log file can reach in bytes. Attempt to exceeding that limit triggers log files rotation. /// - rotations: Number of times log files are rotated before being removed. public convenience init(fileURL: URL, fileSizeLimit: UInt64, rotations: Int) { self.init(fileURL: fileURL, fileSizeLimit: fileSizeLimit, rotations: rotations, fileManager: FileManager.default, sizeLimitedFileFactory: SizeLimitedFileFactoryImpl(), logrotateFactory: LogrotateFactoryImpl()) } init(fileURL: URL, fileSizeLimit: UInt64, rotations: Int, fileManager: OSFileManager, sizeLimitedFileFactory: SizeLimitedFileFactory, logrotateFactory: LogrotateFactory) { self.fileURL = fileURL self.fileSizeLimit = fileSizeLimit self.rotations = rotations self.fileManager = fileManager self.sizeLimitedFileFactory = sizeLimitedFileFactory self.logrotateFactory = logrotateFactory formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" formatter.timeZone = TimeZone(secondsFromGMT: 0) } public func log(time: Date, level: LogLevel, location: String, message: @autoclosure () -> String) { let message = formatter.string(from: time) + " <" + level.logDescription + "> " + location + " " + message() + "\n" log(message) } private func log(_ message: String) { let data = Data(message.utf8) queue.async { self.buffer.append(data) do { try self.openSizeLimitedFile() do { try self.writeBuffer() } catch is SizeLimitedFileQuotaReached { try self.closeSizeLimitedFile() try self.rotateLogFiles() try self.openSizeLimitedFile() try self.writeBuffer() } } catch { let message = self.formatter.string(from: Date()) + " <" + LogLevel.warning.logDescription + "> " + String(describing: error) + "\n" let data = Data(message.utf8) self.buffer.append(data) } } } private func openSizeLimitedFile() throws { guard sizeLimitedFile == nil else { return } if fileManager.itemExists(at: fileURL) == false { _ = fileManager.createFile(at: fileURL) } sizeLimitedFile = try sizeLimitedFileFactory.makeInstance(fileURL: fileURL, fileSizeLimit: fileSizeLimit) } private func writeBuffer() throws { try sizeLimitedFile.write(buffer) buffer.removeAll() } private func closeSizeLimitedFile() throws { try self.sizeLimitedFile.synchronizeAndCloseFile() self.sizeLimitedFile = nil } private func rotateLogFiles() throws { let logrotate = logrotateFactory.makeInstance(fileURL: fileURL, rotations: rotations) try logrotate.rotate() } } private class LogrotateFactoryImpl: LogrotateFactory { func makeInstance(fileURL: URL, rotations: Int) -> Logrotate { return LogrotateImpl(fileURL: fileURL, rotations: rotations, fileManager: FileManager.default) } } private class SizeLimitedFileFactoryImpl: SizeLimitedFileFactory { func makeInstance(fileURL: URL, fileSizeLimit: UInt64) throws -> SizeLimitedFile { return try SizeLimitedFileImpl(fileURL: fileURL, fileSizeLimit: fileSizeLimit, fileFactory: FileHandleFactoryImpl()) } } private class FileHandleFactoryImpl: FileHandleFactory { func makeInstance(forWritingTo: URL) throws -> OSFileHandle { return try FileHandle(forWritingTo: forWritingTo) } }
0
import Foundation import Quick import Nimble import Carlos class StringTransformerTests: QuickSpec { override func spec() { describe("String transformer") { var transformer: StringTransformer! var error: Error! beforeEach { transformer = StringTransformer(encoding: .utf8) } context("when transforming NSData to String") { var result: String! context("when the NSData is a valid string") { let stringSample = "this is a sample string" beforeEach { transformer.transform((stringSample.data(using: .utf8) as NSData?)!) .onSuccess({ result = $0 }) .onFailure({ error = $0 }) } it("should not return nil") { expect(result).notTo(beNil()) } it("should not call the failure closure") { expect(error).to(beNil()) } it("should return the expected String") { expect(result).to(equal(stringSample)) } } } context("when transforming String to NSData") { var result: NSData? let expectedString = "this is the expected string value" beforeEach { transformer.inverseTransform(expectedString) .onSuccess({ result = $0 as NSData? }) .onFailure({ error = $0 }) } it("should call the success closure") { expect(result).notTo(beNil()) } it("should return the expected data") { expect(result).to(equal(expectedString.data(using: .utf8) as NSData?)) } } } } }
0
/// XCTest results hierarchy public struct XCSTests: Codable { struct TestKey: CodingKey { var stringValue: String var intValue: Int? { return nil } init?(stringValue: String) { self.stringValue = stringValue } init?(intValue: Int) { return nil } static let aggregateDeviceStatus = TestKey(stringValue: "_xcsAggrDeviceStatus")! } public var suites: [XCSTestSuite] = [] public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TestKey.self) try container.allKeys.forEach({ (key) in var suite = try container.decodeIfPresent(XCSTestSuite.self, forKey: key) suite?.name = key.stringValue if let testSuite = suite { suites.append(testSuite) } }) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TestKey.self) try suites.forEach({ guard let key = TestKey(stringValue: $0.name) else { return } try container.encode($0, forKey: key) }) } } public extension XCSTests { typealias DeviceIdentifier = String } public extension XCSTests { struct XCSTestSuite: Codable { public var name: String = "" public var classes: [XCSTestClass] = [] public var aggregateResults: [DeviceIdentifier: Double]? public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TestKey.self) try container.allKeys.forEach({ (key) in switch key.stringValue { case TestKey.aggregateDeviceStatus.stringValue: aggregateResults = try container.decodeIfPresent([DeviceIdentifier: Double].self, forKey: key) default: var testClass = try container.decodeIfPresent(XCSTestClass.self, forKey: key) testClass?.name = key.stringValue if let testClass = testClass { classes.append(testClass) } } }) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TestKey.self) try classes.forEach({ guard let key = TestKey(stringValue: $0.name) else { return } try container.encode($0, forKey: key) }) try container.encodeIfPresent(aggregateResults, forKey: TestKey.aggregateDeviceStatus) } } } public extension XCSTests { struct XCSTestClass: Codable { public var name: String = "" public var methods: [XCSTestMethod] = [] public var aggregateResults: [DeviceIdentifier: Double]? public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TestKey.self) try container.allKeys.forEach({ (key) in switch key.stringValue { case TestKey.aggregateDeviceStatus.stringValue: aggregateResults = try container.decodeIfPresent([DeviceIdentifier: Double].self, forKey: key) default: var method = try container.decodeIfPresent(XCSTestMethod.self, forKey: key) method?.name = key.stringValue if let testMethod = method { methods.append(testMethod) } } }) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TestKey.self) try methods.forEach({ guard let key = TestKey(stringValue: $0.name) else { return } try container.encode($0, forKey: key) }) try container.encodeIfPresent(aggregateResults, forKey: TestKey.aggregateDeviceStatus) } } } public extension XCSTests { struct XCSTestMethod: Codable { public var name: String = "" public var deviceResults: [DeviceIdentifier: Int] = [:] public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TestKey.self) try container.allKeys.forEach { (key) in if let value = try container.decodeIfPresent(Int.self, forKey: key) { deviceResults[key.stringValue] = value } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: TestKey.self) try deviceResults.forEach({ if let key = TestKey(stringValue: $0.key) { try container.encode($0.value, forKey: key) } }) } } }
0
// // RunKeeper.swift // Pods // // Created by Mariam AlJamea on 1/17/16. // Copyright © 2016 kitz. All rights reserved. // public extension Applications { public struct RunKeeper: ExternalApplication { public typealias ActionType = Applications.RunKeeper.Action public let scheme = "RunKeeper:" public let fallbackURL = "https://runkeeper.com/index" public let appStoreId = "300235330" public init() {} } } // MARK: - Actions public extension Applications.RunKeeper { public enum Action { case open } } extension Applications.RunKeeper.Action: ExternalApplicationAction { public var paths: ActionPaths { switch self { case .open: return ActionPaths( app: Path( pathComponents: ["app"], queryParameters: [:] ), web: Path() ) } } }
0
// // Responsive_LayoutsApp.swift // Shared // // Created by Dan Wood on 7/15/20. // import SwiftUI @main struct Responsive_LayoutsApp: App { var body: some Scene { WindowGroup { ContentView() } } }
0
// // ConstrainSelfTests.swift // // // Created by Dillon McElhinney on 9/29/19. // @testable import ConstraintHelpers import XCTest class ConstrainSelfTests: XCTestCase { var sut: UIView! override func setUp() { super.setUp() sut = UIView() } override func tearDown() { sut = nil super.tearDown() } func testConstrainingHeight() { // Given let expectedHeight: CGFloat = 10 let expectedAttribute: NSLayoutConstraint.Attribute = .height let expectedRelation: NSLayoutConstraint.Relation = .equal // When sut.constrainSelf(height: expectedHeight) // Then XCTAssertFalse(sut.translatesAutoresizingMaskIntoConstraints, "Calling constrainSelf should set translatesAutoresizingMaskIntoConstraints on the view to be false.") XCTAssertEqual(expectedHeight, sut.constraints.first?.constant, "Calling constrainSelf with a height value should set the constant to \(expectedHeight)") XCTAssertEqual(expectedAttribute, sut.constraints.first?.firstAttribute, "Calling constrainSelf with a height value should set the height attribute") XCTAssertEqual(expectedRelation, sut.constraints.first?.relation, "Calling constrainSelf with a height value should set a constraint with an equal relation") } func testConstrainingWidth() { // Given let expectedWidth: CGFloat = 10 let expectedAttribute: NSLayoutConstraint.Attribute = .width let expectedRelation: NSLayoutConstraint.Relation = .equal // When sut.constrainSelf(width: expectedWidth) // Then XCTAssertFalse(sut.translatesAutoresizingMaskIntoConstraints, "Calling constrainSelf should set translatesAutoresizingMaskIntoConstraints on the view to be false.") XCTAssertEqual(expectedWidth, sut.constraints.first?.constant, "Calling constrainSelf with a width value should set the constant to \(expectedWidth)") XCTAssertEqual(expectedAttribute, sut.constraints.first?.firstAttribute, "Calling constrainSelf with a width value should set the width attribute") XCTAssertEqual(expectedRelation, sut.constraints.first?.relation, "Calling constrainSelf with a width value should set a constraint with an equal relation") } func testConstrainingAspectHeight() { // Given let expectedMultiplier: CGFloat = 2 let expectedAttribute: NSLayoutConstraint.Attribute = .width let expectedRelation: NSLayoutConstraint.Relation = .equal let expectedSecondAttribute: NSLayoutConstraint.Attribute = .height // When sut.constrainSelf(aspectHeight: expectedMultiplier) // Then XCTAssertFalse(sut.translatesAutoresizingMaskIntoConstraints, "Calling constrainSelf should set translatesAutoresizingMaskIntoConstraints on the view to be false.") XCTAssertEqual(expectedMultiplier, sut.constraints.last?.multiplier, "Calling constrainSelf with an aspectHeight value should set the multiplier to \(expectedMultiplier)") XCTAssertEqual(expectedAttribute, sut.constraints.last?.firstAttribute, "Calling constrainSelf with an aspectHeight value should set the width attribute") XCTAssertEqual(expectedRelation, sut.constraints.last?.relation, "Calling constrainSelf with an aspectHeight value should set a constraint with an equal relation") XCTAssertEqual(expectedSecondAttribute, sut.constraints.last?.secondAttribute, "Calling constrainSelf with an aspectHeight value should result in a constraint whose second attribute is height") } func testConstrainingAspectWidth() { // Given let expectedMultiplier: CGFloat = 2 let expectedAttribute: NSLayoutConstraint.Attribute = .height let expectedRelation: NSLayoutConstraint.Relation = .equal let expectedSecondAttribute: NSLayoutConstraint.Attribute = .width // When sut.constrainSelf(aspectWidth: expectedMultiplier) // Then XCTAssertFalse(sut.translatesAutoresizingMaskIntoConstraints, "Calling constrainSelf should set translatesAutoresizingMaskIntoConstraints on the view to be false.") XCTAssertEqual(expectedMultiplier, sut.constraints.last?.multiplier, "Calling constrainSelf with an aspectWidth value should set the multiplier to \(expectedMultiplier)") XCTAssertEqual(expectedAttribute, sut.constraints.last?.firstAttribute, "Calling constrainSelf with an aspectWidth value should set the height attribute") XCTAssertEqual(expectedRelation, sut.constraints.last?.relation, "Calling constrainSelf with an aspectWidth value should set a constraint with an equal relation") XCTAssertEqual(expectedSecondAttribute, sut.constraints.last?.secondAttribute, "Calling constrainSelf with an aspectWidth value should set a constraint whose second attribute is width") } }
0
// // ViewController.swift // SQLite // // Created by Carlos Butron on 06/12/14. // Copyright (c) 2014 Carlos Butron. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var statement: OpaquePointer = nil var data: NSMutableArray = [] override func viewDidLoad() { super.viewDidLoad() loadTabla() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func loadTabla() { let db_path = Bundle.main.path(forResource: "FilmCollection", ofType: "sqlite") print(Bundle.main) var db: OpaquePointer = nil let status = sqlite3_open(db_path!, &db) if(status == SQLITE_OK){ //bbdd open print("open") } else{ //bbdd error print("open error") } let query_stmt = "select * from film" if(sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil) == SQLITE_OK){ data.removeAllObjects() while(sqlite3_step(statement) == SQLITE_ROW){ let Dictionary = NSMutableDictionary() let director = sqlite3_column_text(statement, 1) let buf_director = String(cString: UnsafePointer<CChar>(director!)) let image = sqlite3_column_text(statement, 2) let buf_image = String(cString: UnsafePointer<CChar>(image!)) let title = sqlite3_column_text(statement, 3) let buf_title = String(cString: UnsafePointer<CChar>(title!)) let year = sqlite3_column_text(statement, 4) let buf_year = String(cString: UnsafePointer<CChar>(year!)) Dictionary.setObject(buf_director, forKey:"director" as NSCopying) Dictionary.setObject(buf_image, forKey: "image" as NSCopying) Dictionary.setObject(buf_title, forKey: "title" as NSCopying) Dictionary.setObject(buf_year, forKey: "year" as NSCopying) data.add(Dictionary) //process data } sqlite3_finalize(statement) } else{ print("ERROR") } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: MyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell") as! MyTableViewCell let aux: AnyObject = data[(indexPath as NSIndexPath).row] as AnyObject let table_director = aux["director"] cell.director.text = table_director as? String //var aux1: AnyObject = data[indexPath.row] let table_image = aux["image"] cell.myImage.image = UIImage(named:table_image as! String) let aux3: AnyObject = data[(indexPath as NSIndexPath).row] as AnyObject let table_title = aux["title"] cell.title.text = table_title as? String //var aux4: AnyObject = data[indexPath.row] let table_year = aux3["year"] cell.year.text = table_year as? String return cell } }
0
// // MessageView.swift // MessageViewUI // // Created by Astemir Eleev on 21/03/2019. // Copyright © 2019 Astemir Eleev. All rights reserved. // import UIKit /// MessageView is HUD component that is intended to be used in cases when success or failure messages and activity progress need to be reported to the user. The usage of the component is quite straingforward: /// /// - shared instance - yes, singletons are bad, but in some cases they are useful. You will not be able to create broken state, unless you use concurrently will present different MessageViews. This is the preffered and quite convenient way to use this component in the majority of cases. /// /// The visials can be customized by using the build-in styles [MessageViewBuilder](MessageViewBuilder.swift), or you can create your own presentations and use the `configure` method to change the default appearence. public final class MessageView: UIView { // MARK: - Private properties private var builder: MessageViewBuilder = MessageViewDefaultBuilder() { didSet { loadingIndicator.transform = builder.loadingIndicatorInitialTransform loadingIndicator.color = builder.activityIndicatorColor messageLabel.font = builder.messageFont messageLabel.textColor = builder.messageColor imageView.transform = builder.loadingIndicatorInitialTransform blurEffectView?.removeFromSuperview() blurEffectView = createVisualEffectView() prepareBackground() } } private var state: State = .hidden private static let shared = MessageView() private lazy var loadingIndicator: UIActivityIndicatorView = { let view = UIActivityIndicatorView(style: builder.activityIndicatorStyle) view.translatesAutoresizingMaskIntoConstraints = false view.transform = builder.loadingIndicatorInitialTransform view.color = builder.activityIndicatorColor return view }() private lazy var messageLabel: UILabel = { let label = UILabel(frame: .zero) label.font = builder.messageFont label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.numberOfLines = 0 label.textColor = builder.messageColor return label }() private lazy var imageView: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.tintColor = builder.successColor view.alpha = 0 view.transform = builder.loadingIndicatorInitialTransform return view }() fileprivate lazy var blurEffectView: UIVisualEffectView? = { createVisualEffectView() }() private var defaultWindow: UIWindow? // MARK: - Initializers private init(window: UIWindow? = UIApplication.shared.windows.first) { super.init(frame: .zero) defaultWindow = window alpha = 0 translatesAutoresizingMaskIntoConstraints = false setup() } public required init?(coder aDecoder: NSCoder) { fatalError("Try to use the shared instance instead") } // MARK: - Methods /// Presents message with an activity indicator view. The intention behind this presentation is to report some long running task. /// /// - Parameters: /// - message: is an optioanl `String` message that will be displayed below the activity indicator /// - delay: is a `TimeInterval` parameter that delays the presentation of the component /// - interval: is a `TimeInterval` parameter that will be used to dismiss the component after the specified number of seconds (default is `0.0`, which means that the component needs to be dismissed **manually**) public class func showActivity(withMessage message: String? = nil, afterDelay delay: TimeInterval = 0.25, dismissAfter interval: TimeInterval = 0.0) { State.message.getExecutable(with: message, delay: delay)() hideIfDelayed(interval) } /// Presents a success message. The intention behind this presentation is to report that something was successfull or completed. /// /// - Parameters: /// - message: is an optioanl `String` message that will be displayed below the activity indicator /// - delay: is a `TimeInterval` parameter that delays the presentation of the component /// - interval: is a `TimeInterval` parameter that will be used to dismiss the component after the specified number of seconds (default is `0.0`, which means that the component needs to be dismissed **manually**) public class func showSuccess(withMessage message: String? = nil, afterDelay delay: TimeInterval = 0.25, dismissAfter interval: TimeInterval = 0.0) { State.success.getExecutable(with: message, delay: delay)() hideIfDelayed(interval) } /// Presents a warning message. The intention behind this presentation is to report that something wasn't successfull or failed. /// /// - Parameters: /// - message: is an optioanl `String` message that will be displayed below the activity indicator /// - delay: is a `TimeInterval` parameter that delays the presentation of the component /// - interval: is a `TimeInterval` parameter that will be used to dismiss the component after the specified number of seconds (default is `0.0`, which means that the component needs to be dismissed **manually**) public class func showWarning(withMessage message: String? = nil, afterDelay delay: TimeInterval = 0.25, dismissAfter interval: TimeInterval = 0.0) { State.warning.getExecutable(with: message, delay: delay)() hideIfDelayed(interval) } /// Presents a custom image above the message. The intention behing this presentation style is defined by you, the developer. /// /// - Parameters: /// - image: is a `UIImage` parameter that holds a valid image that will be presented above the text message. The image should be white on transparent background, since the rendering mode is `alwaysTemplate`. /// - color: is a `UIColor` parameter that is used to color the image /// - message: is an optioanl `String` message that will be displayed below the activity indicator /// - delay: is a `TimeInterval` parameter that delays the presentation of the component /// - interval: is a `TimeInterval` parameter that will be used to dismiss the component after the specified number of seconds (default is `0.0`, which means that the component needs to be dismissed **manually**) public class func showCustom(image: UIImage, tintColor color: UIColor = .lightGray, withMessage message: String? = nil, afterDelay delay: TimeInterval = 0.25, dismissAfter interval: TimeInterval = 0.0) { State.custom(image, color).getExecutable(with: message, delay: delay)() hideIfDelayed(interval) } /// Hides the MessageView immediately public class func hide() { State.hidden.getExecutable(with: nil, delay: 0.0)() } /// Hides the MessageView after the specified delay public class func hide(afterDelay delay: TimeInterval) { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { hide() }) } /// Configuration point. Create your own type that conforms to `MessageViewBuilder` protocol and supply it in order to customize the visuals. public class func configure(with builder: MessageViewBuilder) { MessageView.shared.builder = builder } /// Configuration point. Create your own type that conforms to `MessageViewBuilder` protocol, wrap it into `MessageViewStyle` enum type and use more convenient configuration style. public class func configure(with style: MessageViewStyle) { MessageView.shared.builder = style.getBuilder() } /// Updates the text message for the presented `MessageView`. Useful in cases when a single instnace of a `MessageView` needs to be updated without hiding and presenting a new component. /// /// - Parameters: /// - message: a new `String` message that will be displayed /// - interval: is a `TimeInterval` parameter that will be used to dismiss the component after the specified number of seconds (default is `0.0`, which means that the component needs to be dismissed **manually**) public class func update(message: String, dismissAfter interval: TimeInterval = 0.0) { DispatchQueue.main.async { MessageView.shared.messageLabel.text = message hideIfDelayed(interval) } } } // MARK: - Private extension private extension MessageView { // MARK: - Methods private class func hideIfDelayed(_ interval: TimeInterval) { guard interval > 0.0 else { return } hide(afterDelay: interval) } private func createVisualEffectView() -> UIVisualEffectView? { guard let style = builder.backgroundStyle.getBlurStyle() else { return nil } let blurEffect = UIBlurEffect(style: style) let effectView = UIVisualEffectView(effect: blurEffect) return effectView } private func prepareBackground() { switch builder.backgroundStyle { case .color(let instance): backgroundColor = instance case .dark, .light, .extraLight: guard let blurEffectView = blurEffectView else { return } insertSubview(blurEffectView, belowSubview: self) backgroundColor = .clear insertSubview(blurEffectView, at: 0) blurEffectView.fillInSuperview() } } private func setup() { func prepareUIComposition() { addSubview(loadingIndicator) addSubview(messageLabel) addSubview(imageView) NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: builder.loadingIndicatorSize), imageView.heightAnchor.constraint(equalToConstant: builder.loadingIndicatorSize - .smallSpacing), imageView.centerXAnchor.constraint(equalTo: centerXAnchor), imageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -.smallSpacing), loadingIndicator.widthAnchor.constraint(equalToConstant: builder.loadingIndicatorSize), loadingIndicator.heightAnchor.constraint(equalToConstant: builder.loadingIndicatorSize), loadingIndicator.centerXAnchor.constraint(equalTo: centerXAnchor), loadingIndicator.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -.smallSpacing), messageLabel.topAnchor.constraint(equalTo: loadingIndicator.bottomAnchor, constant: .mediumSpacing), messageLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: .largeSpacing), messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -.largeSpacing) ]) } prepareBackground() prepareUIComposition() } private func showImage(withMessage message: String? = nil) { if superview == nil { defaultWindow?.addSubview(self) fillInSuperview() } let data = state.getData(from: builder) imageView.image = data.image imageView.tintColor = data.color loadingIndicator.alpha = 0 messageLabel.text = message blurEffectView?.alpha = 0 UIView.animate(withDuration: builder.animationDuration) { self.alpha = 1 self.blurEffectView?.alpha = 1 self.imageView.alpha = 1 self.imageView.transform = .identity } } private func startAnimating(withMessage message: String? = nil) { if superview == nil { defaultWindow?.addSubview(self) fillInSuperview() } messageLabel.text = message imageView.alpha = 0 blurEffectView?.alpha = 0 loadingIndicator.startAnimating() loadingIndicator.transform = builder.loadingIndicatorInitialTransform loadingIndicator.alpha = 1 UIViewPropertyAnimator(duration: builder.animationDuration, curve: .easeIn) { self.alpha = 1 self.blurEffectView?.alpha = 1 self.loadingIndicator.transform = .identity }.startAnimation() } private func stopAnimating() { if defaultWindow != nil { let transform = builder.loadingIndicatorInitialTransform UIView.animate(withDuration: builder.animationDuration, animations: { self.loadingIndicator.transform = transform self.imageView.transform = transform }, completion: { _ in self.loadingIndicator.stopAnimating() self.messageLabel.text = nil UIView.animate(withDuration: self.builder.animationDuration, animations: { self.alpha = 0 self.blurEffectView?.alpha = 0 }, completion: { _ in self.removeFromSuperview() }) }) } } } // MARK: - Enum type extension public extension MessageView { // MARK: - Enum types /// Private state of the component. Incapsulates the possible cases such as `message` or `success`. Also, it provides conveninet factory methods that produce either executables or data depending on the current state. private enum State: Equatable { // MARK: - Typealisases typealias Data = (image: UIImage?, color: UIColor?) // MARK: - Cases case message case hidden case success case warning case custom(UIImage, UIColor) // MARK: - Methods func getData(from model: MessageViewBuilder) -> Data { switch self { case .success: return (UIImage(systemName: "checkmark.circle", withConfiguration: UIImage.SymbolConfiguration.init(scale: .large))? .withRenderingMode(.alwaysTemplate), model.successColor) case .warning: return (UIImage(systemName: "exclamationmark.triangle", withConfiguration: UIImage.SymbolConfiguration.init(scale: .large))? .withRenderingMode(.alwaysTemplate), model.warningColor) case .custom(let image, let color): return (image, color) default: return (nil, nil) } } func getExecutable(with message: String?, delay: TimeInterval) -> () -> Void { switch self { case .success: return { MessageView.shared.state = .success DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { if MessageView.shared.state == .success { MessageView.shared.showImage(withMessage: message) } }) } case .message: return { MessageView.shared.state = .message DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { if MessageView.shared.state == .message { MessageView.shared.startAnimating(withMessage: message) } }) } case .warning: return { MessageView.shared.state = .warning DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { if MessageView.shared.state == .warning { MessageView.shared.showImage(withMessage: message) } }) } case .custom(let image, let tint): return { MessageView.shared.state = .custom(image, tint) DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { if case .custom = MessageView.shared.state { MessageView.shared.showImage(withMessage: message) } }) } case .hidden: return { MessageView.shared.state = .hidden MessageView.shared.stopAnimating() } } } } enum BackgroundStyle: Equatable { // MARK: - Cases case color(UIColor) case light case extraLight case dark // MARK: - Methods func getBlurStyle() -> UIBlurEffect.Style? { switch self { case .light: return .light case .extraLight: return .extraLight case .dark: return .dark default: return nil } } } }
0
// // Copyright © 2019 MBition GmbH. All rights reserved. // import Foundation /// Representation of user preferred units public struct UserAdaptionValuesModel: Equatable { public let bodyHeight: Int? public let preAdjustment: Bool? // MARK: - Init public init(bodyHeight: Int?, preAdjustment: Bool?) { self.bodyHeight = bodyHeight self.preAdjustment = preAdjustment } }
0
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers import ReactiveSwift import WebKit import XCTest final class ProjectUpdatesViewModelTests: TestCase { fileprivate let vm: ProjectUpdatesViewModelType = ProjectUpdatesViewModel() fileprivate let goToSafariBrowser = TestObserver<URL, Never>() fileprivate let goToUpdateId = TestObserver<Int, Never>() fileprivate let goToUpdateCommentId = TestObserver<Int, Never>() fileprivate let isActivityIndicatorHidden = TestObserver<Bool, Never>() fileprivate let makePhoneCall = TestObserver<URL, Never>() fileprivate let showMailCompose = TestObserver<String, Never>() fileprivate let showNoEmailError = TestObserver<UIAlertController, Never>() fileprivate let webViewLoadRequest = TestObserver<URLRequest, Never>() internal override func setUp() { super.setUp() self.vm.outputs.goToSafariBrowser.observe(self.goToSafariBrowser.observer) self.vm.outputs.goToUpdate.map { _, update in update.id }.observe(self.goToUpdateId.observer) self.vm.outputs.goToUpdateComments.map { $0.id }.observe(self.goToUpdateCommentId.observer) self.vm.outputs.isActivityIndicatorHidden.observe(self.isActivityIndicatorHidden.observer) self.vm.outputs.makePhoneCall.observe(self.makePhoneCall.observer) self.vm.outputs.showMailCompose.observe(self.showMailCompose.observer) self.vm.outputs.showNoEmailError.observe(self.showNoEmailError.observer) self.vm.outputs.webViewLoadRequest.observe(self.webViewLoadRequest.observer) } func testGoToSafariBrowser() { let project = Project.template self.vm.inputs.configureWith(project: project) self.vm.inputs.viewDidLoad() let googleURL = URL(string: "http://www.google.com")! self.goToSafariBrowser.assertValues([]) let navigationAction = self.navigationAction(with: googleURL) XCTAssertEqual( WKNavigationActionPolicy.cancel.rawValue, self.vm.inputs.decidePolicy(forNavigationAction: navigationAction).rawValue ) self.goToSafariBrowser.assertValues([googleURL]) XCTAssertEqual(["Opened External Link"], self.trackingClient.events) XCTAssertEqual("project_updates", self.trackingClient.properties.last!["context"] as? String) } func testGoToUpdate() { let project = Project.template |> (Project.lens.urls.web .. Project.UrlsEnvelope.WebEnvelope.lens.updates) .~ "https://www.kickstarter.com/projects/milk/duds/posts" let updateId = 11_235 self.vm.inputs.configureWith(project: project) self.vm.inputs.viewDidLoad() let navigationAction = self.navigationAction( with: URL(string: "\(project.urls.web.updates!)/\(updateId)")! ) XCTAssertEqual( WKNavigationActionPolicy.cancel.rawValue, self.vm.inputs.decidePolicy(forNavigationAction: navigationAction).rawValue ) self.goToUpdateId.assertValues([updateId]) self.isActivityIndicatorHidden.assertValues([]) self.vm.inputs.webViewDidStartProvisionalNavigation() self.isActivityIndicatorHidden.assertValues([false]) self.vm.inputs.webViewDidFinishNavigation() self.isActivityIndicatorHidden.assertValues([false, true]) } func testGoToUpdateComments() { let project = Project.template |> (Project.lens.urls.web .. Project.UrlsEnvelope.WebEnvelope.lens.updates) .~ "https://www.kickstarter.com/projects/smh/lol/posts" let updateId = 123_456 self.vm.inputs.configureWith(project: project) self.vm.inputs.viewDidLoad() let navigationAction = self.navigationAction( with: URL(string: "\(project.urls.web.updates!)/\(updateId)/comments")! ) XCTAssertEqual( WKNavigationActionPolicy.cancel.rawValue, self.vm.inputs.decidePolicy(forNavigationAction: navigationAction).rawValue ) self.goToUpdateCommentId.assertValues([updateId]) } func testShowMailComposeEmits_WhenEmailLinkIsTapped() { let navigationAction = self.navigationAction(with: URL(string: "mailto:[email protected]")!) self.vm.inputs.canSendEmail(true) _ = self.vm.inputs.decidePolicy(forNavigationAction: navigationAction) self.showMailCompose.assertValues(["[email protected]"]) } func testShowEmailErrorEmits_WhenEmailLinkIsTapped_AndCantSendEmail() { let navigationAction = self.navigationAction(with: URL(string: "mailto:[email protected]")!) self.vm.inputs.canSendEmail(false) _ = self.vm.inputs.decidePolicy(forNavigationAction: navigationAction) self.showNoEmailError.assertDidEmitValue() } func testMakePhoneCallEmits_WhenPhoneLinkIsTapped() { let phoneUrl = URL(string: "tel://5551234567")! let navigationAction = self.navigationAction(with: phoneUrl) self.vm.inputs.viewDidLoad() _ = self.vm.inputs.decidePolicy(forNavigationAction: navigationAction) self.makePhoneCall.assertValues([phoneUrl]) } func testWebViewLoadRequests() { let project = Project.template |> (Project.lens.urls.web .. Project.UrlsEnvelope.WebEnvelope.lens.updates) .~ "https://www.kickstarter.com/projects/shrimp/ijc/posts" let updatesIndexRequest = AppEnvironment.current.apiService.preparedRequest( forURL: URL(string: project.urls.web.updates!)! ) self.vm.inputs.configureWith(project: project) self.vm.inputs.viewDidLoad() self.webViewLoadRequest.assertValues([updatesIndexRequest]) } func testIFrameRequest() { let project = Project.template |> (Project.lens.urls.web .. Project.UrlsEnvelope.WebEnvelope.lens.updates) .~ "https://www.kickstarter.com/projects/shrimp/ijc/posts" let updatesIndexRequest = AppEnvironment.current.apiService.preparedRequest( forURL: URL(string: project.urls.web.updates!)! ) self.vm.inputs.configureWith(project: project) self.vm.inputs.viewDidLoad() self.webViewLoadRequest.assertValues([updatesIndexRequest]) let updateRequest = URLRequest(url: URL(string: "https://www.youtube.com/watch")!) let navigationAction = WKNavigationActionData( navigationType: .linkActivated, request: updateRequest, sourceFrame: WKFrameInfoData.init(mainFrame: true, request: updateRequest), targetFrame: WKFrameInfoData.init(mainFrame: false, request: updateRequest) ) XCTAssertEqual( WKNavigationActionPolicy.allow.rawValue, self.vm.inputs.decidePolicy(forNavigationAction: navigationAction).rawValue ) self.webViewLoadRequest.assertValues([updatesIndexRequest], "Update loaded in VC, not web view.") } private func navigationAction(with url: URL) -> WKNavigationActionData { let request = URLRequest(url: url) return WKNavigationActionData( navigationType: .linkActivated, request: request, sourceFrame: WKFrameInfoData.init(mainFrame: true, request: request), targetFrame: WKFrameInfoData.init(mainFrame: true, request: request) ) } }
0
// // ViewController.swift // Example // // Created by David Ask on 2017-02-18. // Copyright © 2017 Formbound AB. All rights reserved. // import UIKit import Pin class ViewController: UIViewController { let backgroundView = UIImageView(image: UIImage(named: "Background")) let titleLabel = UILabel() let textContainer = UIView() let longTextLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() // Create and configure the background view backgroundView.contentMode = .scaleAspectFill backgroundView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(backgroundView) // Create and configure the title label titleLabel.textColor = .white titleLabel.font = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize * 2) titleLabel.text = "Welcome to the Pin iOS example!" titleLabel.textAlignment = .center titleLabel.numberOfLines = 0 titleLabel.translatesAutoresizingMaskIntoConstraints = false view.addSubview(titleLabel) // Create and configure the container view textContainer.layer.masksToBounds = true textContainer.layer.cornerRadius = 5 textContainer.layer.borderColor = UIColor(white: 1, alpha: 0.3).cgColor textContainer.layer.borderWidth = 1 textContainer.backgroundColor = UIColor(white: 1, alpha: 0.1) textContainer.translatesAutoresizingMaskIntoConstraints = false view.addSubview(textContainer) // Create and configure the long text label longTextLabel.textColor = .white longTextLabel.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tristique magna sapien. Aliquam nec metus sed elit finibus ultricies. Sed in pulvinar est, sit amet placerat mi. Curabitur consectetur dolor vehicula, finibus sem in, consectetur velit. Vestibulum nulla massa, tempor eget nisl a, laoreet ultricies quam. Vivamus et massa arcu." longTextLabel.numberOfLines = 0 longTextLabel.translatesAutoresizingMaskIntoConstraints = false textContainer.addSubview(longTextLabel) NSLayoutConstraint.make { constraints in constraints += backgroundView.pinEdges(to: view) constraints += [ titleLabel.topPin == topLayoutGuide.bottomPin + 30, titleLabel.centerXPin.equal(to: view.centerXPin), titleLabel.widthPin <= view.widthPin * 0.75, textContainer.bottomPin == bottomLayoutGuide.topPin - 30, textContainer.leftPin == view.leftMarginPin, textContainer.rightPin == view.rightMarginPin ] constraints += longTextLabel.pinEdgeMargins(to: textContainer) }.activate() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
0
// // AmuseViewModel.swift // DYTV // // Created by CodeLL on 2016/10/13. // Copyright © 2016年 coderLL. All rights reserved. // import UIKit class AmuseViewModel : BaseViewModel{ } extension AmuseViewModel { func loadAmuseData(finishedCallback: @escaping () -> ()) { loadAnchorData(method: .get, URLString: "http://www.douyutv.com/api/v1/getHotRoom/2", finishedCallback: finishedCallback) } }
0
// // TransactionImageView.swift // p2p_wallet // // Created by Chung Tran on 07/04/2021. // import Foundation import RxSwift import SolanaSwift import UIKit final class TransactionImageView: BEView { private let _backgroundColor: UIColor? private let _cornerRadius: CGFloat? private let basicIconSize: CGFloat private let miniIconsSize: CGFloat private let statusIconSize: CGSize private lazy var basicIconImageView = UIImageView( width: basicIconSize, height: basicIconSize, tintColor: .black ) private lazy var statusIconImageView: UIImageView = { let image = UIImageView(width: statusIconSize.width, height: statusIconSize.height, tintColor: .iconSecondary) image.isHidden = true return image }() private lazy var fromTokenImageView = CoinLogoImageView(size: miniIconsSize) private lazy var toTokenImageView = CoinLogoImageView(size: miniIconsSize) init( size: CGFloat, backgroundColor: UIColor? = nil, cornerRadius: CGFloat? = nil, basicIconSize: CGFloat = 24.38, miniIconsSize: CGFloat = 30, statusIconSize: CGSize = .init(width: 18, height: 18) ) { _backgroundColor = backgroundColor _cornerRadius = cornerRadius self.basicIconSize = basicIconSize self.miniIconsSize = miniIconsSize self.statusIconSize = statusIconSize super.init(frame: .zero) configureForAutoLayout() autoSetDimensions(to: .init(width: size, height: size)) } override func commonInit() { super.commonInit() let backgroundView = UIView(backgroundColor: _backgroundColor, cornerRadius: _cornerRadius) addSubview(backgroundView) backgroundView.autoPinEdgesToSuperviewEdges() addSubview(basicIconImageView) basicIconImageView.autoCenterInSuperview() addSubview(fromTokenImageView) fromTokenImageView.autoPinToTopLeftCornerOfSuperview() addSubview(toTokenImageView) toTokenImageView.autoPinToBottomRightCornerOfSuperview() addSubview(statusIconImageView) statusIconImageView.autoPinToBottomRightCornerOfSuperview(xInset: -2, yInset: 0) fromTokenImageView.alpha = 0 toTokenImageView.alpha = 0 } func setUp(imageType: ImageType) { switch imageType { case let .oneImage(image): fromTokenImageView.alpha = 0 toTokenImageView.alpha = 0 basicIconImageView.isHidden = false basicIconImageView.image = image case let .fromOneToOne(from, to): basicIconImageView.isHidden = true fromTokenImageView.alpha = 1 toTokenImageView.alpha = 1 fromTokenImageView.setUp(token: from) toTokenImageView.setUp(token: to) } } func setUp(statusImage: UIImage?) { statusIconImageView.isHidden = false statusIconImageView.image = statusImage } } // MARK: - Model extension TransactionImageView { enum ImageType { case oneImage(image: UIImage) case fromOneToOne(from: Token?, to: Token?) } } // MARK: - Reactive extension Reactive where Base == TransactionImageView { var imageType: Binder<Base.ImageType> { Binder(base) { $0.setUp(imageType: $1) } } }
0
import XCTest class TransferUserFundsTest: BaseTests { var transferFundMenu: XCUIElement! var transferFundSourceMenu: XCUIElement! var transferFunds: TransferFunds! var selectDestination: TransferFundsSelectDestination! var addTransferMethod: AddTransferMethod! var elementQuery: XCUIElementQuery! let listppcUrl = "/rest/v3/users/usr-token/prepaid-cards" let ppcInfoUrl = "/rest/v3/users/usr-token/prepaid-cards/trm-token" var expectedUSDestinationPrepaidLabel: String = { if #available(iOS 11.2, *) { return "USD\nVisa •••• " } else { return "USD Visa •••• " } }() var expectedUSDestinationLabel: String = { if #available(iOS 11.2, *) { return "United States\nending in " } else { return "United States ending in " } }() var expectedCanadaDestinationLabel: String = { if #available(iOS 11.2, *) { return "Canada\nending in 1235" } else { return "Canada ending in 1235" } }() var expectedJapanDestinationLabel: String = { if #available(iOS 11.2, *) { return "Japan\nending in 1200" } else { return "Japan ending in 1200" } }() override func setUp() { super.setUp() app = XCUIApplication() app.launchArguments.append("enable-testing") app.launch() spinner = app.activityIndicators["activityIndicator"] transferFundMenu = app.tables.cells .containing(.staticText, identifier: "Transfer Funds") .element(boundBy: 0) transferFundSourceMenu = app.tables.cells .containing(.staticText, identifier: "Transfer Funds Source") .element(boundBy: 0) transferFunds = TransferFunds(app: app) selectDestination = TransferFundsSelectDestination(app: app) addTransferMethod = AddTransferMethod(app: app) if #available(iOS 13.0, *) { elementQuery = app.tables["scheduleTransferTableView"].buttons } else { elementQuery = app.tables["scheduleTransferTableView"].staticTexts } mockServer.setupStub(url: "/rest/v3/users/usr-token/balances", filename: "ListBalancesResponseSuccess", method: HTTPMethod.get) } /* Given that no Transfer methods have been created When module is loaded Then the user will have the ability to create a method */ func testTransferFunds_noTransferMethod() { mockServer.setUpEmptyResponse(url: "/rest/v3/users/usr-token/transfer-methods") XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() // TRANSFER FROM transferFunds.verifyTransferFrom(isAvailableFunds: true) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "mobileAddTransferMethod".localized()) // assert NOTE XCTAssertTrue(transferFunds.notesSectionLabel.exists) // assert Continue button XCTAssertTrue(transferFunds.nextLabel.exists) } func testTransferFunds_userBalanceError() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) mockServer.setupStubError(url: "/rest/v3/users/usr-token/balances", filename: "ListBalancesResponseSuccess", method: .get, statusCode: 500) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() waitForExistence(app.alerts["Unexpected Error"]) XCUIApplication() .alerts["Unexpected Error"] .scrollViews .otherElements .buttons["Done"] .tap() waitForNonExistence(spinner) XCTAssertTrue(transferFundMenu.exists) } /* Given that Transfer methods exist When module is loaded Then first available transfer method will be selected */ func testTransferFunds_firstAvailableMethodIsSelected() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer max funds XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // TRANSFER FROM XCTAssertEqual(transferFunds.transferSourceTitleLabel.label, "mobileAvailableFunds".localized()) XCTAssertEqual(transferFunds.transferSourceSubtitleLabel.label, "CAD, EUR, USD") // TRANSFER TO XCTAssertTrue(transferFunds.transferSectionLabel.exists) // Add Destination Section XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.verifyBankAccountDestination(type: "Bank Account", endingDigit: "1234") // Notes XCTAssertTrue(transferFunds.notesSectionLabel.exists) transferFunds.verifyNotes() // Next Button XCTAssertTrue(transferFunds.nextLabel.exists) } /* Given that Transfer methods exist When user select a different transfer method with different currency Then the destination currency should be updated AND Then Payee can enter the amount */ func testTransferFunds_switchTransferMethodCurrency() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer max funds XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.addSelectDestinationLabel.tap() // Select Destination (CAD) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundCAD", method: HTTPMethod.post) let cadBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 1) cadBankAccount.tap() waitForNonExistence(spinner) transferFunds.transferMaxAllFunds.tap() // Assert Destination Amount is automatically insert into the amount field XCTAssertEqual(transferFunds.transferAmount.value as? String, "7,301.64") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "CAD") } /* Given that Transfer methods exist When user select a different transfer method with error occurs Then will not show the error And "Amount available: N/A" is shown And transfer max funds is not shown */ func testTransferFunds_switchTransferMethodWithTransactionLimitError() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer max funds XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.addSelectDestinationLabel.tap() // Select Destination (CAD) mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferBelowTransactionLimitError", method: HTTPMethod.post) let cadBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 1) cadBankAccount.tap() waitForNonExistence(spinner) // Assert Available available: N/A XCTAssertEqual(transferFunds.transferAmountLabel.label, transferFunds.notAvailableFunds) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertFalse(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should not exist") } /* Given that Transfer methods exist When navigate to the Transfer view and error occurs Then will not show the error And "Amount available: N/A" is shown And transfer max funds is not shown */ func testTransferFunds_TransferMethodWithBelowTransactionLimitError() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferBelowTransactionLimitError", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") // Assert Available available: N/A XCTAssertEqual(transferFunds.transferAmountLabel.label, transferFunds.notAvailableFunds) // Transfer max funds XCTAssertFalse(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should not exist") } func testTransferFunds_createTransferWithAllFunds() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer all funds row XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // Tap on the Transfer max funds transferFunds.transferMaxAllFunds.tap() // Assert Destination Amount is automatically insert into the amount field XCTAssertEqual(transferFunds.transferAmount.value as? String, "452.14") } /* Given that Transfer methods exist When user selects TransferAllFunds AND then remove the All Funds amount AND enter a different fund amount Then the transfer fund amount should show different fund amount. */ func testTransferFunds_switchAllFundsToEnterFundsUSD() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer all funds row XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // Tap on the Transfer max funds transferFunds.transferMaxAllFunds.tap() // Assert Destination Amount is automatically insert into the amount field XCTAssertEqual(transferFunds.transferAmount.value as? String, "452.14") transferFunds.enterTransferAmount(amount: "999.99") XCTAssertEqual(transferFunds.transferAmount.value as? String, "999.99") // Tap on the Transfer max funds again transferFunds.transferAmountLabel.tap() transferFunds.transferMaxAllFunds.tap() checkSelectFieldValueIsEqualTo("452.14", transferFunds.transferAmount) } /* Given that User has 2 bank accounts which has different Currency from the Source. When user transfer the fund Then the user should see 2 FX quotes */ // Transfer Requiring more than 2 FX func testTransferFunds_createTransferWithFX() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundMultiCurrencies", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) // Add Destination Section XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.verifyBankAccountDestination(type: "Bank Account", endingDigit: "1234") // Transfer Section XCTAssertTrue(transferFunds.transferSectionLabel.exists) // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "5,855.17", "USD")) // Transfer all funds row XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // Turn the Transfer All Switch On transferFunds.transferMaxAllFunds.tap() XCTAssertEqual(transferFunds.transferAmount.value as? String, "5,855.17") // Next Button XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() // Assert Confirmation Page // waitForExistence(elementQuery["Confirm"]) } func testTransferFunds_createTransferWithoutFX() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) // Transfer Section XCTAssertTrue(transferFunds.transferSectionLabel.exists) // Amount row XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer all funds row XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // Add Destination Section XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.verifyBankAccountDestination(type: "Bank Account", endingDigit: "6789") // Notes XCTAssertTrue(transferFunds.notesSectionLabel.exists) // Turn the Transfer max funds transferFunds.transferMaxAllFunds.tap() XCTAssertEqual(transferFunds.transferAmount.value as? String, "452.14") // Next Button XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() // Assert Confirmation Page // waitForExistence(elementQuery["Confirm"]) } /* Given that user is on the Transfer fund page and selected a Transfer Destination When user enter the digit for the transfer amount Then amount field will be formatted correctly */ func testTransferFunds_createTransferWhenDestinationAmountIsSet() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") XCTAssertTrue(transferFunds.transferAmount.exists) transferFunds.transferAmount.tap() transferFunds.transferAmount.clearAmountFieldAndEnterText(text: ".12345") transferFunds.transferSectionLabel.tap() XCTAssertEqual(transferFunds.transferAmount.value as? String, "123.45") transferFunds.transferAmount.clearAndEnterText(text: "123456789012") XCTAssertEqual(transferFunds.transferAmount.value as? String, "1,234,567,890.12") transferFunds.transferAmount.typeText("1234.56") XCTAssertEqual(transferFunds.transferAmount.value as? String, "1,234,567,890.12") transferFunds.transferSectionLabel.tap() XCTAssertEqual(transferFunds.transferAmount.value as? String, "1,234,567,890.12") } // MARK: Select Destination Page func testTransferFunds_selectDestination() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyBankAccountDestination(type: TransferMethods.bankAccount, endingDigit: "1234") transferFunds.addSelectDestinationLabel.tap() let usdBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 0) let cadBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 1) let prepaidCard = app.tables.element.children(matching: .cell).element(boundBy: 2) XCTAssertTrue(selectDestination.selectDestinationTitle.exists) XCTAssertTrue(selectDestination.addTransferMethodButton.exists) waitForNonExistence(spinner) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 0), TransferMethods.bankAccount) XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 0), expectedUSDestinationLabel + "1234") XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 1), TransferMethods.bankAccount) XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 1), expectedCanadaDestinationLabel) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 2), TransferMethods.prepaidCard) XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 2), expectedUSDestinationPrepaidLabel + "4281") // Assert first row is checked by default assertButtonTrue(element: usdBankAccount) assertButtonFalse(element: cadBankAccount) assertButtonFalse(element: prepaidCard) // Assert can go back to previous page // selectDestination.clickBackButton() clickBackButton() transferFunds.verifyTransferFundsTitle() } func testTransferFunds_currencyFormatting() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyBankAccountDestination(type: TransferMethods.bankAccount, endingDigit: "1234") transferFunds.transferAmount.tap() transferFunds.transferAmount.clearAmountFieldAndEnterText(text: "1.23") transferFunds.addSelectDestinationLabel.tap() XCTAssertTrue(selectDestination.selectDestinationTitle.exists) XCTAssertTrue(selectDestination.addTransferMethodButton.exists) waitForNonExistence(spinner) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 3), TransferMethods.bankAccount) XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 3), expectedJapanDestinationLabel) selectDestination.tapSelectDestinationRow(index: 3) waitForNonExistence(spinner) XCTAssertTrue(transferFunds.transferAmount.exists) transferFunds.transferAmount.tap() transferFunds.transferAmount.typeText("2") XCTAssertEqual(transferFunds.transferAmount.value as? String, "12") } private func assertButtonTrue(element: XCUIElement) { if #available(iOS 13.0, *) { XCTAssertTrue(element.buttons["checkmark"].exists, "By default the first row should be selected") } else { XCTAssertTrue(element.buttons["More Info"].exists, "By default the first row should be selected") } } private func assertButtonFalse(element: XCUIElement) { if #available(iOS 13.0, *) { XCTAssertFalse(element.buttons["checkmark"].exists, "By default the first row should be selected") } else { XCTAssertFalse(element.buttons["More Info"].exists, "By default the first row should be selected") } } // MARK: UI Error Handling /* When user's account has available fund but has no Transfer method when user tab "Next" Then "Add a transfer method first" footer shows under "Destination" section Then "Enter amount or select tranfer all funds" footer shows under "Transfer all funds" section */ func testTransferFunds_createTransferWhenDestinationNotSet() { mockServer.setUpEmptyResponse(url: "/rest/v3/users/usr-token/transfer-methods") mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() // Transfer From transferFunds.verifyTransferFrom(isAvailableFunds: true) // Transfer To XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "mobileAddTransferMethod".localized()) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForNonExistence(spinner) app.swipeDown() // Assert inline errors XCTAssertEqual(transferFunds.transferMethodRequireError.label, "noTransferMethodAdded".localized()) XCTAssertEqual(transferFunds.invalidAmountError.label, "transferAmountInvalid".localized()) } func testTransferFunds_createTransferWhenDestinationAmountNotSet() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() // Transfer From transferFunds.verifyTransferFrom(isAvailableFunds: true) // Transfer To XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertTrue(transferFunds.transferAmount.exists) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForNonExistence(spinner) app.swipeDown() XCTAssertEqual(transferFunds.invalidAmountError.label, "transferAmountInvalid".localized()) } /* When user enters amount below the transaction limit in transfer amount Field And when user tab Next Then shows error dialog */ func testTransferFunds_createTransferBelowTransactionLimit() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) // Transfer From transferFunds.verifyTransferFrom(isAvailableFunds: true) // Transfer To XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertTrue(transferFunds.transferAmount.exists) // Enter amount lower than the transaction limit transferFunds.enterTransferAmount(amount: "0.01") mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferBelowTransactionLimitError", method: HTTPMethod.post) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForExistence(app.alerts["Error"]) let predicate = NSPredicate(format: "label CONTAINS[c] 'Requested transfer amount $0.01, is below the transaction limit of $1.00.'") XCTAssert(app.alerts["Error"].staticTexts.element(matching: predicate).exists) } func testTransferFunds_createTransferDescriptionLength() { let over255String = """ 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefghij1234567890abcdefghij1234567890abcdefghij 1234567890abcdefgEND """ mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.enterTransferAmount(amount: "1000") if #available(iOS 13.0, *) { transferFunds.notesDescriptionTextField.tap() transferFunds.notesDescriptionTextField.typeText(over255String) } else { transferFunds.enterNotes(description: over255String) } app.swipeUpSlow() mockServer.setupStubError(url: "/rest/v3/transfers", filename: "NoteDescriptionLengthValidationError", method: HTTPMethod.post) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForNonExistence(spinner) let error = app.tables["createTransferTableView"].staticTexts["transferTableViewFooterViewIdentifier"].label // show error at footer XCTAssertTrue(error.contains("Notes should be between 1 and 255 characters")) } /* Given that Transfer methods exist When user transfers the fund Then the over limit error occurs and the app should display the error (Your attempted transaction has exceeded the approved payout limit) If someone transfers > what is maximally transferable by the account eg, CAD limit is $99,999 */ func testTransferFunds_createTransferOverLimitError() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListOneBankAccountTransferUSD", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() // waitForNonExistence(transferFunds.addSelectDestinationSectionLabel) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertTrue(transferFunds.transferAmount.exists) transferFunds.enterTransferAmount(amount: "999999999") // Next Button mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferErrorLimitExceeded", method: HTTPMethod.post) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForExistence(app.alerts["Error"]) let predicate = NSPredicate(format: """ label CONTAINS[c] 'Your attempted transaction has exceeded the approved payout limit; \ please contact Hyperwallet for further assistance.' """) XCTAssert(app.alerts["Error"].staticTexts.element(matching: predicate).exists) } /* Given that Transfer methods exist And insufficient funds to transfer When user transfers the fund Then Amount Less than fee error occurs and the app should display the error */ func testTransferFunds_createTransferInsufficientFundsError() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertTrue(transferFunds.transferAmount.exists) transferFunds.enterTransferAmount(amount: "1000000") // Next Button mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferErrorOverAvailableFund", method: HTTPMethod.post) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.tapContinueButton() waitForExistence(app.alerts["Error"]) let predicate = NSPredicate(format: "label CONTAINS[c] 'You do not have enough funds in any single currency to complete this transfer'") XCTAssert(app.alerts["Error"].staticTexts.element(matching: predicate).exists) } func testTransferFunds_createTransferInvalidSourceError() { mockServer.setupStubError(url: "/rest/v3/users/usr-token/transfer-methods", filename: "InvalidSourceError", method: HTTPMethod.get) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) waitForExistence(app.alerts["Error"]) let predicate = NSPredicate(format: "label CONTAINS[c] 'The source token you provided doesn’t exist or is not a valid source.'") XCTAssert(app.alerts["Error"].staticTexts.element(matching: predicate).exists) } // swiftlint:disable function_body_length // MARK: Add Transfer Method Tests func testTransferFunds_addTransferMethodWhenNoTransferMethods() { mockServer.setUpEmptyResponse(url: "/rest/v3/users/usr-token/transfer-methods") mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) mockServer.setupStub(url: "/graphql", filename: "TransferMethodConfigurationBankAccountBusinessResponse", method: HTTPMethod.post) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "mobileAddTransferMethod".localized()) transferFunds.addSelectDestinationLabel.tap() // Assert Add a transfer method View waitForNonExistence(spinner) XCTAssertTrue(app.navigationBars["mobileAddTransferMethodHeader".localized()].exists) XCTAssertTrue(app.tables.staticTexts["United States"].exists) XCTAssertTrue(app.tables.staticTexts["USD"].exists) mockServer.setupStub(url: "/rest/v3/users/usr-token/bank-accounts", filename: "BankAccountIndividualResponse", method: HTTPMethod.post) // Tap on Bank Account app.tables["selectTransferMethodTypeTable"].cells["Bank Account"].tap() XCTAssert(app.navigationBars["Bank Account"].exists) addTransferMethod.setBranchId("021000021") addTransferMethod.setBankAccountId("12345") addTransferMethod.selectAccountType("CHECKING") addTransferMethod.clickCreateTransferMethodButton() waitForNonExistence(spinner) // Assert navigate to the Transfer Fund again transferFunds.verifyTransferFundsTitle() XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, "Bank Account") transferFunds.verifyBankAccountDestination(type: "Bank Account", endingDigit: "2345") mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "AddNewTransferMethodOneTransferMethod", method: HTTPMethod.get) waitForNonExistence(spinner) transferFunds.verifyTransferFundsTitle() app.tables["createTransferTableView"].staticTexts["transferDestinationSubtitleLabel"].tap() waitForNonExistence(spinner) // Assert added account is set as the Transfer Destination XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 0), "Bank Account") XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 0), expectedUSDestinationLabel + "2345") } // MARK: Select PPC as the Transfer source func testTransferFunds_createTransferPrepaidCard_transferFromPrepaidCard() { // Get the transfer method list mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) // Get the Available funds mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) // List the available PPC of the user to select from source mockServer.setupStub(url: listppcUrl, filename: "PrepaidCardPrimaryOnlyResponse", method: HTTPMethod.get) // Retreive details of PPC by trm-token mockServer.setupStub(url: "/rest/v3/users/usr-token/prepaid-cards/trm-token", filename: "GetPrepaidCardSuccessResponse", method: HTTPMethod.get) XCTAssertTrue(transferFundSourceMenu.exists) transferFundSourceMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFrom(isAvailableFunds: true) // Select Transfer source - PPC transferFunds.transferSourceTitleLabel.tap() let app = XCUIApplication() app.launchArguments.append("enable-testing") XCTAssert(app.tables.staticTexts["CAD, EUR, USD"].exists) let ppcCell = app.tables.element.children(matching: .cell).element(boundBy: 1) ppcCell.tap() waitForNonExistence(spinner) // Transfer From by PPC Section transferFunds.verifyTransferFrom(isAvailableFunds: false) transferFunds.verifyPPCInfo(brandType: transferFunds.prepaidCardVisa, endingDigit: "9285", currency: "USD") // Transfer Destination Section - Bank Account transferFunds.verifyTransferFundsTitle() transferFunds.verifyBankAccountDestination(type: "Bank Account", endingDigit: "1234") // Transfer Section XCTAssertTrue(transferFunds.transferSectionLabel.exists) // Amount XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, String(format: "mobileAvailableBalance".localized(), "$", "452.14", "USD")) // Transfer max funds XCTAssertTrue(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should exist") // NOTE XCTAssertTrue(transferFunds.notesSectionLabel.exists) transferFunds.verifyNotes() // Continue Button XCTAssertTrue(transferFunds.nextLabel.exists) } /* Given that user selects a Secondary Prepaid Card method for Transfer From When create transfer with a Bank Account Transfer To method Then user can create transfer successfully */ func testTransferFunds_TransferFromSecondaryPPC() { // Get the transfer method list mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) // Get the Available funds mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) // List the available PPC of the user to select from source mockServer.setupStub(url: listppcUrl, filename: "PrepaidCardSecondaryResponse", method: HTTPMethod.get) // Retreive details of PPC by trm-token mockServer.setupStub(url: "/rest/v3/users/usr-token/prepaid-cards/trm-token", filename: "GetPrepaidCardSuccessResponse", method: HTTPMethod.get) XCTAssertTrue(transferFundSourceMenu.exists) transferFundSourceMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFrom(isAvailableFunds: true) transferFunds.verifyTransferFundsTitle() // TRANSFER FROM transferFunds.verifyTransferFrom(isAvailableFunds: true) // Available Funds XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") let balance = String(format: transferFunds.availableBalanceFormat, "$", "452.14", "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, balance) // TRANSFER TO XCTAssertTrue(transferFunds.transferSectionLabel.exists) // Add Destination Section XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertEqual(transferFunds.addSelectDestinationLabel.label, TransferMethods.bankAccount) transferFunds.verifyBankAccountDestination(type: TransferMethods.bankAccount, endingDigit: "1234") // assert NOTE XCTAssertTrue(transferFunds.notesSectionLabel.exists) // assert Continue button app.scroll(to: transferFunds.nextLabel) XCTAssertTrue(transferFunds.nextLabel.exists) transferFunds.transferSourceTitleLabel.tap() // Assert Transfer from list let transferFromTitle = transferFunds.getTransferFromTitle() XCTAssertEqual(transferFromTitle.label, transferFunds.transferFromHeaderLabel) XCTAssertEqual(transferFunds.getSelectSourceRowTitle(index: 0), transferFunds.availableFunds) XCTAssertEqual(transferFunds.getSelectSourceRowTitle(index: 1), transferFunds.prepaidCard) XCTAssertEqual(transferFunds.getSelectSourceRowTitle(index: 2), transferFunds.prepaidCard) let ppcCell = app.tables.element.children(matching: .cell).element(boundBy: 1) ppcCell.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFrom(isAvailableFunds: false) transferFunds.verifyPPCInfo(brandType: transferFunds.prepaidCardVisa, endingDigit: "8884", currency: "USD") } // MARK: Select PPC as the Transfer Destination /* Given that Transfer methods exist that contains prepaid cards as well AND user selects Prepaid Card as the Transfer To When Payee enters the amount and Notes Then Next button is enabled */ func testTransferFunds_createTransfer_transferTosPrepaidCard() { mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) // Get the Available funds mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) // List the available PPC of the user to select from source mockServer.setupStub(url: listppcUrl, filename: "PrepaidCardPrimaryOnlyResponse", method: HTTPMethod.get) // Retreive details of PPC by trm-token mockServer.setupStub(url: "/rest/v3/users/usr-token/prepaid-cards/trm-token", filename: "GetPrepaidCardSuccessResponse", method: HTTPMethod.get) XCTAssertTrue(transferFundMenu.exists) transferFundMenu.tap() waitForNonExistence(spinner) // Select PPC as the transfer method from Destination transferFunds.verifyBankAccountDestination(type: TransferMethods.bankAccount, endingDigit: "1234") transferFunds.addSelectDestinationLabel.tap() let usdBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 0) let cadBankAccount = app.tables.element.children(matching: .cell).element(boundBy: 1) let prepaidCardTransferMethod = app.tables.element.children(matching: .cell).element(boundBy: 2) XCTAssertTrue(selectDestination.selectDestinationTitle.exists) XCTAssertTrue(selectDestination.addTransferMethodButton.exists) waitForNonExistence(spinner) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 0), TransferMethods.bankAccount) XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 0), transferFunds.getDestinationLabel(country: "United States", type: TransferMethods.bankAccount, endingDigit: "1234")) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 1), TransferMethods.bankAccount) XCTAssertEqual(selectDestination.getSelectDestinationRowTitle(index: 2), TransferMethods.prepaidCard) let ppcInfo = "USD\n\(transferFunds.prepaidCardVisa)\(transferFunds.numberMask)4281" XCTAssertEqual(selectDestination.getSelectDestinationRowDetail(index: 2), ppcInfo) // Assert first row is checked by default assertButtonTrue(element: usdBankAccount) assertButtonFalse(element: cadBankAccount) assertButtonFalse(element: prepaidCardTransferMethod) // Select Prepaid card as the destination selectDestination.tapSelectDestinationRow(index: 2) // Assert can go back to previous page waitForNonExistence(spinner) XCTAssertTrue(app.navigationBars[transferFunds.title].exists) // Assert Prepaid Card is set as the Destination transferFunds.verifyPrepaidCardDestination(brandType: transferFunds.prepaidCardVisa, endingDigit: "4281") } // swiftlint:disable function_body_length func testTransferFunds_switchTransferMethodWithTransactionLimitErrorForPPC() { // Get the transfer method list mockServer.setupStub(url: "/rest/v3/users/usr-token/transfer-methods", filename: "ListMoreThanOneTransferMethod", method: HTTPMethod.get) // Get the Available funds mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) // List the available PPC of the user to select from source mockServer.setupStub(url: listppcUrl, filename: "PrepaidCardPrimaryOnlyResponse", method: HTTPMethod.get) XCTAssertTrue(transferFundSourceMenu.exists) transferFundSourceMenu.tap() waitForNonExistence(spinner) transferFunds.verifyTransferFrom(isAvailableFunds: true) transferFunds.transferSourceTitleLabel.tap() mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferBelowTransactionLimitError", method: HTTPMethod.post) var ppcCell = app.tables.element.children(matching: .cell).element(boundBy: 1) ppcCell.tap() waitForNonExistence(spinner) // Transfer From by PPC Section transferFunds.verifyTransferFrom(isAvailableFunds: false) transferFunds.verifyPPCInfo(brandType: transferFunds.prepaidCardVisa, endingDigit: "9285", currency: "USD") // Transfer Destination Section - Bank Account transferFunds.verifyTransferFundsTitle() // Assert Available available: N/A XCTAssertEqual(transferFunds.transferAmountLabel.label, transferFunds.notAvailableFunds) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertFalse(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should not exist") transferFunds.transferSourceTitleLabel.tap() mockServer.setupStub(url: "/rest/v3/transfers", filename: "AvailableFundUSD", method: HTTPMethod.post) ppcCell = app.tables.element.children(matching: .cell).element(boundBy: 0) ppcCell.tap() waitForNonExistence(spinner) XCTAssertEqual(transferFunds.transferAmount.value as? String, "0.00") XCTAssertEqual(transferFunds.transferCurrency.value as? String, "USD") let balance = String(format: transferFunds.availableBalanceFormat, "$", "452.14", "USD") XCTAssertEqual(transferFunds.transferAmountLabel.label, balance) transferFunds.transferSourceTitleLabel.tap() mockServer.setupStubError(url: "/rest/v3/transfers", filename: "TransferBelowTransactionLimitError", method: HTTPMethod.post) ppcCell = app.tables.element.children(matching: .cell).element(boundBy: 1) ppcCell.tap() waitForNonExistence(spinner) // Transfer From by PPC Section transferFunds.verifyTransferFrom(isAvailableFunds: false) transferFunds.verifyPPCInfo(brandType: transferFunds.prepaidCardVisa, endingDigit: "9285", currency: "USD") // Transfer Destination Section - Bank Account transferFunds.verifyTransferFundsTitle() // Assert Available available: N/A XCTAssertEqual(transferFunds.transferAmountLabel.label, transferFunds.notAvailableFunds) XCTAssertTrue(transferFunds.addSelectDestinationSectionLabel.exists) XCTAssertFalse(transferFunds.transferMaxAllFunds.exists, "Transfer all funds switch should not exist") } }
0
// // Scene9Controller.swift // Blocky // // Created by Lodewijck Vogelzang on 17-08-14. // Copyright (c) 2014 Lodewijck Vogelzang. All rights reserved. // import UIKit final class Level9: Level { let levelNumber = 9 var tiles = [[1,1,1,1,1,1,1], [0,0,0,1,0,0,0]] let cameraFollowsBlock = false let blocky: Blocky let enemies: [Enemy] let foods: [Food] init() { let pattern0 = [("W", 0.5), ("W", 0.5), ("W", 0.5), ("W", 0.5), ("E", 0.5), ("E", 0.5), ("E", 0.5), ("E", 0.5)] let enemy0 = Enemy(enemyNumber: 0, startLocation: (5,0), animationPattern: pattern0) blocky = Blocky(startLocation: (6,0), endLocation: (0,0)) enemies = [enemy0] foods = [] } }
0
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length // swiftlint:disable line_length import UIKit import MaterialComponents.MaterialButtons extension TabBarIconSwiftExample { func setupAlignmentButton() -> MDCRaisedButton { let alignmentButton = MDCRaisedButton() alignmentButton.setTitle("Change Alignment", for: .normal) alignmentButton.setTitleColor(.white, for: .normal) self.view.addSubview(alignmentButton) alignmentButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: alignmentButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: alignmentButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -40).isActive = true return alignmentButton } func setupAppBar() -> MDCAppBar { let appBar = MDCAppBar() self.addChildViewController(appBar.headerViewController) appBar.headerViewController.headerView.backgroundColor = UIColor.white appBar.headerViewController.headerView.minimumHeight = 76 + 72 appBar.headerViewController.headerView.tintColor = MDCPalette.blue.tint500 appBar.headerStackView.bottomBar = self.tabBar appBar.headerStackView.setNeedsLayout() return appBar } func setupExampleViews() { view.backgroundColor = UIColor.white appBar.addSubviewsToParent() let badgeIncrementItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:#selector(incrementDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = badgeIncrementItem self.title = "Tabs With Icons" setupScrollingContent() } func setupScrollView() -> UIScrollView { let scrollView = UIScrollView(frame: CGRect()) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isPagingEnabled = false scrollView.isScrollEnabled = false self.view.addSubview(scrollView) scrollView.backgroundColor = UIColor.red let views = ["scrollView": scrollView, "header": self.appBar.headerStackView] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[header][scrollView]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)) return scrollView } func setupScrollingContent() { // The scrollView will have two UIViews (pages.) One has a label with text (infoLabel); we call // this infoPage. Another has 1+ star images; we call this self.starPage. Tapping on the 'INFO' // tab will show the infoPage and tapping on the 'STARS' tab will show the self.starPage. // Create the first view and its content. Then add to scrollView. let infoPage = UIView(frame: CGRect()) infoPage.translatesAutoresizingMaskIntoConstraints = false infoPage.backgroundColor = MDCPalette.lightBlue.tint300 scrollView.addSubview(infoPage) let infoLabel = UILabel(frame: CGRect()) infoLabel.translatesAutoresizingMaskIntoConstraints = false infoLabel.textColor = UIColor.white infoLabel.numberOfLines = 0 infoLabel.text = "Tabs enable content organization at a high level," + " such as switching between views" infoPage.addSubview(infoLabel) // Layout the views to be equal height and width to each other and self.view, // hug the edges of the scrollView and meet in the middle. NSLayoutConstraint(item: infoLabel, attribute: .centerX, relatedBy: .equal, toItem: infoPage, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoLabel, attribute: .centerY, relatedBy: .equal, toItem: infoPage, attribute: .centerY, multiplier: 1, constant: -50).isActive = true NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[infoLabel]-50-|", options: [], metrics: nil, views: ["infoLabel": infoLabel])) NSLayoutConstraint(item: infoPage, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoPage, attribute: .height, relatedBy: .equal, toItem: self.scrollView, attribute: .height, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: self.starPage, attribute: .width, relatedBy: .equal, toItem: infoPage, attribute: .width, multiplier: 1, constant: 0).isActive = true let views = ["infoPage": infoPage, "starPage": self.starPage] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[infoPage][starPage]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[infoPage]|", options: [], metrics: nil, views: views)) addStar(centered: true) } func setupStarPage() -> UIView { let starPage = UIView(frame: CGRect()) starPage.translatesAutoresizingMaskIntoConstraints = false starPage.backgroundColor = MDCPalette.lightBlue.tint200 self.scrollView.addSubview(starPage) return starPage } func addStar(centered: Bool) { let starImage = UIImage(named:"TabBarDemo_ic_star", in:Bundle(for: type(of: self)), compatibleWith:nil) let starView = UIImageView(image: starImage) starView.translatesAutoresizingMaskIntoConstraints = false starPage.addSubview(starView) starView.sizeToFit() let x = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < x <=2 let y = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < y <=2 NSLayoutConstraint(item: starView, attribute: .centerX, relatedBy: .equal, toItem: starPage, attribute: .centerX, multiplier: x, constant: 0).isActive = true NSLayoutConstraint(item: starView, attribute: .centerY, relatedBy: .equal, toItem: self.starPage, attribute: .centerY, multiplier: y, constant: 0).isActive = true } } extension TabBarIconSwiftExample { override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { (_) in if let selectedItem = self.tabBar.selectedItem { self.tabBar(self.tabBar, didSelect: selectedItem) } }, completion: nil) super.viewWillTransition(to: size, with: coordinator) } } // MARK: - Catalog by convention extension TabBarIconSwiftExample { class func catalogBreadcrumbs() -> [String] { return ["Tab Bar", "Icons and Text (Swift)"] } class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } }
0
// // HitObjectEnums.swift // iosu // // Created by xieyi on 2017/5/16. // Copyright © 2017年 xieyi. All rights reserved. // import Foundation enum HitSound { case normal //0 case whistle //2 case finish //4 case clap //8 } enum HitObjectType{ case circle case slider case spinner case none //Unknown hitobject type } enum CircleType{ case plain case sliderHead case sliderEnd case sliderArrow } enum SliderType{ case linear //L case passThrough //P case bezier //B case catmull //C case none //Invalid slider type }
0
// // Copyright © 2020 Essential Developer Ltd. All rights reserved. // import XCTest import RxSwift import MVVMWithRxSwift class PaymentFormViewControllerIntegrationTests: XCTestCase { func test_initialState_showsFieldCells() { let (sut, vm) = makeSUT() let state = ViewModelStateSpy(vm.state) assert(sut, isShowingAllFieldsFor: state.current) } func test_focusOnField_showsOnlyFocusedFieldCell() { let (sut, vm) = makeSUT() let state = ViewModelStateSpy(vm.state) sut.focusOnFieldCell(inSection: 0, atIndex: 0) assert(sut, isShowingSingleFieldWithSuggestions: [], for: state.current) } func test_enterTextOnFocusedField_showsFocusedFieldWithSuggestionCells() { let service = SuggestionsServiceStub() let (sut, vm) = makeSUT(service: service) let state = ViewModelStateSpy(vm.state) sut.focusOnFieldCell(inSection: 0, atIndex: 0) sut.enterTextOnFieldCell(service.stub.query, inSection: 0, atIndex: 0) assert(sut, isShowingSingleFieldWithSuggestions: service.stub.suggestions, for: state.current) } func test_selectSuggestionCell_showsAllFields() { let service = SuggestionsServiceStub() let (sut, vm) = makeSUT(service: service) let state = ViewModelStateSpy(vm.state) sut.focusOnFieldCell(inSection: 0, atIndex: 0) sut.enterTextOnFieldCell(service.stub.query, inSection: 0, atIndex: 0) sut.selectSuggestion(inSection: 1, atIndex: 0) assert(sut, isShowingAllFieldsFor: state.current) } // MARK: - Helpers private func makeSUT(service: SuggestionsServiceStub = .init()) -> (PaymentFormViewController, PaymentFormViewModel) { let vm = PaymentFormViewModel(service: service) let sut = PaymentFormViewController(viewModel: vm) sut.view.frame = iPhone12Frame return (sut, vm) } private var iPhone12Frame: CGRect { CGRect(x: 0, y: 0, width: 585, height: 1266) } private class ViewModelStateSpy { private(set) var current: PaymentFormViewModel.State? private let disposeBag = DisposeBag() init(_ observable: Observable<PaymentFormViewModel.State>) { observable.subscribe(onNext: { [weak self] state in self?.current = state }).disposed(by: disposeBag) } } private func assert(_ sut: PaymentFormViewController, isShowingAllFieldsFor state: PaymentFormViewModel.State?, file: StaticString = #file, line: UInt = #line) { guard case let .fields(fields) = state else { return XCTFail("Expected .fields state", file: file, line: line) } XCTAssertEqual(sut.numberOfSections(), 1, "Expected one section", file: file, line: line) XCTAssertEqual(sut.numberOfCells(inSection: 0), fields.count, "Expected cells for every field in the first section", file: file, line: line) fields.enumerated().forEach { (index, field) in let cell = sut.cell(inSection: 0, atIndex: index) as? FieldCell XCTAssertEqual(cell?.cellTitleLabel.text, field.title, "Wrong cell title for field at index \(index)", file: file, line: line) XCTAssertEqual(cell?.inputTextField.text, field.text.value, "Wrong cell text for field at index \(index)", file: file, line: line) } } private func assert(_ sut: PaymentFormViewController, isShowingSingleFieldWithSuggestions expectedSuggestions: [Suggestion], for state: PaymentFormViewModel.State?, file: StaticString = #file, line: UInt = #line) { guard case let .focus(field, suggestions) = state else { return XCTFail("Expected .focus state") } XCTAssertEqual(sut.numberOfSections(), 2, "Expected two sections", file: file, line: line) XCTAssertEqual(sut.numberOfCells(inSection: 0), 1, "Expected one field cell in the first section", file: file, line: line) XCTAssertEqual(sut.numberOfCells(inSection: 1), expectedSuggestions.count, "Expected cells for every suggestion in the second session", file: file, line: line) let fieldCell = sut.cell(inSection: 0, atIndex: 0) as? FieldCell XCTAssertEqual(fieldCell?.cellTitleLabel.text, field.title, "Wrong cell title for focused field") XCTAssertEqual(fieldCell?.inputTextField.text, field.text.value, "Wrong cell text for focused field") suggestions.enumerated().forEach { (index, suggestion) in let suggestionCell = sut.cell(inSection: 1, atIndex: index) XCTAssertEqual(suggestionCell?.textLabel?.text, suggestion.text, "Wrong cell text for suggestion at index \(index)", file: file, line: line) } } } private extension PaymentFormViewController { func numberOfSections() -> Int { tableView.numberOfSections } func numberOfCells(inSection section: Int) -> Int { tableView.numberOfRows(inSection: section) } func cell(inSection section: Int, atIndex index: Int) -> UITableViewCell? { tableView.cellForRow(at: IndexPath(row: index, section: section)) } func focusOnFieldCell(inSection section: Int, atIndex index: Int) { let firstFieldCell = cell(inSection: section, atIndex: index) as? FieldCell firstFieldCell?.focusButton.sendActions(for: .touchUpInside) } func enterTextOnFieldCell(_ text: String, inSection section: Int, atIndex index: Int) { let firstFieldCell = cell(inSection: section, atIndex: index) as? FieldCell firstFieldCell?.inputTextField.text = text firstFieldCell?.inputTextField.sendActions(for: .editingChanged) } func selectSuggestion(inSection section: Int, atIndex index: Int) { tableView.delegate?.tableView?(tableView, didSelectRowAt: IndexPath(row: index, section: section)) } }
0
// // UITextField+Binding.swift // RxSwiftForms // // Created by Michael Long on 2/20/18. // Copyright © 2018 Hoy Long. All rights reserved. // import UIKit import RxSwift import RxCocoa /// Implements the FxBindableValue protocol for UITextFields, allowing them to be bound to FxFields. extension UITextField: FxBindableValue { /// Binds the field value to the view using Rx. public func bindFieldToView<E>(_ field: FxField<E>) -> Disposable? { return field.rx.text .asDriver(onErrorJustReturn: "") .drive(self.rx.text) } // Binds updates to the textfield's value back to the FxField. public func bindViewToField<E>(_ field: FxField<E>) -> Disposable? { return rx.text .orEmpty .distinctUntilChanged() .bind(to: field.rx.text) } } //extension UITextField: FxBindableKeyboard {} //extension UITextField: FxBindablePlaceholder {}
0
// // RUCUserInfoController.swift // RandomUserClient // // Created by Dmitry Petukhov on 01/07/2019. // Copyright © 2019 Dmitry Petukhov. All rights reserved. // import NeedleFoundation import UIKit protocol RUCUserInfoDependency: Dependency { var realmServiceMethods: RealmServiceMethods { get } } class RUCUserInfoComponent: Component<RUCUserInfoDependency>, RUCUserInfoBuilder { var rucUserInfoViewController: UIViewController { return RUCUserInfoViewController(realmServiceMethods: dependency.realmServiceMethods) } } protocol RUCUserInfoBuilder { var rucUserInfoViewController: UIViewController { get } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { case c, { deinit { { struct A { class case c,
0
// // GenreView.swift // App // // Created by Kotaro Suto on 2021/08/14. // import SwiftUI struct GenreFilterView: View { @Binding var selectedGenres: [String: Bool] var body: some View { ScrollView(.horizontal) { HStack { ForEach(Array(selectedGenres.keys), id: \.self) { genre in GenreView(genreName: genre, selectedGenres: $selectedGenres) } } } .padding() } } struct GenreView_Previews: PreviewProvider { static var previews: some View { GenreFilterView(selectedGenres: .constant(["Test": false, "Test2": false, "TEST3": false])) .frame(height: 80) .previewLayout(.sizeThatFits) } } struct GenreView: View { var genreName: String @State var isSelected: Bool = false @Binding var selectedGenres: [String: Bool] var body: some View { Button(action: { isSelected.toggle() selectedGenres[genreName] = isSelected }, label: { Text(genreName) .foregroundColor(.white) .padding() .background(isSelected ? Color.red : Color.gray) .cornerRadius(15) }) } }
0
import Foundation import XCTest import SIL public final class ModuleTests: XCTestCase { public func testAvgPool1D() { testRoundtrip("Tests/SILTests/Resources/AvgPool1D.sil") } private func testRoundtrip(_ silPath: String) { do { guard let expectedData = FileManager.default.contents(atPath: silPath) else { return XCTFail("\(silPath) not found") } guard let expected = String(data: expectedData, encoding: .utf8) else { return XCTFail("\(silPath) not in UTF-8") } let module = try Module.parse(fromSILPath: silPath) let actual = module.description + "\n" if (expected != actual) { if let actualFile = FileManager.default.makeTemporaryFile() { let actualPath = actualFile.path FileManager.default.createFile(atPath: actualPath, contents: Data(actual.utf8)) if shelloutOrFail("colordiff", "-u", silPath, actualPath) { XCTFail("Roundtrip failed: expected \(silPath), actual: \(actualPath)") } else { XCTFail("Roundtrip failed: expected \(silPath), actual: \n\(actual)") } } else { XCTFail("Roundtrip failed") } } } catch { XCTFail(String(describing: error)) } } } extension ModuleTests { public static let allTests = [ ("testAvgPool1D", testAvgPool1D), ] }
0
// // YouTubeCommentFlowWindowDataSource.swift // MeetupTweet // // Created by Yoshinori Imajo on 2018/04/07. // Copyright © 2018年 Yoshinori Imajo. All rights reserved. // import AppKit import RxSwift import TwitterAPI class YouTubeCommentFlowWindowDataSource: FlowWindowDataSource { var subscription: Disposable? private let tweetSearchUseCase: TwitterStraemAPIUseCase private var window: NSWindow? private var stackView: NSStackView! private var disposeBag: DisposeBag! private var comments: [String: (comment: CommentType, view: MultiCommentView)] = [:] private var waitingCommentsQueue: [CommentType] = [] init(oauthClient: OAuthClient) { self.tweetSearchUseCase = TwitterStraemAPIUseCase(oauthClient: oauthClient) } func search(_ search: String, screen: NSScreen) { disposeBag = DisposeBag() refreshComments() window = makeTweetWindow(screen) stackView = makeStackView(from: window!) window!.contentView!.addSubview(stackView) let tweetStream = tweetSearchUseCase.startStream(search) .observeOn(MainScheduler.instance) .startWith(Announce(search: search)) .filter { !$0.message.hasPrefix("RT") } subscription = Observable.of(tweetStream, AnnounceUseCase.intervalTextStream(search)) .merge() .subscribe(onNext: { [unowned self] comment in self.addComment(comment) }) subscription?.disposed(by: disposeBag) } func stop() { window?.orderOut(nil) refreshComments() disposeBag = nil } } private extension YouTubeCommentFlowWindowDataSource { func refreshComments() { tweetSearchUseCase.stopStream() subscription?.dispose() comments = [:] } func addComment(_ comment: CommentType) { let view = makeMultiCommentView(comment) stackView.addView(view, in: .bottom) removeCommentIfOverHeight() } func removeCommentIfOverHeight() { if stackView.frame.size.height < stackViewSubviewsHeight { for view in stackView.arrangedSubviews { if stackView.frame.size.height < stackViewSubviewsHeight { stackView.removeView(view) } } } } func makeMultiCommentView(_ comment: CommentType) -> MultiCommentView { let commentView: MultiCommentView switch comment.type { case .tweet: commentView = MultiCommentView.makeView(comment.message, name: comment.name) if let url = comment.imageURL { URLSession.shared.rx.data(request: URLRequest(url: url)) .subscribe(onNext: { data in DispatchQueue.main.async { commentView.imageView.image = NSImage(data: data) } }) .disposed(by: disposeBag) } case .announce: commentView = MultiCommentView.makeView(comment.message, name: comment.name, fontColor: NSColor.red) commentView.imageView.image = NSApp.applicationIconImage } commentView.layoutSubtreeIfNeeded() commentView.frame.origin = CGPoint(x: 0, y: 0) return commentView } func makeTweetWindow(_ screen: NSScreen) -> NSWindow { let menuHeight: CGFloat = 23.0 let size = CGSize(width: windowWidth, height: screen.frame.size.height - menuHeight) let origin = CGPoint(x: calculateOriginX(screenWidth: screen.frame.size.width), y: 0) let frame = NSRect(origin: origin, size: size) let window = NSWindow(contentRect: frame, styleMask: .fullSizeContentView, backing: .buffered, defer: false, screen: screen) window.contentView!.wantsLayer = true window.isOpaque = false window.hasShadow = false window.isMovable = true window.isMovableByWindowBackground = true window.isReleasedWhenClosed = false window.backgroundColor = NSColor.green.withAlphaComponent(0.2) window.level = NSWindow.Level(Int(CGWindowLevelForKey(.maximumWindow))) window.makeKeyAndOrderFront(nil) return window } func makeStackView(from window: NSWindow) -> NSStackView { let view = NSStackView(frame: NSRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height)) view.orientation = .vertical view.alignment = .left view.spacing = spacing return view } var stackViewSubviewsHeight: CGFloat { return stackView.arrangedSubviews.reduce(0) { (total, view) -> CGFloat in total + view.frame.size.height + self.spacing } } var spacing: CGFloat { return 30 } var velocity: CGFloat { return 5.0 } var windowWidth: CGFloat { return 400 } func calculateOriginX(screenWidth: CGFloat) -> CGFloat { return screenWidth - windowWidth } }
0
// // SubSettingTimeTable.swift // unitool // // Created by そうへい on 2018/12/13. // Copyright © 2018 そうへい. All rights reserved. // import UIKit @available(iOS 10.0, *) class SubSettingTimeTable: UIViewController, UIWebViewDelegate{ let mainView = UIScrollView() let periodTotal = InputView() let weekdayView = InputView() let weekdaySelect = UISegmentedControl() let nofityView = InputView() let nofitySelector = UISwitch() let SaveSetting = InputButton() let SyncTimeTable = InputButton() let DelectTimeTable = InputButton() @objc func saveSettingEvent() { let periodInt = Int(periodTotal.Input.text ?? "-1")! let weekdayInt = weekdaySelect.selectedSegmentIndex if periodInt >= 1, periodInt <= 8{ UserSetting["timetable"]["period"].int = periodInt UserSetting["timetable"]["weekday"].int = weekdayInt UserSetting["timetable"]["nofity"].bool = nofitySelector.isOn updateTimeTable() UserDefaults.standard.set(UserSetting.rawString(),forKey: "UserSetting") self.navigationController?.popToRootViewController(animated: true) }else{ showAlert(type: 2, msg: "時限数は1~8の数字を設置してください") } } @objc func SyncTimeTableEvent() { let alert: UIAlertController = UIAlertController(title: "時間割同期", message: "学内情報から今の時間割を自動同期します\n同期が完了すると現在の時間割は削除されます", preferredStyle: UIAlertController.Style.alert) let defaultAction: UIAlertAction = UIAlertAction(title: "同期", style: UIAlertAction.Style.default, handler:{ (action: UIAlertAction!) -> Void in SchoolAPI.syncTimetable(completion: { (success, msg, data) in switch success{ case true: updateSubject(data: data) updateTimeTable() self.navigationController?.popToRootViewController(animated: true) showAlert(type: 1, msg: msg ?? "完成") case false: showAlert(type: 2, msg: msg ?? "エラー") } }, team: 1) }) let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{ (action: UIAlertAction!) -> Void in print("キャンセル") }) alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } @objc func DelectTimeTableEvent() { let alert: UIAlertController = UIAlertController(title: "時間割削除", message: "現在の時間割は削除されます\n宜しいでしょうか?", preferredStyle: UIAlertController.Style.alert) let defaultAction: UIAlertAction = UIAlertAction(title: "削除", style: UIAlertAction.Style.default, handler:{ (action: UIAlertAction!) -> Void in delAllSubject() updateTimeTable() self.navigationController?.popToRootViewController(animated: true) showAlert(type: 1, msg: "時間割初期化完了") }) let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{ (action: UIAlertAction!) -> Void in print("キャンセル") }) alert.addAction(cancelAction) alert.addAction(defaultAction) present(alert, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() setupVC() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { mainView.endEditing(true) } func setupVC(){ self.title = "時間割設定" self.view.backgroundColor = Color_White periodTotal.Lable.text = "時限数" periodTotal.Input.keyboardType = .numberPad periodTotal.Input.textAlignment = .center periodTotal.Input.text = "\(UserSetting["timetable"]["period"].intValue)" weekdayView.Lable.text = "土日表示" weekdayView.Input.isUserInteractionEnabled = false weekdayView.Line.isHidden = true nofityView.Lable.text = nil nofityView.Input.isUserInteractionEnabled = false nofityView.Line.isHidden = true let nofityText = UILabel() nofityText.text = "授業開始前通知(10分前)" nofityText.textColor = Color_GreyFont nofityText.font = UIFont.systemFont(ofSize: 15) nofitySelector.isOn = UserSetting["timetable"]["nofity"].boolValue nofitySelector.onTintColor = Color_GreyFont weekdaySelect.insertSegment(withTitle: "しない", at: 0, animated: false) weekdaySelect.insertSegment(withTitle: "土", at: 1, animated: false) weekdaySelect.insertSegment(withTitle: "土日", at: 2, animated: false) weekdaySelect.tintColor = Color_GreyFont weekdaySelect.selectedSegmentIndex = UserSetting["timetable"]["weekday"].intValue SaveSetting.setTitle("保存", for: .normal) SaveSetting.addTarget(self, action: #selector(saveSettingEvent), for: .touchUpInside) SyncTimeTable.setTitle("時間割同期", for: .normal) SyncTimeTable.addTarget(self, action: #selector(SyncTimeTableEvent), for: .touchUpInside) DelectTimeTable.setTitle("時間割初期化", for: .normal) DelectTimeTable.addTarget(self, action: #selector(DelectTimeTableEvent), for: .touchUpInside) DelectTimeTable.setBackgroundImage(UIImage(color: UIColor.red.lighter()), for: .normal) DelectTimeTable.setBackgroundImage(UIImage(color: UIColor.red.lighter().darkened()), for: .highlighted) self.view.addSubview(mainView) let singleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapRecognized)) singleTapGestureRecognizer.numberOfTapsRequired = 1 singleTapGestureRecognizer.isEnabled = true singleTapGestureRecognizer.cancelsTouchesInView = false mainView.addGestureRecognizer(singleTapGestureRecognizer) mainView.addSubview(periodTotal) mainView.addSubview(weekdayView) mainView.addSubview(nofityView) mainView.addSubview(SaveSetting) mainView.addSubview(SyncTimeTable) mainView.addSubview(DelectTimeTable) weekdayView.addSubview(weekdaySelect) nofityView.addSubview(nofitySelector) nofityView.addSubview(nofityText) mainView.isScrollEnabled = true mainView.snp.makeConstraints { (make) in make.edges.equalTo(view) } periodTotal.snp.makeConstraints { (make) in make.width.equalToSuperview().offset(-50) make.height.equalTo(70) make.top.equalToSuperview().offset(25) make.centerX.equalToSuperview() } weekdayView.snp.makeConstraints { (make) in make.width.equalToSuperview().offset(-50) make.height.equalTo(70) make.top.equalTo(periodTotal.snp.bottom).offset(10) make.centerX.equalToSuperview() } weekdaySelect.snp.makeConstraints { (make) in make.width.equalTo(weekdayView) make.height.equalTo(30) make.center.equalToSuperview() } nofityView.snp.makeConstraints { (make) in make.width.equalToSuperview().offset(-50) make.height.equalTo(70) make.top.equalTo(weekdaySelect.snp.bottom).offset(10) make.centerX.equalToSuperview() } nofityText.snp.makeConstraints { (make) in make.left.equalToSuperview() make.height.equalTo(30) make.centerY.equalToSuperview() } nofitySelector.snp.makeConstraints { (make) in make.right.equalToSuperview() make.height.equalTo(30) make.centerY.equalToSuperview() } SaveSetting.snp.makeConstraints { (make) in make.width.equalTo(250) make.height.equalTo(50) make.top.equalTo(nofityView.snp.bottom).offset(10) make.centerX.equalToSuperview() } SyncTimeTable.snp.makeConstraints { (make) in make.width.equalTo(250) make.height.equalTo(50) make.centerX.equalToSuperview() make.top.equalTo(SaveSetting.snp.bottom).offset(15) } DelectTimeTable.snp.makeConstraints { (make) in make.width.equalTo(250) make.height.equalTo(50) make.centerX.equalToSuperview() make.top.equalTo(SyncTimeTable.snp.bottom).offset(15) make.bottom.equalToSuperview() } } @objc func tapRecognized() { self.view.endEditing(true) } }
0
// // Timer+CYBlock.swift // SDClientsPlatformSwift // // Created by Peter Lee on 2016/12/23. // Copyright © 2016年 ZTESoft. All rights reserved. // import Foundation extension Timer { static func cy_scheduledTimer(withTimeInterval interval: TimeInterval, repeats:Bool, block:(Timer)->()) -> Timer { return self.scheduledTimer(timeInterval: interval, target: self, selector: #selector(Timer.cy_timerBlock(_:)), userInfo: block, repeats: repeats) } @objc static func cy_timerBlock(_ timer:Timer) { let block:((Timer)->())? = timer.userInfo as? (Timer)->() if block != nil { block!(timer) } } }
0
import Foundation protocol TargetRule { var target: Target { get } var action: Action { get } } class TargetRuleEntity: TargetRule { let target: Target let action: Action init(target: Target, action: Action) { self.target = target self.action = action } }
0
// // InfoModel.swift // YZTableViewAdapter_Example // // Created by 戚译中 on 2019/4/11. // Copyright © 2019 CocoaPods. All rights reserved. // import UIKit class InfoModel { let image: UIImage? = nil let title = "我是标题" let content = "我是长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长长的文案" }
0
/* * VariableSetStmt.swift * Swiftgres * * Copyright (c) 2018 David Piper, @_davidpiper * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ public extension PostgresStatement { public struct VariableSetStatement { } }
0
// // AppDelegate.swift // DanTang // // Created by KeenTeam on 2017/3/24. // Copyright © 2017年 KT. 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. // 创建 window window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() // 检测用户是不是第一次启动 if !UserDefaults.standard.bool(forKey: YMFirstLaunch) { window?.rootViewController = YMTabBarController() //window?.rootViewController = YMNewfeatureViewController() //UserDefaults.standard.set(true, forKey: YMFirstLaunch) } else { window?.rootViewController = YMTabBarController() } 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:. } }
0
import XCTest @testable import GraphQL class VisitorTests : XCTestCase { func test() throws { } } extension VisitorTests { static var allTests: [(String, (VisitorTests) -> () throws -> Void)] { return [ ("test", test), ] } }
0
// // ProfileCreateRequest.swift // AppStoreConnect-Swift-SDK // // Created by Patrick Balestra on 12/24/19. // import Foundation #if os(Linux) import FoundationNetworking #endif /// A request containing a single resource. public struct ProfileCreateRequest: Codable { public struct Data: Codable { /// The resource's attributes. public var attributes: ProfileCreateRequest.Data.Attributes /// The types and IDs of the related data to update. public var relationships: ProfileCreateRequest.Data.Relationships /// The resource type.Value: profiles public private(set) var type: String = "profiles" } /// The resource data. public var data: ProfileCreateRequest.Data /// - Parameters: /// - id: The opaque resource ID that uniquely identifies the resource. /// - name: /// - profileType: init(id: String, name: String, profileType: ProfileType, certificateIds: [String] = [], deviceIds: [String] = []) { data = .init( attributes: .init( name: name, profileType: profileType ), relationships: .init( bundleId: .init(data: .init(id: id)), certificates: .init(data: certificateIds.map { .init(id: $0) }), devices: .init(data: deviceIds.map { .init(id: $0) }) ) ) } } // MARK: ProfileCreateRequest.Data extension ProfileCreateRequest.Data { /// Attributes that describe a resource. public struct Attributes: Codable { /// The name of the profile. public var name: String? /// The type of the profile. public var profileType: ProfileType? } public struct Relationships: Codable { /// ProfileCreateRequest.Data.Relationships.BundleId (Required) public var bundleId: ProfileCreateRequest.Data.Relationships.BundleId /// ProfileCreateRequest.Data.Relationships.Certificates (Required) public var certificates: ProfileCreateRequest.Data.Relationships.Certificates /// ProfileCreateRequest.Data.Relationships.Devices public var devices: ProfileCreateRequest.Data.Relationships.Devices } } // MARK: ProfileCreateRequest.Data.Relationships extension ProfileCreateRequest.Data.Relationships { public struct BundleId: Codable { /// ProfileCreateRequest.Data.Relationships.BundleId.Data (Required) public var data: ProfileCreateRequest.Data.Relationships.BundleId.Data } public struct Certificates: Codable { /// ProfileCreateRequest.Data.Relationships.Certificates.Data (Required) public var data: [ProfileCreateRequest.Data.Relationships.Certificates.Data] } public struct Devices: Codable { /// ProfileCreateRequest.Data.Relationships.Devices.Data (Required) public var data: [ProfileCreateRequest.Data.Relationships.Devices.Data] } } // MARK: ProfileCreateRequest.Data.Relationships.BundleId extension ProfileCreateRequest.Data.Relationships.BundleId { public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public var `id`: String /// The resource type.Value: apps public private(set) var type: String = "bundleIds" } } // MARK: ProfileCreateRequest.Data.Relationships.Certificates extension ProfileCreateRequest.Data.Relationships.Certificates { public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public var `id`: String /// The resource type.Value: apps public private(set) var type: String = "certificates" } } // MARK: ProfileCreateRequest.Data.Relationships.Devices extension ProfileCreateRequest.Data.Relationships.Devices { public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public var `id`: String /// The resource type.Value: apps public private(set) var type: String = "devices" } }
0
// // SKConversion.swift // StringKit 0.9.0 // // Legend: // if applicable: Nil values are possible. // safe: Errors can't happen. // discardable: Discardable result. // optional: Parameter not required. // default: Explains the standard value. // like: Shows a possible example. // independet: The property or method can be used independently from the framework. // // Created by: // - Rainer Niemann, [email protected] // - Andreas Niemann, [email protected] // // This project is licensed under the MIT License. See the LICENSE.md file for details. // // MARK: IMPORTS - TESTED #if os(macOS) import Cocoa #elseif os(Linux) import Foundation #else import UIKit #endif // MARK: STRING CONVERSION EXTENSION - TESTED public extension String { /// StringKit: Returns the Bool value from a string (if applicable). public var boolValue: Bool? { let selfLowerCase: String = self.trimmed.lowercased() if selfLowerCase == "true" || selfLowerCase == "1" || selfLowerCase == "right" { return true } else if selfLowerCase == "false" || selfLowerCase == "0" || selfLowerCase == "wrong" { return false } return nil } /// StringKit: Returns the UInt value from a string (if applicable). public var UIntValue: UInt? { guard let doubleValue: Double = Double(self), doubleValue > 0 else { return UInt(self) } return UInt(doubleValue) } /// StringKit: Returns the UInt8 value from a string (if applicable). public var UInt8Value: UInt8? { guard let doubleValue: Double = Double(self), doubleValue > 0 else { return UInt8(self) } return UInt8(doubleValue) } /// StringKit: Returns the UInt16 value from a string (if applicable). public var UInt16Value: UInt16? { guard let doubleValue: Double = Double(self), doubleValue > 0 else { return UInt16(self) } return UInt16(doubleValue) } /// StringKit: Returns the UInt32 value from a string (if applicable). public var UInt32Value: UInt32? { guard let doubleValue: Double = Double(self), doubleValue > 0 else { return UInt32(self) } return UInt32(doubleValue) } /// StringKit: Returns the UInt64 value from a string (if applicable). public var UInt64Value: UInt64? { guard let doubleValue: Double = Double(self), doubleValue > 0 else { return UInt64(self) } return UInt64(doubleValue) } /// StringKit: Returns the Int value from a string (if applicable). public var intValue: Int? { guard let doubleValue: Double = Double(self) else { return Int(self) } return Int(doubleValue) } /// StringKit: Returns the Int8 value from a string (if applicable). public var int8Value: Int8? { guard let doubleValue: Double = Double(self) else { return Int8(self) } return Int8(doubleValue) } /// StringKit: Returns the Int16 value from a string (if applicable). public var int16Value: Int16? { guard let doubleValue: Double = Double(self) else { return Int16(self) } return Int16(doubleValue) } /// StringKit: Returns the Int32 value from a string (if applicable). public var int32Value: Int32? { guard let doubleValue: Double = Double(self) else { return Int32(self) } return Int32(doubleValue) } /// StringKit: Returns the Int64 value from a string (if applicable). public var int64Value: Int64? { guard let doubleValue: Double = Double(self) else { return Int64(self) } return Int64(doubleValue) } /// StringKit: Returns the Float value from a string (if applicable). /// /// - Parameters /// - locale: The possibility to choose a locale (optional, default: Locale.current). public func floatValue(locale: Locale = Locale.current) -> Float? { let formatter: NumberFormatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Float } /// StringKit: Returns the Float32 value from a string (if applicable). /// /// - Parameters /// - locale: The possibility to choose a locale (optional, default: Locale.current). public func float32Value(locale: Locale = Locale.current) -> Float32? { let formatter: NumberFormatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Float32 } /// StringKit: Returns the Float64 value from a string (if applicable). /// /// - Parameters /// - locale: The possibility to choose a locale (optional, default: Locale.current). public func float64Value(locale: Locale = Locale.current) -> Float64? { let formatter: NumberFormatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Float64 } /// StringKit: Returns the Double value from a string (if applicable). /// /// - Parameters /// - locale: The possibility to choose a locale (optional, default: Locale.current). public func doubleValue(locale: Locale = Locale.current) -> Double? { let formatter: NumberFormatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? Double } /// StringKit: Returns the Decimal value from a string (if applicable). public var decimalValue: Decimal? { return Decimal(string: self) } /// StringKit: Returns the CGFloat value from a string (if applicable). /// /// - Parameters /// - locale: The possibility to choose a locale (optional, default: Locale.current). public func cgFloatValue(locale: Locale = Locale.current) -> CGFloat? { let formatter: NumberFormatter = NumberFormatter() formatter.locale = locale formatter.allowsFloats = true return formatter.number(from: self) as? CGFloat } /// StringKit: Returns a Date object in format of "HH:mm:ss" (if applicable). public var timeValue: Date? { let formatter: DateFormatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "HH:mm:ss" return formatter.date(from: self.trimmed.lowercased()) } /// StringKit: Returns a Date object in format of "yyyy-MM-dd" (if applicable). public var dateValue: Date? { let formatter: DateFormatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd" return formatter.date(from: self.trimmed.lowercased()) } /// StringKit: Returns a Date object in format of "yyyy-MM-dd HH:mm:ss" (if applicable). public var dateTimeValue: Date? { let formatter: DateFormatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.date(from: self.trimmed.lowercased()) } /// StringKit: Returns a date object converted from a string of date format (if applicable). /// /// - Parameters: /// - format: The format of the target date object. public func date(withFormat format: String) -> Date? { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: self) } /// StringKit: Returns an array encoded in ASCII (if applicable). /// /// - Parameters: /// - ignoreNonValidValues: The possibility to ignore and remove non valid values (optional, default: false). public func asciiEncoded(ignoreNonValidValues: Bool = false) -> Array<Int>? { guard !self.isEmpty else { return [0] } var resultArray: Array<Int> = Array<Int>() if ignoreNonValidValues { return self.unicodeScalars.filter({ $0.isASCII }).map({ Int($0.value) }) } for unicodeScalar in self.unicodeScalars { guard unicodeScalar.isASCII else { return nil } resultArray.append(Int(unicodeScalar.value)) } return resultArray } /// StringKit: Returns an array decoded from ASCII (if applicable). /// /// - Parameters: /// - ignoreNonValidValues: The possibility to ignore and remove non valid values (optional, default: false). public func asciiDecoded(ignoreNonValidValues: Bool = false) -> Array<String>? { guard !self.isEmpty else { return Array<String>() } var resultArray: Array<String> = Array<String>() let ascii: Array<Int> = self.components(separatedBy: " ").map({ Int($0) ?? -1 }) if ignoreNonValidValues { return ascii.filter({ UnicodeScalar($0)!.isASCII }).map({ String(describing: UnicodeScalar($0)!) }) } for asciiValue in ascii { guard let unicodeScalar = UnicodeScalar(asciiValue) else { return nil } guard unicodeScalar.isASCII else { return nil } resultArray.append(String(unicodeScalar)) } return resultArray } /// StringKit: Returns an array encoded in Unicode. public func unicodeEncoded() -> Array<Int> { guard !self.isEmpty else { return Array<Int>() } return self.unicodeScalars.map({ $0.hashValue }) } /// StringKit: Returns an array decoded from Unicode. public func unicodeDecoded() -> Array<String> { guard !self.isEmpty else { return Array<String>() } return self.components(separatedBy: " ").map({ String(describing: UnicodeScalar(Int($0)!)!) }) } /// StringKit: Returns a string encoded in base64 (if applicable). public func base64Encoded() -> String? { guard !self.isEmpty else { return nil } return data(using: .utf8)?.base64EncodedString() } /// StringKit: Encodes a string in base64 and returns the result (if applicable; discardable). @discardableResult public mutating func base64Encode() -> String? { guard !self.isEmpty, let base64: String = self.base64Encoded() else { return nil } self = base64 return self } /// StringKit: Returns a string decoded from base64 (if applicable). public func base64Decoded() -> String? { guard !self.isEmpty else { return String() } guard let decodedData: Data = Data(base64Encoded: self) else { return nil } return String(data: decodedData, encoding: .utf8) } /// StringKit: Decodes a string from base64 and returns the result (if applicable; discardable). @discardableResult public mutating func base64Decode() -> String? { guard !self.isEmpty, let decodedData: String = self.base64Decoded() else { return nil } self = decodedData return self } /// StringKit: Returns the URL value from a string (if applicable). public var urlValue: URL? { return URL(string: self) } /// StringKit: Returns a string encoded in URL format (if applicable). public func urlEncoded() -> String? { guard !self.isEmpty else { return nil } return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) } /// StringKit: Encodes a string in URL format and returns the result (if applicable; discardable). @discardableResult public mutating func urlEncode() -> String? { guard !self.isEmpty, let encodedData: String = self.urlEncoded() else { return nil } self = encodedData return self } /// StringKit: Returns a string decoded from URL format (if applicable). public func urlDecoded() -> String? { guard !self.isEmpty else { return nil } return self.removingPercentEncoding } /// StringKit: Decodes a string from URL format and returns the result (if applicable; discardable). @discardableResult public mutating func urlDecode() -> String? { guard !self.isEmpty, let decodedData: String = self.urlDecoded() else { return nil } self = decodedData return self } }
0
// // ElementOfButton.swift // ViewElementsCore // // Created by Wirawit Rueopas on 14/7/18. // Copyright © 2018 Wirawit Rueopas. All rights reserved. // import UIKit public func ElementOfButton(_ props: Button.Props) -> ElementOf<Button> { return ElementOf<Button>(props: props) } open class Button: UIButton, ElementableView { public struct Props: Equatable { public let id: String public let image: UIImage? public let title: String? public let didTap: () -> Void public init(id: String, image: UIImage?, title: String?, didTap: @escaping () -> Void) { self.id = id self.image = image self.title = title self.didTap = didTap } public static func ==(lhs: Props, rhs: Props) -> Bool { return lhs.id == rhs.id } } public typealias PropsType = Props private var currentDidTapBlock: (() -> Void)? open func setup() { addTarget(self, action: #selector(didTap), for: .touchUpInside) } open func render(props: Button.PropsType) { setTitle(props.title, for: .normal) setImage(props.image, for: .normal) currentDidTapBlock = props.didTap } @objc func didTap() { currentDidTapBlock?() } open class func buildMethod() -> ViewBuildMethod { return .frame(.zero) } }
0
import UIKit public extension UITableView { // MARK: - Registration func registerHeaderFooterClass(_ headerFooterClass: UITableViewHeaderFooterView.Type) { let className = classNameWithoutModule(headerFooterClass) self.register(headerFooterClass, forHeaderFooterViewReuseIdentifier: className) } func registerCellClass(_ cellClass: UITableViewCell.Type) { let className = classNameWithoutModule(cellClass) self.register(cellClass, forCellReuseIdentifier: className) } func registerCellNibForClass(_ cellClass: AnyClass) { let className = classNameWithoutModule(cellClass) self.register(UINib(nibName: className, bundle: nil), forCellReuseIdentifier: className) } // MARK: - Reuse func dequeueReusableHeaderFooterView(withClass headerFooterClass: UITableViewHeaderFooterView.Type) -> UITableViewHeaderFooterView? { let className = classNameWithoutModule(headerFooterClass) return self.dequeueReusableHeaderFooterView(withIdentifier: className) } func dequeueReusableCell(withClass cellClass: UITableViewCell.Type, for indexPath: IndexPath) -> UITableViewCell { let className = classNameWithoutModule(cellClass) return self.dequeueReusableCell(withIdentifier: className, for: indexPath) } }
0
// // URLRequest+Extensions.swift // Fondue // // Created by Vikram Kriplaney on 01.12.19. // import Foundation /// URLRequest modifiers public extension URLRequest { enum HttpMethod: String { case get = "GET" case post = "POST" case put = "PUT" case delete = "DELETE" case head = "HEAD" case patch = "PATCH" case connect = "CONNECT" case options = "OPTIONS" case trace = "TRACE" } /// Returns a request with modified URL parameters func adding(parameters: URL.ConvertibleParameters) -> Self { modified(self) { $0.url = $0.url?.with(parameters: parameters) } } /// Returns a new request with modified headers. Any existing headers with the same name are overwritten. func adding(headers: [String: String]) -> Self { modified(self) { $0.allHTTPHeaderFields = ($0.allHTTPHeaderFields ?? [:]).merging(headers) { $1 } } } /// Returns a new request with a modified header. Any existing header with the same name is overwritten. func adding(header: String, value: String) -> Self { adding(headers: [header: value]) } /// Returns a request with a modified HTTP method. func with(method: HttpMethod) -> Self { modified(self) { $0.httpMethod = method.rawValue } } func with(body: Data?, contentType: String? = nil) -> Self { modified(self) { $0.httpBody = body if let contentType = contentType { $0.addValue(contentType, forHTTPHeaderField: "Content-Type") } } } /// Returns a new request with a modified HTTP body. /// - Parameter body: A plain text body func with(body: String) -> Self { with(body: body.data(using: .utf8), contentType: "text/plain; charset=utf-8") } /// Returns a new request with a modified HTTP body and `Content-Type` header. /// - Parameter body: Any `Encodable` type, will be encoded as JSON /// - Parameter encoder: An optional `JSONEncoder` func with<T: Encodable>(body: T, encoder: JSONEncoder = .shared) -> Self { with(body: try? encoder.encode(body), contentType: "application/json; charset=utf-8") } /// Returns a new request with a modified HTTP body and `Content-Type` header. /// - Parameter body: A dictionary or parameters, will be encoded as a URL form body func with(body: URL.Parameters) -> Self { with(body: body.query?.data(using: .utf8), contentType: "application/x-www-form-urlencoded; charset=utf-8") } /* /// Returns a new request with a modified HTTP body. /// - Parameter body: Any `Encodable` type /// - Parameter encoder: A custom encoder func with<T: Encodable, E: TopLevelEncoder>(body: T, encoder: E) -> Self where E.Output == Data { modified(self) { $0.httpBody = try? encoder.encode(body) } } */ /// Returns a new request with a modified `User-Agent` header. /// - Parameter userAgent: The new user-agent string func with(userAgent: String) -> Self { adding(header: "User-Agent", value: userAgent) } } public extension JSONDecoder { /// A convenient, shared `JSONDecoder` static var shared = modified(JSONDecoder()) { $0.keyDecodingStrategy = .convertFromSnakeCase } } public extension JSONEncoder { /// A convenient, shared `JSONEncoder` static var shared = JSONEncoder() } public extension URL { /// Creates a request from this `URL`. /// - Parameter path: An optional path to append to the URL /// - Parameter method: An optional HTTP method, `.get` by default /// - Returns: a `URLRequest` func request(_ method: URLRequest.HttpMethod = .get, path: String? = nil) -> URLRequest { if let path = path, !path.isEmpty { return URLRequest(url: appendingPathComponent(path)).with(method: method) } return URLRequest(url: self).with(method: method) } } #if canImport(Combine) import Combine @available(iOS 13.0, tvOS 13.0, OSX 10.15, macCatalyst 13.0, watchOS 6.0, *) public extension URLRequest { /// Wraps an HTTP error status code and a possibly decoded value struct ErrorWrapper: Error { public let data: Data? public let response: HTTPURLResponse? public let statusCode: HTTPStatusCode? } /// Creates a publisher for this request and decodable type. /// /// Example: /// /// func employee(name: String) -> AnyPublisher<Employee, Error> { /// URL(string: "https://api.foo.com/employees")! /// .request(path: name).publisher() /// } /// - Parameter session: Optional session. `URLSession.shared` is used by default. /// - Parameter decoder: Optional decoder. `JSONDecoder.shared` is used by default. /// - Returns: A publisher that wraps a data task and decoding for the URL request /// func publisher<T: Decodable>( session: URLSession = .shared, decoder: JSONDecoder = .shared ) -> AnyPublisher<T, Error> { session.dataTaskPublisher(for: self) .tryMap { data, response -> JSONDecoder.Input in if let httpResponse = response as? HTTPURLResponse, let statusCode = HTTPStatusCode(rawValue: httpResponse.statusCode), statusCode.isError { throw ErrorWrapper(data: data, response: httpResponse, statusCode: statusCode) } else { return data } } .map { $0.dumpJson() } .decode(type: T.self, decoder: decoder) .handleEvents(receiveCompletion: { completion in if case let .failure(error) = completion { debugPrint(error) } }) .eraseToAnyPublisher() } /// Publishes just the HTTP status of this request func statusPublisher( session: URLSession = .shared, decoder: JSONDecoder = .shared ) -> AnyPublisher<HTTPStatusCode?, Error> { session.dataTaskPublisher(for: self) .map { ($0.response as? HTTPURLResponse)?.statusCode ?? -1 } .map(HTTPStatusCode.init) .mapError { $0 as Error } .eraseToAnyPublisher() } } extension Data { @discardableResult func dumpJson(title: String? = nil) -> Self { #if DEBUG print("----- \(title ?? "JSON Dump") -----") guard let object = try? JSONSerialization.jsonObject(with: self), let data = try? JSONSerialization.data(withJSONObject: object, options: .prettyPrinted), let json = String(data: data, encoding: .utf8) else { print(String(data: self, encoding: .utf8) ?? "Unknown data encoding") return self } print(json) #endif return self } } #endif
0
// // Terminal.swift // cd2swiftTest // // Created by Jianing Wang on 2019/4/10. // Copyright © 2019 Jianing Wang. All rights reserved. // import Foundation public protocol Terminal { func open(_ path: String, _ newOption: NewOptionType, _ clear: ClearOptionType) throws }
0
// 647. Palindromic Substrings /** Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Note: The input string length won't exceed 1000. */ /** Idea: for loop, and consider each one as center of substring, check substring is palidome or not. Two case need consider. Odd, and Even. Runtime: O(N*N/2) = O(N^2) Space complexity: O(1) */ func countSubstrings(_ s: String) -> Int { var str: [Character] = [Character](s) var answer: Int = 0 var templ = 0, tempr = 0 for i in 0...str.count - 1 { templ = i tempr = i answer += 1 // check even while tempr < str.count - 1 && str[i] == str[tempr + 1] { tempr += 1 answer += 1 } // check odd while templ > 0 && tempr < str.count - 1 && str[templ - 1] == str[tempr + 1] { templ -= 1 tempr += 1 answer += 1 } } return answer }
0
// swiftlint:disable:next type_body_length internal struct TypeContentsOrderRuleExamples { static let defaultOrderParts = [ """ // Type Aliases typealias CompletionHandler = ((TestEnum) -> Void) """, """ // Subtypes class TestClass { // 10 lines } struct TestStruct { // 3 lines } enum TestEnum { // 5 lines } """, """ // Type Properties static let cellIdentifier: String = "AmazingCell" """, """ // Instance Properties var shouldLayoutView1: Bool! weak var delegate: TestViewControllerDelegate? private var hasLayoutedView1: Bool = false private var hasLayoutedView2: Bool = false private var hasAnyLayoutedView: Bool { return hasLayoutedView1 || hasLayoutedView2 } """, """ // IBOutlets @IBOutlet private var view1: UIView! @IBOutlet private var view2: UIView! """, """ // Initializers override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } """, """ // Type Methods static func makeViewController() -> TestViewController { // some code } """, """ // View Life-Cycle Methods override func viewDidLoad() { super.viewDidLoad() view1.setNeedsLayout() view1.layoutIfNeeded() hasLayoutedView1 = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() view2.setNeedsLayout() view2.layoutIfNeeded() hasLayoutedView2 = true } """, """ // IBActions @IBAction func goNextButtonPressed() { goToNextVc() delegate?.didPressTrackedButton() } """, """ // Other Methods func goToNextVc() { /* TODO */ } func goToInfoVc() { /* TODO */ } func goToRandomVc() { let viewCtrl = getRandomVc() present(viewCtrl, animated: true) } private func getRandomVc() -> UIViewController { return UIViewController() } """, """ // Subscripts subscript(_ someIndexThatIsNotEvenUsed: Int) -> String { get { return "This is just a test" } set { log.warning("Just a test", newValue) } } """ ] static let nonTriggeringExamples = [ [ "class TestViewController: UIViewController {", TypeContentsOrderRuleExamples.defaultOrderParts.joined(separator: "\n\n"), "}" ].joined(separator: "\n") ] static let triggeringExamples = [ """ class TestViewController: UIViewController { // Subtypes ↓class TestClass { // 10 lines } // Type Aliases typealias CompletionHandler = ((TestEnum) -> Void) } """, """ class TestViewController: UIViewController { // Stored Type Properties ↓static let cellIdentifier: String = "AmazingCell" // Subtypes class TestClass { // 10 lines } } """, """ class TestViewController: UIViewController { // Stored Instance Properties ↓var shouldLayoutView1: Bool! // Stored Type Properties static let cellIdentifier: String = "AmazingCell" } """, """ class TestViewController: UIViewController { // IBOutlets @IBOutlet private ↓var view1: UIView! // Computed Instance Properties private var hasAnyLayoutedView: Bool { return hasLayoutedView1 || hasLayoutedView2 } } """, """ class TestViewController: UIViewController { // Initializers override ↓init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } // IBOutlets @IBOutlet private var view1: UIView! @IBOutlet private var view2: UIView! } """, """ class TestViewController: UIViewController { // View Life-Cycle Methods override ↓func viewDidLoad() { super.viewDidLoad() view1.setNeedsLayout() view1.layoutIfNeeded() hasLayoutedView1 = true } // Type Methods static func makeViewController() -> TestViewController { // some code } } """, """ class TestViewController: UIViewController { // IBActions @IBAction ↓func goNextButtonPressed() { goToNextVc() delegate?.didPressTrackedButton() } // View Life-Cycle Methods override func viewDidLoad() { super.viewDidLoad() view1.setNeedsLayout() view1.layoutIfNeeded() hasLayoutedView1 = true } } """, """ class TestViewController: UIViewController { // Other Methods ↓func goToNextVc() { /* TODO */ } // IBActions @IBAction func goNextButtonPressed() { goToNextVc() delegate?.didPressTrackedButton() } } """, """ class TestViewController: UIViewController { // Subscripts ↓subscript(_ someIndexThatIsNotEvenUsed: Int) -> String { get { return "This is just a test" } set { log.warning("Just a test", newValue) } } // MARK: Other Methods func goToNextVc() { /* TODO */ } } """ ] }
0
// // practicaApp.swift // Shared // // Created by skynet on 23/12/21. // import SwiftUI @main struct practicaApp: App { var body: some Scene { WindowGroup { ContentView() } } }
0
// // PostsLikeViewController.swift // Piction-SDK-iOS-Example // // Created by jhseo on 14/06/2019. // Copyright © 2019 Piction Network. All rights reserved. // import UIKit import PictionSDK class PostsLikeViewController: UIViewController { @IBOutlet weak var uriTextField: UITextField! @IBOutlet weak var postIdTextField: UITextField! @IBOutlet weak var responseTextView: UITextView! @IBOutlet weak var executeButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var isLoading: Bool = false { didSet(loading) { loading ? self.activityIndicator.stopAnimating() : self.activityIndicator.startAnimating() self.executeButton.isEnabled = loading } } @IBAction func executeBtnPressed(_ sender: Any) { self.responseTextView.text = "" self.isLoading = true PictionSDK.posts.like(uri: uriTextField.text ?? "", postId: Int(postIdTextField.text ?? "0") ?? 0, success: { response in self.responseTextView.text = JsonUtil.toString(dict: response.toDict()) self.isLoading = false }, failure: { error in self.responseTextView.text = String(describing: error) self.isLoading = false }) } }
0
// // AppDelegate.swift // StickersApp // // Created by Phil Wright on 9/1/15. // Copyright © 2015 Touchopia, LLC. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } }
0
/// Create rounded rectangles. /// /// A rounded rectangle consists of 4 lines and 4 quarter circles. /// It is also a tile and needed to be added to a group for display. /// /// Here's how you create it and add it to a group. /// ```swift /// let roundRect = RoundRect(x: 0, y: 0, width: 80, height: 80, radius: 5, fill: Color.blue, outline: Color.white) /// /// // Add the rounded rectangle to a group for display. /// let group = Group() /// group.append(roundRect) /// ``` public class RoundRect: Tile { /// Create a rounded rectangle. /// - Parameters: /// - x: the x coordinate of the upper left corner of the tile. /// - y: the y coordinate of the upper left corner of the tile. /// - width: the width of the rectangle. /// - height: the height of the rectangle. /// - r: the radius of the rounded corner. /// - fill: the color used to fill the rectangle, nil by default. /// - outline: the color of the outline, nil by default. /// - stroke: the width of the outline, 1 by default. public init(x: Int, y: Int, width: Int, height: Int, radius r: Int, fill: UInt32! = nil, outline: UInt32! = nil, stroke: Int = 1) { let _bitmap = Bitmap(width: width, height: height, bitCount: 4) let _palette = Palette(count: 3) super.init(x: x, y: y, bitmap: _bitmap, palette: _palette) palette.makeTransparent(0) for i in 0..<width { for j in r..<(height - r) { bitmap[i, j] = 2 } } helper(r, r, r, color: 2, xOffset: width - 2 * r - 1, yOffset: height - 2 * r - 1, fill: true) if let value = fill { palette[2] = value } else { palette[2] = 0 palette.makeTransparent(2) } if let outline = outline { palette[1] = outline for w in r..<(width - r) { for line in 0..<stroke { bitmap[w, line] = 1 bitmap[w, height - line - 1] = 1 } } for h in r..<(height - r) { for line in 0..<stroke { bitmap[line, h] = 1 bitmap[width - line - 1, h] = 1 } } helper(r, r, r, color: 1, xOffset: width - 2 * r - 1, yOffset: height - 2 * r - 1, stroke: stroke) } } func helper(_ x0: Int, _ y0: Int, _ r: Int, color: UInt32, xOffset: Int = 0, yOffset: Int = 0, stroke: Int = 1, cornerFlag: UInt8 = 0x0F, fill: Bool = false) { var f = 1 - r var ddFX = 1 var ddFY = -2 * r var x = 0 var y = r while x < y { if f >= 0 { y -= 1 ddFY += 2 f += ddFY } x += 1 ddFX += 2 f += ddFX if (cornerFlag & 0x08) != 0 { if fill { for w in (x0 - y)..<(x0 + y + xOffset) { bitmap[w, y0 + x + yOffset] = color } for w in (x0 - x)..<(x0 + x + xOffset) { bitmap[w, y0 + y + yOffset] = color } } else { for line in 0..<stroke { bitmap[x0 - y + line, y0 + x + yOffset] = color bitmap[x0 - x, y0 + y + yOffset - line] = color } } } if (cornerFlag & 0x01) != 0 { if fill { for w in (x0 - y)..<(x0 + y + xOffset) { bitmap[w, y0 - x] = color } for w in (x0 - x)..<(x0 + x + xOffset) { bitmap[w, y0 - y] = color } } else { for line in 0..<stroke { bitmap[x0 - y + line, y0 - x] = color bitmap[x0 - x, y0 - y + line] = color } } } if (cornerFlag & 0x04) != 0 { for line in 0..<stroke { bitmap[x0 + x + xOffset, y0 + y + yOffset - line] = color bitmap[x0 + y + xOffset - line, y0 + x + yOffset] = color } } if (cornerFlag & 0x02) != 0 { for line in 0..<stroke { bitmap[x0 + x + xOffset, y0 - y + line] = color bitmap[x0 + y + xOffset - line, y0 - x] = color } } } } /// Fill the rounded rectangle with a specified color. /// - Parameter color: a UInt32 color value. public func fill(color: UInt32?) { if let color = color { palette[2] = color palette.makeOpaque(2) } else { palette[2] = 0 palette.makeTransparent(2) } } /// Set the color of outline. /// - Parameter color: a UInt32 color value. public func outline(color: UInt32?) { if let color = color { palette[1] = color palette.makeOpaque(1) } else { palette[1] = 0 palette.makeTransparent(1) } } }
0
// // EFQRCodeRecognizer.swift // EyreFree // // Created by EyreFree on 2017/3/28. // // Copyright (c) 2017 EyreFree <[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 CoreImage public class EFQRCodeRecognizer { private var image: CGImage? { didSet { contentArray = nil } } public func setImage(image: CGImage?) { self.image = image } private var contentArray: [String]? public init(image: CGImage) { self.image = image } public func recognize() -> [String]? { if nil == contentArray { contentArray = getQRString() } return contentArray } // Get QRCodes from image private func getQRString() -> [String]? { guard let finalImage = self.image else { return nil } let result = finalImage.toCIImage().recognizeQRCode(options: [CIDetectorAccuracy : CIDetectorAccuracyHigh]) if result.count <= 0 { return finalImage.grayscale()?.toCIImage().recognizeQRCode(options: [CIDetectorAccuracy : CIDetectorAccuracyLow]) } return result } }
0
// // FJAddressPickerDemoTests.swift // FJAddressPickerDemoTests // // Created by jun on 2017/6/20. // Copyright © 2017年 JUN. All rights reserved. // import XCTest @testable import FJAddressPickerDemo class FJAddressPickerDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // MtsApiRoomToNodeIds.swift // MTS // // Created by Rand Dow on 6/5/19. // Copyright © 2019 Rand Dow. All rights reserved. // import Foundation enum NodeIdSubNetOffset : Int { case RoomNode = 0 case Repeater1 = 1 case Repeater2 = 2 case Lock1 = 3 case Lock2 = 4 case Lock3 = 5 case Lock4 = 6 case Lock5 = 7 } // Request struct MtsRoom : Codable { var RoomName: String init(_ room: String) { RoomName = room } } // Response struct MtsRoomToNodeIds : Codable { var RoomName: String var NodeIds: [Int] } func MTSConvert(_ data: MtsRoom) throws -> Data { return try! JSONEncoder().encode(data) } func MTSConvert(_ data: [MtsRoomToNodeIds]) throws -> Data { return try! JSONEncoder().encode(data) }
0
// // GetStartedVC.swift // OnBoardingApp // // Created by Navnit Baldha on 31/05/20. // Copyright © 2020 Navneet Baldha. All rights reserved. // import Foundation import UIKit import Photos class GetStartedVC: UIViewController { @IBOutlet weak var sliderContainerView: UIView! @IBOutlet weak var getingStartedButton: UIButton! } extension GetStartedVC { override func viewDidLoad() { self.navigationController?.isNavigationBarHidden = true initializer() } func initializer() { let mGettingStartedSliderVC = GettingStartedSliderVC(nibName:Constants.gettingStartedSliderVC , bundle: nil) mGettingStartedSliderVC.view.frame = CGRect(x: 0, y: 0, width: sliderContainerView.frame.width, height: sliderContainerView.frame.height) addChild(mGettingStartedSliderVC) mGettingStartedSliderVC.didMove(toParent: self) sliderContainerView.addSubview(mGettingStartedSliderVC.view) } @IBAction func getingStartedAction(_ sender: AnyObject) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let rootViewController = mainStoryboard.instantiateViewController(withIdentifier: "CardTabBarController") // navigationController let navigationController = UINavigationController(rootViewController: rootViewController) navigationController.navigationBar.isHidden = true if #available(iOS 13.0, *) { let sceneDelegate = UIApplication.shared.connectedScenes .first!.delegate as! SceneDelegate sceneDelegate.window!.rootViewController = navigationController/* ViewController Instance */ // iOS12 or earlier } else { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window!.rootViewController = navigationController /* ViewController Instance */ } } }
0
// // GameScene.swift // Agora-Screen-Sharing-iOS // // Created by GongYuhua on 2017/1/3. // Copyright © 2016年 Agora. All rights reserved. // import SpriteKit import AVFoundation func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } #if !(arch(x86_64) || arch(arm64)) fileprivate func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x + y*y) } func normalized() -> CGPoint { return self / length() } } class GameScene: SKScene { fileprivate let ship = SKSpriteNode(imageNamed: "spaceship") fileprivate var backgroundPlayer: AVAudioPlayer? override func didMove(to view: SKView) { backgroundColor = SKColor.white ship.position = CGPoint(x: size.width * 0.5, y: size.height * 0.1) addChild(ship) run(SKAction.repeatForever( SKAction.sequence([ SKAction.run(addDust), SKAction.wait(forDuration: 1.0) ]) )) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touchLocation = touches.first?.location(in: self) { fireStar(to: touchLocation) } } func loadBackGroundMusic() { if let fileURL = Bundle.main.url(forResource: "space", withExtension: "mp3"), let player = try? AVAudioPlayer(contentsOf: fileURL) { player.numberOfLoops = -1 player.play() backgroundPlayer = player } } } private extension GameScene { func addDust() { let dust = SKSpriteNode(imageNamed: "dust") let actualX = random(min: dust.size.width / 2, max: size.width - dust.size.width / 2) dust.position = CGPoint(x: actualX, y: size.height + dust.size.width / 2) dust.zPosition = -2 addChild(dust) let actualDuration = random(min: CGFloat(2), max: CGFloat(4)) let actionMove = SKAction.move(to: CGPoint(x: actualX, y: -dust.size.height / 2), duration: TimeInterval(actualDuration)) let actionMoveDone = SKAction.removeFromParent() dust.run(SKAction.sequence([actionMove, actionMoveDone])) } func fireStar(to location: CGPoint) { let star = SKSpriteNode(imageNamed: "star") star.position = ship.position + CGPoint(x: 0, y: 5) let offset = location - star.position if (offset.y < 0) { return } star.zPosition = -1 addChild(star) let direction = offset.normalized() let shootAmount = direction * 1000 let realDest = shootAmount + star.position let actionMove = SKAction.move(to: realDest, duration: 1.5) let rotation = SKAction.rotate(byAngle: 18, duration: 1.5) let actionMoveDone = SKAction.removeFromParent() star.run(SKAction.sequence([SKAction.group([actionMove, rotation]), actionMoveDone])) run(SKAction.playSoundFileNamed("shoot.mp3", waitForCompletion: false)) } } private extension GameScene { func random(min: CGFloat, max: CGFloat) -> CGFloat { return CGFloat.random(in: min...max) } }
0
// // MapController.swift // Swagslist // // Created by Aidan Brady on 9/24/16. // Copyright © 2016 Aidan Brady. All rights reserved. // import UIKit import MapKit class MapController : UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.isScrollEnabled = true let coords = CLLocationCoordinate2D(latitude: 33.77586305, longitude: -84.39651936) let region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(self.mapView.region.span.longitudeDelta/8192, self.mapView.region.span.latitudeDelta/8192)) self.mapView.setRegion(region, animated: false) doRefresh() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 56 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return SharedData.eventList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "EventCell") as! EntryCell let entry = SharedData.eventList[indexPath.row] let date = Date(timeIntervalSince1970: Double(Double(entry.endTime)/1000)) let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short cell.nameLabel.text = entry.name cell.distanceLabel.text = "Ends " + formatter.string(from: date) cell.apparelIcon.isHidden = !entry.swagSet.contains("APPAREL") cell.foodIcon.isHidden = !entry.swagSet.contains("FOOD") cell.trinketsIcon.isHidden = !entry.swagSet.contains("TRINKETS") cell.promotedIcon.isHidden = !entry.premium return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let destController = mainStoryboard.instantiateViewController(withIdentifier: "ViewEntryController") as! ViewEntryController destController.eventEntry = SharedData.eventList[indexPath.row] self.navigationController!.pushViewController(destController, animated: true) tableView.cellForRow(at: indexPath)!.setSelected(false, animated: true) } @IBAction func onRefresh(_ sender: AnyObject) { doRefresh() } func doRefresh() { if !Operations.refreshing { DispatchQueue.global(qos: .background).async { Operations.refreshing = true let list = NetHandler.getEvents() DispatchQueue.main.async { SharedData.eventList = list self.tableView.reloadData() Operations.refreshing = false self.mapView.removeAnnotations(self.mapView.annotations) for entry in SharedData.eventList { let coords = CLLocationCoordinate2D(latitude: entry.latitude, longitude: entry.longitude) let point = MKPointAnnotation() point.coordinate = coords point.title = entry.name self.mapView.addAnnotation(point) } } } } } }
0
// // PerformanceTest.swift // SwiftCSV // // Created by 杉本裕樹 on 2016/04/23. // Copyright © 2016年 Naoto Kaneko. All rights reserved. // import XCTest @testable import SwiftCSV class PerformanceTest: XCTestCase { var csv: CSV! override func setUp() { let csvURL = ResourceHelper.url(forResource: "large", withExtension: "csv")! csv = try! CSV(url: csvURL) } func testParsePerformance() { measure { _ = self.csv.namedRows } } }
0
// // AppDelegate.swift // Cam // // Created by Yuichi Murata on 2019/02/09. // Copyright © 2019 Yuichi Murata. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength) func applicationDidFinishLaunching(_ aNotification: Notification) { if let button = statusItem.button { button.image = NSImage(named: NSImage.Name("StatusBarButtonImage")) } let menu = NSMenu() menu.addItem(NSMenuItem(title: "Quit Cam", action: #selector(NSApplication.terminate(_:)), keyEquivalent:"Q")) statusItem.menu = menu } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
0
// // TestCell.swift // SFKit_Example // // Created by 黄山锋 on 2020/3/4. // Copyright © 2020 CocoaPods. All rights reserved. // import UIKit class TestCell: UICollectionViewCell { @IBOutlet weak var imgView: UIImageView! override func awakeFromNib() { super.awakeFromNib() } }
0
// SharelockAPI.swift // // Copyright (c) 2015 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Cocoa let SharelockAPIDomainError = "com.auth0.sharelock.api" @objc class SharelockAPI: NSObject { let baseURL: NSURL init(baseURL: NSURL) { self.baseURL = baseURL } func linkForSecret(secret: Secret, callback: (Secret, NSError?) -> Void) { let newURL = NSURL(string: "create", relativeToURL: self.baseURL)! let params = ["d": secret.data!, "a": secret.aclString!] request(.POST, newURL, parameters: params) .validate(statusCode: 200..<300) .responseString { (_, response, responseString, err) in if let error = err { if (response?.statusCode == 400) { let badRequestError = NSError(domain: SharelockAPIDomainError, code: 0, userInfo: [ NSLocalizedDescriptionKey: NSLocalizedString("Couldn't generate link", comment: "Link Generation Failed Title"), NSLocalizedFailureReasonErrorKey: NSLocalizedString("Please check that you provide a valid email or twitter handle", comment: "Link Generation Failed Message") ]) callback(secret, badRequestError) } else { callback(secret, error) } } else { if let link = NSURL(string: responseString!, relativeToURL: self.baseURL) { secret.link = link callback(secret, nil) } else { let invalidLinkError = NSError(domain: SharelockAPIDomainError, code: 1, userInfo: [ NSLocalizedDescriptionKey: NSLocalizedString("Couldn't generate link", comment: "Link Generation Failed Title"), NSLocalizedFailureReasonErrorKey: NSLocalizedString("The link generated was invalid. Please try again later.", comment: "Invalid Link Message") ]) callback(secret, invalidLinkError) } } } } }
0
import Foundation public extension ApplicationClient { /* Model: MarketplaceInfo Used By: Payment */ class MarketplaceInfo: Codable { public var membershipId: String public var dateOfJoining: String? public var name: String public enum CodingKeys: String, CodingKey { case membershipId = "membership_id" case dateOfJoining = "date_of_joining" case name } public init(dateOfJoining: String? = nil, membershipId: String, name: String) { self.membershipId = membershipId self.dateOfJoining = dateOfJoining self.name = name } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) membershipId = try container.decode(String.self, forKey: .membershipId) do { dateOfJoining = try container.decode(String.self, forKey: .dateOfJoining) } catch DecodingError.typeMismatch(let type, let context) { print("Type '\(type)' mismatch:", context.debugDescription) print("codingPath:", context.codingPath) } catch {} name = try container.decode(String.self, forKey: .name) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try? container.encodeIfPresent(membershipId, forKey: .membershipId) try? container.encode(dateOfJoining, forKey: .dateOfJoining) try? container.encodeIfPresent(name, forKey: .name) } } }
0
// // Color.swift // SubscriptionManager // // Created by Aitor Zubizarreta on 10/11/2020. // Copyright © 2020 Aitor Zubizarreta. All rights reserved. // import SwiftUI extension Color { static let customBgLightGray = Color(red: 244.0/255.0, green: 244.0/255.0, blue: 244.0/255.0) // Rows. static let customRowBlue = Color(red: 39.0/255.0, green: 125.0/255.0, blue: 161.0/255.0, opacity: 1.0) static let customRowBlueDark = Color(red: 87.0/255.0, green: 117.0/255.0, blue: 144.0/255.0, opacity: 1.0) static let customRowGreen = Color(red: 67.0/255.0, green: 170.0/255.0, blue: 139.0/255.0, opacity: 1.0) static let customRowGreenDark = Color(red: 77.0/255.0, green: 144.0/255.0, blue: 142.0/255.0, opacity: 1.0) static let customRowPistachio = Color(red: 144.0/255.0, green: 190.0/255.0, blue: 109.0/255.0, opacity: 1.0) static let customRowYellow = Color(red: 249.0/255.0, green: 199.0/255.0, blue: 79.0/255.0, opacity: 1.0) static let customRowMango = Color(red: 249.0/255.0, green: 132.0/255.0, blue: 74.0/255.0, opacity: 1.0) static let customRowOrange = Color(red: 248.0/255.0, green: 150.0/255.0, blue: 30.0/255.0, opacity: 1.0) static let customRowOrangeDark = Color(red: 243.0/255.0, green: 114.0/255.0, blue: 44.0/255.0, opacity: 1.0) static let customRowRed = Color(red: 249.0/255.0, green: 65.0/255.0, blue: 68.0/255.0, opacity: 1.0) static let customLightGrey = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0) static let customDarkGrey = Color(red: 218.0/255.0, green: 218.0/255.0, blue: 218.0/255.0, opacity: 1.0) static let customDarkText = Color(red: 137.0/255.0, green: 137.0/255.0, blue: 137.0/255.0, opacity: 1.0) // Buttons. static let customRedText = Color(red: 255.0/255.0, green: 83.0/255.0, blue: 58.0/255.0, opacity: 1.0) static let customRedButton = Color(red: 250.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, opacity: 1.0) static let customBlueText = Color(red: 42.0/255.0, green: 124.0/255.0, blue: 255.0/255.0, opacity: 1.0) static let customBlueButton = Color(red: 237.0/255.0, green: 242.0/255.0, blue: 252.0/255.0, opacity: 1.0) static let customGrayButton = Color(red: 241.0/255.0, green: 241.0/255.0, blue: 243.0/255.0, opacity: 1.0) static let customGrayBorderButton = Color(red: 222.0/255.0, green: 222.0/255.0, blue: 222.0/255.0, opacity: 1.0) static let customGreenText = Color(red: 75.0/255.0, green: 163.0/255.0, blue: 0.0/255.0, opacity: 1.0) static let customGreenButton = Color(red: 239.0/255.0, green: 252.0/255.0, blue: 238.0/255.0, opacity: 1.0) }
0
/* The MIT License (MIT) Copyright (c) 2015 Kyohei Yamaguchi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit class 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 didTapButton(sender: KYShutterButton) { switch sender.buttonState { case .Normal: sender.buttonState = .Recording case .Recording: sender.buttonState = .Normal } } }
0
import Foundation public struct ScandinavianFoldingFilter: BasicTokenFilter, BuiltinTokenFilter { /// :nodoc: public static var typeKey = TokenFilterType.scandinavianFolding /// Holds the string that Elasticsearch uses to identify the filter type public let type = typeKey.rawValue /// :nodoc: public let name: String public init() { self.name = self.type } }
0
// // ReactiveComponentUIViewTests.swift // GoReactive_Tests // // Created by Gal Orlanczyk on 28/12/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import XCTest import GoReactive import GoReactiveTests class ReactiveComponentUIViewTests: GoReactiveTestCase { let view = UIView(frame: .zero) func testIsHidden() { let boolProperty = Property<Bool>(false) boolProperty.bind(to: self.view.reactiveComponent.isHidden).add(to: self.cancelableGroup) boolProperty.value = true XCTAssertEqual(boolProperty.value, view.isHidden) } func testAlpha() { let property = Property<CGFloat>(1) property.bind(to: self.view.reactiveComponent.alpha).add(to: self.cancelableGroup) property.value = 0 XCTAssertEqual(property.value, view.alpha) } }
0
import swiftMetal import COpenCL import Foundation import Metal internal final class Image: MetalTexture { internal class Descriptor { internal var image_type: cl_mem_object_type internal var image_width: Int internal var image_height: Int internal var image_depth: Int internal var image_array_size: Int internal var image_row_pitch: Int internal var image_slice_pitch: Int internal var num_mip_levels: Int internal var num_samples: Int internal init(image_type: cl_mem_object_type, image_width: Int = 0, image_height: Int = 0, image_depth: Int = 0, image_array_size: Int = 0, image_row_pitch: Int = 0, image_slice_pitch: Int = 0, num_mip_levels: Int = 0, num_samples: Int = 0) { self.image_type = image_type self.image_width = image_width self.image_height = image_height self.image_depth = image_depth self.image_array_size = image_array_size self.image_row_pitch = image_row_pitch self.image_slice_pitch = image_slice_pitch self.num_mip_levels = num_mip_levels self.num_samples = num_samples } } internal init?(metalDevice: MetalDevice, flags: cl_mem_flags, imageFormat: cl_image_format, imageDesc: Descriptor, hostPtr: UnsafeRawPointer?) { let descriptor = MTLTextureDescriptor() let textureTypeForMemObjectType: [cl_mem_object_type: MTLTextureType] = [ cl_mem_object_type(CL_MEM_OBJECT_IMAGE1D): .type1D, cl_mem_object_type(CL_MEM_OBJECT_IMAGE1D_ARRAY): .type1DArray, cl_mem_object_type(CL_MEM_OBJECT_IMAGE1D_BUFFER): .typeTextureBuffer, cl_mem_object_type(CL_MEM_OBJECT_IMAGE2D): .type2D, cl_mem_object_type(CL_MEM_OBJECT_IMAGE2D_ARRAY): .type2DArray, cl_mem_object_type(CL_MEM_OBJECT_IMAGE3D): .type3D, ] guard let textureType = textureTypeForMemObjectType[imageDesc.image_type] else { return nil } let pixelFormatsForImageFormat: [cl_channel_order: [cl_channel_type: MTLPixelFormat]] = [ cl_channel_order(CL_BGRA): [ cl_channel_type(CL_UNORM_INT8): .bgra8Unorm, ], cl_channel_order(CL_RGBA): [ cl_channel_type(CL_SIGNED_INT32): .rgba32Sint, cl_channel_type(CL_UNORM_INT8): .rgba8Unorm, cl_channel_type(CL_UNSIGNED_INT32): .rgba32Uint, ], ] guard let pixelFormats = pixelFormatsForImageFormat[imageFormat.image_channel_order], let pixelFormat = pixelFormats[imageFormat.image_channel_data_type] else { preconditionFailure(String(format: "0x%04x 0x%04x", imageFormat.image_channel_order, imageFormat.image_channel_data_type)) } descriptor.textureType = textureType descriptor.pixelFormat = pixelFormat descriptor.width = imageDesc.image_width descriptor.height = imageDesc.image_height descriptor.depth = imageDesc.image_depth descriptor.arrayLength = imageDesc.image_array_size descriptor.mipmapLevelCount = Int(imageDesc.num_mip_levels) guard let texture = metalDevice.device.makeTexture(descriptor: descriptor) else { return nil } if let _hostPtr = hostPtr { texture.replace(region: MTLRegion(origin: MTLOrigin(), size: MTLSize(width: texture.width, height: texture.height, depth: texture.depth)), mipmapLevel: 0, withBytes: _hostPtr, bytesPerRow: 0) } super.init(metalDevice: metalDevice, texture: texture) } }
0
import PromiseKit import XCTest class WhenTests: XCTestCase { func testEmpty() { let e = expectation(description: "") let promises: [Promise<Void>] = [] when(fulfilled: promises).done { _ in e.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testInt() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value(2) let p3 = Promise.value(3) let p4 = Promise.value(4) when(fulfilled: [p1, p2, p3, p4]).done { x in XCTAssertEqual(x[0], 1) XCTAssertEqual(x[1], 2) XCTAssertEqual(x[2], 3) XCTAssertEqual(x[3], 4) XCTAssertEqual(x.count, 4) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testDoubleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") when(fulfilled: p1, p2).done{ x, y in XCTAssertEqual(x, 1) XCTAssertEqual(y, "abc") e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testTripleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value( 1.0) when(fulfilled: p1, p2, p3).done { u, v, w in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testQuadrupleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value(1.0) let p4 = Promise.value(true) when(fulfilled: p1, p2, p3, p4).done { u, v, w, x in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testQuintupleTuple() { let e1 = expectation(description: "") let p1 = Promise.value(1) let p2 = Promise.value("abc") let p3 = Promise.value(1.0) let p4 = Promise.value(true) let p5 = Promise.value("a" as Character) when(fulfilled: p1, p2, p3, p4, p5).done { u, v, w, x, y in XCTAssertEqual(1, u) XCTAssertEqual("abc", v) XCTAssertEqual(1.0, w) XCTAssertEqual(true, x) XCTAssertEqual("a" as Character, y) e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testVoid() { let e1 = expectation(description: "") let p1 = Promise.value(1).done { _ in } let p2 = Promise.value(2).done { _ in } let p3 = Promise.value(3).done { _ in } let p4 = Promise.value(4).done { _ in } when(fulfilled: p1, p2, p3, p4).done(e1.fulfill) waitForExpectations(timeout: 1, handler: nil) } func testRejected() { enum Error: Swift.Error { case dummy } let e1 = expectation(description: "") let p1 = after(.milliseconds(100)).map{ true } let p2: Promise<Bool> = after(.milliseconds(200)).map{ throw Error.dummy } let p3 = Promise.value(false) when(fulfilled: p1, p2, p3).catch { _ in e1.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testProgress() { let ex = expectation(description: "") XCTAssertNil(Progress.current()) let p1 = after(.milliseconds(10)) let p2 = after(.milliseconds(20)) let p3 = after(.milliseconds(30)) let p4 = after(.milliseconds(40)) let progress = Progress(totalUnitCount: 1) progress.becomeCurrent(withPendingUnitCount: 1) when(fulfilled: p1, p2, p3, p4).done { _ in XCTAssertEqual(progress.completedUnitCount, 1) ex.fulfill() } progress.resignCurrent() waitForExpectations(timeout: 1, handler: nil) } func testProgressDoesNotExceed100Percent() { let ex1 = expectation(description: "") let ex2 = expectation(description: "") XCTAssertNil(Progress.current()) let p1 = after(.milliseconds(10)) let p2 = after(.milliseconds(20)).done { throw NSError(domain: "a", code: 1, userInfo: nil) } let p3 = after(.milliseconds(30)) let p4 = after(.milliseconds(40)) let progress = Progress(totalUnitCount: 1) progress.becomeCurrent(withPendingUnitCount: 1) let promise = when(fulfilled: p1, p2, p3, p4) progress.resignCurrent() promise.catch { _ in ex2.fulfill() } var x = 0 func finally() { x += 1 if x == 4 { XCTAssertLessThanOrEqual(1, progress.fractionCompleted) XCTAssertEqual(progress.completedUnitCount, 1) ex1.fulfill() } } let q = DispatchQueue.main p1.done(on: q, finally) p2.ensure(on: q, finally) p3.done(on: q, finally) p4.done(on: q, finally) waitForExpectations(timeout: 1, handler: nil) } func testUnhandledErrorHandlerDoesNotFire() { enum Error: Swift.Error { case test } let ex = expectation(description: "") let p1 = Promise<Void>(error: Error.test) let p2 = after(.milliseconds(100)) when(fulfilled: p1, p2).done{ _ in XCTFail() }.catch { error in XCTAssertTrue(error as? Error == Error.test) ex.fulfill() } waitForExpectations(timeout: 1, handler: nil) } func testUnhandledErrorHandlerDoesNotFireForStragglers() { enum Error: Swift.Error { case test case straggler } let ex1 = expectation(description: "") let ex2 = expectation(description: "") let ex3 = expectation(description: "") let p1 = Promise<Void>(error: Error.test) let p2 = after(.milliseconds(100)).done { throw Error.straggler } let p3 = after(.milliseconds(200)).done { throw Error.straggler } when(fulfilled: p1, p2, p3).catch { error -> Void in XCTAssertTrue(Error.test == error as? Error) ex1.fulfill() } p2.ensure { after(.milliseconds(100)).done(ex2.fulfill) } p3.ensure { after(.milliseconds(100)).done(ex3.fulfill) } waitForExpectations(timeout: 1, handler: nil) } func testAllSealedRejectedFirstOneRejects() { enum Error: Swift.Error { case test1 case test2 case test3 } let ex = expectation(description: "") let p1 = Promise<Void>(error: Error.test1) let p2 = Promise<Void>(error: Error.test2) let p3 = Promise<Void>(error: Error.test3) when(fulfilled: p1, p2, p3).catch { error in XCTAssertTrue(error as? Error == Error.test1) ex.fulfill() } waitForExpectations(timeout: 1) } }
0
// // ResetAllCell.swift // Yelp // // Created by Duy Huynh Thanh on 10/22/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit class ResetAllCell: UITableViewCell { 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 } }
0
import XCTest import GlobalsProviders import SwiftRewriterLib class UIKitGlobalsProviderTests: BaseGlobalsProviderTestCase { override func setUp() { super.setUp() sut = UIKitGlobalsProvider() globals = sut.definitionsSource() types = sut.knownTypeProvider() typealiases = sut.typealiasProvider() } func testDefinedUIGraphicsGetCurrentContext() { assertDefined(function: "UIGraphicsGetCurrentContext", paramTypes: [], returnType: .optional(.typeName("CGContext"))) } func testDefinedUIViewNoIntrinsicMetric() { assertDefined(variable: "UIViewNoIntrinsicMetric", type: .cgFloat) } func testDefinedUILayoutFittingCompressedSize() { assertDefined(variable: "UILayoutFittingCompressedSize", type: "CGSize") } func testDefinedUILayoutFittingExpandedSize() { assertDefined(variable: "UILayoutFittingExpandedSize", type: "CGSize") } func testDefinedUIResponder() { assertDefined(typeName: "UIResponder", signature: """ class UIResponder: NSObject, UIResponderStandardEditActions { var canBecomeFirstResponder: Bool { get } var canResignFirstResponder: Bool { get } var isFirstResponder: UIResponder? { get } var undoManager: UndoManager? { get } func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool func resignFirstResponder() -> Bool func target(forAction action: Selector, withSender sender: Any?) -> Any? func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) func remoteControlReceived(with event: UIEvent?) func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) func touchesEstimatedPropertiesUpdated(_ touches: Set<UITouch>) func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) } """) } func testDefinedUIViewController() { assertDefined(typeName: "UIViewController", signature: """ class UIViewController: UIResponder, NSCoding, UIAppearanceContainer, UITraitEnvironment, UIContentContainer, UIFocusEnvironment { var view: UIView init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) func viewDidLoad() func viewWillAppear(_ animated: Bool) func viewDidAppear(_ animated: Bool) func viewWillDisappear(_ animated: Bool) func viewDidDisappear(_ animated: Bool) func viewWillLayoutSubviews() func viewDidLayoutSubviews() } """) } func testDefinedUILayoutConstraintAxis() { assertDefined(typeName: "UILayoutConstraintAxis", signature: """ enum UILayoutConstraintAxis: Int { case horizontal case vertical } """) } func testDefinedUIView() { assertDefined(typeName: "UIView") } func testDefinedUIWindow() { assertDefined(typeName: "UIWindow", signature: """ class UIWindow: UIView { } """) } func testDefinedUITableViewCell() { assertDefined(typeName: "UITableViewCell", signature: """ class UITableViewCell: UIView, UIGestureRecognizerDelegate { var accessoryType: UITableViewCellAccessoryType var accessoryView: UIView? var backgroundView: UIView? var contentView: UIView { get } var detailTextLabel: UILabel? { get } var editingAccessoryType: UITableViewCellAccessoryType var editingAccessoryView: UIView? var editingStyle: UITableViewCellEditingStyle { get } var focusStyle: UITableViewCellFocusStyle var imageView: UIImageView? { get } var indentationLevel: Int var indentationWidth: CGFloat var isEditing: Bool var isHighlighted: Bool var isSelected: Bool var multipleSelectionBackgroundView: UIView? var reuseIdentifier: String? { get } var selectedBackgroundView: UIView? var selectionStyle: UITableViewCellSelectionStyle var separatorInset: UIEdgeInsets var shouldIndentWhileEditing: Bool var showingDeleteConfirmation: Bool { get } var showsReorderControl: Bool var textLabel: UILabel? { get } var userInteractionEnabledWhileDragging: Bool init(style: UITableViewCellStyle, reuseIdentifier: String?) func didTransition(to state: UITableViewCellStateMask) func dragStateDidChange(_ dragState: UITableViewCellDragState) func prepareForReuse() func setEditing(_ editing: Bool, animated: Bool) func setHighlighted(_ highlighted: Bool, animated: Bool) func setSelected(_ selected: Bool, animated: Bool) func willTransition(to state: UITableViewCellStateMask) } """) } func testDefinedUIScrollView() { assertDefined(typeName: "UIScrollView", signature: """ class UIScrollView: UIView { var adjustedContentInset: UIEdgeInsets { get } var alwaysBounceHorizontal: Bool var alwaysBounceVertical: Bool var bounces: Bool var bouncesZoom: Bool var canCancelContentTouches: Bool var contentInset: UIEdgeInsets var contentInsetAdjustmentBehavior: UIScrollViewContentInsetAdjustmentBehavior var contentLayoutGuide: UILayoutGuide { get } var contentOffset: CGPoint var contentSize: CGSize var decelerationRate: CGFloat var delaysContentTouches: Bool var directionalPressGestureRecognizer: UIGestureRecognizer { get } var frameLayoutGuide: UILayoutGuide { get } var indexDisplayMode: UIScrollViewIndexDisplayMode var indicatorStyle: UIScrollViewIndicatorStyle var isDecelerating: Bool { get } var isDirectionalLockEnabled: Bool var isDragging: Bool { get } var isPagingEnabled: Bool var isScrollEnabled: Bool var isTracking: Bool { get } var isZoomBouncing: Bool { get } var isZooming: Bool { get } var keyboardDismissMode: UIScrollViewKeyboardDismissMode var maximumZoomScale: CGFloat var minimumZoomScale: CGFloat var panGestureRecognizer: UIPanGestureRecognizer { get } var pinchGestureRecognizer: UIPinchGestureRecognizer? { get } var refreshControl: UIRefreshControl? var scrollIndicatorInsets: UIEdgeInsets var scrollsToTop: Bool var showsHorizontalScrollIndicator: Bool var showsVerticalScrollIndicator: Bool var zoomScale: CGFloat weak var delegate: UIScrollViewDelegate? func adjustedContentInsetDidChange() func flashScrollIndicators() func scrollRectToVisible(_ rect: CGRect, animated: Bool) func setContentOffset(_ contentOffset: CGPoint, animated: Bool) func setZoomScale(_ scale: CGFloat, animated: Bool) func touchesShouldBegin(_ touches: Set<UITouch>, with event: UIEvent?, in view: UIView) -> Bool func touchesShouldCancel(in view: UIView) -> Bool func zoom(to rect: CGRect, animated: Bool) } """) } func testDefinedUITableView() { assertDefined(typeName: "UITableView", signature: """ class UITableView: UIScrollView { var allowsMultipleSelection: Bool var allowsMultipleSelectionDuringEditing: Bool var allowsSelection: Bool var allowsSelectionDuringEditing: Bool var backgroundView: UIView? var cellLayoutMarginsFollowReadableWidth: Bool var dragInteractionEnabled: Bool var estimatedRowHeight: CGFloat var estimatedSectionFooterHeight: CGFloat var estimatedSectionHeaderHeight: CGFloat var hasActiveDrag: Bool { get } var hasActiveDrop: Bool { get } var hasUncommittedUpdates: Bool { get } var indexPathForSelectedRow: IndexPath? { get } var indexPathsForSelectedRows: [IndexPath]? { get } var indexPathsForVisibleRows: [IndexPath]? { get } var insetsContentViewsToSafeArea: Bool var isEditing: Bool var numberOfSections: Int { get } var remembersLastFocusedIndexPath: Bool var rowHeight: CGFloat var sectionFooterHeight: CGFloat var sectionHeaderHeight: CGFloat var sectionIndexBackgroundColor: UIColor? var sectionIndexColor: UIColor? var sectionIndexMinimumDisplayRowCount: Int var sectionIndexTrackingBackgroundColor: UIColor? var separatorColor: UIColor? var separatorEffect: UIVisualEffect? var separatorInset: UIEdgeInsets var separatorInsetReference: UITableViewSeparatorInsetReference var separatorStyle: UITableViewCellSeparatorStyle var style: UITableViewStyle { get } var tableFooterView: UIView? var tableHeaderView: UIView? var visibleCells: [UITableViewCell] { get } weak var dataSource: UITableViewDataSource? weak var delegate: UITableViewDelegate? weak var dragDelegate: UITableViewDragDelegate? weak var dropDelegate: UITableViewDropDelegate? weak var prefetchDataSource: UITableViewDataSourcePrefetching? init(frame: CGRect, style: UITableViewStyle) func beginUpdates() func cellForRow(at indexPath: IndexPath) -> UITableViewCell? func deleteRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) func deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) func dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> UITableViewCell func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell? func dequeueReusableHeaderFooterView(withIdentifier identifier: String) -> UITableViewHeaderFooterView? func deselectRow(at indexPath: IndexPath, animated: Bool) func endUpdates() func footerView(forSection section: Int) -> UITableViewHeaderFooterView? func headerView(forSection section: Int) -> UITableViewHeaderFooterView? func indexPath(for cell: UITableViewCell) -> IndexPath? func indexPathForRow(at point: CGPoint) -> IndexPath? func indexPathsForRows(in rect: CGRect) -> [IndexPath]? func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) func insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) func moveRow(at indexPath: IndexPath, to newIndexPath: IndexPath) func moveSection(_ section: Int, toSection newSection: Int) func numberOfRows(inSection section: Int) -> Int func performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) func rect(forSection section: Int) -> CGRect func rectForFooter(inSection section: Int) -> CGRect func rectForHeader(inSection section: Int) -> CGRect func rectForRow(at indexPath: IndexPath) -> CGRect func register(_ aClass: AnyClass?, forHeaderFooterViewReuseIdentifier identifier: String) func register(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) func register(_ nib: UINib?, forCellReuseIdentifier identifier: String) func register(_ nib: UINib?, forHeaderFooterViewReuseIdentifier identifier: String) func reloadData() func reloadRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) func reloadSectionIndexTitles() func reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) func scrollToNearestSelectedRow(at scrollPosition: UITableViewScrollPosition, animated: Bool) func scrollToRow(at indexPath: IndexPath, at scrollPosition: UITableViewScrollPosition, animated: Bool) func selectRow(at indexPath: IndexPath?, animated: Bool, scrollPosition: UITableViewScrollPosition) func setEditing(_ editing: Bool, animated: Bool) } """) } }
0
import Foundation import Metal public let standardImageVertices:[Float] = [-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0] extension MTLCommandBuffer { func renderQuad(pipelineState:MTLRenderPipelineState, uniformSettings:ShaderUniformSettings? = nil, inputTexture:Texture, imageVertices:[Float] = standardImageVertices, outputTexture:Texture, outputOrientation:ImageOrientation = .portrait) { let vertexBuffer = sharedMetalRenderingDevice.device.makeBuffer(bytes: imageVertices, length: imageVertices.count * MemoryLayout<Float>.size, options: [])! vertexBuffer.label = "Vertices" let firstInputRotation = inputTexture.orientation.rotationNeededForOrientation(outputOrientation) let firstInputTextureCoordinates = firstInputRotation.textureCoordinates() let textureBuffer = sharedMetalRenderingDevice.device.makeBuffer(bytes: firstInputTextureCoordinates, length: firstInputTextureCoordinates.count * MemoryLayout<Float>.size, options: [])! textureBuffer.label = "Texture Coordinates" let renderPass = MTLRenderPassDescriptor() renderPass.colorAttachments[0].texture = outputTexture.texture renderPass.colorAttachments[0].clearColor = MTLClearColorMake(1, 0, 0, 1) renderPass.colorAttachments[0].storeAction = .store renderPass.colorAttachments[0].loadAction = .clear guard let renderEncoder = self.makeRenderCommandEncoder(descriptor: renderPass) else { fatalError("Could not create render encoder") } renderEncoder.setFrontFacing(.counterClockwise) renderEncoder.setRenderPipelineState(pipelineState) renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) renderEncoder.setVertexBuffer(textureBuffer, offset: 0, index: 1) uniformSettings?.restoreShaderSettings(renderEncoder: renderEncoder) renderEncoder.setFragmentTexture(inputTexture.texture, index: 0) renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) renderEncoder.endEncoding() } } func generateRenderPipelineState(device:MetalRenderingDevice, vertexFunctionName:String, fragmentFunctionName:String, operationName:String) -> MTLRenderPipelineState { guard let vertexFunction = device.shaderLibrary.makeFunction(name: vertexFunctionName) else { fatalError("\(operationName): could not compile vertex function \(vertexFunctionName)") } guard let fragmentFunction = device.shaderLibrary.makeFunction(name: fragmentFunctionName) else { fatalError("\(operationName): could not compile fragment function \(fragmentFunctionName)") } let descriptor = MTLRenderPipelineDescriptor() descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm descriptor.sampleCount = 1 descriptor.vertexFunction = vertexFunction descriptor.fragmentFunction = fragmentFunction do { return try device.device.makeRenderPipelineState(descriptor: descriptor) } catch { fatalError("\(operationName): could not create render pipeline state") } }
0
// // ViewController.swift // SimonSaysLab // // Created by James Campagno on 5/31/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit /* TODO: - gameWon() isnt triggering, so either the color isnt being registered/received or the colors arent connect to send - FIXED^^^ Need to put the condition to check for each buttons. - Find out which ibaction func to dump these under, either the viewdidLoad or the gamestarttapped. - FIXED^^^ - Need to refactor a bit and have a restart button that clears everything as well as have a loss conditional to trigger. */ class ViewController: UIViewController { @IBOutlet weak var displayColorView: UIView! @IBOutlet weak var startGameButton: UIButton! @IBOutlet weak var winLabel: UILabel! var simonSaysGame = SimonSays() var buttonsClicked = 0 override func viewDidLoad() { super.viewDidLoad() hideInitially() } @IBAction func redButton(_ sender: UIButton) { simonSaysGame.guessRed() buttonsClicked += 1 print("\(buttonsClicked) || Touched Red") checkCondition() } @IBAction func greenButton(_ sender: UIButton) { simonSaysGame.guessGreen() buttonsClicked += 1 print("\(buttonsClicked) || Touched Green") checkCondition() } @IBAction func yellowButton(_ sender: UIButton) { simonSaysGame.guessYellow() buttonsClicked += 1 print("\(buttonsClicked) || Touched Yellow") checkCondition() } @IBAction func blueButton(_ sender: UIButton) { simonSaysGame.guessBlue() buttonsClicked += 1 print("\(buttonsClicked) || Touched Blue") checkCondition() } func hideInitially() { winLabel.isHidden = true displayColorView.isHidden = true } func revealNow() { winLabel.isHidden = false displayColorView.isHidden = false } func checkCondition() { if simonSaysGame.wonGame() { print("Conditions fulfilled, game won") winLabel.text = "You Won!" } } func restart() { if winLabel.text == "You Won!" { buttonsClicked = 0 // displayTheColors() winLabel.text = "Game On!" } } } // MARK: - SimonSays Game Methods extension ViewController { @IBAction func startGameTapped(_ sender: UIButton) { UIView.transition(with: startGameButton, duration: 0.9, options: .transitionFlipFromBottom , animations: { self.startGameButton.isHidden = true }, completion: nil) displayTheColors() } fileprivate func displayTheColors() { self.view.isUserInteractionEnabled = false UIView.transition(with: displayColorView, duration: 1.5, options: .transitionCurlUp, animations: { self.displayColorView.backgroundColor = self.simonSaysGame.nextColor()?.colorToDisplay self.displayColorView.alpha = 0.0 self.displayColorView.alpha = 1.0 }, completion: { _ in if !self.simonSaysGame.sequenceFinished() { self.displayTheColors() } else { self.view.isUserInteractionEnabled = true print("Pattern to match: \(self.simonSaysGame.patternToMatch)") } }) } }
0
// RUN: %target-typecheck-verify-swift // REQUIRES: concurrency // Make sure the import succeeds import _Concurrency // Make sure the type shows up (including under its old name, for // short-term source compatibility) @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension PartialAsyncTask { } @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) extension UnownedJob { }
0
import NinetyNineSwiftProblems import SolutionTester extension SolutionTester { // P10 (*) Run-length encoding of a list. func testP10() { Test("Run-length encoding of a list") { assertEquals( List("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e").encode().description, List((4, "a"), (1, "b"), (2, "c"), (2, "a"), (1, "d"), (4, "e")).description ) assertEquals( List(1, 1, 2, 3, 5, 8).encode().description, List((2, 1), (1, 2), (1, 3), (1, 5), (1, 8)).description ) assertEquals(List("a").encode().description, List((1, "a")).description) } } }
0
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import XCTest @testable import VCNetworking class StringTests: XCTestCase { func testNormalString() throws { let actualString = "https://test.com/xyz" XCTAssertEqual(actualString, actualString.stringByAddingPercentEncodingForRFC3986()!) } func testStringWithSpaces() throws { let actualString = "https://test.com/x y z" XCTAssertEqual(actualString.stringByAddingPercentEncodingForRFC3986()!, "https://test.com/x%20y%20z") } func testAlreadyPercentEncodedString() throws { let actualString = "https://test.com/x%20y%20z" XCTAssertEqual(actualString.stringByAddingPercentEncodingForRFC3986()!, "https://test.com/x%20y%20z") } }
0
// // MineOfferModel.swift // Rencaiyoujia // // Created by zhangyu on 2020/1/15. // Copyright © 2020 zhangyu. All rights reserved. // import UIKit import ObjectMapper class MineOfferModel: NSObject,Mappable { var id:Int? var companyId:Int? var companyName:String? var jobName:String? var workyears:String? var interviewTime:String? var sjScore:Int? var applyId:Int? var acceptState:Int? var contate:String? var phone:String? var attention:String? required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] companyId <- map["companyId"] companyName <- map["companyName"] jobName <- map["jobName"] workyears <- map["workyears"] interviewTime <- map["interviewTime"] sjScore <- map["sjScore"] applyId <- map["applyId"] acceptState <- map["acceptState"] contate <- map["contate"] phone <- map["phone"] attention <- map["attention"] } }
0
// // SPWindowController.swift // Sequel Ace // // Created by Jakub Kašpar on 24.01.2021. // Copyright © 2020-2022 Sequel-Ace. All rights reserved. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // // More info at <https://github.com/Sequel-Ace/Sequel-Ace> import Cocoa import SnapKit @objc final class SPWindowController: NSWindowController { @objc lazy var databaseDocument: SPDatabaseDocument = SPDatabaseDocument(windowController: self) @objc let uniqueID: UUID = UUID() override func awakeFromNib() { super.awakeFromNib() if let window = window { window.collectionBehavior = [window.collectionBehavior, .fullScreenPrimary] } setupAppearance() } // MARK: - Accessory private lazy var tabAccessoryView: SPWindowTabAccessory = SPWindowTabAccessory() deinit { print("Deinit called") } } // MARK: - Private API private extension SPWindowController { func setupAppearance() { databaseDocument.updateWindowTitle(self) window?.contentView?.addSubview(databaseDocument.databaseView()) databaseDocument.databaseView()?.frame = window?.contentView?.frame ?? NSRect(x: 0, y: 0, width: 800, height: 400) if #available(macOS 10.13, *) { window?.tab.accessoryView = tabAccessoryView } } } // MARK: - Public API @objc extension SPWindowController { func updateWindow(title: String, tabTitle: String) { window?.title = title if #available(macOS 10.13, *) { window?.tab.title = tabTitle } tabAccessoryView.setTitle(title: tabTitle) } func updateWindowAccessory(color: NSColor?, isSSL: Bool) { tabAccessoryView.update(color: color, isSSL: isSSL) } } extension SPWindowController: NSWindowDelegate { public func windowShouldClose(_ sender: NSWindow) -> Bool { if !databaseDocument.parentTabShouldClose() { return false } if let appDelegate = NSApp.delegate as? SPAppController{ appDelegate.setSpfSessionDocData(nil) } return true } func windowWillClose(_ notification: Notification) { // Tell listeners that this database document is being closed - fixes retain cycles and allows cleanup NotificationCenter.default.post(name: NSNotification.Name.SPDocumentWillClose, object: databaseDocument) } }
0
// // Stack.swift // Calculator // // Created by klwx on 2017/9/20. // Copyright © 2017年 wufan. All rights reserved. // import UIKit class Stack: NSObject { // 是否为空(默认为空) var isEmpty: Bool { get { if stackArray.count == 0 { return true } else { return false } } } // 栈的长度 var stackLength: Int { get { return stackArray.count } } // 保存元素的数组 private var stackArray: [Any] = [] //MARK - func // 初始化 // 入栈 func push(object: Any) -> Void { stackArray.append(object) } // 出栈 func pop() -> Any? { let object = topObject() stackArray.removeLast() return object } // 返回栈顶元素 func topObject() -> Any? { return stackArray.last } // 清空栈 func removeStack() -> Void { stackArray.removeAll() } }
0
//////////////////////////////////////////////////////////////////////////////// // Throw and Catch enum PrinterError: Error { case NoPaper case OutOfService } func doPrint() throws { throw PrinterError.NoPaper } do { try doPrint() } catch PrinterError.NoPaper { print("No paper") } catch { print("Printer has other error") } //////////////////////////////////////////////////////////////////////////////// // Another Full Example enum VendingMachineError: Error { case InvalidSelection case InsufficientFunds(coinsNeeded: Int) case OutOfStock } struct Item { var price: Int var count: Int } class VendingMachine { var inventroy = [ "Candy Bar": Item(price: 4, count: 3), "Chips": Item(price: 3, count: 4) ] var coinsDepoisted = 0 func dispenceSnack(_ name: String) { print("Despencing \(name)") } func vend(itemNamed name: String) throws { guard let item = inventroy[name] else { throw VendingMachineError.InvalidSelection } guard item.count > 0 else { throw VendingMachineError.OutOfStock } guard item.price <= coinsDepoisted else { throw VendingMachineError.InsufficientFunds( coinsNeeded: item.price - coinsDepoisted) } dispenceSnack(name) coinsDepoisted -= item.price var newItem = item newItem.count -= 1 inventroy[name] = newItem } } var vendingMachine = VendingMachine() do { try vendingMachine.vend(itemNamed: "Chips") } catch VendingMachineError.InvalidSelection { print("Invalied seleciton.") } catch VendingMachineError.InsufficientFunds(let coinsNeeded) { print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.") } catch VendingMachineError.OutOfStock { print("Out of stock..") } //////////////////////////////////////////////////////////////////////////////// // Converting Errors to Optional Values func someThrowingFuction() throws -> Int { return 0 } let x = try? someThrowingFuction() var y: Int? = nil do { y = try someThrowingFuction() } catch { y = nil } //////////////////////////////////////////////////////////////////////////////// // Specifying Cleanup Actions // Use a defer statement to execute a set of statements // just before code execution leaves the current block of code. // Note: not when leave current function // Use defer could put some pairs of code together, e.g., open/close. class File {} func openFile(_ name: String) -> File { print("Open file \(name)") return File() } func closeFile(_ name: String) { print("Close file \(name)") } func exists(_ name: String) -> Bool { return true } func processFile(_ name: String) { if exists(name) { let file = openFile(name) defer { closeFile(name) } print("- Will leave the block of defer.") } print("- After leave the block of defer.") } processFile("test.txt") //////////////////////////////////////////////////////////////////////////////// // Assert // When to use assertions? // When a condition has the potential to be false, but must definitely be true. // Suitable scenarios for an assertion check include: // Array's index is out of range. // Invalid parameter for a function. // An optional variant must have non-nil value. // Assertions only work in debug mode. // In debug mode, if an assertion failed, App will stop at it. // In release mode, if an assertion failed, App will just terminate. let age = -3 //assert(age >= 0, "Age can't be negative.") // This assert will fail func lookforSomething(_ name:String) throws{ //这里是作用域1 整个函数作用域 print("1-1") if name == ""{ //这里是作用域2 if的作用域 print("2-1") defer{ print("2-2") } print("2-3") } print("1-2") defer{ print("1-3") } print("1-4") if name == "hello"{ //作用域3 print("3-1") defer{ print("3-2") } print("3-3") defer{ print("3-4") } } } //有兴趣的看看依次输出什么 //try! lookforSomething("") //调出 debug Area 快捷键 shift+ command + y try! lookforSomething("hello")
0
// // Tweet.swift // Twitter // // Created by Fiona Thompson on 2/27/17. // Copyright © 2017 Fiona Thompson. All rights reserved. // import UIKit class Tweet: NSObject { var profileUrl: URL? var text : String? var user: User? var timestamp : Date? var retweetCount : Int = 0 var favoriteCount: Int = 0 init(dictionary: NSDictionary){ text = dictionary["text"] as? String retweetCount = (dictionary["retweet_count"] as? Int) ?? 0 favoriteCount = (dictionary["favourites_count"] as? Int) ?? 0 let timeStampString = dictionary["created_at"] as? String if let timeStampString = timeStampString{ let formatter = DateFormatter() formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" timestamp = formatter.date(from: timeStampString) } let profileUrlString = (dictionary["user"] as! NSDictionary)["profile_image_url_https"] as? String if let profileUrlString = profileUrlString { profileUrl = URL(string: profileUrlString) } user = User(dictionary: dictionary["user"] as! NSDictionary) } class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet]{ var tweets = [Tweet]() for dictionary in dictionaries{ let tweet = Tweet(dictionary: dictionary) tweets.append(tweet) } return tweets } }
0
import UIKit public typealias UCollectionView = CollectionView open class CollectionView: UICollectionView, AnyDeclarativeProtocol, DeclarativeProtocolInternal { public var declarativeView: CollectionView { self } public lazy var properties = Properties<CollectionView>() lazy var _properties = PropertiesInternal() @UState public var height: CGFloat = 0 @UState public var width: CGFloat = 0 @UState public var top: CGFloat = 0 @UState public var leading: CGFloat = 0 @UState public var left: CGFloat = 0 @UState public var trailing: CGFloat = 0 @UState public var right: CGFloat = 0 @UState public var bottom: CGFloat = 0 @UState public var centerX: CGFloat = 0 @UState public var centerY: CGFloat = 0 var __height: UState<CGFloat> { _height } var __width: UState<CGFloat> { _width } var __top: UState<CGFloat> { _top } var __leading: UState<CGFloat> { _leading } var __left: UState<CGFloat> { _left } var __trailing: UState<CGFloat> { _trailing } var __right: UState<CGFloat> { _right } var __bottom: UState<CGFloat> { _bottom } var __centerX: UState<CGFloat> { _centerX } var __centerY: UState<CGFloat> { _centerY } var scrollPosition: UState<CGPoint>? public static var defaultLayout: UICollectionViewFlowLayout { return CollectionViewFlowLayout().itemSize(50).minimumInteritemSpacing(5).minimumLineSpacing(5) } public convenience init (_ layout: UICollectionViewLayout) { self.init(frame: .zero, collectionViewLayout: layout) } public convenience init () { self.init(frame: .zero, collectionViewLayout: CollectionView.defaultLayout) } public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) translatesAutoresizingMaskIntoConstraints = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() onLayoutSubviews() } open override func didMoveToSuperview() { super.didMoveToSuperview() movedToSuperview() } // MARK: Keyboard Dismiss Mode @discardableResult public func keyboardDismissMode(_ mode: UIScrollView.KeyboardDismissMode) -> Self { keyboardDismissMode = mode return self } // MARK: - Refresh Control #if !os(tvOS) @discardableResult public func refreshControl(_ refreshControl: UIRefreshControl) -> Self { if #available(iOS 10.0, *) { self.refreshControl = refreshControl } else { addSubview(refreshControl) } return self } #endif // MARK: ContentInsetAdjustment @discardableResult public func contentInsetAdjustment(_ mode: ContentInsetAdjustment) -> Self { if #available(iOS 11.0, *) { guard let mode = ContentInsetAdjustmentBehavior(rawValue: mode.rawValue) else { return self } contentInsetAdjustmentBehavior = mode } return self } // MARK: Paging #if !os(tvOS) @discardableResult public func paging(_ enabled: Bool) -> Self { isPagingEnabled = enabled return self } #endif // MARK: Scrolling @discardableResult public func scrolling(_ enabled: Bool) -> Self { isScrollEnabled = enabled return self } // MARK: Indicators @discardableResult public func hideIndicator(_ indicators: NSLayoutConstraint.Axis...) -> Self { if indicators.contains(.horizontal) { showsHorizontalScrollIndicator = false } if indicators.contains(.vertical) { showsVerticalScrollIndicator = false } return self } // MARK: Indicators @discardableResult public func hideAllIndicators() -> Self { showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false return self } // MARK: Content Inset @discardableResult public func contentInset(_ insets: UIEdgeInsets) -> Self { contentInset = insets return self } @discardableResult public func contentInset(top: CGFloat = 0, left: CGFloat = 0, right: CGFloat = 0, bottom: CGFloat = 0) -> Self { contentInset(.init(top: top, left: left, bottom: bottom, right: right)) } // MARK: Scroll Indicator Inset @discardableResult public func scrollIndicatorInsets(_ insets: UIEdgeInsets) -> Self { scrollIndicatorInsets = insets return self } @discardableResult public func scrollIndicatorInsets(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Self { scrollIndicatorInsets(.init(top: top, left: left, bottom: bottom, right: right)) } // MARK: Delegate @discardableResult public func delegate(_ delegate: UICollectionViewDelegate) -> Self { self.delegate = delegate return self } // MARK: Delegate @discardableResult public func dataSource(_ dataSource: UICollectionViewDataSource) -> Self { self.dataSource = dataSource return self } } extension CollectionView: UIScrollViewDelegate { @discardableResult public func contentOffset(_ position: CGPoint, animated: Bool = true) -> Self { setContentOffset(position, animated: animated) return self } @discardableResult public func scrollPosition(_ binding: UIKitPlus.UState<CGPoint>) -> Self { scrollPosition = binding return self } @discardableResult public func scrollPosition<V>(_ expressable: ExpressableState<V, CGPoint>) -> Self { scrollPosition = expressable.unwrap() return self } public func scrollViewDidScroll(_ scrollView: UIScrollView) { scrollPosition?.wrappedValue = scrollView.contentOffset } }