label
int64
0
1
text
stringlengths
0
2.8M
0
import Foundation extension Conference { // TODO: componentize with Speaker public struct Staff: Codable, CustomStringConvertible, Equatable, Hashable { private enum CodingKeys: String, CodingKey { case id case nickname case firstname = "first_name" case lastname = "last_name" case avatarURL = "avatar_url" } public let id: String public let nickname: String public let firstname: String? public let lastname: String? public let avatarURL: URL public var description: String { return "Staff(id: \(id), nickname: \(nickname), firstname: \(firstname.debugDescription), " + "lastname: \(lastname.debugDescription), avatarURL: \(avatarURL))" } public var hashValue: Int { return id.hashValue } } }
0
// // CompleteStr.swift // Leet // // Created by 58 on 2021/10/28. // import Cocoa class CompleteStr: NSObject { static func strStr(_ haystack: String, _ needle: String) -> Int { if needle.count == 0 { return 0 } else if haystack.count == 0 { return -1 } else if needle.count > haystack.count { return -1 }else if needle.count == haystack.count { if needle == haystack { return 0 } return -1 } for i in 0 ... haystack.count - needle.count { let startIndex = haystack.index(haystack.startIndex, offsetBy: i) let endIndex = haystack.index(startIndex, offsetBy: needle.count) let str = haystack[startIndex ..< endIndex] if str == needle { return i } } return -1 } }
0
// Copyright 2020 Espressif Systems // // 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. // // ParamDropDownTableViewCell.swift // ESPRainMaker // import DropDown import UIKit class ParamDropDownTableViewCell: DropDownTableViewCell { override func layoutSubviews() { super.layoutSubviews() // Customise dropdown element for param screen // Hide row selection button checkButton.isHidden = true leadingSpaceConstraint.constant = 15.0 trailingSpaceConstraint.constant = 15.0 backgroundColor = UIColor.clear backView.layer.borderWidth = 1 backView.layer.cornerRadius = 10 backView.layer.borderColor = UIColor.clear.cgColor backView.layer.masksToBounds = true layer.shadowOpacity = 0.18 layer.shadowOffset = CGSize(width: 1, height: 2) layer.shadowRadius = 2 layer.shadowColor = UIColor.black.cgColor layer.masksToBounds = false } @IBAction override func dropDownButtonTapped(_: Any) { // Configuring dropdown attributes DropDown.appearance().backgroundColor = UIColor.white DropDown.appearance().selectionBackgroundColor = #colorLiteral(red: 0.04705882353, green: 0.4392156863, blue: 0.9098039216, alpha: 1) let dropDown = DropDown() dropDown.dataSource = datasource dropDown.width = UIScreen.main.bounds.size.width - 100 dropDown.anchorView = self dropDown.show() // Selecting param value in dropdown list if let index = datasource.firstIndex(where: { $0 == currentValue }) { dropDown.selectRow(at: index) } // Assigning action for dropdown item selection dropDown.selectionAction = { [unowned self] (_: Int, item: String) in if self.param.dataType?.lowercased() == "string" { DeviceControlHelper.updateParam(nodeID: self.device.node?.node_id, parameter: [self.device.name ?? "": [self.param.name ?? "": item]], delegate: paramDelegate) param.value = item } else { DeviceControlHelper.updateParam(nodeID: self.device.node?.node_id, parameter: [self.device.name ?? "": [self.param.name ?? "": Int(item)]], delegate: paramDelegate) param.value = Int(item) } currentValue = item DispatchQueue.main.async { controlValueLabel.text = item } } } }
0
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -I %S/Inputs/custom-modules %s | FileCheck %s // REQUIRES: objc_interop import nullability // null_resettable properties. // CHECK-LABEL: sil hidden @_TF18nullability_silgen18testNullResettable func testNullResettable(sc: SomeClass) { sc.defaultedProperty = nil sc.defaultedProperty = "hello" let str: String = sc.defaultedProperty if sc.defaultedProperty == nil { } } func testFunnyProperty(sc: SomeClass) { sc.funnyProperty = "hello" var str: String = sc.funnyProperty }
0
/// DefaultTapTableCell wraps a default table view /// /// - version: 1.8.0 /// - date: 04/05/22 /// - author: Adamas public final class DefaultTapTableCell: TapTableCell<DefaultTapView, DefaultTapRow> {}
0
// // TweetDetailViewController.swift // Titter // // Created by Karan Khurana on 7/31/16. // Copyright © 2016 Karan Khurana. All rights reserved. // import UIKit class TweetDetailViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var tweetUserLabel: UILabel! @IBOutlet weak var tweetScreenNameLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var timeStampLabel: UILabel! @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var likesCountLabel: UILabel! @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var replyButton: UIButton! var tweet: Tweet! var liked: Bool = false var retweeted: Bool = false let likeImageON = UIImage(named: "like-action-on") let likeImageOff = UIImage(named: "like-action-pressed") let retweetImageON = UIImage(named: "retweet-action-on") let retweetImageOff = UIImage(named: "retweet-action-pressed") override func viewDidLoad() { super.viewDidLoad() profileImageView.layer.cornerRadius = 3 profileImageView.clipsToBounds = true profileImageView.setImageWithURL(tweet.user.profileURL!) tweetUserLabel.text = tweet.user.name as? String tweetScreenNameLabel.text = tweet.user.screenname as? String tweetTextLabel.text = tweet.text as? String let formatter = NSDateFormatter() formatter.dateFormat = "M/dd/yy hh:mm a" timeStampLabel.text = formatter.stringFromDate(tweet.timestamp!) retweetCountLabel.text = String(tweet.retweetCount) likesCountLabel.text = String(tweet.favoritesCount) if tweet.isFavorite { liked = true likeButton.setImage(likeImageON, forState: .Normal) } else { liked = false } if tweet.isRetweeted{ retweeted = true retweetButton.setImage(retweetImageON, forState: .Normal) } else { retweeted = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didPressLikeButton(sender: AnyObject) { if liked { liked = false likeButton.setImage(likeImageOff, forState: .Normal) TwitterClient.sharedInstance.removeFavorite(tweet.id) } else { liked = true likeButton.setImage(likeImageON, forState: .Normal) TwitterClient.sharedInstance.addFavorite(tweet.id) } } @IBAction func didPressRetweetButton(sender: AnyObject) { if retweeted { retweeted = false retweetButton.setImage(retweetImageOff, forState: .Normal) TwitterClient.sharedInstance.unReTweet(tweet.id) } else { retweeted = true retweetButton.setImage(retweetImageON, forState: .Normal) print(tweet.id) TwitterClient.sharedInstance.reTweet(tweet.id) } } @IBAction func didTapProfileImage(sender: UITapGestureRecognizer) { print("tapped") self.performSegueWithIdentifier("TweetToProfile", sender: self) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let profileViewController = segue.destinationViewController as! ProfileViewController profileViewController.senderTweet = tweet } }
0
// // NeonAnchorable.swift // Neon // // Created by Mike on 10/1/15. // Copyright © 2015 Mike Amaral. All rights reserved. // #if os(iOS) import UIKit #else import Cocoa #endif public protocol Anchorable : Frameable {} public extension Anchorable { /// Fill the superview, with optional padding values. /// /// - note: If you don't want padding, simply call `fillSuperview()` with no parameters. /// /// - parameters: /// - left: The padding between the left side of the view and the superview. /// /// - right: The padding between the right side of the view and the superview. /// /// - top: The padding between the top of the view and the superview. /// /// - bottom: The padding between the bottom of the view and the superview. /// @discardableResult public func fillSuperview(left: CGFloat = 0, right: CGFloat = 0, top: CGFloat = 0, bottom: CGFloat = 0) -> Self { let width : CGFloat = superFrame.width - (left + right) let height : CGFloat = superFrame.height - (top + bottom) frame = CGRect(x: left, y: top, width: width, height: height) return self } @discardableResult public func fillSuperview(insets: UIEdgeInsets) -> Self { return fillSuperview(left: insets.left, right: insets.right, top: insets.top, bottom: insets.bottom) } @discardableResult public func fillSuperview(horizontal: CGFloat) -> Self { return fillSuperview(left: horizontal, right: horizontal) } @discardableResult public func fillSuperview(vertical: CGFloat) -> Self { return fillSuperview(top: vertical, bottom: vertical) } /// Anchor a view in the center of its superview. /// /// - parameters: /// - width: The width of the view. /// /// - height: The height of the view. /// @discardableResult public func anchorInCenter(width: CGFloat = AutoWidth, height: CGFloat = AutoHeight) -> Self { let xOrigin : CGFloat = (superFrame.width / 2.0) - (width / 2.0) let yOrigin : CGFloat = (superFrame.height / 2.0) - (height / 2.0) frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height) if height == AutoHeight { setDimensionAutomatically() .anchorInCenter(width: width, height: self.height) } if width == AutoWidth { setDimensionAutomatically() .anchorInCenter(width: self.width, height: height) } return self } @discardableResult public func anchorInCenter(size: CGSize) -> Self { return anchorInCenter(width: size.width, height: size.height) } /// Anchor a view in one of the four corners of its superview. /// /// - parameters: /// - corner: The `CornerType` value used to specify in which corner the view will be anchored. /// /// - xPad: The *horizontal* padding applied to the view inside its superview, which can be applied /// to the left or right side of the view, depending upon the `CornerType` specified. /// /// - yPad: The *vertical* padding applied to the view inside its supeview, which will either be on /// the top or bottom of the view, depending upon the `CornerType` specified. /// /// - width: The width of the view. /// /// - height: The height of the view. /// @discardableResult public func anchorInCorner(_ corner: Corner = .topLeft, xPad: CGFloat = 0.0, yPad: CGFloat = 0.0, width: CGFloat = AutoWidth, height: CGFloat = AutoHeight) -> Self { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch corner { case .topLeft: xOrigin = xPad yOrigin = yPad case .bottomLeft: xOrigin = xPad yOrigin = superFrame.height - height - yPad case .topRight: xOrigin = superFrame.width - width - xPad yOrigin = yPad case .bottomRight: xOrigin = superFrame.width - width - xPad yOrigin = superFrame.height - height - yPad } frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height) if height == AutoHeight { setDimensionAutomatically() .anchorInCorner(corner, xPad: xPad, yPad: yPad, width: width, height: self.height) } if width == AutoWidth { setDimensionAutomatically() .anchorInCorner(corner, xPad: xPad, yPad: yPad, width: self.width, height: height) } return self } @discardableResult public func anchorInCorner(_ corner: Corner, padding: CGPoint, size: CGSize) -> Self { return anchorInCorner(corner, xPad: padding.x, yPad: padding.y, width: size.width, height: size.height) } /// Anchor a view in its superview, centered on a given edge. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against and centered relative to. /// /// - padding: The padding applied to the view inside its superview. How this padding is applied /// will vary depending on the `Edge` provided. Views centered against the top or bottom of /// their superview will have the padding applied above or below them respectively, whereas views /// centered against the left or right side of their superview will have the padding applied to the /// right and left sides respectively. /// /// - width: The width of the view. /// /// - height: The height of the view. /// @discardableResult public func anchorToEdge(_ edge: Edge = .left, padding: CGFloat, width: CGFloat, height: CGFloat) -> Self { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 switch edge { case .top: xOrigin = (superFrame.width / 2.0) - (width / 2.0) yOrigin = padding case .left: xOrigin = padding yOrigin = (superFrame.height / 2.0) - (height / 2.0) case .bottom: xOrigin = (superFrame.width / 2.0) - (width / 2.0) yOrigin = superFrame.height - height - padding case .right: xOrigin = superFrame.width - width - padding yOrigin = (superFrame.height / 2.0) - (height / 2.0) } frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height) if height == AutoHeight { setDimensionAutomatically() .anchorToEdge(edge, padding: padding, width: width, height: self.height) } if width == AutoWidth { setDimensionAutomatically() .anchorToEdge(edge, padding: padding, width: self.width, height: height) } return self } @discardableResult public func anchorToEdge(_ edge: Edge, padding: CGFloat, size: CGSize) -> Self { return anchorToEdge(edge, padding: padding, width: size.width, height: size.height) } /// Anchor a view in its superview, centered on a given edge and filling either the width or /// height of that edge. For example, views anchored to the `.Top` or `.Bottom` will have /// their widths automatically sized to fill their superview, with the xPad applied to both /// the left and right sides of the view. /// /// - parameters: /// - edge: The `Edge` used to specify which face of the superview the view /// will be anchored against, centered relative to, and expanded to fill. /// /// - xPad: The horizontal padding applied to the view inside its superview. If the `Edge` /// specified is `.Top` or `.Bottom`, this padding will be applied to the left and right sides /// of the view when it fills the width superview. /// /// - yPad: The vertical padding applied to the view inside its superview. If the `Edge` /// specified is `.Left` or `.Right`, this padding will be applied to the top and bottom sides /// of the view when it fills the height of the superview. /// /// - otherSize: The size parameter that is *not automatically calculated* based on the provided /// edge. For example, views anchored to the `.Top` or `.Bottom` will have their widths automatically /// calculated, so `otherSize` will be applied to their height, and subsequently views anchored to /// the `.Left` and `.Right` will have `otherSize` applied to their width as their heights are /// automatically calculated. /// @discardableResult public func anchorAndFillEdge(_ edge: Edge, xPad: CGFloat, yPad: CGFloat, otherSize: CGFloat) -> Self { var xOrigin : CGFloat = 0.0 var yOrigin : CGFloat = 0.0 var width : CGFloat = 0.0 var height : CGFloat = 0.0 var autoSize : Bool = false switch edge { case .top: xOrigin = xPad yOrigin = yPad width = superFrame.width - (2 * xPad) height = otherSize autoSize = true case .left: xOrigin = xPad yOrigin = yPad width = otherSize height = superFrame.height - (2 * yPad) case .bottom: xOrigin = xPad yOrigin = superFrame.height - otherSize - yPad width = superFrame.width - (2 * xPad) height = otherSize autoSize = true case .right: xOrigin = superFrame.width - otherSize - xPad yOrigin = yPad width = otherSize height = superFrame.height - (2 * yPad) } frame = CGRect(x: xOrigin, y: yOrigin, width: width, height: height) if height == AutoHeight && autoSize { setDimensionAutomatically() .anchorAndFillEdge(edge, xPad: xPad, yPad: yPad, otherSize: self.height) } return self } @discardableResult public func anchorAndFillEdge(_ edge: Edge, padding: CGFloat, otherSize: CGFloat) -> Self { return anchorAndFillEdge(edge, xPad: padding, yPad: padding, otherSize: otherSize) } }
0
// // FormError.swift // TasCar // // Created by Enrique Republic on 01/08/2019. // Copyright © 2019 Enrique Canedo. All rights reserved. // import UIKit enum FormError: LocalizedError { case emptyBrand, unknown var errorDescription: String? { switch self { case .emptyBrand: return "no_brand_selected".localized case .unknown: return "unknown".localized } } }
0
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import SwiftUI import UIKit extension Color { static let tertiaryBackground = Color( UIColor( dynamicProvider: { switch $0.userInterfaceStyle { case .dark: return .tertiarySystemGroupedBackground default: return .secondarySystemGroupedBackground } } ) ) static let quaternaryBackground = Color( UIColor( dynamicProvider: { switch $0.userInterfaceStyle { case .dark: return .quaternarySystemFill default: return .tertiarySystemGroupedBackground } } ) ) }
0
// // MDCourseCoreDataStorage_Tests.swift // MyDictionary_App_SwiftTests // // Created by Dmytro Chumakov on 24.08.2021. // import XCTest @testable import MyDictionary_App_Swift final class MDCourseCoreDataStorage_Tests: XCTestCase { fileprivate var courseCoreDataStorage: MDCourseCoreDataStorageProtocol! override func setUpWithError() throws { try super.setUpWithError() let coreDataStack: MDCoreDataStack = TestCoreDataStack() let courseCoreDataStorage: MDCourseCoreDataStorageProtocol = MDCourseCoreDataStorage.init(operationQueue: Constants_For_Tests.operationQueueManager.operationQueue(byName: MDConstants.QueueName.courseCoreDataStorageOperationQueue)!, managedObjectContext: coreDataStack.privateContext, coreDataStack: coreDataStack) self.courseCoreDataStorage = courseCoreDataStorage } } extension MDCourseCoreDataStorage_Tests { func test_Create_Course_Functionality() { let expectation = XCTestExpectation(description: "Create Course Expectation") courseCoreDataStorage.createCourse(Constants_For_Tests.mockedCourse) { createResult in switch createResult { case .success(let courseEntity): XCTAssertTrue(courseEntity.userId == Constants_For_Tests.mockedCourse.userId) XCTAssertTrue(courseEntity.courseId == Constants_For_Tests.mockedCourse.courseId) XCTAssertTrue(courseEntity.languageId == Constants_For_Tests.mockedCourse.languageId) XCTAssertTrue(courseEntity.languageName == Constants_For_Tests.mockedCourse.languageName) XCTAssertTrue(courseEntity.createdAt == Constants_For_Tests.mockedCourse.createdAt) expectation.fulfill() case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout) } func test_Create_Courses_Functionality() { let expectation = XCTestExpectation(description: "Create Courses Expectation") courseCoreDataStorage.createCourses(Constants_For_Tests.mockedCourses) { createResult in switch createResult { case .success(let courseEntities): XCTAssertTrue(courseEntities.count == Constants_For_Tests.mockedCourses.count) expectation.fulfill() case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout) } func test_Read_Course_Functionality() { let expectation = XCTestExpectation(description: "Read Course Expectation") courseCoreDataStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in switch createResult { case .success(let createCourseEntity): courseCoreDataStorage.readCourse(fromCourseId: createCourseEntity.courseId) { readResult in switch readResult { case .success(let readCourseEntity): XCTAssertTrue(readCourseEntity.userId == createCourseEntity.userId) XCTAssertTrue(readCourseEntity.courseId == createCourseEntity.courseId) XCTAssertTrue(readCourseEntity.languageId == createCourseEntity.languageId) XCTAssertTrue(readCourseEntity.languageName == createCourseEntity.languageName) XCTAssertTrue(readCourseEntity.createdAt == createCourseEntity.createdAt) expectation.fulfill() case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout) } func test_Delete_Course_Functionality() { let expectation = XCTestExpectation(description: "Delete Course Expectation") courseCoreDataStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in switch createResult { case .success(let createCourseEntity): courseCoreDataStorage.deleteCourse(fromCourseId: createCourseEntity.courseId) { deleteResult in switch deleteResult { case .success: expectation.fulfill() case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout) } func test_Delete_All_Courses_Functionality() { let expectation = XCTestExpectation(description: "Delete All Courses Expectation") courseCoreDataStorage.createCourse(Constants_For_Tests.mockedCourse) { [unowned self] createResult in switch createResult { case .success: courseCoreDataStorage.deleteAllCourses() { deleteResult in switch deleteResult { case .success: expectation.fulfill() case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } case .failure(let error): XCTExpectFailure(error.localizedDescription) expectation.fulfill() } } wait(for: [expectation], timeout: Constants_For_Tests.testExpectationTimeout) } }
0
// // DeviceDetailBorrow.swift // TAC-DM // // Created by Harold Liu on 8/20/15. // Copyright (c) 2015 TAC. All rights reserved. // import UIKit class DeviceDetailBorrow:UIViewController , UITextFieldDelegate , UIAlertViewDelegate, DMDelegate { var borrowDeviceName:String? var borrowDeviceID:String? var borrowDeviceDescription:String? var dmModel:DatabaseModel! @IBOutlet weak var deviceName: UILabel! @IBOutlet weak var nameText: UITextField! @IBOutlet weak var phoneText: UITextField! @IBOutlet weak var submitButton: UIButton! override func viewDidLoad() { super.viewDidLoad() configureUI() deviceName.text = borrowDeviceName dmModel = DatabaseModel.getInstance() dmModel.delegate = self } func configureUI () { UIGraphicsBeginImageContext(self.view.frame.size) UIImage(named: "device background")?.drawInRect(self.view.bounds) let image :UIImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() self.view.backgroundColor = UIColor(patternImage: image) self.submitButton.layer.cornerRadius = 8.0 self.nameText.delegate = self self.phoneText.delegate = self } // MARK:- Keyboard Dismiss override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let _ = touches.first{ self.view.endEditing(true) } super.touchesBegan(touches , withEvent:event) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func backAction(sender: AnyObject) { SVProgressHUD.dismiss() self.navigationController?.popViewControllerAnimated(true) } @IBAction func submitAction() { let alertVC:UIAlertController //input judge with regex if (nameText.text!.isName() && phoneText.text!.isNumber()) { alertVC = UIAlertController(title: "确认信息", message: "姓名: \(nameText.text!) \n 联系方式: \(phoneText.text!) \n 所借物品: \(borrowDeviceName!)", preferredStyle: UIAlertControllerStyle.Alert) alertVC.addAction(UIAlertAction(title: "确认信息", style: UIAlertActionStyle.Default, handler: dealConfirmAction)) alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)) } else { alertVC = UIAlertController(title: "请输入正确的信息", message: nil, preferredStyle: .Alert) alertVC.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) } self.presentViewController(alertVC, animated: true, completion: nil) } func dealConfirmAction (alert:UIAlertAction!) { dmModel.borrowItem(nameText.text!, tele: phoneText.text!, itemId: borrowDeviceID!, itemName: borrowDeviceName!, itemDescription: borrowDeviceDescription!, number: 1) SVProgressHUD.show() } func getRequiredInfo(Info: String) { //设备借阅成功或者失败给出反馈 print("借设备时得到的服务器返回值: \(Info)") switch Info { case "1": print("借设备成功") SVProgressHUD.showSuccessWithStatus("Now you can take the device with you", maskType: .Black) (tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true) case "0": print("借设备失败") SVProgressHUD.showErrorWithStatus("Sorry,there are some troubles,please contact with TAC member", maskType: .Black) default: print("device borrow other:\(Info)") } } }
0
// // ModuleContextGenerator.swift // // // Created by Alexander Filimonov on 13/03/2020. // /// Protocol for generalizing modules that can generate contexts public protocol ModuleContextGenerator { func generate() throws -> [FileContext] }
0
// // Randomizable.swift // Splashy // // Created by Pedro Carrasco on 03/03/18. // Copyright © 2018 Pedro Carrasco. All rights reserved. // import UIKit protocol Randomizable { static func random() -> CGFloat static func randomBetween(min: CGFloat, and max: CGFloat) -> CGFloat }
0
import UIKit import XCTest import MusicMojoLyrica class testLyrics: LyricsSearchManagerProtocol { var lyric:String! var err:Error! var asyncExpectation: XCTestExpectation? func test() { let lyricManager = LyricsSearchManager() lyricManager.delegate = self let _ = lyricManager.fetchLyricsForTrack(artist: "K. J. Yesudas", song: "Gori Tera Gaon Bada Pyara") } func lyricsFound(lyrics:String) { lyric = lyrics guard let expectation = asyncExpectation else { XCTFail("failed") return } expectation.fulfill() } func lyricsError(error:Error) { err = error guard let expectation = asyncExpectation else { XCTFail("failed") return } expectation.fulfill() } } class Tests: XCTestCase { var x :XCTestExpectation! 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 testSuccessLyricsFetch() { // This is an example of a functional test case. let expectation1 = expectation(description: "delegate called") let delegate = testLyrics() delegate.asyncExpectation = expectation1 let manager = LyricsSearchManager() manager.delegate = delegate let _ = manager.fetchLyricsForTrack(artist: "Kesha", song: "Tik Tok") //let _ = manager.fetchLyricsForTrack(artist: "Kesha", song: "Tik Tok") self.waitForExpectations(timeout: 1) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } guard let result = delegate.lyric else { XCTFail("Expected delegate to be called") return } XCTAssertNotNil(result) print(result) } } func testFiledLyrics() { // This is an example of a functional test case. let expectation1 = expectation(description: "delegate called") let delegate = testLyrics() delegate.asyncExpectation = expectation1 let manager = LyricsSearchManager() manager.delegate = delegate let _ = manager.fetchLyricsForTrack(artist: "K. J. Yesudas", song: "Gore Tera Gaon Bada Pyara") //let _ = manager.fetchLyricsForTrack(artist: "Kesha", song: "Tik Tok") self.waitForExpectations(timeout: 1) { error in if let errorD = delegate.err { XCTAssertNotNil(errorD.localizedDescription) }else { XCTAssert(true) } } } 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
// // AppFonts.swift // Radishing // // Created by Nathaniel Dillinger on 5/1/18. // Copyright © 2018 Nathaniel Dillinger. All rights reserved. // import Foundation enum AppFonts: String { case fancy = "Another-day-in-Paradise" case normal = "Avenir Next Demi Bold" case normalBold = "Avenir Next Bold" }
0
import SwiftUI import ActomatonUI import VideoPlayerMulti import AVFoundation struct VideoPlayerMultiExample: Example { var exampleIcon: Image { Image(systemName: "film") } var exampleInitialState: Home.State.Current { .videoPlayerMulti(VideoPlayerMulti.State(displayMode: .singleSyncedPlayer)) } func exampleView(store: Store<Home.Action, Home.State, Home.Environment>) -> AnyView { Self.exampleView( store: store, action: Home.Action.videoPlayerMulti, statePath: /Home.State.Current.videoPlayerMulti, environment: { $0.videoPlayerMulti }, makeView: VideoPlayerMultiView.init ) } }
0
// // Solution368.swift // leetcode // // Created by youzhuo wang on 2020/12/25. // Copyright © 2020 youzhuo wang. All rights reserved. // import Foundation class Solution368 { // 动态规划 func largestDivisibleSubset(_ nums: [Int]) -> [Int] { if nums.count == 0 { return [] } let sortNums = nums.sorted() var dp:[Int] = Array.init(repeating: 1, count: nums.count) // var numList:[Int] = Array.init() var dpList:[[Int]] = Array.init(repeating: [], count: nums.count) dpList[0] = [sortNums[0]] for i in 1..<sortNums.count { var maxCount = dp[i] var maxList:[Int] = [sortNums[i]] for j in (0..<i).reversed() { if sortNums[i] % sortNums[j] == 0 { // maxList if dp[j]+1 > maxCount { maxCount = dp[j]+1 // dpList[j].append(sortNums[i]) maxList = dpList[j] maxList.append(sortNums[i]) // maxList = dpList[j].append(sortNums[i]) } } } dp[i] = maxCount dpList[i] = maxList } let maxValue = dp.max() for i in 0..<dp.count { if dp[i] == maxValue { return dpList[i] } } return [] } // 并查集 func largestDivisibleSubset2(_ nums: [Int]) -> [Int] { return [] } func test() { print(largestDivisibleSubset([3,4,16,8])) print(largestDivisibleSubset([1])) print(largestDivisibleSubset([2,3])) print(largestDivisibleSubset([1,2,3])) print(largestDivisibleSubset([1,2,4,8])) } } // 多叉树 // 1,2 // 1,3 // 1 // 2 3 // 1 // 2 // 4 // 8 //
0
// // ViewController.swift // MapKitGeocodingTest // // Created by Kuba Suder on 26.08.2015. // Copyright (c) 2015 Kuba Suder. All rights reserved. // import MapKit import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var map: MKMapView! @IBOutlet weak var result: UILabel! @IBOutlet weak var addressField: UITextField! var marker: MKPointAnnotation? override func viewDidLoad() { super.viewDidLoad() } func textFieldShouldReturn(textField: UITextField) -> Bool { searchPressed() textField.resignFirstResponder() return true } @IBAction func searchPressed() { result.hidden = false map.hidden = true if let marker = self.marker { map.removeAnnotation(marker) self.marker = nil } guard let text = addressField.text where !text.isEmpty else { result.text = "Address is empty!" return } result.text = "Searching..." let geocoder = CLGeocoder() // let's prioritize US addresses (this doesn't seem to work though?) let region = CLCircularRegion( center: CLLocationCoordinate2D(latitude: 39.05, longitude: -95.78), radius: 3_000_000, identifier: "USA" ) geocoder.geocodeAddressString(text, inRegion: region) { placemarks, error in if let places = placemarks { for (i, place) in places.enumerate() { NSLog("\(i + 1))\n" + "- name: \(place.name)\n" + "- location: \(place.location)\n" + "- country: \(place.ISOcountryCode) (\(place.country))\n" + "- area: \(place.administrativeArea), \(place.subAdministrativeArea)\n" + "- region: \(place.region)\n" + "- thoroughfare: \(place.thoroughfare), \(place.subThoroughfare)\n" + "- locality: \(place.locality), \(place.subLocality)\n" + "- address: \(place.addressDictionary)\n" + "- postal code: \(place.postalCode)\n" + "- water area: \(place.inlandWater) / \(place.ocean)\n" + "- areas of interest: \(place.areasOfInterest)\n" ) } let placesWithLocations = places.filter { p in p.location != nil } if let first = placesWithLocations.first { self.result.text = "Found \(places.count) place(s), I think you're here: \(first.name)" self.map.hidden = false let marker = MKPointAnnotation() marker.coordinate = first.location!.coordinate self.marker = marker self.map.addAnnotation(marker) self.map.showAnnotations([marker], animated: true) } else { self.result.text = "No places found." } } if let error = error { self.result.text = "Error: \(error)" } } } }
0
// // AudioPlayerError+Ex.swift // AudioService // // Created by Archer on 2019/2/25. // import Fatal extension AudioPlayerError: ErrorConvertible { public var message: String { switch self { case .itemNotConsideredPlayable, .noItemsConsideredPlayable: return "音频无法播放" case .maximumRetryCountHit: return "播放失败,请重试" case .foundationError(let error): if let urlError = error as? URLError { if urlError.code == URLError.timedOut { return "请求超时" } else if urlError.code == URLError.cannotFindHost { return "找不到服务器" } else if urlError.code == URLError.cannotConnectToHost { return "无法连接服务器" } else if urlError.code == URLError.notConnectedToInternet { return "你好像没有联网" } } let nsError = error as NSError if let message = nsError.userInfo["message"] as? String { return message } return "未知错误" } } public var code: Int { switch self { case .itemNotConsideredPlayable: return -10086 case .noItemsConsideredPlayable: return -10010 case .maximumRetryCountHit: return -10000 case .foundationError: return -9999 } } }
0
// // UIView+HideKeyboard.swift // rft // // Created by Levente Vig on 2018. 10. 27.. // Copyright © 2018. Levente Vig. All rights reserved. // import Foundation import UIKit extension UIView { /** Hides the keyboard if the view is tapped. - Parameter onTap: Easy toggle for hiding the keyboard. The default value is true. */ func shouldHideKeyboard(onTap: Bool = true) { let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeybard)) self.addGestureRecognizer(tap) } /** Hides the keyboard if swiped down on the view.. - Parameter onSwipeDown: Easy toggle for hiding the keyboard. The default value is true. */ func shouldHideKeyboard(onSwipeDown: Bool = true) { let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(hideKeybard)) swipeDown.direction = .down self.addGestureRecognizer(swipeDown) } @objc fileprivate func hideKeybard() { self.endEditing(true) } }
0
// // CardView.swift // StackingElements // // Created by recherst on 2021/10/8. // import SwiftUI struct CardView: View { var tool: Tool var reader: GeometryProxy @Binding var swiped: Int @Binding var show: Bool @Binding var selected: Tool var name: Namespace.ID var body: some View { VStack { Spacer(minLength: 0) ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom), content: { VStack { Image(tool.image) .resizable() .aspectRatio(contentMode: .fit) .matchedGeometryEffect(id: tool.image, in: name) .padding(.top) .padding(.horizontal, 25) HStack { VStack(alignment: .leading, spacing: 12, content: { Text(tool.name) .font(.system(size: 40)) .fontWeight(.bold) .foregroundColor(.black) Text("Design tool") .font(.system(size: 20)) .foregroundColor(.black) Button(action: { withAnimation(.spring()) { selected = tool show.toggle() } }, label: { Text("Know More >") .font(.system(size: 20)) .fontWeight(.bold) .foregroundColor(Color("orange")) }) .padding(.top) }) Spacer(minLength: 0) } .padding(.horizontal, 30) .padding(.bottom, 15) .padding(.top, 25) } HStack { Text("#") .font(.system(size: 60)) .fontWeight(.bold) .foregroundColor(Color.gray.opacity(0.6)) Text("\(tool.place)") .font(.system(size: 120)) .fontWeight(.bold) .foregroundColor(Color.gray.opacity(0.6)) } .offset(x: -15, y: 25) }) .frame(height: reader.frame(in: .global).height - 120) .padding(.vertical, 10) .background(Color.white) .cornerRadius(25) .padding(.horizontal, 30 + (CGFloat(tool.id - swiped) * 10)) .offset(y:tool.id - swiped <= 2 ? CGFloat(tool.id - swiped) * 25 : 50) .shadow(color: Color.black.opacity(0.12), radius: 5, x: 0, y: 5) Spacer(minLength: 0) } .contentShape(Rectangle()) } } struct CardView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
0
// // TimelineViewController.swift // twitter_alamofire_demo // // Created by Aristotle on 2018-08-11. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit import AlamofireImage class TimelineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { func did(post: Tweet) { getTweets() print(post.text) } var tweets: [Tweet] = [] var selectedTweet: Tweet? @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshTweets(_:)), for: UIControlEvents.valueChanged) tableView.insertSubview(refreshControl, at: 0) tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 140 tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 getTweets() tableView.reloadData() // Do any additional setup after loading the view. } @objc func refreshTweets(_ refreshControl: UIRefreshControl) { getTweets() tableView.reloadData() refreshControl.endRefreshing() print("Refreshed") } func getTweets() { APIManager.shared.getHomeTimeLine { (tweets, error) in if let tweets = tweets { self.tweets = tweets self.tableView.reloadData() print("Actually Refreshed") } else if let error = error { print("Error getting home timeline: " + error.localizedDescription) } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TweetCell", for: indexPath) as! TweetCell cell.tweet = tweets[indexPath.row] if (cell.tweet.favorited == true) { cell.favoriteButton.setImage(UIImage(named: "favor-icon-red"), for: .normal) } if (cell.tweet.retweeted == true) { cell.retweetButton.setImage(UIImage(named: "retweet-icon-green"), for: .normal) } cell.profilePictureImageView.layer.cornerRadius = cell.profilePictureImageView.frame.width / 2 selectedTweet = tweets[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) selectedTweet = tweets[indexPath.row] self.performSegue(withIdentifier: "tweetSegue", sender: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didTapLogout(_ sender: Any) { APIManager.shared.logout() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "tweetSegue") { let vc = segue.destination as! TweetViewController vc.tweet = selectedTweet } if (segue.identifier == "composeSegue") { let vc = segue.destination as! ComposeTweetViewController vc.delegate = (self as! ComposeViewControllerDelegate) } } override func viewWillAppear(_ animated: Bool) { self.tabBarController?.navigationItem.rightBarButtonItem = self.navigationItem.rightBarButtonItem; self.tabBarController?.navigationItem.leftBarButtonItem = self.navigationItem.leftBarButtonItem } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // Dictionary+App.swift // QiitaCollection // // Created by ANZ on 2015/03/01. // Copyright (c) 2015年 anz. All rights reserved. // import Foundation extension Dictionary { }
0
// // Key.swift // MusicNotationKit // // Created by Kyle Sherman on 7/11/15. // Copyright © 2015 Kyle Sherman. All rights reserved. // public struct Key { private let type: KeyType private let noteLetter: NoteLetter private let accidental: Accidental? public init(noteLetter: NoteLetter, accidental: Accidental? = nil, type: KeyType = .Major) { self.noteLetter = noteLetter self.accidental = accidental self.type = type } }
0
sharedAuthy.approveRequest(approvalRequest, completion: { (error: AUTError?) -> Void in // ... }) sharedAuthy.denyRequest(approvalRequest, completion: { (error: AUTError?) -> Void in // ... })
0
// // StockPrice.swift // TMEStockExchange // // Created by sagar kothari on 26/10/17. // Copyright © 2017 sagar kothari. All rights reserved. // import Foundation struct StockPrice { let date: Date let price: Int }
0
// // XcodeSwiftAppUITestsLaunchTests.swift // XcodeSwiftAppUITests // // Created by Daniel Lacasse on 2022-04-07. // import XCTest class XcodeSwiftAppUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
0
/** * @extension Dictionary * @since 0.3.0 * @hidden */ internal extension Dictionary where Value: Equatable { /** * @method keyOf * @since 0.3.0 * @hidden */ internal func keyOf(_ value: Value) -> Key? { return self.first { $1 == value }?.key } }
0
import PackageDescription let package = Package( name: "RotationalCipher" //"rotational-cipher" )
0
public func solution(inout A : [Int]) -> Int { // write your code in Swift 2.2 A[0] = 0 A[A.count - 1] = 0 var maxEnding = 0 var maxSlice = 0 var maxSliceLeft = Array(count: A.count, repeatedValue: 0) for i in 0..<A.count { maxEnding = max(0, maxEnding + A[i]) maxSliceLeft[i] = maxEnding } var maxSliceRight = Array(count: A.count, repeatedValue: 0) maxEnding = 0 maxSlice = 0 for var i = A.count - 2; i >= 1; i-- { maxEnding = max(0, maxEnding + A[i]) maxSliceRight[i] = maxEnding } var maxDoubleSlice = 0 for i in 1..<(A.count - 1) { maxDoubleSlice = max(maxDoubleSlice, maxSliceLeft[i - 1] + maxSliceRight[i + 1]) } return maxDoubleSlice }
0
// // Copyright © 2017 Essential Developer. All rights reserved. // import Foundation import QuizEngine struct ResultsPresenter { let result: Result<Question<String>, [String]> let questions: [Question<String>] let correctAnswers: Dictionary<Question<String>, [String]> var title: String { return "Result" } var summary: String { return "You got \(result.score)/\(result.answers.count) correct" } var presentableAnswers: [PresentableAnswer] { return questions.map { question in guard let userAnswer = result.answers[question], let correctAnswer = correctAnswers[question] else { fatalError("Couldn't find correct answer for question: \(question)") } return presentableAnswer(question, userAnswer, correctAnswer) } } private func presentableAnswer(_ question: Question<String>, _ userAnswer: [String], _ correctAnswer: [String]) -> PresentableAnswer { switch question { case .singleAnswer(let value), .multipleAnswer(let value): return PresentableAnswer( question: value, answer: formattedAnswer(correctAnswer), wrongAnswer: formattedWrongAnswer(userAnswer, correctAnswer)) } } private func formattedAnswer(_ answer: [String]) -> String { return answer.joined(separator: ", ") } private func formattedWrongAnswer(_ userAnswer: [String], _ correctAnswer: [String]) -> String? { return correctAnswer == userAnswer ? nil : formattedAnswer(userAnswer) } }
0
// RUN: not --crash %target-swift-frontend %s -parse class C {} class D : C {} @_silgen_name("consume") func consume(_: [C]) // note, returns () // Assert/crash while emitting diagnostic for coercion from () to Bool // in the context of a collection cast. func test(x: [D]) -> Bool { return consume(x) // no way to coerce from () to Bool }
0
// // CreateMonitoredItemsResponse.swift // // // Created by Gerardo Grisolini on 25/02/2020. // import Foundation class CreateMonitoredItemsResponse: MessageBase, OPCUADecodable { let typeId: NodeIdNumeric let responseHeader: ResponseHeader var results: [MonitoredItemCreateResult] = [] var diagnosticInfos: [DiagnosticInfo] = [] required override init(bytes: [UInt8]) { typeId = NodeIdNumeric(method: .createSubscriptionResponse) let part = bytes[20...43].map { $0 } responseHeader = ResponseHeader(bytes: part) var index = 44 var count = UInt32(bytes: bytes[index..<(index+4)]) index += 4 if count < UInt32.max { for _ in 0..<count { let statusCode = StatusCodes(rawValue: UInt32(bytes: bytes[index..<(index+4)]))! index += 4 var result = MonitoredItemCreateResult(statusCode: statusCode) result.monitoredItemId = UInt32(bytes: bytes[index..<(index+4)]) index += 4 result.revisedSamplingInterval = Double(bytes: bytes[index..<(index+8)].map { $0 }) index += 8 result.revisedQueueSize = UInt32(bytes: bytes[index..<(index+4)]) index += 4 result.filterResult.typeId = Nodes.node(index: &index, bytes: bytes) result.filterResult.encodingMask = bytes[index] index += 1 results.append(result) } } count = UInt32(bytes: bytes[index..<(index+4)]) index += 4 if count < UInt32.max { for _ in 0..<count { let len = UInt32(bytes: bytes[index..<(index+4)]) index += 4 if let text = String(bytes: bytes[index..<(index+len.int)], encoding: .utf8) { let info = DiagnosticInfo(info: text) diagnosticInfos.append(info) } index += len.int } } super.init(bytes: bytes[0...15].map { $0 }) } } public struct MonitoredItemCreateResult: Promisable { public let statusCode: StatusCodes public var monitoredItemId: UInt32 = 0 var revisedSamplingInterval: Double = 0 var revisedQueueSize: UInt32 = 0 var filterResult: Filter = Filter() }
0
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import UIKit import Beagle // MARK: - Protocols public protocol TextComponents: ServerDrivenComponent { } public protocol TextComponentHeader: ServerDrivenComponent { } public protocol ActionDummy: Action { } // MARK: - Dummy Impl struct TextComponentHeaderDefault: TextComponentHeader { func toView(renderer: BeagleRenderer) -> UIView { return UIView() } } struct TextComponentsDefault: TextComponents { func toView(renderer: BeagleRenderer) -> UIView { return UIView() } } struct ActionDummyDefault: ActionDummy { func execute(controller: BeagleController, origin: UIView) {} }
0
// // ImageTableViewCell.swift // SwiftImageDemo // // Created by Jie Cao on 11/26/15. // Copyright © 2015 JieCao. All rights reserved. // import UIKit class ImageTableViewCell: UITableViewCell { @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var photoView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
0
// // SearchResultViewController.swift // Netflix // // Created by SERDAR TURAN on 21.12.2020. // import UIKit class SearchResultViewController: UIViewController { var searchResultView = SearchResultView() lazy var favoriteManager: FavoriteManagerProtocol = FavoriteManager() var searchResults: [SearchResult] = [] { didSet { searchResultView.viewModels = searchResults.map({ SearchResultViewModel(searchResult: $0, favorites: favoriteManager.favorites) }) } } weak var coordinator: ResultDetailing? override func loadView() { view = searchResultView } override func viewDidLoad() { super.viewDidLoad() listenEvents() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) favoriteManager.getFavorites() } func listenEvents() { searchResultView.resultSelected = { [weak self] searchResult in self?.coordinator?.showResultDetail(result: searchResult) } searchResultView.favoriteSelected = { [weak self] searchResult in self?.favoriteManager.favoriteAction(result: searchResult) } favoriteManager.favoritesChanged = { [weak self] favorites in self?.searchResultView.viewModels = self?.searchResultView.viewModels.map({ SearchResultViewModel(searchResult: $0.searchResult, favorites: favorites)}) ?? [] } } }
0
// The MIT License // // Copyright (c) 2018-2019 Alejandro Barros Cuetos. [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Resolvable protocol provides some extension points for resolving dependencies with property injection. /// Protocol to implement to solve DI using property injection public protocol HelixResolvable { /// This method will be called right after instance is created by the container. /// This method will be called just after the instance is created by the Helix /// /// - Parameter container: The Helix instance that called it func resolveDependencies(with helix: Helix) /// This method will be called when all the dependencies are resolved func didResolveDependencies() } extension HelixResolvable { func resolveDependencies(with helix: Helix) {} func didResolveDependencies() {} }
0
// // LDLoginViewController.swift // RxSwiftStudy // // Created by 文刂Rn on 2018/4/18. // Copyright © 2018年 Apple. All rights reserved. // import UIKit import SnapKit let kNavHeight = 64 let kLiftMargin = 30 let kTopMargin = 30 let kLoginButtonHeight = 44 class LDLoginViewController: UIViewController { /// MARK 用户名 fileprivate lazy var userTextField: UITextField = { var userTextField = UITextField() userTextField.placeholder = "请输入用户名" userTextField.borderStyle = .roundedRect userTextField.font = UIFont.systemFont(ofSize: 14) return userTextField }() /// MARK 密码 fileprivate lazy var pwdTextField: UITextField = { var pwdTextField = UITextField() pwdTextField.placeholder = "请输入密码" pwdTextField.borderStyle = .roundedRect pwdTextField.font = UIFont.systemFont(ofSize: 14) return pwdTextField }() /// MARK 登录 fileprivate lazy var loginButton: UIButton = { var loginButton = UIButton() loginButton.setTitle("登录", for: .normal) loginButton.backgroundColor = UIColor.lightGray loginButton.isEnabled = false loginButton.layer.cornerRadius = 5; loginButton.layer.masksToBounds = true return loginButton }() } extension LDLoginViewController { override func viewDidLoad() { super.viewDidLoad() setup() } } extension LDLoginViewController { func setup() { setNavgation() setUI() setConstraints() } func setNavgation() { navigationItem.title = "登录" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(rightBarButtonItemClick)) view.backgroundColor = UIColor.white } func setUI() { view.addSubview(userTextField) view.addSubview(pwdTextField) view.addSubview(loginButton) } func setConstraints() { userTextField.snp.makeConstraints { (make) in make.top.equalTo(view).offset(kNavHeight + kTopMargin) make.left.equalTo(view).offset(kTopMargin) make.right.equalTo(view).offset(-kTopMargin) make.height.equalTo(30) } pwdTextField.snp.makeConstraints { (make) in make.left.right.height.equalTo(userTextField) make.top.equalTo(userTextField.snp.bottom).offset(kTopMargin) } loginButton.snp.makeConstraints { (make) in make.top.equalTo(pwdTextField.snp.bottom).offset(40) make.left.equalTo(view).offset(40) make.right.equalTo(view).offset(-40) make.height.equalTo(44) } } @objc func rightBarButtonItemClick() { navigationController?.pushViewController(LDRegisterViewController(), animated: true) } }
0
// // FundsRequest.swift // MyMonero // // Created by Paul Shapiro on 6/15/17. // Copyright (c) 2014-2018, MyMonero.com // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // import Foundation import CoreImage import UIKit class FundsRequest: PersistableObject { // // Types/Constants enum NotificationNames: String { case infoUpdated = "FundsRequest_NotificationNames_infoUpdated" var notificationName: NSNotification.Name { return NSNotification.Name(self.rawValue) } } enum DictKey: String { // (For persistence) case from_fullname = "from_fullname" case to_walletHexColorString = "to_walletHexColorString" case to_address = "to_address" case payment_id = "payment_id" case amount = "amount" case message = "message" case description = "description" case amountCurrency = "amountCurrency" case is_displaying_local_wallet = "is_displaying_local_wallet" } // // Properties - Persisted Values var from_fullname: String? var to_walletSwatchColor: Wallet.SwatchColor? var to_address: MoneroAddress! var payment_id: MoneroPaymentID? var amount: String? var message: String? var description: String? var amountCurrency: CcyConversionRates.CurrencySymbol? // nil if no amount var is_displaying_local_wallet: Bool? // // Properties - Transient var qrCode_cgImage: CGImage! var cached__qrCode_image_small: UIImage! // // 'Protocols' - Persistable Object override func new_dictRepresentation() -> [String: Any] { var dict = super.new_dictRepresentation() // since it constructs the base object for us do { if let value = self.from_fullname { dict[DictKey.from_fullname.rawValue] = value } if let value = self.to_walletSwatchColor { dict[DictKey.to_walletHexColorString.rawValue] = value.jsonRepresentation() } dict[DictKey.to_address.rawValue] = self.to_address if let value = self.payment_id { dict[DictKey.payment_id.rawValue] = value } if let value = self.amount { dict[DictKey.amount.rawValue] = value } if let value = self.message { dict[DictKey.message.rawValue] = value } if let value = self.description { dict[DictKey.description.rawValue] = value } if let value = self.amountCurrency { dict[DictKey.amountCurrency.rawValue] = value } if let value = self.is_displaying_local_wallet { dict[DictKey.is_displaying_local_wallet.rawValue] = value } } return dict } // // Lifecycle - Init - Reading existing (already saved) wallet override class func collectionName() -> String { return "FundsRequests" } required init?(withPlaintextDictRepresentation dictRepresentation: DocumentPersister.DocumentJSON) throws { try super.init(withPlaintextDictRepresentation: dictRepresentation) // this will set _id for us // self.from_fullname = dictRepresentation[DictKey.from_fullname.rawValue] as? String if let hexString = dictRepresentation[DictKey.to_walletHexColorString.rawValue] as? String { self.to_walletSwatchColor = Wallet.SwatchColor.new( from_jsonRepresentation: hexString ) } self.to_address = dictRepresentation[DictKey.to_address.rawValue] as? String self.payment_id = dictRepresentation[DictKey.payment_id.rawValue] as? String self.amount = dictRepresentation[DictKey.amount.rawValue] as? String self.message = dictRepresentation[DictKey.message.rawValue] as? String self.description = dictRepresentation[DictKey.description.rawValue] as? String self.amountCurrency = dictRepresentation[DictKey.amountCurrency.rawValue] as? CcyConversionRates.CurrencySymbol self.is_displaying_local_wallet = dictRepresentation[DictKey.is_displaying_local_wallet.rawValue] as? Bool ?? false // nil -> false // self.setup() } // // Lifecycle - Init - For adding new required init() { super.init() } convenience init( from_fullname: String?, to_walletSwatchColor: Wallet.SwatchColor?, // this may be nil if is_displaying_local_wallet is true to_address: MoneroAddress, payment_id: MoneroPaymentID?, amount: String?, message: String?, description: String?, amountCurrency: CcyConversionRates.CurrencySymbol?, is_displaying_local_wallet: Bool ) { self.init() // self.from_fullname = from_fullname self.to_walletSwatchColor = to_walletSwatchColor self.to_address = to_address self.payment_id = payment_id self.amount = amount self.message = message self.description = description self.amountCurrency = amountCurrency self.is_displaying_local_wallet = is_displaying_local_wallet // self.setup() } func setup() { self.setup_qrCode_cgImage() self.cached__qrCode_image_small = QRCodeImages.new_qrCode_UIImage( fromCGImage: self.qrCode_cgImage, withQRSize: .small ) } func setup_qrCode_cgImage() { let noSlashes_uri = self.new_URI(inMode: .addressAsFirstPathComponent) self.qrCode_cgImage = QRCodeImages.new_qrCode_cgImage( withContentString: noSlashes_uri.absoluteString ) } // // Interface - Runtime - Accessors/Properties func new_URI(inMode uriMode: MoneroUtils.URIs.URIMode) -> URL { return MoneroUtils.URIs.Requests.new_URL( address: self.to_address, amount: self.amount, description: self.description, paymentId: self.payment_id, message: self.message, amountCurrency: self.amountCurrency, uriMode: uriMode ) } }
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 for { func c { let end = { struct A { class case ,
0
// // PatternPreferences.swift // Prephirences /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation //MARK: composite pattern public class CompositePreferences: PreferencesType , ArrayLiteralConvertible { var array: [PreferencesType] = [] // MARK: singleton static let sharedInstance = CompositePreferences([]) // TODO make it lazy // MARK: init public init(_ array: [PreferencesType]){ self.array = array } // MARK: ArrayLiteralConvertible public typealias Element = PreferencesType public convenience required init(arrayLiteral elements: Element...) { self.init([]) for element in elements { self.array.append(element) } } // MARK: PreferencesType public subscript(key: String) -> AnyObject? { get { // first return win for prefs in array { if let value: AnyObject = prefs.objectForKey(key){ return value } } return nil } } public func objectForKey(key: String) -> AnyObject? { return self[key] } public func hasObjectForKey(key: String) -> Bool { return self[key] != nil } public func stringForKey(key: String) -> String? { return self[key] as? String } public func arrayForKey(key: String) -> [AnyObject]? { return self[key] as? [AnyObject] } public func dictionaryForKey(key: String) -> [String : AnyObject]? { return self[key] as? [String: AnyObject] } public func dataForKey(key: String) -> NSData? { return self[key] as? NSData } public func stringArrayForKey(key: String) -> [String]? { return self.arrayForKey(key) as? [String] } public func integerForKey(key: String) -> Int { return self[key] as? Int ?? 0 } public func floatForKey(key: String) -> Float { return self[key] as? Float ?? 0 } public func doubleForKey(key: String) -> Double { return self[key] as? Double ?? 0 } public func boolForKey(key: String) -> Bool { if let b = self[key] as? Bool { return b } return false } public func URLForKey(key: String) -> NSURL? { return self[key] as? NSURL } public func dictionary() -> [String : AnyObject] { var dico = [String : AnyObject]() for prefs in array.reverse() { dico += prefs.dictionary() } return dico } } public class MutableCompositePreferences: CompositePreferences, MutablePreferencesType { public var affectOnlyFirstMutable: Bool public override convenience init(_ array: [PreferencesType]){ self.init(array, affectOnlyFirstMutable: true) } public init(_ array: [PreferencesType], affectOnlyFirstMutable: Bool){ self.affectOnlyFirstMutable = affectOnlyFirstMutable super.init(array) } override public subscript(key: String) -> AnyObject? { get { // first return win for prefs in array { if let value: AnyObject = prefs.objectForKey(key){ return value } } return nil } set { for prefs in array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.setObject(newValue, forKey: key) if affectOnlyFirstMutable { break } } } } } public func setObject(value: AnyObject?, forKey key: String) { self[key] = value } public func removeObjectForKey(key: String) { self[key] = nil } public func setInteger(value: Int, forKey key: String){ self[key] = value } public func setFloat(value: Float, forKey key: String){ self[key] = value } public func setDouble(value: Double, forKey key: String) { setObject(NSNumber(double: value), forKey: key) } public func setBool(value: Bool, forKey key: String) { self[key] = value } public func setURL(url: NSURL?, forKey key: String) { self[key] = url } public func setObjectsForKeysWithDictionary(dictionary: [String : AnyObject]){ for prefs in array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.setObjectsForKeysWithDictionary(dictionary) if affectOnlyFirstMutable { break } } } } public func clearAll() { for prefs in array { if let mutablePrefs = prefs as? MutablePreferencesType { mutablePrefs.clearAll() } } } } //MARK: proxy pattern public class ProxyPreferences { private let proxiable: PreferencesType private let parentKey: String var separator: String? public convenience init(preferences proxiable: PreferencesType) { self.init(preferences: proxiable, key: "") } public convenience init(preferences proxiable: PreferencesType, key parentKey: String) { self.init(preferences: proxiable, key: parentKey, separator: nil) } public init(preferences proxiable: PreferencesType, key parentKey: String, separator: String?) { self.proxiable = proxiable self.parentKey = parentKey self.separator = separator } private func computeKey(key: String) -> String { return self.parentKey + (self.separator ?? "") + key } private func hasRecursion() -> Bool { return self.separator != nil } public subscript(key: String) -> AnyObject? { get { let finalKey = computeKey(key) if let value: AnyObject = self.proxiable.objectForKey(finalKey) { return value } if hasRecursion() { return ProxyPreferences(preferences: self.proxiable, key: finalKey, separator: self.separator) } return nil } } } extension ProxyPreferences: PreferencesType { public func objectForKey(key: String) -> AnyObject? { return self.proxiable.objectForKey(key) } public func hasObjectForKey(key: String) -> Bool { return self.proxiable.hasObjectForKey(key) } public func stringForKey(key: String) -> String? { return self.proxiable.stringForKey(key) } public func arrayForKey(key: String) -> [AnyObject]? { return self.proxiable.arrayForKey(key) } public func dictionaryForKey(key: String) -> [String : AnyObject]? { return self.proxiable.dictionaryForKey(key) } public func dataForKey(key: String) -> NSData? { return self.proxiable.dataForKey(key) } public func stringArrayForKey(key: String) -> [String]? { return self.proxiable.stringArrayForKey(key) } public func integerForKey(key: String) -> Int { return self.proxiable.integerForKey(key) } public func floatForKey(key: String) -> Float { return self.proxiable.floatForKey(key) } public func doubleForKey(key: String) -> Double { return self.proxiable.doubleForKey(key) } public func boolForKey(key: String) -> Bool { return self.proxiable.boolForKey(key) } public func URLForKey(key: String) -> NSURL? { return self.proxiable.URLForKey(key) } public func unarchiveObjectForKey(key: String) -> AnyObject? { return self.proxiable.unarchiveObjectForKey(key) } public func dictionary() -> [String : AnyObject] { return self.proxiable.dictionary() } } public class MutableProxyPreferences: ProxyPreferences { private var mutable: MutablePreferencesType { return self.proxiable as! MutablePreferencesType } public init(preferences proxiable: MutablePreferencesType, key parentKey: String, separator: String) { super.init(preferences: proxiable, key: parentKey, separator: separator) } override public subscript(key: String) -> AnyObject? { get { let finalKey = computeKey(key) if let value: AnyObject = self.proxiable.objectForKey(finalKey) { return value } if hasRecursion() { return ProxyPreferences(preferences: self.proxiable, key: finalKey, separator: self.separator) } return nil } set { let finalKey = computeKey(key) if newValue == nil { self.mutable.removeObjectForKey(finalKey) } else { self.mutable.setObject(newValue, forKey: finalKey) } } } } extension MutableProxyPreferences: MutablePreferencesType { public func setObject(value: AnyObject?, forKey key: String){ self.mutable.setObject(value, forKey: key) } public func removeObjectForKey(key: String){ self.mutable.removeObjectForKey(key) } public func setInteger(value: Int, forKey key: String){ self.mutable.setInteger(value, forKey: key) } public func setFloat(value: Float, forKey key: String){ self.mutable.setFloat(value, forKey: key) } public func setDouble(value: Double, forKey key: String){ self.mutable.setDouble(value, forKey: key) } public func setBool(value: Bool, forKey key: String){ self.mutable.setBool(value, forKey: key) } public func setURL(url: NSURL?, forKey key: String){ self.mutable.setURL(url, forKey: key) } public func setObjectToArchive(value: AnyObject?, forKey key: String) { self.mutable.setObjectToArchive(value, forKey: key) } public func clearAll(){ self.mutable.clearAll() } public func setObjectsForKeysWithDictionary(registrationDictionary: [String : AnyObject]){ self.mutable.setObjectsForKeysWithDictionary(registrationDictionary) } } // MARK: adapter generic // Allow to implement 'dictionary' using the new 'keys' // Subclasses must implement objectForKey & keys public protocol PreferencesAdapter: PreferencesType { func keys() -> [String] } extension PreferencesAdapter { public func dictionary() -> [String : AnyObject] { var dico:Dictionary<String, AnyObject> = [:] for name in self.keys() { if let value: AnyObject = self.objectForKey(name) { dico[name] = value } } return dico } } // MARK : KVC // object must informal protocol NSKeyValueCoding public class KVCPreferences: PreferencesAdapter { private let object: NSObject public init(_ object: NSObject) { self.object = object } public func objectForKey(key: String) -> AnyObject? { return self.object.valueForKey(key) } public func keys() -> [String] { var names: [String] = [] var count: UInt32 = 0 // FIXME: not recursive? let properties = class_copyPropertyList(self.object.classForCoder, &count) for var i = 0; i < Int(count); ++i { let property: objc_property_t = properties[i] let name: String = String.fromCString(property_getName(property))! names.append(name) } free(properties) return names } } public class MutableKVCPreferences: KVCPreferences { public override init(_ object: NSObject) { super.init(object) } public subscript(key: String) -> AnyObject? { get { return self.objectForKey(key) } set { self.setObject(newValue, forKey: key) } } } extension MutableKVCPreferences: MutablePreferencesType { public func setObject(value: AnyObject?, forKey key: String){ if (self.object.respondsToSelector(NSSelectorFromString(key))) { self.object.setValue(value, forKey: key) } } public func removeObjectForKey(key: String){ if (self.object.respondsToSelector(NSSelectorFromString(key))) { self.object.setValue(nil, forKey: key) } } public func setInteger(value: Int, forKey key: String){ self.setObject(NSNumber(integer: value), forKey: key) } public func setFloat(value: Float, forKey key: String){ self.setObject(NSNumber(float: value), forKey: key) } public func setDouble(value: Double, forKey key: String){ self.setObject(NSNumber(double: value), forKey: key) } public func setBool(value: Bool, forKey key: String){ self.setObject(NSNumber(bool: value), forKey: key) } public func clearAll(){ // not implemented, maybe add protocol to set defaults attributes values } }
0
import UIKit import Flutter import GoogleMaps @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) GMSServices.provideAPIKey("AIzaSyBO33PDWnPErmLw9IzjakDoyYsH8vl8UkI") return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
0
// // ScanViewController.swift // breadwallet // // Created by Adrian Corscadden on 2016-12-12. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit import AVFoundation typealias ScanCompletion = (PaymentRequest?) -> Void typealias KeyScanCompletion = (String) -> Void enum ScanViewType { case payment } class ScanViewController : UIViewController, Trackable { static func presentCameraUnavailableAlert(fromRoot: UIViewController) { let alertController = UIAlertController(title: S.Send.cameraUnavailableTitle, message: S.Send.cameraUnavailableMessage, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: S.Button.settings, style: .`default`, handler: { _ in if let appSettings = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(appSettings) } })) fromRoot.present(alertController, animated: true, completion: nil) } static var isCameraAllowed: Bool { return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) != .denied } let completion: ScanCompletion? let scanKeyCompletion: KeyScanCompletion? let isValidURI: (String) -> Bool fileprivate let guide = CameraGuideView() fileprivate let session = AVCaptureSession() private let toolbar = UIView() private let close = UIButton.close private let flash = UIButton.icon(image: #imageLiteral(resourceName: "flash-off").withRenderingMode(.alwaysTemplate), accessibilityLabel: S.Scanner.flashButtonLabel) fileprivate var currentUri = "" private let scanViewType: ScanViewType // this constructor was added to support DigiId. It switches the scan mode to .digiid, and does basically the same // as the other constructors. It does not create a Payment class instance, to check whether the scanned url is valid. // Instead of using PaymentRequest, it does it with DigiIdRequest. init( isValidURI: @escaping (String) -> Bool) { self.scanViewType = .payment self.scanKeyCompletion = nil self.isValidURI = isValidURI self.completion = nil super.init(nibName: nil, bundle: nil) } init(completion: @escaping ScanCompletion, isValidURI: @escaping (String) -> Bool) { scanViewType = .payment self.completion = completion self.scanKeyCompletion = nil self.isValidURI = isValidURI super.init(nibName: nil, bundle: nil) } init(scanKeyCompletion: @escaping KeyScanCompletion, isValidURI: @escaping (String) -> Bool) { scanViewType = .payment self.scanKeyCompletion = scanKeyCompletion self.completion = nil self.isValidURI = isValidURI super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { view.backgroundColor = .black flash.tintColor = C.Colors.text toolbar.backgroundColor = C.Colors.background view.addSubview(toolbar) toolbar.addSubview(close) toolbar.addSubview(flash) view.addSubview(guide) toolbar.constrainBottomCorners(sidePadding: 0, bottomPadding: 0) if E.isIPhoneX { toolbar.constrain([ toolbar.constraint(.height, constant: 60.0) ]) close.constrain([ close.constraint(.leading, toView: toolbar), close.constraint(.top, toView: toolbar, constant: 2.0), close.constraint(.width, constant: 44.0), close.constraint(.height, constant: 44.0) ]) flash.constrain([ flash.constraint(.trailing, toView: toolbar), flash.constraint(.top, toView: toolbar, constant: 2.0), flash.constraint(.width, constant: 44.0), flash.constraint(.height, constant: 44.0) ]) } else { toolbar.constrain([ toolbar.constraint(.height, constant: 48.0) ]) close.constrain([ close.constraint(.leading, toView: toolbar), close.constraint(.top, toView: toolbar, constant: 2.0), close.constraint(.bottom, toView: toolbar, constant: -2.0), close.constraint(.width, constant: 44.0) ]) flash.constrain([ flash.constraint(.trailing, toView: toolbar), flash.constraint(.top, toView: toolbar, constant: 2.0), flash.constraint(.bottom, toView: toolbar, constant: -2.0), flash.constraint(.width, constant: 44.0) ]) } guide.constrain([ guide.constraint(.leading, toView: view, constant: C.padding[6]), guide.constraint(.trailing, toView: view, constant: -C.padding[6]), guide.constraint(.centerY, toView: view), NSLayoutConstraint(item: guide, attribute: .width, relatedBy: .equal, toItem: guide, attribute: .height, multiplier: 1.0, constant: 0.0) ]) guide.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) close.tap = { [weak self] in //self?.saveEvent("scan.dismiss") self?.dismiss(animated: true, completion: { self?.completion?(nil) }) } addCameraPreview() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.spring(0.8, animations: { self.guide.transform = .identity }, completion: { _ in }) } private func addCameraPreview() { guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return } guard let input = try? AVCaptureDeviceInput(device: device) else { return } session.addInput(input) let previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.frame = view.bounds view.layer.insertSublayer(previewLayer, at: 0) let output = AVCaptureMetadataOutput() output.setMetadataObjectsDelegate(self, queue: .main) session.addOutput(output) if output.availableMetadataObjectTypes.contains(where: { objectType in return objectType == AVMetadataObject.ObjectType.qr }) { output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr] } else { print("no qr code support") } DispatchQueue(label: "qrscanner").async { self.session.startRunning() } if device.hasTorch { flash.tap = { [weak self] in do { try device.lockForConfiguration() device.torchMode = device.torchMode == .on ? .off : .on device.unlockForConfiguration() if device.torchMode == .on { //self?.saveEvent("scan.torchOn") self?.flash.tintColor = C.Colors.weirdRed self?.flash.setImage(#imageLiteral(resourceName: "flash-on").withRenderingMode(.alwaysTemplate), for: .normal) } else { //self?.saveEvent("scan.torchOn") self?.flash.tintColor = C.Colors.text self?.flash.setImage(#imageLiteral(resourceName: "flash-off").withRenderingMode(.alwaysTemplate), for: .normal) } } catch let error { print("Camera Torch error: \(error)") } } } else { flash.isHidden = true } } override var prefersStatusBarHidden: Bool { return true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ScanViewController : AVCaptureMetadataOutputObjectsDelegate { func metadataOutput(_ captureOutput: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if let data = metadataObjects as? [AVMetadataMachineReadableCodeObject] { if data.count == 0 { guide.state = .normal } else { data.forEach { guard let uri = $0.stringValue else { return } if completion != nil { handleURI(uri) } else if scanKeyCompletion != nil { handleKey(uri) } } } } } func handleURI(_ uri: String) { if self.currentUri != uri { switch scanViewType { case .payment: if let paymentRequest = PaymentRequest(string: uri) { //saveEvent("scan.auroracoinUri") guide.state = .positive //Add a small delay so the green guide will be seen DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { self.dismiss(animated: true, completion: { self.completion?(paymentRequest) }) }) } else { guide.state = .negative } } self.currentUri = uri } } func handleKey(_ address: String) { if isValidURI(address) { //saveEvent("scan.privateKey") guide.state = .positive DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { self.dismiss(animated: true, completion: { self.scanKeyCompletion?(address) }) }) } else { guide.state = .negative } } }
0
// // HotViewController.swift // RJBilibili // // Created by TouchWorld on 2021/1/4. // Copyright © 2021 RJSoft. All rights reserved. // import UIKit import JXSegmentedView import MJRefresh private let CellID = "HotTableViewCell" private let HeaderViewID = "HotTableViewHeaderView" class HotViewController: UIViewController { private var hotTableView: UITableView! private lazy var titles: [String] = { var titles = [String]() for i in 0..<10 { titles.append(String(i)) } return titles }() override func viewDidLoad() { super.viewDidLoad() setupInit() } // MARK: - Setup Init private func setupInit() { view.backgroundColor = .white setupTableView() } private func setupTableView() { hotTableView = UITableView(frame: CGRect.zero, style: .grouped) view.addSubview(hotTableView) hotTableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } hotTableView.backgroundColor = .white hotTableView.estimatedRowHeight = 0.0 hotTableView.estimatedSectionHeaderHeight = 0.0 hotTableView.estimatedSectionFooterHeight = 0.0 hotTableView.separatorInset = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0) hotTableView.showsHorizontalScrollIndicator = false hotTableView.dataSource = self hotTableView.delegate = self hotTableView.register(HotTableViewCell.self, forCellReuseIdentifier: CellID) hotTableView.register(HotTableViewHeaderView.self, forHeaderFooterViewReuseIdentifier: HeaderViewID) hotTableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData)) hotTableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in guard let self = self else { return } self.loadMoreData() }) hotTableView.mj_footer?.ignoredScrollViewContentInsetBottom = 44.0 } } // MARK: - Network extension HotViewController { @objc func loadNewData() { hotTableView.mj_header?.endRefreshing() titles.removeAll() for i in 0..<10 { titles.append(String(i)) } hotTableView.reloadData() } func loadMoreData() { hotTableView.mj_footer?.endRefreshing() let count = titles.count for i in count..<(count + 10) { titles.append(String(i)) } hotTableView.reloadData() } } // MARK: - UITableViewDataSource extension HotViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let title = titles[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: CellID, for: indexPath) as! HotTableViewCell cell.title = title cell.iconName = "test" return cell } } // MARK: - UITableViewDelegate extension HotViewController: UITableViewDelegate { func tableViewDidEndMultipleSelectionInteraction(_ tableView: UITableView) { } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120.0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 100.0 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.1 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderViewID) as! HotTableViewHeaderView return headerView } } // MARK: - JXSegmentedListContainerViewListDelegate extension HotViewController: JXSegmentedListContainerViewListDelegate { func listView() -> UIView { return self.view } }
0
// // NetworkService.swift // FlightSearchFinal // // Created by Эмиль Шалаумов on 08.12.2019. // Copyright © 2019 Emil Shalaumov. All rights reserved. // import Foundation protocol NetworkServiceProtocol { func performTaskReturningBody(_ request: URLRequest, completion: @escaping(Result<Data?, Error>) -> Void) func performTaskReturningHeader(_ request: URLRequest, completion: @escaping(Result<HTTPURLResponse?, Error>) -> Void) } final class NetworkService: NetworkServiceProtocol { private let session = URLSession.shared /// Performs a network request and returns response body /// Waits for 200 - OK response code as API returns it when contains response data in body /// /// - Parameters: /// - request: HTTP / HTTPS request contained of predefined parameters /// - completion: returns response body of Data type in case of successful execution, otherwise returns error with description func performTaskReturningBody(_ request: URLRequest, completion: @escaping(Result<Data?, Error>) -> Void) { performDataTask(request, expectedCode: 200) { result in switch result { case .success(let response): completion(.success(response.data)) case .failure(let error): completion(.failure(error)) } } } /// Performs a network request and returns response header /// Waits for 201 - Created response code as API returns it when contains session key in header /// /// - Parameters: /// - request: HTTP / HTTPS request contained of predefined parameters /// - completion: returns response header of HTTPURLResponse type in case of successful execution, otherwise returns error with description func performTaskReturningHeader(_ request: URLRequest, completion: @escaping(Result<HTTPURLResponse?, Error>) -> Void) { performDataTask(request, expectedCode: 201) { result in switch result { case .success(let response): completion(.success(response.header)) case .failure(let error): completion(.failure(error)) } } } private func performDataTask(_ request: URLRequest, expectedCode: Int, completion: @escaping(Result<(header: HTTPURLResponse, data: Data?), Error>) -> Void) { session.dataTask(with: request) { data, response, error in if let error = error { completion(.failure(error)) } else if let response = response as? HTTPURLResponse { if response.statusCode == expectedCode { completion(.success((response, data))) } else { let customError = NSError(domain: "Invalid response code", code: response.statusCode, userInfo: nil) completion(.failure(customError)) } } }.resume() } }
0
// // RatesNetwork.swift // CryptoAPI // // Created by Alexander Eskin on 4/3/20. // Copyright © 2020 PixelPlex. All rights reserved. // import Foundation enum RatesNetwork: Resty { case rates(coins: [String]) case ratesHistory(coins: [String]) } extension RatesNetwork { var path: String { switch self { case .rates(let coins): return "rates/\(coins.description)" case .ratesHistory(coins: let coins): return "rates/\(coins.description)/history" } } var method: HTTPMethod { return .get } var bodyParameters: [String: Any]? { return nil } var queryParameters: [String: String]? { return nil } var headers: [String: String]? { return ["Content-type": "application/json"] } }
0
import UIKit @IBDesignable public class TLFloatLabelTextView: UITextView { let animationDuration = 0.0 let placeholderTextColor = UIColor.lightGray.withAlphaComponent(0.65) fileprivate var isIB = false fileprivate var titleLabel = UILabel() fileprivate var hintLabel = UILabel() fileprivate var initialTopInset:CGFloat = 0 let bottomLineView = UIView() // MARK:- Properties override public var accessibilityLabel:String? { get { if text.isEmpty { return titleLabel.text! } else { return text } } set { } } var titleFont:UIFont = UIFont.boldSystemFont(ofSize: 15.0) { didSet { titleLabel.font = titleFont } } public var hint:String = "" { didSet { titleLabel.text = hint titleLabel.sizeToFit() var r = titleLabel.frame r.size.width = frame.size.width titleLabel.frame = r hintLabel.text = hint hintLabel.sizeToFit() } } @IBInspectable var hintYPadding:CGFloat = 0.0 { didSet { adjustTopTextInset() } } @IBInspectable var titleYPadding:CGFloat = 0.0 { didSet { var r = titleLabel.frame r.origin.y = titleYPadding titleLabel.frame = r } } public var titleTextColour:UIColor = UIColor.gray { didSet { if !isFirstResponder { titleLabel.textColor = titleTextColour bottomLineView.backgroundColor = titleLabel.textColor } } } public var titleActiveTextColour:UIColor = UIColor.cyan { didSet { if isFirstResponder { titleLabel.textColor = titleActiveTextColour bottomLineView.backgroundColor = titleLabel.textColor } } } // MARK:- Init required public init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) setup() } override init(frame:CGRect, textContainer:NSTextContainer?) { super.init(frame:frame, textContainer:textContainer) setup() } deinit { if !isIB { let nc = NotificationCenter.default nc.removeObserver(self, name:NSNotification.Name.UITextViewTextDidChange, object:self) nc.removeObserver(self, name:NSNotification.Name.UITextViewTextDidBeginEditing, object:self) nc.removeObserver(self, name:NSNotification.Name.UITextViewTextDidEndEditing, object:self) } } // MARK:- Overrides override public func prepareForInterfaceBuilder() { isIB = true setup() } fileprivate func setYPositionOfBottomLineView() { let r = textRect() let fixedWidth = self.frame.size.width let newSize = self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude)) var newFrame = self.frame newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) if newFrame.size.height > self.frame.height { bottomLineView.frame = CGRect(x: r.origin.x, y:newFrame.size.height - 1 , width:r.size.width, height:1) } else { bottomLineView.frame = CGRect(x: r.origin.x, y:self.frame.height - 1 , width:r.size.width, height:1) } } override public func layoutSubviews() { super.layoutSubviews() adjustTopTextInset() hintLabel.alpha = text.isEmpty ? 1.0 : 0.0 let r = textRect() hintLabel.frame = CGRect(x:r.origin.x, y:r.origin.y, width:hintLabel.frame.size.width, height:hintLabel.frame.size.height) setTitlePositionForTextAlignment() setYPositionOfBottomLineView() let isResp = isFirstResponder if isResp { titleLabel.textColor = titleActiveTextColour bottomLineView.backgroundColor = titleLabel.textColor } else { titleLabel.textColor = titleTextColour bottomLineView.backgroundColor = titleLabel.textColor } // Should we show or hide the title label? if text.isEmpty { if isResp { showTitle(isResp) } else { // Hide hideTitle(isResp) } } else { // Show showTitle(isResp) } } // MARK:- Private Methods fileprivate func setup() { initialTopInset = textContainerInset.top textContainer.lineFragmentPadding = 0.0 titleActiveTextColour = tintColor // Placeholder label hintLabel.font = font hintLabel.text = hint hintLabel.numberOfLines = 0 hintLabel.lineBreakMode = NSLineBreakMode.byWordWrapping hintLabel.textColor = placeholderTextColor insertSubview(hintLabel, at:0) insertSubview(bottomLineView, at:1) // Set up title label titleLabel.alpha = 0.0 titleLabel.font = titleFont titleLabel.textColor = titleTextColour bottomLineView.backgroundColor = titleLabel.textColor if !hint.isEmpty { titleLabel.text = hint titleLabel.sizeToFit() } self.addSubview(titleLabel) // Observers if !isIB { let nc = NotificationCenter.default nc.addObserver(self, selector:#selector(UIView.layoutSubviews), name:NSNotification.Name.UITextViewTextDidChange, object:self) nc.addObserver(self, selector:#selector(UIView.layoutSubviews), name:NSNotification.Name.UITextViewTextDidBeginEditing, object:self) nc.addObserver(self, selector:#selector(UIView.layoutSubviews), name:NSNotification.Name.UITextViewTextDidEndEditing, object:self) } } fileprivate func adjustTopTextInset() { var inset = textContainerInset inset.top = initialTopInset + titleLabel.font.lineHeight + hintYPadding textContainerInset = inset } fileprivate func textRect()->CGRect { var r = UIEdgeInsetsInsetRect(bounds, contentInset) r.origin.x += textContainer.lineFragmentPadding r.origin.y += textContainerInset.top return r.integral } fileprivate func setTitlePositionForTextAlignment() { var titleLabelX = textRect().origin.x var placeholderX = titleLabelX if textAlignment == NSTextAlignment.center { titleLabelX = (frame.size.width - titleLabel.frame.size.width) * 0.5 placeholderX = (frame.size.width - hintLabel.frame.size.width) * 0.5 } else if textAlignment == NSTextAlignment.right { titleLabelX = frame.size.width - titleLabel.frame.size.width placeholderX = frame.size.width - hintLabel.frame.size.width } var r = titleLabel.frame r.origin.x = titleLabelX titleLabel.frame = r r = hintLabel.frame r.origin.x = placeholderX hintLabel.frame = r } fileprivate func showTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: [UIViewAnimationOptions.beginFromCurrentState, UIViewAnimationOptions.curveEaseOut], animations:{ // Animation self.titleLabel.alpha = 1.0 // set your superview's background color self.titleLabel.backgroundColor = self.superview?.backgroundColor var r = self.titleLabel.frame r.origin.y = self.titleYPadding + self.contentOffset.y self.titleLabel.frame = r }, completion:nil) } fileprivate func hideTitle(_ animated:Bool) { let dur = animated ? animationDuration : 0 UIView.animate(withDuration: dur, delay:0, options: [UIViewAnimationOptions.beginFromCurrentState, UIViewAnimationOptions.curveEaseIn], animations:{ // Animation self.titleLabel.alpha = 0.0 self.titleLabel.backgroundColor = self.backgroundColor var r = self.titleLabel.frame r.origin.y = self.titleLabel.font.lineHeight + self.hintYPadding self.titleLabel.frame = r }, completion:nil) } }
0
// // PlaySoundsViewController.swift // PitchPerfect // // Created by Edmund Korley on 2016-10-13. // Copyright © 2016 Edmund Korley. All rights reserved. // import UIKit import AVFoundation class PlaySoundsViewController: UIViewController { @IBOutlet weak var snailButton: UIButton! @IBOutlet weak var chipmunkButton: UIButton! @IBOutlet weak var rabbitButton: UIButton! @IBOutlet weak var vaderButton: UIButton! @IBOutlet weak var echoButton: UIButton! @IBOutlet weak var reverbButton: UIButton! @IBOutlet weak var stopButton: UIButton! var recordedAudioURL: NSURL! var audioFile: AVAudioFile! var audioEngine: AVAudioEngine! var audioPlayerNode: AVAudioPlayerNode! var stopTimer: Timer! enum ButtonType: Int { case Slow = 0, Fast, Chipmunk, Vader, Echo, Reverb } @IBAction func playSoundForButton(sender: UIButton) { print("Play Sound Button Pressed") switch(ButtonType(rawValue: sender.tag)!) { case .Slow: playSound(rate: 0.5) case .Fast: playSound(rate: 1.5) case .Chipmunk: playSound(rate: 1000) case .Vader: playSound(rate: -1000) case .Echo: playSound(echo: true) case .Reverb: playSound(reverb: true) } configureUI(playState: .Playing) } @IBAction func stopButtonPressed(sender: AnyObject) { print("Stop Audio Button Pressed") stopAudio() } override func viewDidLoad() { super.viewDidLoad() print("PlaySoundsViewController has loaded") setupAudio() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { configureUI(playState: .NotPlaying) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // HomeAssembly.swift // Duyog // // Created by Mounir Ybanez on 12/07/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class HomeAssembly: HomeAssemblyProtocol { var generator: HomeViewControllerGeneratorProtocol! init(generator: HomeViewControllerGeneratorProtocol) { self.generator = generator } func assemble(_ moduleOutput: HomeModuleOutputProtocol? = nil) -> UIViewController { let viewController = generator.generate() let interactor = HomeInteractor() let presenter = HomePresenter() interactor.output = presenter presenter.output = viewController viewController.moduleOutput = moduleOutput viewController.interactor = interactor return viewController as! UIViewController } }
0
// // MainCoordinator.swift // HackingWithSwift // // Created by Thomas Kellough on 6/18/20. // Copyright © 2020 Hacking with Swift. All rights reserved. // import Foundation import UIKit class MainCoordinator: Coordinator { var navigationController: UINavigationController var children = [Coordinator]() init(navigationController: UINavigationController) { self.navigationController = navigationController } func start() { let vc = ViewController.instantiate() navigationController.pushViewController(vc, animated: true) vc.coordinator = self } func show(_ project: Project) { let detailVC = DetailViewController.instantiate() detailVC.project = project detailVC.coordinator = self navigationController.pushViewController(detailVC, animated: true) } func read(_ project: Project) { let readVC = ReadViewController.instantiate() readVC.project = project navigationController.pushViewController(readVC, animated: true) } }
0
// // MetaTextBecameFirstResponderHandler // RxSwiftForms // // Created by Michael Long on 3/19/18. // Copyright © 2018 Hoy Long. All rights reserved. // import UIKit open class MetaTextBecameFirstResponderHandler: MetaTextBehaviorResponding { public static let name = "MetaTextBecameFirstResponderHandler" public var name: String? { return nil } // Allow more than one public var priority: MetaTextPriority { return .low } internal weak var textField: MetaTextField? internal let handler: (_ textField: MetaTextField) -> Void public init(_ handler: @escaping (_ textField: MetaTextField) -> Void) { self.handler = handler } public func add(to textField: MetaTextField) -> Bool { self.textField = textField return true } public var canBecomeFirstResponder: Bool? { return nil } public func responder(status: MetaTextResponderStatus) { guard let textField = textField else { return } if status == .becameFirst { handler(textField) } } }
0
// // FloatingPointExtensionsTests.swift // Swiftest // // Created by Brian Strobach on 5.04.2018. // Copyright © 2018 Appsaurus // import XCTest @testable import Swiftest final class FloatingPointExtensionsTests: XCTestCase { func testAbs() { XCTAssertEqual(Float(-9.3).abs, Float(9.3)) XCTAssertEqual(Double(-9.3).abs, Double(9.3)) } func testIsPositive() { XCTAssert(Float(1).isPositive) XCTAssertFalse(Float(0).isPositive) XCTAssertFalse(Float(-1).isPositive) XCTAssert(Double(1).isPositive) XCTAssertFalse(Double(0).isPositive) XCTAssertFalse(Double(-1).isPositive) } func testIsNegative() { XCTAssert(Float(-1).isNegative) XCTAssertFalse(Float(0).isNegative) XCTAssertFalse(Float(1).isNegative) XCTAssert(Double(-1).isNegative) XCTAssertFalse(Double(0).isNegative) XCTAssertFalse(Double(1).isNegative) } func testCeil() { XCTAssertEqual(Float(9.3).ceil, Float(10.0)) XCTAssertEqual(Double(9.3).ceil, Double(10.0)) } func testDegreesToRadians() { XCTAssertEqual(Float(180).degreesToRadians, Float.pi) XCTAssertEqual(Double(180).degreesToRadians, Double.pi) } func testFloor() { XCTAssertEqual(Float(9.3).floor, Float(9.0)) XCTAssertEqual(Double(9.3).floor, Double(9.0)) } func testRadiansToDegrees() { XCTAssertEqual(Float.pi.radiansToDegrees, Float(180)) XCTAssertEqual(Double.pi.radiansToDegrees, Double(180)) } func testOperators() { XCTAssert((Float(5.0) ± Float(2.0)) == (Float(3.0), Float(7.0)) || (Float(5.0) ± Float(2.0)) == (Float(7.0), Float(3.0))) XCTAssert((±Float(2.0)) == (Float(2.0), Float(-2.0)) || (±Float(2.0)) == (Float(-2.0), Float(2.0))) XCTAssert((Double(5.0) ± Double(2.0)) == (Double(3.0), Double(7.0)) || (Double(5.0) ± Double(2.0)) == (Double(7.0), Double(3.0))) XCTAssert((±Double(2.0)) == (Double(2.0), Double(-2.0)) || (±Double(2.0)) == (Double(-2.0), Double(2.0))) } }
0
// // pastpaper.swift // NFLSers-iOS // // Created by Qingyang Hu on 22/02/2018. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import ObjectMapper class File: Codable { init(_ object:[String:Any]){ let name = object["Key"] as! String if(name.last == "/"){ self.name = String(name.dropLast()) }else{ self.name = name } let range = self.name.range(of: "/", options: .backwards) if let range = range { self.filename = String(self.name[range.upperBound...]) } else { self.filename = self.name } if let date = object["LastModified"] as? String, let size = object["Size"] as? String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .none self.date = dateFormatter.date(from: date) self.size = numberFormatter.number(from: size)?.doubleValue } else { self.date = nil self.size = nil } } init(specialAction:String, withName name:String) { self.name = specialAction self.filename = name self.date = nil self.size = nil } let name:String let filename:String let date:Date? let size:Double? }
0
// // SettingsViewController.swift // Swiift-project1 // // Created by Kezikov Boris on 09.02.2020. // Copyright © 2020 epam. All rights reserved. // import UIKit class SettingsViewController: UIViewController{ @IBOutlet weak var rightBorder: UITextField! @IBOutlet weak var leftBorder: UITextField! weak var delegate: SettingsVCDelegate? @IBOutlet weak var but: UIButton! @IBAction func onClick(_ sender: UIButton) { let leftText:String = leftBorder.text ?? "0" let rightText:String = rightBorder.text ?? "0" if (Service.validateInput(value: leftText) && Service.validateInput(value: rightText) && Int(rightText)! > Int(leftText)!){ delegate?.callBack(left: leftText, right: rightText) } else{ Service.toast(title: NSLocalizedString(Constants.badRequestTitle, comment:""), message: NSLocalizedString(Constants.incorrectInputMessage, comment: ""),vc: self) } } public override func viewDidLoad() { super.viewDidLoad() self.definesPresentationContext = true } } protocol SettingsVCDelegate: class { func callBack(left:String, right:String) }
0
// // ObjectToSent.swift // OptionalComponents // // Created by Florentin Lupascu on 28/05/2019. // Copyright © 2019 Florentin Lupascu. All rights reserved. // import Foundation class ObjectModel { var comment: String var components: [Component] init(comment:String, components: [Component]) { self.comment = comment self.components = components } }
0
import XCTest #if !canImport(ObjectiveC) func allTests() -> [XCTestCaseEntry] { return [ testCase(ScheduledNotificationsViewControllerTests.allTests), ] } #endif
0
// // BottomSheetHeaderView.swift // BottomSheetPractice // // Created by Nathan Hancock on 9/19/18. import UIKit protocol BottomSheetHeaderViewDelegate: class { func didAdjustHeight(_ height: CGFloat) func didOverPan() func panDidRelease(_ startPoint: CGPoint, _ endPoint: CGPoint, _ velocity: CGPoint) } class BottomSheetHeaderView: UIView { weak var delegate: BottomSheetHeaderViewDelegate! var startingPoint: CGPoint? override func didMoveToSuperview() { super.didMoveToSuperview() setupPanGestureRecognizer() } override func awakeFromNib() { super.awakeFromNib() setupPanGestureRecognizer() } fileprivate func setupPanGestureRecognizer() { let panGR = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) addGestureRecognizer(panGR) } @objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) { if gestureRecognizer.state == .began { startingPoint = gestureRecognizer.location(in: self.superview) } let currentPoint = gestureRecognizer.location(in: self.superview) if startingPoint!.y - currentPoint.y < -200 { delegate.didOverPan() //toggling this back and forth quickly "cancels" the current touch without disabling the gesture recognizer. gestureRecognizer.isEnabled = false gestureRecognizer.isEnabled = true } guard let view = gestureRecognizer.view, view == self else { return } if gestureRecognizer.state == .began || gestureRecognizer.state == .changed { let translation = gestureRecognizer.translation(in: self) delegate.didAdjustHeight(translation.y) gestureRecognizer.setTranslation(CGPoint.zero, in: self) } if gestureRecognizer.state == .ended, let startingPoint = startingPoint { let velocity = gestureRecognizer.velocity(in: self.superview) let endpoint = gestureRecognizer.location(in: self.superview) delegate.panDidRelease(startingPoint, endpoint, velocity) } } }
0
import Foundation /// A predicate that determines if a state change should notify subscribers or not, by comparing previous and new states and returning a Bool true in /// case it should emit it, or false in case it should not emit it. /// It comes with some standard options like `.always`, `.never`, `.when(old, new) -> Bool` and, for `Equatable` structures, `.whenDifferent`. public enum ShouldEmitValue<StateType> { // private let evaluate: (StateType, StateType) -> Bool /// It will always emit changes, regardless of previous and new state case always /// It will never emit changes, regardless of previous and new state case never /// It's a custom-defined predicate, you'll be given old and new state, and must return a Bool indicating what you've decided from that change, /// being `true` when you want this change to be notified, or `false` when you want it to be ignored. case when((StateType, StateType) -> Bool) /// Evaluates the predicate and returns `true` in case this should be emitted, or `false` in case this change should be ignored public func shouldEmit(previous: StateType, new: StateType) -> Bool { switch self { case .always: return true case .never: return false case let .when(evaluate): return evaluate(previous, new) } } /// Evaluates the predicate and returns `true` in case this should be ignored, or `false` in case this change should be emitted. It's the exact /// inversion of `shouldEmit` and useful for operator `.removeDuplicates` that some Reactive libraries offer. public func shouldRemove(previous: StateType, new: StateType) -> Bool { !shouldEmit(previous: previous, new: new) } } extension ShouldEmitValue where StateType: Equatable { /// For `Equatable` structures, `.whenDifferent` will run `==` operator between old and new state, and notify when they are different, or ignore /// when they are equal. public static var whenDifferent: ShouldEmitValue<StateType> { .when(!=) } }
0
// // ViewController.swift // TitlebarAndToolbar // // Created by Lu Yibin on 16/3/24. // Copyright © 2016年 Lu Yibin. All rights reserved. // import Cocoa extension OptionSet { func optionState(_ opt: Self.Element) -> Int { return self.contains(opt) ? NSControl.StateValue.on.rawValue : NSControl.StateValue.off.rawValue } } class ViewController: NSViewController, NSWindowDelegate { @IBOutlet weak var unifiedTitleAndToolbarCheckbox: NSButton! @IBOutlet weak var titleAppearsTransparentCheckbox: NSButton! @IBOutlet weak var titleVisibilityCheckbox: NSButton! @IBOutlet weak var fullContentViewCheckbox: NSButton! @IBOutlet weak var titleAccessoryViewCheckbox: NSButton! @IBOutlet weak var titleAccessoryViewLayoutMatrix: NSMatrix! @IBOutlet weak var showToolbarCheckbox: NSButton! @IBOutlet weak var titleBarCheckBox: NSButton! @IBOutlet weak var closeButtonCheckBox: NSButton! @IBOutlet weak var miniaturizeButtonCheckBox: NSButton! @IBOutlet weak var zoomButtonCheckBox: NSButton! @IBOutlet weak var toolbarButtonCheckBox: NSButton! @IBOutlet weak var documentIconButtonCheckBox: NSButton! @IBOutlet weak var documentVersionsButtonCheckBox: NSButton! @IBOutlet var codeTextView: NSTextView! var windowControllers = [NSWindowController]() @objc dynamic var titleAccessoryViewEnabled : Bool { return self.titleAccessoryViewCheckbox.state == NSControl.StateValue.on } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.codeTextView.font = NSFont(name: "Monaco", size: 12) generateCode() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func showWindowWithTitle(_ controller:NSWindowController, title:String) { windowControllers.append(controller) controller.window?.title = title controller.showWindow(self) } func instantiateWindowController() -> NSWindowController? { if let storyboard = self.storyboard { return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "windowController")) as? NSWindowController } return nil } func generateCode() { var code : String = "" if unifiedTitleAndToolbarCheckbox.state == NSControl.StateValue.on { code.append("window.styleMask.insert(NSWindow.StyleMask.unifiedTitleAndToolbar)\n") } else { code.append("window.styleMask.remove(NSWindow.StyleMask.unifiedTitleAndToolbar)\n") } if fullContentViewCheckbox.state == NSControl.StateValue.on { code.append("window.styleMask.insert(NSWindow.StyleMask.fullSizeContentView)\n") } else { code.append("window.styleMask.remove(NSWindow.StyleMask.fullSizeContentView)\n") } if titleBarCheckBox.state == NSControl.StateValue.on { code.append("window.styleMask.insert(NSWindow.StyleMask.titled)\n") } else { code.append("window.styleMask.remove(NSWindow.StyleMask.titled)\n") } let showToolbar = showToolbarCheckbox.state == NSControl.StateValue.on code.append("window.toolbar?.isVisible = \(showToolbar)\n") let visibility = titleVisibilityCheckbox.state == NSControl.StateValue.off ? ".hidden" : ".visible" code.append("window.titleVisibility = \(visibility)\n") let transparent = titleAppearsTransparentCheckbox.state == NSControl.StateValue.on code.append("window.titlebarAppearsTransparent = \(transparent)\n") self.codeTextView.string = code } @IBAction func titleAccessoryChecked(_ sender: AnyObject) { self.willChangeValue(forKey: "titleAccessoryViewEnabled") self.didChangeValue(forKey: "titleAccessoryViewEnabled") self.attributeChanged(sender) } @IBAction func attributeChanged(_ sender: AnyObject) { generateCode() } func setToDefault() { let userDefaults = UserDefaults.standard if let defaultStyleMask = self.view.window?.styleMask { unifiedTitleAndToolbarCheckbox.state = NSControl.StateValue(rawValue: defaultStyleMask.optionState(NSWindow.StyleMask.unifiedTitleAndToolbar)) userDefaults.set(unifiedTitleAndToolbarCheckbox.state, forKey: "unifiedTitleAndToolbar") fullContentViewCheckbox.state = NSControl.StateValue(rawValue: defaultStyleMask.optionState(NSWindow.StyleMask.fullSizeContentView)) userDefaults.set(fullContentViewCheckbox.state, forKey: "fullSizeContentView") titleBarCheckBox.state = NSControl.StateValue(rawValue: defaultStyleMask.optionState(NSWindow.StyleMask.titled)) userDefaults.set(titleBarCheckBox.state, forKey: "titleBar") } self.titleAccessoryViewCheckbox.state = NSControl.StateValue.off userDefaults.set(NSControl.StateValue.off, forKey: "hasTitleAccessoryView") titleVisibilityCheckbox.state = NSControl.StateValue.on userDefaults.set(titleVisibilityCheckbox.state, forKey: "titleVisibility") titleAppearsTransparentCheckbox.state = NSControl.StateValue.off userDefaults.set(titleAppearsTransparentCheckbox.state, forKey: "transparentTitleBar") } @IBAction func restoreSettings(_ sender: AnyObject) { guard let popUpButton = sender as? NSPopUpButton, let item = popUpButton.selectedItem else { return } let userDefaults = UserDefaults.standard if item.tag == 1 { setToDefault() } else if item.tag == 2 { setToDefault() titleVisibilityCheckbox.state = NSControl.StateValue.off userDefaults.set(titleVisibilityCheckbox.state, forKey: "titleVisibility") showToolbarCheckbox.state = NSControl.StateValue.on userDefaults.set(showToolbarCheckbox.state, forKey:"showToolbar") } else if item.tag == 3 { setToDefault() fullContentViewCheckbox.state = NSControl.StateValue.on userDefaults.set(fullContentViewCheckbox.state, forKey: "fullSizeContentView") titleVisibilityCheckbox.state = NSControl.StateValue.off userDefaults.set(titleVisibilityCheckbox.state, forKey: "titleVisibility") titleAppearsTransparentCheckbox.state = NSControl.StateValue.on userDefaults.set(titleAppearsTransparentCheckbox.state, forKey: "transparentTitleBar") showToolbarCheckbox.state = NSControl.StateValue.off userDefaults.set(showToolbarCheckbox.state, forKey:"showToolbar") } generateCode() } @IBAction func launchWindow(_ sender: AnyObject) { if let controller = instantiateWindowController() { if let window = controller.window { if unifiedTitleAndToolbarCheckbox.state == NSControl.StateValue.on { window.styleMask.insert(NSWindow.StyleMask.unifiedTitleAndToolbar) } else { window.styleMask.remove(NSWindow.StyleMask.unifiedTitleAndToolbar) } if fullContentViewCheckbox.state == NSControl.StateValue.on { window.styleMask.insert(NSWindow.StyleMask.fullSizeContentView) } else { window.styleMask.remove(NSWindow.StyleMask.fullSizeContentView) } if titleBarCheckBox.state == NSControl.StateValue.on { window.styleMask.insert(NSWindow.StyleMask.titled) } else { window.styleMask.remove(NSWindow.StyleMask.titled) } window.toolbar?.isVisible = showToolbarCheckbox.state == NSControl.StateValue.on showWindowWithTitle(controller, title: "Window") if titleAccessoryViewEnabled { if let titlebarController = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "titlebarViewController")) as? NSTitlebarAccessoryViewController { switch self.titleAccessoryViewLayoutMatrix.selectedRow { case 0: titlebarController.layoutAttribute = .bottom case 1: titlebarController.layoutAttribute = .left case 2: titlebarController.layoutAttribute = .right case 3: titlebarController.layoutAttribute = .top default: titlebarController.layoutAttribute = .bottom } // layoutAttribute has to be set before added to window window.addTitlebarAccessoryViewController(titlebarController) } } window.titleVisibility = titleVisibilityCheckbox.state == NSControl.StateValue.off ? .hidden : .visible window.titlebarAppearsTransparent = titleAppearsTransparentCheckbox.state == NSControl.StateValue.on // Buttons window.standardWindowButton(.closeButton)?.isHidden = closeButtonCheckBox.intValue == 0 window.standardWindowButton(.miniaturizeButton)?.isHidden = miniaturizeButtonCheckBox.intValue == 0 window.standardWindowButton(.zoomButton)?.isHidden = zoomButtonCheckBox.intValue == 0 window.standardWindowButton(.toolbarButton)?.isHidden = toolbarButtonCheckBox.intValue == 0 window.standardWindowButton(.documentIconButton)?.isHidden = documentIconButtonCheckBox.intValue == 0 window.standardWindowButton(.documentVersionsButton)?.isHidden = documentVersionsButtonCheckBox.intValue == 0 } } } }
0
// // DetailsViewController.swift // Instagram // // Created by Malvern Madondo on 6/29/17. // Copyright © 2017 Malvern Madondo. All rights reserved. // import UIKit import Parse import ParseUI class DetailsViewController: UIViewController { @IBOutlet weak var captionLabel: UILabel! @IBOutlet weak var detailImageView: PFImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! var myInstaPost: PFObject! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let myInstaPost = myInstaPost{ detailImageView.file = myInstaPost["media"] as? PFFile captionLabel.text = myInstaPost["caption"] as? String let name = myInstaPost["author"] as! PFUser nameLabel.text = name.username! + " posted a new pic:" if let postTime = myInstaPost.createdAt{ let dateFormatter = DateFormatter() dateFormatter.dateStyle = .short //medium dateFormatter.timeStyle = .short let timeStr = dateFormatter.string(from: postTime) timeLabel.text = "On " + timeStr } //self.performSegue(withIdentifier: "detailSegue", sender: self) detailImageView.loadInBackground() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // SettingsViewController.swift // StarPteranoMac // // Created by takayoshi on 2018/10/25. // Copyright © 2018 pgostation. All rights reserved. // import Cocoa final class SettingsViewController: NSViewController { static weak var instance: SettingsViewController? static let width: CGFloat = 128 init() { super.init(nibName: nil, bundle: nil) let view = SettingsView() self.view = view view.accountButton.action = #selector(accountAction) view.generalButton.action = #selector(generalAction) view.uiButton.action = #selector(uiAction) view.notifyButton.action = #selector(notifyAction) view.searchButton.action = #selector(searchAction) view.colorButton.action = #selector(colorAction) view.detailButton.action = #selector(detailAction) view.filter0Button.action = #selector(filter0Action) view.filter1Button.action = #selector(filter1Action) view.filter2Button.action = #selector(filter2Action) view.filter3Button.action = #selector(filter3Action) SettingsViewController.instance = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func accountAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.accountButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = AccountSettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func generalAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.generalButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = GeneralSettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func uiAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.uiButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = UISettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func notifyAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.notifyButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = NotifySettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func filter0Action() { filterAction(index: 0) DispatchQueue.main.async { guard let view = self.view as? SettingsView else { return } view.filter0Button.highlight(true) } } @objc func filter1Action() { filterAction(index: 1) DispatchQueue.main.async { guard let view = self.view as? SettingsView else { return } view.filter1Button.highlight(true) } } @objc func filter2Action() { filterAction(index: 2) DispatchQueue.main.async { guard let view = self.view as? SettingsView else { return } view.filter2Button.highlight(true) } } @objc func filter3Action() { filterAction(index: 3) DispatchQueue.main.async { guard let view = self.view as? SettingsView else { return } view.filter3Button.highlight(true) } } private func filterAction(index: Int) { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = FilterSettingsViewController(index: index) self.addChild(vc) self.view.addSubview(vc.view) } @objc func searchAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.searchButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = SearchSettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func colorAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.colorButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = ColorSettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } @objc func detailAction() { guard let view = self.view as? SettingsView else { return } DispatchQueue.main.async { view.clearHighlight() view.detailButton.highlight(true) } self.children.first?.view.removeFromSuperview() self.children.first?.removeFromParent() let vc = DetailSettingsViewController() self.addChild(vc) self.view.addSubview(vc.view) } } private class SettingsView: NSView { private let backView = CALayer() let accountButton = NSButton() let generalButton = NSButton() let uiButton = NSButton() let notifyButton = NSButton() let searchButton = NSButton() let colorButton = NSButton() let detailButton = NSButton() let filter0Button = NSButton() let filter1Button = NSButton() let filter2Button = NSButton() let filter3Button = NSButton() init() { super.init(frame: SettingsWindow.contentRect) self.wantsLayer = true self.layer?.addSublayer(backView) self.addSubview(accountButton) self.addSubview(generalButton) self.addSubview(uiButton) self.addSubview(notifyButton) self.addSubview(searchButton) self.addSubview(colorButton) self.addSubview(detailButton) self.addSubview(filter0Button) self.addSubview(filter1Button) self.addSubview(filter2Button) self.addSubview(filter3Button) setProperties() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setProperties() { backView.backgroundColor = NSColor.textBackgroundColor.cgColor func setButtonStyle(button: NSButton) { button.bezelStyle = .shadowlessSquare button.showsBorderOnlyWhileMouseInside = true } accountButton.title = I18n.get("SETTINGS_ACCOUNT") setButtonStyle(button: accountButton) accountButton.highlight(true) generalButton.title = I18n.get("SETTINGS_GENERAL") setButtonStyle(button: generalButton) uiButton.title = I18n.get("SETTINGS_UI") setButtonStyle(button: uiButton) notifyButton.title = I18n.get("SETTINGS_NOTIFICATIONS") setButtonStyle(button: notifyButton) searchButton.title = I18n.get("SETTINGS_SEARCH") setButtonStyle(button: searchButton) colorButton.title = I18n.get("SETTINGS_COLOR") setButtonStyle(button: colorButton) detailButton.title = I18n.get("SETTINGS_DETAIL") setButtonStyle(button: detailButton) filter0Button.title = I18n.get("SETTINGS_FILTER") + "1\n" + (SettingsData.filterName(index: 0) ?? "").prefix(6) setButtonStyle(button: filter0Button) filter1Button.title = I18n.get("SETTINGS_FILTER") + "2\n" + (SettingsData.filterName(index: 1) ?? "").prefix(6) setButtonStyle(button: filter1Button) filter2Button.title = I18n.get("SETTINGS_FILTER") + "3\n" + (SettingsData.filterName(index: 2) ?? "").prefix(6) setButtonStyle(button: filter2Button) filter3Button.title = I18n.get("SETTINGS_FILTER") + "4\n" + (SettingsData.filterName(index: 3) ?? "").prefix(6) setButtonStyle(button: filter3Button) } override func updateLayer() { setProperties() } func clearHighlight() { accountButton.highlight(false) generalButton.highlight(false) uiButton.highlight(false) notifyButton.highlight(false) searchButton.highlight(false) colorButton.highlight(false) detailButton.highlight(false) filter0Button.highlight(false) filter1Button.highlight(false) filter2Button.highlight(false) filter3Button.highlight(false) } override func layout() { let height: CGFloat = 40 backView.frame = NSRect(x: 0, y: 0, width: SettingsViewController.width, height: SettingsWindow.contentRect.height) accountButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height, width: SettingsViewController.width, height: height) generalButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 2, width: SettingsViewController.width, height: height) uiButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 3, width: SettingsViewController.width, height: height) notifyButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 4, width: SettingsViewController.width, height: height) /*searchButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 5, width: SettingsViewController.width, height: height)*/ colorButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 5, width: SettingsViewController.width, height: height) detailButton.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 6, width: SettingsViewController.width, height: height) filter0Button.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 7, width: SettingsViewController.width, height: height) filter1Button.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 8, width: SettingsViewController.width, height: height) filter2Button.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 9, width: SettingsViewController.width, height: height) filter3Button.frame = NSRect(x: 0, y: SettingsWindow.contentRect.height - height * 10, width: SettingsViewController.width, height: height) } }
0
/* 1. Two Sum Tag: Array、 Hash Table https://leetcode.com/problems/two-sum/description/ */ /** Hash Table实现. 时间复杂度O(n), 空间复杂度O(n) */ func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var numIndexDic: [Int: Int] = [:] for i in 0..<nums.count { let diff = target - nums[i] if numIndexDic.keys.contains(diff) { return [numIndexDic[diff]!, i] } numIndexDic[nums[i]] = i } return [] }
0
import Foundation public class UploadRequest: HttpRequest { private var task: URLSessionUploadTask? private var uploadFileUrl: URL? private var tmpFileUrl: URL? { get { return URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("upload-\(tag)") } } // MARK: - Public Methods public func uploadFileUrl(_ url: URL) -> Self { uploadFileUrl = url return self } // MARK: - Overridden methods public override func cancel() { super.cancel() if let task = task { task.cancel() clearTmpFile() NotificationCenter.default.post(name: Notification.Name(rawValue: "SilkRequestEnded"), object: nil) } } public override func execute() -> Bool { if !(super.execute()) { return false } if let uploadFileUrl = uploadFileUrl, FileManager.default.fileExists(atPath: uploadFileUrl.path) { task = manager.backgroundSession.uploadTask(with: request as URLRequest, fromFile: uploadFileUrl) } else if let bodyData = request.httpBody { if let tmpFileUrl = tmpFileUrl { if (try? bodyData.write(to: tmpFileUrl, options: [.atomic])) != nil { task = manager.backgroundSession.uploadTask(with: request as URLRequest, fromFile: tmpFileUrl) } else { print("[Silk] unable to write tmp upload file") } } } else { print("[Silk] unable to execute request - no data to upload") return false } if let task = task { task.taskDescription = tag manager.registerRequest(self) task.resume() NotificationCenter.default.post(name: Notification.Name(rawValue: "SilkRequestStarted"), object: nil) return true } else { return false } } override func handleResponse(_ response: HTTPURLResponse, error: NSError?, task: URLSessionTask) { super.handleResponse(response, error: error, task: task) clearTmpFile() } // MARK: - Private Methods private func clearTmpFile() { if let tmpFileUrl = tmpFileUrl, FileManager.default.fileExists(atPath: tmpFileUrl.path) { do { try FileManager.default.removeItem(at: tmpFileUrl) } catch {} } } }
0
public class BulgeDistortion: BasicOperation { public var radius:Float = 0.25 { didSet { uniformSettings["radius"] = radius } } public var scale:Float = 0.5 { didSet { uniformSettings["scale"] = scale } } public var center:Position = Position.center { didSet { uniformSettings["center"] = center } } public init() { super.init(fragmentFunctionName:"bulgeDistortionFragment", numberOfInputs:1) ({radius = 0.25})() ({scale = 0.5})() ({center = Position.center})() } }
0
// // NotesTableViewCell.swift // Notes // // Created by Vasilis Sakkas on 28/03/2019. // Copyright © 2019 Vasilis Sakkas. All rights reserved. // import UIKit class NotesTableViewCell: UITableViewCell { static let reuse_id = "NotesTableViewCell" var note : Note? { didSet { noteTitleLabel.text = note!.title } } private let noteTitleLabel: UILabel = { let label = UILabel() return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) uiSetup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func uiSetup() { contentView.addSubview(noteTitleLabel) noteTitleLabel.anchor(top: nil, left: contentView.leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 0, height: 0, enableInsets: false) noteTitleLabel.anchor(centerX: nil, centerY: contentView.centerYAnchor) } }
0
// // Created by duan on 2018/3/7. // 2018 Copyright (c) RxSwiftCommunity. All rights reserved. // #if os(iOS) || os(tvOS) || os(macOS) import QuartzCore import RxSwift import RxCocoa public extension ThemeProxy where Base: CAShapeLayer { /// (set only) bind a stream to strokeColor var strokeColor: ThemeAttribute<CGColor?> { get { return .empty() } set { if let value = newValue.value { base.strokeColor = value } let disposable = newValue.stream .take(until: base.rx.deallocating) .observe(on: MainScheduler.instance) .bind(to: base.rx.strokeColor) hold(disposable, for: "strokeColor") } } /// (set only) bind a stream to fillColor var fillColor: ThemeAttribute<CGColor?> { get { return .empty() } set { if let value = newValue.value { base.fillColor = value } let disposable = newValue.stream .take(until: base.rx.deallocating) .observe(on: MainScheduler.instance) .bind(to: base.rx.fillColor) hold(disposable, for: "fillColor") } } } #endif
0
import UIKit import SnapKit import ThemeKit import SectionsTableView import HUD class GuidesViewController: ThemeViewController { private static let spinnerRadius: CGFloat = 8 private static let spinnerLineWidth: CGFloat = 2 private let delegate: IGuidesViewDelegate private let tableView = UITableView(frame: .zero, style: .plain) private let filterHeaderView = FilterHeaderView() private let spinner = HUDProgressView( strokeLineWidth: GuidesViewController.spinnerLineWidth, radius: GuidesViewController.spinnerRadius, strokeColor: .themeGray ) private var viewItems = [GuideViewItem]() init(delegate: IGuidesViewDelegate) { self.delegate = delegate super.init() tabBarItem = UITabBarItem(title: "guides.tab_bar_item".localized, image: UIImage(named: "Guides Tab Bar"), tag: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "guides.title".localized view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } tableView.separatorStyle = .none tableView.backgroundColor = .clear tableView.registerCell(forClass: GuideCell.self) tableView.dataSource = self tableView.delegate = self filterHeaderView.onSelect = { [weak self] index in self?.delegate.onSelectFilter(index: index) } view.addSubview(spinner) spinner.snp.makeConstraints { maker in maker.center.equalToSuperview() maker.width.height.equalTo(GuidesViewController.spinnerRadius * 2 + GuidesViewController.spinnerLineWidth) } delegate.onLoad() } } extension GuidesViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { viewItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.dequeueReusableCell(withIdentifier: String(describing: GuideCell.self), for: indexPath) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? GuideCell { let index = indexPath.row cell.bind( viewItem: viewItems[index], first: index == 0, last: index == viewItems.count - 1 ) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate.onTapGuide(index: indexPath.row) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let index = indexPath.row return GuideCell.height( containerWidth: tableView.width, viewItem: viewItems[index], first: index == 0, last: index == viewItems.count - 1 ) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { filterHeaderView.headerHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { filterHeaderView } } extension GuidesViewController: IGuidesView { func set(filterViewItems: [FilterHeaderView.ViewItem]) { filterHeaderView.reload(filters: filterViewItems) } func set(viewItems: [GuideViewItem]) { self.viewItems = viewItems } func refresh() { tableView.reloadData() } func setSpinner(visible: Bool) { if visible { spinner.isHidden = false spinner.startAnimating() } else { spinner.isHidden = true spinner.stopAnimating() } } }
0
// // Xcore // Copyright © 2017 Xcore // MIT license, see LICENSE file for details // import UIKit open class ZoomAnimator: TransitionAnimator { private let source: ZoomAnimatorSource private let destination: ZoomAnimatorDestination public required init(source: ZoomAnimatorSource, destination: ZoomAnimatorDestination, direction: AnimationDirection) { self.source = source self.destination = destination super.init() self.direction = direction } open override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { direction == .in ? source.zoomAnimatorSourceDuration : destination.zoomAnimatorDestinationDuration } open override func transition(context: TransitionContext, direction: AnimationDirection) { switch direction { case .in: animateTransitionForPush(context) case .out: animateTransitionForPop(context) } } private func animateTransitionForPush(_ context: TransitionContext) { guard let sourceView = context.from.view, let destinationView = context.to.view else { return context.completeTransition() } let containerView = context.containerView let transitioningImageView = transitioningPushImageView() containerView.backgroundColor = sourceView.backgroundColor sourceView.alpha = 1 destinationView.alpha = 0 if direction == .out { containerView.insertSubview(destinationView, belowSubview: sourceView) } containerView.addSubview(transitioningImageView) source.zoomAnimatorSourceStateChanged(state: .began) destination.zoomAnimatorDestinationStateChanged(state: .began) let destinationViewFrame = destination.zoomAnimatorDestinationViewFrame(direction: direction) source.zoomAnimatorSourceAnimation(animations: { sourceView.alpha = 0 destinationView.alpha = 1 transitioningImageView.frame = destinationViewFrame }, completion: { sourceView.alpha = 1 transitioningImageView.alpha = 0 transitioningImageView.removeFromSuperview() self.source.zoomAnimatorSourceStateChanged(state: .ended) self.destination.zoomAnimatorDestinationStateChanged(state: .ended) context.completeTransition() }) } private func animateTransitionForPop(_ context: TransitionContext) { guard let sourceView = context.to.view, let destinationView = context.from.view else { return context.completeTransition() } let containerView = context.containerView let transitioningImageView = transitioningPopImageView() containerView.backgroundColor = destinationView.backgroundColor destinationView.alpha = 1 sourceView.alpha = 0 if direction == .out { containerView.insertSubview(sourceView, belowSubview: destinationView) } containerView.addSubview(transitioningImageView) source.zoomAnimatorSourceStateChanged(state: .began) destination.zoomAnimatorDestinationStateChanged(state: .began) let sourceViewFrame = destination.zoomAnimatorDestinationViewFrame(direction: direction) if transitioningImageView.frame.maxY < 0 { transitioningImageView.frame.origin.y = -transitioningImageView.frame.height } destination.zoomAnimatorDestinationAnimation(animations: { destinationView.alpha = 0 sourceView.alpha = 1 transitioningImageView.frame = sourceViewFrame }, completion: { destinationView.alpha = 1 transitioningImageView.removeFromSuperview() self.source.zoomAnimatorSourceStateChanged(state: .ended) self.destination.zoomAnimatorDestinationStateChanged(state: .ended) context.completeTransition() }) } private func transitioningPushImageView() -> UIImageView { let imageView = source.zoomAnimatorSourceView().snapshotImageView() imageView.frame = source.zoomAnimatorSourceViewFrame(direction: direction) return imageView } private func transitioningPopImageView() -> UIImageView { let imageView = source.zoomAnimatorSourceView().snapshotImageView() imageView.frame = destination.zoomAnimatorDestinationViewFrame(direction: direction) return imageView } }
0
// swift-tools-version:5.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Drawer", platforms: [ .iOS(.v11), ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "Drawer", targets: ["Drawer"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "Drawer", dependencies: []), .testTarget( name: "DrawerTests", dependencies: ["Drawer"], path: "Drawer/DrawerTests"), ] )
0
//: Playground - noun: a place where people can play import UIKit var greetings:String = "Hello " var name:String? = "Alok" print(greetings + " ") if let name = name{ print(name) } else{ print("nothing") } // part 2 println("\npart 2") println(greetings + name!)
0
// // MusicAccount.swift // MyMusic // // Created by Yerneni, Naresh on 4/29/17. // Copyright © 2017 Yerneni, Naresh. All rights reserved. // import Foundation class MusicAccount { // func post(unfavoriteTweetID : Int, success : @escaping (Tweet) -> (), error : @escaping (Error) -> ()) { // homeTimeLineService.post(unfavoriteTweetID: unfavoriteTweetID, success: success, error: error) // } }
0
// // Business.swift // Yelp // // Created by Joe Gasiorek on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit public class Business: NSObject { var imageUrl : String? var name : String? var ratingImageUrl : String? var numReviews: Int? var address: String? var categories: String? var distance: Float? init(dictionary: AnyObject) { self.imageUrl = dictionary["image_url"] as? String self.name = dictionary["name"] as? String self.ratingImageUrl = dictionary["rating_img_url"] as? String self.numReviews = dictionary["review_count"] as? Int } public static func businessesWithDictionaries(dictionaries: NSArray) -> [Business] { var list = [Business]() for dict in dictionaries { var business = Business(dictionary: dict) } return list } }
0
// // // Confirmation3DSData.swift // // Copyright (c) 2021 Tinkoff Bank // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public struct Confirmation3DSData: Codable { var acsUrl: String var pareq: String var md: String enum CodingKeys: String, CodingKey { case acsUrl = "ACSUrl" case pareq = "PaReq" case md = "MD" } }
0
// // BlurredBackgroundView.swift // // Created by Jeff on 12/4/15. // Copyright © 2015 Jeff Greenberg. All rights reserved. // import UIKit /// UIView that's a blurred image for background display public class BlurredBackgroundView: UIView { private var imageView: UIImageView! private var effectView: UIVisualEffectView! public func getBlurEffect() -> UIBlurEffect { return (self.effectView.effect as! UIBlurEffect) } convenience init(frame: CGRect, img: UIImage) { self.init(frame: frame) self.setImageWithBlurEffect(img) } override init(frame: CGRect) { super.init(frame: frame) } public convenience required init?(coder aDecoder: NSCoder) { self.init(frame: CGRectZero) } /// create blurred background based on image /// adds image & effect as subviews private func setImageWithBlurEffect(img: UIImage) { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) effectView = UIVisualEffectView(effect: blurEffect) imageView = UIImageView(image: img) addSubview(imageView) addSubview(effectView) } public override func layoutSubviews() { super.layoutSubviews() imageView.frame = bounds effectView.frame = bounds } }
0
// // SearchControllerHandler.swift // ReadTheMantra // // Created by Alex Vorobiev on 29.11.2021. // Copyright © 2021 Alex Vorobiev. All rights reserved. // import UIKit final class SearchControllerHandler: NSObject { private var searchResultsContinuation: AsyncStream<Void>.Continuation? private var dismissContinuation: AsyncStream<Void>.Continuation? init(_ searchController: UISearchController) { super.init() searchController.searchResultsUpdater = self searchController.delegate = self } func listenForSearchUpdating() async -> AsyncStream<Void> { AsyncStream<Void> { continuation in self.searchResultsContinuation = continuation } } func listenForSearchControllerDismiss() async -> AsyncStream<Void> { AsyncStream<Void> { continuation in self.dismissContinuation = continuation } } deinit { searchResultsContinuation?.finish() dismissContinuation?.finish() } } extension SearchControllerHandler: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { searchResultsContinuation?.yield() } } extension SearchControllerHandler: UISearchControllerDelegate { func didDismissSearchController(_ searchController: UISearchController) { dismissContinuation?.yield() } }
0
// // PKRigidBody.swift // BulletPhysics // // Created by Adam Eisfeld on 2020-06-10. // Copyright © 2020 adam. All rights reserved. // import Foundation /// RigidBody instances are attached to PhysicsWorlds to represent a rigid body in the simulation. public class PKRigidBody: PKBRigidBody { /// A unique identifier for this rigid body, used internally public let uuid: String = UUID().uuidString /// The type of this rigid body public let type: PKRigidBodyType /// Creates a new rigid body /// - Parameters: /// - type: The type of rigid body to create /// - shape: The shape to use for collision detections for this rigid body public init(type: PKRigidBodyType, shape: PKCollisionShape) { self.type = type super.init(collisionShape: shape.internalShape, rigidBodyType: type.internalType, mass: type.mass) } }
0
/* SingleBoard - C.H.I.P Copyright (c) 2018 Adam Thayer Licensed under the MIT license, as follows: 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.) */ class ChipBoard: ChipCapabilities { public let i2cMainBus: BoardI2CBus = { return SysI2CBus(busIndex: 1) }() public private(set) lazy var i2cBus: BoardI2CBusSet = { return SysI2CBoard(range: 1...2, mainBus: self.i2cMainBus) }() }
0
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "DeclarativeUIKit", platforms: [ .iOS(.v10) ], products: [ .library( name: "DeclarativeUIKit", targets: ["DeclarativeUIKit"]), ], targets: [ .target( name: "DeclarativeUIKit", dependencies: []), .testTarget( name: "DeclarativeUIKitTests", dependencies: ["DeclarativeUIKit"]), ] )
0
// // C2DriveLength+Parsing.swift // Pods // // Created by Jesse Curry on 10/27/15. // // extension C2DriveLength { /** */ init(driveLengthWithLow low:UInt8) { let driveLengthMultiplier:C2DriveLength = 0.01 self = C2DriveLength(low) * driveLengthMultiplier } }
0
// // FolderEventFilterSpec.swift // FBSnapshotsViewer // // Created by Anton Domashnev on 13/03/2017. // Copyright © 2017 Anton Domashnev. All rights reserved. // import Quick import Nimble @testable import FBSnapshotsViewer class FolderEventFilterSpec: QuickSpec { override func spec() { describe(".apply") { context("when known filter") { it("filters unknown events") { expect(FolderEventFilter.known.apply(to: FolderEvent.unknown)).to(beFalse()) expect(FolderEventFilter.known.apply(to: FolderEvent.created(path: "path1", object: .folder))).to(beTrue()) expect(FolderEventFilter.known.apply(to: FolderEvent.renamed(path: "path2", object: .file))).to(beTrue()) expect(FolderEventFilter.known.apply(to: FolderEvent.deleted(path: "path1", object: .folder))).to(beTrue()) expect(FolderEventFilter.known.apply(to: FolderEvent.modified(path: "path2", object: .file))).to(beTrue()) } } context("when type filder") { it("filters by type") { expect(FolderEventFilter.type(.file).apply(to: FolderEvent.unknown)).to(beFalse()) expect(FolderEventFilter.type(.file).apply(to: FolderEvent.created(path: "path1", object: .folder))).to(beFalse()) expect(FolderEventFilter.type(.folder).apply(to: FolderEvent.deleted(path: "path1", object: .folder))).to(beTrue()) } } context("when path regex") { it("filters using regular expression on path") { let filter = FolderEventFilter.pathRegex("(diff)_.+\\.png$") expect(filter.apply(to: FolderEvent.unknown)).to(beFalse()) expect(filter.apply(to: FolderEvent.created(path: "testuser/documents/project/tests/diff_myimage.png", object: .folder))).to(beTrue()) expect(filter.apply(to: FolderEvent.deleted(path: "testuser/documents/project/tests/diffmyimage.png", object: .folder))).to(beFalse()) expect(filter.apply(to: FolderEvent.modified(path: "testuser/documents/project/tests/_myimage.png", object: .folder))).to(beFalse()) expect(filter.apply(to: FolderEvent.renamed(path: "testuser/documents/project/tests/diff_myimage.jpg", object: .folder))).to(beFalse()) } } context("when compound") { it("sums up two filters") { let filter1 = FolderEventFilter.pathRegex("(diff)_.+\\.png$") let filter2 = FolderEventFilter.type(.file) let resultFilter = filter1 & filter2 expect(resultFilter.apply(to: FolderEvent.created(path: "testuser/documents/project/tests/diff_myimage.png", object: .folder))).to(beFalse()) expect(resultFilter.apply(to: FolderEvent.created(path: "testuser/documents/project/tests/myimage.png", object: .folder))).to(beFalse()) expect(resultFilter.apply(to: FolderEvent.created(path: "testuser/documents/project/tests/myimage.png", object: .file))).to(beFalse()) expect(resultFilter.apply(to: FolderEvent.created(path: "testuser/documents/project/tests/diff_myimage.png", object: .file))).to(beTrue()) } } } } }
0
// // ViewController.swift // SimonSays // // Created by Formative Mini on 8/19/18. // Copyright © 2018 Formative Web Solutions. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
0
// // ReactNavigationImplementation.swift // NativeNavigation // // Created by Leland Richardson on 2/14/17. // // import Foundation import UIKit @objc public protocol ReactNavigationImplementation: class { func makeNavigationController(rootViewController: UIViewController) -> UINavigationController func reconcileScreenConfig( viewController: ReactViewController, navigationController: UINavigationController?, prev: [String: AnyObject], next: [String: AnyObject] ) func reconcileTabConfig( tabBarItem: UITabBarItem, prev: [String: AnyObject], next: [String: AnyObject] ) func reconcileTabBarConfig( tabBar: UITabBar, prev: [String: AnyObject], next: [String: AnyObject] ) func getBarHeight(viewController: ReactViewController, navigationController: UINavigationController?, config: [String: AnyObject]) -> CGFloat; } // this is a convenience class to allow us to easily assign lambdas as press handlers class BlockBarButtonItem: UIBarButtonItem { var actionHandler: ((Void) -> Void)? convenience init(title: String?, style: UIBarButtonItemStyle) { self.init(title: title, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self } convenience init(image: UIImage?, style: UIBarButtonItemStyle) { self.init(image: image, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self } convenience init( title: String?, image: UIImage?, style: UIBarButtonItemStyle, enabled: Bool?, tintColor: UIColor?, titleTextAttributes: [String: Any]? ) { if let title = title { self.init(title: title, style: style) } else { self.init(image: image, style: style) } if let enabled = enabled { isEnabled = enabled } if let tintColor = tintColor { self.tintColor = tintColor } if let titleTextAttributes = titleTextAttributes { // TODO(lmr): what about other control states? do we care? setTitleTextAttributes(titleTextAttributes, for: .normal) } } func barButtonItemPressed(sender: UIBarButtonItem) { actionHandler?() } } func stringHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { let a = stringForKey(key, prev) let b = stringForKey(key, next) if let a = a, let b = b { return a != b } else if let a = a { return true } else if let b = b { return true } return false } func boolHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { let a = boolForKey(key, prev) let b = boolForKey(key, next) if let a = a, let b = b { return a != b } else if let a = a { return true } else if let b = b { return true } return false } func numberHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { if let before = prev[key] as? NSNumber, (before != nil) { if let after = next[key] as? NSNumber, (after != nil) { return before != after } else { return true } } else if let after = next[key] as? NSNumber, (after != nil) { return true } return false } func mapHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { if let before = prev[key] { if let after = next[key] { return true // TODO: could do more here... } else { return true } } else if let after = next[key] { return true } return false } func colorForKey(_ key: String, _ props: [String: AnyObject]) -> UIColor? { guard let val = props[key] as? NSNumber, (val != nil) else { return nil } let argb: UInt = val.uintValue; let a = CGFloat((argb >> 24) & 0xFF) / 255.0; let r = CGFloat((argb >> 16) & 0xFF) / 255.0; let g = CGFloat((argb >> 8) & 0xFF) / 255.0; let b = CGFloat(argb & 0xFF) / 255.0; return UIColor(red: r, green: g, blue: b, alpha: a) } func stringForKey(_ key: String, _ props: [String: AnyObject]) -> String? { if let val = props[key] as? String?, (val != nil) { return val } return nil } func intForKey(_ key: String, _ props: [String: AnyObject]) -> Int? { if let val = props[key] as? Int { return val } return nil } func floatForKey(_ key: String, _ props: [String: AnyObject]) -> CGFloat? { if let val = props[key] as? CGFloat { return val } return nil } func doubleForKey(_ key: String, _ props: [String: AnyObject]) -> Double? { if let val = props[key] as? Double { return val } return nil } func boolForKey(_ key: String, _ props: [String: AnyObject]) -> Bool? { if let val = props[key] as? Bool { return val } return nil } func imageForKey(_ key: String, _ props: [String: AnyObject]) -> UIImage? { if let json = props[key] as? NSDictionary, (json != nil) { return RCTConvert.uiImage(json) } return nil } func barButtonStyleFromString(_ string: String?) -> UIBarButtonItemStyle { switch(string) { case .some("done"): return .done default: return .plain } } func statusBarStyleFromString(_ string: String?) -> UIStatusBarStyle { switch(string) { case .some("light"): return .lightContent default: return .default } } func statusBarAnimationFromString(_ string: String?) -> UIStatusBarAnimation { switch(string) { case .some("slide"): return .slide case .some("none"): return .none default: return UIStatusBarAnimation.fade } } func textAttributesFromPrefix( _ prefix: String, _ props: [String: AnyObject] ) -> [String: Any]? { var attributes: [String: Any] = [:] if let color = colorForKey("\(prefix)Color", props) { attributes[NSForegroundColorAttributeName] = color } else if let color = colorForKey("foregroundColor", props) { attributes[NSForegroundColorAttributeName] = color } let fontName = stringForKey("\(prefix)FontName", props) let fontSize = floatForKey("\(prefix)FontSize", props) // TODO(lmr): use system font if no fontname is given if let name = fontName, let size = fontSize { if let font = UIFont(name: name, size: size) { attributes[NSFontAttributeName] = font } } return attributes.count == 0 ? nil : attributes } func lower(_ key: String) -> String { let i = key.index(key.startIndex, offsetBy: 1) return key.substring(to: i).lowercased() + key.substring(from: i) } func configurebarButtonItemFromPrefix( _ prefix: String, _ props: [String: AnyObject], _ passedItem: UIBarButtonItem? ) -> BlockBarButtonItem? { // ?.customView = nil // ?.setBackButtonBackgroundImage(nil, for: .focused, barMetrics: .default) // ?.style = .done // ?.tintColor = UIColor.black // ?.width = 20 // ?.accessibilityLabel = "" // ?.image = nil // ?.isEnabled = false let title = stringForKey(lower("\(prefix)Title"), props) let image = imageForKey(lower("\(prefix)Image"), props) let enabled = boolForKey(lower("\(prefix)Enabled"), props) let tintColor = colorForKey(lower("\(prefix)TintColor"), props) let style = stringForKey(lower("\(prefix)Style"), props) let titleTextAttributes = textAttributesFromPrefix(lower("\(prefix)Title"), props) if let prev = passedItem { if ( title != prev.title || enabled != prev.isEnabled || tintColor != prev.tintColor ) { return BlockBarButtonItem( title: title ?? prev.title, image: image ?? prev.image, style: barButtonStyleFromString(style), enabled: enabled, tintColor: tintColor, titleTextAttributes: titleTextAttributes ) } else { return nil } } else { if (title != nil || image != nil) { return BlockBarButtonItem( title: title, image: image, style: barButtonStyleFromString(style), enabled: enabled, tintColor: tintColor, titleTextAttributes: titleTextAttributes ) } else { return nil } } } func configureBarButtonArrayForKey(_ key: String, _ props: [String: AnyObject]) -> [BlockBarButtonItem]? { if let buttons = props[key] as? [AnyObject] { var result = [BlockBarButtonItem]() for item in buttons { if let buttonProps = item as? [String: AnyObject] { if let button = configurebarButtonItemFromPrefix("", buttonProps, nil) { result.append(button) } } } return result } return nil } open class DefaultReactNavigationImplementation: ReactNavigationImplementation { public func getBarHeight( viewController: ReactViewController, navigationController: UINavigationController?, config: [String: AnyObject] ) -> CGFloat { var statusBarHidden = false var navBarHidden = false var hasPrompt = false; if let hidden = boolForKey("statusBarHidden", config) { statusBarHidden = hidden } if let hidden = boolForKey("hidden", config) { navBarHidden = hidden } if let prompt = stringForKey("prompt", config) { hasPrompt = true } if let navController = navigationController { return navController.navigationBar.frame.height + (statusBarHidden ? 0 : 20) } // make a best guess based on config return (statusBarHidden ? 0 : 20) + (navBarHidden ? 0 : 44) + (hasPrompt ? 30 : 0) } public func makeNavigationController(rootViewController: UIViewController) -> UINavigationController { // TODO(lmr): pass initialConfig // TODO(lmr): do we want to provide a way to customize the NavigationBar class? return UINavigationController(rootViewController: rootViewController) } public func reconcileTabConfig( tabBarItem: UITabBarItem, prev: [String: AnyObject], next: [String: AnyObject] ){ if mapHasChanged("image", prev, next) { tabBarItem.image = imageForKey("image", next) } if stringHasChanged("title", prev, next) { tabBarItem.title = stringForKey("title", next) } // badgeValue // selectedImage // titlePositionAdjustment // tabBarItem.title = title // tabBarItem.badgeColor // tabBarItem.badgeTextAttributes(for: .normal) // tabBarItem.badgeValue // tabBarItem.selectedImage // tabBarItem.imageInsets // tabBarItem.titleTextAttributes(for: .normal) // tabBarItem.titlePositionAdjustment } public func reconcileTabBarConfig( tabBar: UITabBar, prev: [String: AnyObject], next: [String: AnyObject] ) { if boolHasChanged("translucent", prev, next) { if let translucent = boolForKey("translucent", next) { tabBar.isTranslucent = translucent } else { tabBar.isTranslucent = false } } if numberHasChanged("tintColor", prev, next) { if let tintColor = colorForKey("tintColor", next) { tabBar.tintColor = tintColor } else { } } if numberHasChanged("barTintColor", prev, next) { if let barTintColor = colorForKey("barTintColor", next) { tabBar.barTintColor = barTintColor } else { } } // tabBar.alpha // tabBar.backgroundColor // itemPositioning // barStyle // itemSpacing float // itemWidth: float // backgroundImage: image // shadowImage: image // selectionIndicatorImage: image // unselectedItemTintColor: color } public func reconcileScreenConfig( viewController: ReactViewController, navigationController: UINavigationController?, prev: [String: AnyObject], next: [String: AnyObject] ) { // status bar if let statusBarHidden = boolForKey("statusBarHidden", next) { viewController.setStatusBarHidden(statusBarHidden) } else { viewController.setStatusBarHidden(false) } if stringHasChanged("statusBarStyle", prev, next) { if let statusBarStyle = stringForKey("statusBarStyle", next) { viewController.setStatusBarStyle(statusBarStyleFromString(statusBarStyle)) } else { viewController.setStatusBarStyle(.default) } } if let statusBarAnimation = stringForKey("statusBarAnimation", next) { viewController.setStatusBarAnimation(statusBarAnimationFromString(statusBarAnimation)) } else { viewController.setStatusBarAnimation(.fade) } viewController.updateStatusBarIfNeeded() let navItem = viewController.navigationItem if let titleView = titleAndSubtitleViewFromProps(next) { if let title = stringForKey("title", next) { // set the title anyway, for accessibility viewController.title = title } navItem.titleView = titleView } else if let title = stringForKey("title", next) { navItem.titleView = nil viewController.title = title } if let screenColor = colorForKey("screenColor", next) { viewController.view.backgroundColor = screenColor } if let prompt = stringForKey("prompt", next) { navItem.prompt = prompt } else if navItem.prompt != nil { navItem.prompt = nil } if let rightBarButtonItems = configureBarButtonArrayForKey("rightButtons", next) { for (i, item) in rightBarButtonItems.enumerated() { item.actionHandler = { [weak viewController] in viewController?.emitEvent("onRightPress", body: i as AnyObject?) } } navItem.setRightBarButtonItems(rightBarButtonItems, animated: true) } else if let rightBarButtonItem = configurebarButtonItemFromPrefix("right", next, navItem.rightBarButtonItem) { rightBarButtonItem.actionHandler = { [weak viewController] in viewController?.emitEvent("onRightPress", body: nil) } navItem.setRightBarButton(rightBarButtonItem, animated: true) } // TODO(lmr): we have to figure out how to reset this back to the default "back" behavior... if let leftBarButtonItems = configureBarButtonArrayForKey("leftButtons", next) { for (i, item) in leftBarButtonItems.enumerated() { item.actionHandler = { [weak viewController] in viewController?.emitEvent("onLeftPress", body: i as AnyObject?) } } navItem.setLeftBarButtonItems(leftBarButtonItems, animated: true) } else if let leftBarButtonItem = configurebarButtonItemFromPrefix("left", next, navItem.leftBarButtonItem) { leftBarButtonItem.actionHandler = { [weak viewController] in // TODO(lmr): we want to dismiss here... viewController?.emitEvent("onLeftPress", body: nil) } navItem.setLeftBarButton(leftBarButtonItem, animated: true) } if let hidesBackButton = boolForKey("hidesBackButton", next) { navItem.setHidesBackButton(hidesBackButton, animated: true) } if let navController = navigationController { if let hidesBarsOnTap = boolForKey("hidesBarsOnTap", next) { navController.hidesBarsOnTap = hidesBarsOnTap } if let hidesBarsOnSwipe = boolForKey("hidesBarsOnSwipe", next) { navController.hidesBarsOnSwipe = hidesBarsOnSwipe } if let hidesBarsWhenKeyboardAppears = boolForKey("hidesBarsWhenKeyboardAppears", next) { navController.hidesBarsWhenKeyboardAppears = hidesBarsWhenKeyboardAppears } if let hidden = boolForKey("hidden", next) { navController.setNavigationBarHidden(hidden, animated: true) } if let isToolbarHidden = boolForKey("isToolbarHidden", next) { navController.setToolbarHidden(isToolbarHidden, animated: true) } let navBar = navController.navigationBar if let titleAttributes = textAttributesFromPrefix("title", next) { navBar.titleTextAttributes = titleAttributes } if let backIndicatorImage = imageForKey("backIndicatorImage", next) { navBar.backIndicatorImage = backIndicatorImage } if let backIndicatorTransitionMaskImage = imageForKey("backIndicatorTransitionMaskImage", next) { navBar.backIndicatorTransitionMaskImage = backIndicatorTransitionMaskImage } if let backgroundColor = colorForKey("backgroundColor", next) { navBar.barTintColor = backgroundColor } if let foregroundColor = colorForKey("foregroundColor", next) { navBar.tintColor = foregroundColor } if let alpha = floatForKey("alpha", next) { navBar.alpha = alpha } if let translucent = boolForKey("translucent", next) { navBar.isTranslucent = translucent } // navigationController?.navigationBar.barStyle = .blackTranslucent // navigationController?.navigationBar.shadowImage = nil } // viewController.navigationItem.titleView = nil // viewController.navigationItem.accessibilityHint = "" // viewController.navigationItem.accessibilityLabel = "" // viewController.navigationItem.accessibilityValue = "" // viewController.navigationItem.accessibilityTraits = 1 // TODO: // right button(s) // statusbar stuff } } func getFont(_ name: String, _ size: CGFloat) -> UIFont { guard let font = UIFont(name: name, size: size) else { return UIFont.systemFont(ofSize: size) } return font } func buildFontFromProps(nameKey: String, sizeKey: String, defaultSize: CGFloat, props: [String: AnyObject]) -> UIFont { let name = stringForKey(nameKey, props) let size = floatForKey(sizeKey, props) if let name = name, let size = size { return getFont(name, size) } else if let name = name { return getFont(name, defaultSize) } else if let size = size { return UIFont.systemFont(ofSize: size) } else { return UIFont.systemFont(ofSize: defaultSize) } } func titleAndSubtitleViewFromProps(_ props: [String: AnyObject]) -> UIView? { guard let title = stringForKey("title", props) else { return nil } guard let subtitle = stringForKey("subtitle", props) else { return nil } let titleHeight = 18 let subtitleHeight = 12 let foregroundColor = colorForKey("foregroundColor", props) let titleLabel = UILabel(frame: CGRect(x:0, y:-5, width:0, height:0)) titleLabel.backgroundColor = UIColor.clear if let titleColor = colorForKey("titleColor", props) { titleLabel.textColor = titleColor } else if let titleColor = foregroundColor { titleLabel.textColor = titleColor } else { titleLabel.textColor = UIColor.gray } titleLabel.font = buildFontFromProps(nameKey: "titleFontName", sizeKey: "titleFontSize", defaultSize: 17, props: props) titleLabel.text = title titleLabel.sizeToFit() let subtitleLabel = UILabel(frame: CGRect(x:0, y:titleHeight, width:0, height:0)) subtitleLabel.backgroundColor = UIColor.clear if let subtitleColor = colorForKey("subtitleColor", props) { subtitleLabel.textColor = subtitleColor } else if let titleColor = foregroundColor { subtitleLabel.textColor = titleColor } else { subtitleLabel.textColor = UIColor.black } subtitleLabel.font = buildFontFromProps(nameKey: "subtitleFontName", sizeKey: "subtitleFontSize", defaultSize: 12, props: props) subtitleLabel.text = subtitle subtitleLabel.sizeToFit() let titleView = UIView( frame: CGRect( x: 0, y:0, width: max(Int(titleLabel.frame.size.width), Int(subtitleLabel.frame.size.width)), height: titleHeight + subtitleHeight ) ) titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width if widthDiff > 0 { var frame = titleLabel.frame frame.origin.x = widthDiff / 2 titleLabel.frame = frame } else { var frame = subtitleLabel.frame frame.origin.x = abs(widthDiff) / 2 subtitleLabel.frame = frame } return titleView }
0
import SwiftUI import Trigonometry extension SwiftUI.Angle: Trigonometry.Angle { }
0
import Foundation struct Pets : Codable { let name : String? let type : PetType? enum CodingKeys: String, CodingKey { case name = "name" case type = "type" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decodeIfPresent(String.self, forKey: .name) type = try values.decodeIfPresent(PetType.self, forKey: .type) } }
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 func a { protocol C { struct S { var d { class A { var d = [ f = ( var { class case ,
0
#if os(Linux) import CPostgreSQLLinux #else import CPostgreSQLMac #endif public enum Error: Swift.Error { case cannotEstablishConnection case indexOutOfRange case columnNotFound case invalidSQL(message: String) case noQuery case noResults } public class Database { private let host: String private let port: String private let dbname: String private let user: String private let password: String public init(host: String = "localhost", port: String = "5432", dbname: String, user: String, password: String) { self.host = host self.port = port self.dbname = dbname self.user = user self.password = password } @discardableResult public func execute(_ query: String, _ values: [Value]? = [], on connection: Connection? = nil) throws -> [[String: Value]] { let internalConnection: Connection if let conn = connection { internalConnection = conn } else { internalConnection = try makeConnection() } guard !query.isEmpty else { throw Error.noQuery } let res: Result.ResultPointer if let values = values, values.count > 0 { let paramsValues = bind(values) res = PQexecParams(internalConnection.connection, query, Int32(values.count), nil, paramsValues, nil, nil, Int32(0)) defer { paramsValues.deinitialize() paramsValues.deallocate(capacity: values.count) } } else { res = PQexec(internalConnection.connection, query) } defer { PQclear(res) } switch Status(result: res) { case .nonFatalError: throw Error.invalidSQL(message: String(cString: PQresultErrorMessage(res))) case .fatalError: throw Error.invalidSQL(message: String(cString: PQresultErrorMessage(res))) case .unknown: throw Error.invalidSQL(message: String(cString: PQresultErrorMessage(res))) case .tuplesOk: return Result(resultPointer: res).dictionary default: break } return [] } func bind(_ values: [Value]) -> UnsafeMutablePointer<UnsafePointer<Int8>?> { let paramsValues = UnsafeMutablePointer<UnsafePointer<Int8>?>.allocate(capacity: values.count) var v = [[UInt8]]() for i in 0..<values.count { var ch = [UInt8](values[i].utf8) ch.append(0) v.append(ch) paramsValues[i] = UnsafePointer<Int8>(OpaquePointer(v.last!)) } return paramsValues } public func makeConnection() throws -> Connection { return try Connection(host: self.host, port: self.port, dbname: self.dbname, user: self.user, password: self.password) } }
0
// // CDH_SQLiteManager.swift // SQLite // // Created by chendehao on 16/8/6. // Copyright © 2016年 CDHao. All rights reserved. // 使用 FMDB 封装的 SQLite 数据库的方法 import UIKit import FMDB class CDH_SQLiteManager: NSObject { // 工具类一般都设计为单例对象 static let shareInstance : CDH_SQLiteManager = CDH_SQLiteManager() // MARK : - 定义数据对象 var db : FMDatabase! } // MARK : - 打开数据库的操作 extension CDH_SQLiteManager{ func openDB(dbPath : String) -> Bool { db = FMDatabase(path: dbPath) return db.open() } } // MARK : - 执行 SQLiteManager 的操作 extension CDH_SQLiteManager { func execSQL(sqlString : String) -> Bool { return db.executeUpdate(sqlString, withArgumentsInArray: nil) } } // MARK : - 事务相关的操作 extension CDH_SQLiteManager { func beginTansation() -> Void { db.beginTransaction() } func commitTransation() -> Void { db.commit() } func rollbackTransation() -> Void { db.rollback() } } // MARK : - 查询数据操作 extension CDH_SQLiteManager { func queryData(querySQLString : String) -> [[String : NSObject]] { // 1.执行查询语句 // 这里看没有进行校验 , 最好加上校验, let resultSet = db.executeQuery(querySQLString, withArgumentsInArray: nil) // 2.开始查询数据 let count = resultSet.columnCount() // 3.2定义数组 var tempArray = [[String : NSObject]]() // 3.3查询数据 while resultSet.next() { // 遍历所有的键值对 var dict = [String : NSObject]() for i in 0..<count { // 转为 oc 字符 let key = resultSet.columnNameForIndex(i) let value = resultSet.stringForColumnIndex(i) dict[key] = value } // 将字典放入到数组中 tempArray.append(dict) } return tempArray } }
0
// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftFFmpeg", products: [ .library( name: "SwiftFFmpeg", targets: ["SwiftFFmpeg"] ) ], targets: [ .systemLibrary( name: "CFFmpeg", pkgConfig: "libavformat" ), .target( name: "SwiftFFmpeg", dependencies: ["CFFmpeg"] ), .target( name: "SwiftFFmpegExamples", dependencies: ["SwiftFFmpeg"] ), .testTarget( name: "SwiftFFmpegTests", dependencies: ["SwiftFFmpeg"] ), ] )
0
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension View { /// Adds an action to perform when this view appears for the time. /// /// - Parameter action: The action to perform. If `action` is `nil`, the call /// has no effect. /// /// - Returns: A view that triggers `action` when this view appears for the /// time. public func onFirstAppear(perform action: (() -> Void)? = nil) -> some View { modifier(FirstAppearActionModifier(action: action)) } /// Adds an action to perform when this view appears for the time or when the /// given id value changes. /// /// - Parameters: /// - id: When the value of the id changes it fires an action. /// - action: The action to perform. If `action` is `nil`, the call /// has no effect. /// /// - Returns: A view that triggers `action` when this view appears for the /// time or when the given id value changes. public func onFirstAppear<ID>( with id: ID, perform action: (() -> Void)? = nil ) -> some View where ID: Hashable { onFirstAppear(perform: action) .onChange(of: id) { _ in action?() } } /// Adds an action to perform when this view appears or when the given id value /// changes. /// /// - Parameters: /// - id: When the value of the id changes it fires an action. /// - action: The action to perform. If `action` is `nil`, the call /// has no effect. /// /// - Returns: A view that triggers `action` when this view appears or when the /// given id value changes. public func onAppear<ID>( with id: ID, perform action: (() -> Void)? = nil ) -> some View where ID: Hashable { onAppear(perform: action) .onChange(of: id) { _ in action?() } } } // MARK: - ViewModifier @MainActor private struct FirstAppearActionModifier: ViewModifier { @State private var didAppear = false let action: (() -> Void)? func body(content: Content) -> some View { content .onAppear { if !didAppear { didAppear = true action?() } } } }
0
// // FloatingButton.swift // Vendee // // Created by Ashish Kayastha on 12/4/15. // Copyright © 2015 Ashish Kayastha. All rights reserved. // import UIKit @IBDesignable class FloatingButton: UIButton { var lightGray = UIColor(hexString: "#F2F2F2") let darkGray = UIColor(white: 0.8, alpha: 1.0) let borderColor = UIColor(hexString: "#B9B9B9") var fillColor: UIColor! = UIColor(hexString: "#F2F2F2") override func drawRect(rect: CGRect) { let path = UIBezierPath(ovalInRect: rect) // Add fill fillColor.setFill() path.fill() // Add border layer.cornerRadius = bounds.size.width / 2 layer.borderWidth = 1.0 layer.borderColor = borderColor?.CGColor // Add shadow layer.shadowColor = borderColor?.CGColor layer.shadowOffset = CGSizeMake(0, 0) layer.shadowOpacity = 1.0 layer.shadowRadius = 6/7 layer.shadowPath = UIBezierPath( roundedRect: bounds, cornerRadius: bounds.size.width / 2 ).CGPath // Add border shadow // let shadowPathWidth: CGFloat = 1.0 // let layerAndShadowRadius = layer.cornerRadius // layer.shadowPath = CGPathCreateCopyByStrokingPath(CGPathCreateWithRoundedRect(bounds, layerAndShadowRadius, layerAndShadowRadius, nil), nil, shadowPathWidth, .Round, .Bevel, 0.0) } override var highlighted: Bool { didSet { fillColor = highlighted ? darkGray : lightGray setNeedsDisplay() } } }
0
// // Header.swift // IHaven // // Created by 梁霄 on 2020/6/12. // Copyright © 2020 梁霄. All rights reserved. // import SwiftUI struct MainHeader: View { var body: some View { HStack(alignment: .center) { RandomBtn() Spacer() Text("IHaven") .font(.title) .fontWeight(.ultraLight) .foregroundColor(Color.purple) .multilineTextAlignment(.center) Spacer() FilterBtn() } .padding(.horizontal,10) .padding(.vertical, 3) .frame(height: 40) .background(Color.black.opacity(0.5)) } } /** * 查询条件按钮 */ struct RandomBtn: View { static var RandomBtnWidth:CGFloat = 18.0 var body : some View{ Button(action: { ImageRepository.shared.clean(); ImageRepository.shared.query.random() ImageRepository.shared.load(succCallBack: {}) {} }){ Image(nsImage: NSImage(named: "RandomBtn")!).resizable() } .frame(width: RandomBtn.RandomBtnWidth, height: RandomBtn.RandomBtnWidth) .buttonStyle(PlainButtonStyle()) } } /** * 查询按钮 */ struct FilterBtn: View { static var FilterBtnWidth:CGFloat = 18.0 @EnvironmentObject var iHavenContext: IHavenContext var body : some View{ Button(action: { withAnimation(.easeOut(duration: 0.3)) { self.iHavenContext.currentState = .Filter } }){ Image(nsImage: NSImage(named: "FilterBtn")!).resizable() } .frame(width: FilterBtn.FilterBtnWidth, height: FilterBtn.FilterBtnWidth) .buttonStyle(PlainButtonStyle()) } }
0
// // RelativeIndirectablePointerIntPair.swift // Echo // // Created by Alejandro Alonso // Copyright © 2019 - 2021 Alejandro Alonso. All rights reserved. // struct RelativeIndirectablePointerIntPair< Pointee, IntTy: FixedWidthInteger >: RelativePointer { let offset: Int32 var intMask: Int32 { Int32(MemoryLayout<Int32>.alignment - 1) & ~0x1 } var int: IntTy { IntTy(offset & intMask) >> 1 } var isSet: Bool { int & 1 != 0 } func address(from ptr: UnsafeRawPointer) -> UnsafeRawPointer { let offsetIndirect = offset & ~intMask let addr = ptr + Int(offsetIndirect & ~1) if Int(offsetIndirect) & 1 == 1 { return addr.load(as: UnsafeRawPointer.self) } else { return addr } } func pointee(from ptr: UnsafeRawPointer) -> Pointee? { if isNull { return nil } return address(from: ptr).load(as: Pointee.self) } } extension UnsafeRawPointer { func relativeIndirectableIntPairAddress<T, U: FixedWidthInteger>( as type: T.Type, and typ2: U.Type ) -> UnsafeRawPointer { let relativePointer = RelativeIndirectablePointerIntPair<T, U>( offset: load(as: Int32.self) ) return relativePointer.address(from: self) } }
0
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(SceneKitTests.allTests), ] } #endif
0
// // CGPointExtension.swift // WhatsNewKit-iOS // // Created by Dima Vorona on 31/08/2018. // Copyright © 2018 WhatsNewKit. All rights reserved. // import CoreGraphics public func * (lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x * rhs.x, y: lhs.y * rhs.y) }
0
// // SpotifySettingCell.swift // MyMusic // // Created by kathy yin on 5/8/17. // Copyright © 2017 Yerneni, Naresh. All rights reserved. // import UIKit protocol SpotifySettingCellDelegate :class{ func didChangeSpotifLoginStatus(isOn: Bool) } class SpotifySettingCell: UITableViewCell { @IBOutlet weak var loginSwitch: UISwitch! weak var delegate: SpotifySettingCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func onSwitchLoginStatus(_ sender: UISwitch) { delegate?.didChangeSpotifLoginStatus(isOn: sender.isOn) } }
0
extension DatabaseConfigurationFactory { public static func postgres( url urlString: String, maxConnectionsPerEventLoop: Int = 1, connectionPoolTimeout: NIO.TimeAmount = .seconds(10), encoder: PostgresDataEncoder = .init(), decoder: PostgresDataDecoder = .init() ) throws -> DatabaseConfigurationFactory { guard let url = URL(string: urlString) else { throw FluentPostgresError.invalidURL(urlString) } return try .postgres( url: url, maxConnectionsPerEventLoop: maxConnectionsPerEventLoop, connectionPoolTimeout: connectionPoolTimeout, encoder: encoder, decoder: decoder ) } public static func postgres( url: URL, maxConnectionsPerEventLoop: Int = 1, connectionPoolTimeout: NIO.TimeAmount = .seconds(10), encoder: PostgresDataEncoder = .init(), decoder: PostgresDataDecoder = .init() ) throws -> DatabaseConfigurationFactory { guard let configuration = PostgresConfiguration(url: url) else { throw FluentPostgresError.invalidURL(url.absoluteString) } return .postgres( configuration: configuration, maxConnectionsPerEventLoop: maxConnectionsPerEventLoop, connectionPoolTimeout: connectionPoolTimeout ) } public static func postgres( hostname: String, port: Int = PostgresConfiguration.ianaPortNumber, username: String, password: String, database: String? = nil, tlsConfiguration: TLSConfiguration? = nil, maxConnectionsPerEventLoop: Int = 1, connectionPoolTimeout: NIO.TimeAmount = .seconds(10), encoder: PostgresDataEncoder = .init(), decoder: PostgresDataDecoder = .init() ) -> DatabaseConfigurationFactory { return .postgres( configuration: .init( hostname: hostname, port: port, username: username, password: password, database: database, tlsConfiguration: tlsConfiguration ), maxConnectionsPerEventLoop: maxConnectionsPerEventLoop, connectionPoolTimeout: connectionPoolTimeout ) } public static func postgres( configuration: PostgresConfiguration, maxConnectionsPerEventLoop: Int = 1, connectionPoolTimeout: NIO.TimeAmount = .seconds(10), encoder: PostgresDataEncoder = .init(), decoder: PostgresDataDecoder = .init() ) -> DatabaseConfigurationFactory { return DatabaseConfigurationFactory { FluentPostgresConfiguration( middleware: [], configuration: configuration, maxConnectionsPerEventLoop: maxConnectionsPerEventLoop, connectionPoolTimeout: connectionPoolTimeout, encoder: encoder, decoder: decoder ) } } } struct FluentPostgresConfiguration: DatabaseConfiguration { var middleware: [AnyModelMiddleware] let configuration: PostgresConfiguration let maxConnectionsPerEventLoop: Int /// The amount of time to wait for a connection from /// the connection pool before timing out. let connectionPoolTimeout: NIO.TimeAmount let encoder: PostgresDataEncoder let decoder: PostgresDataDecoder func makeDriver(for databases: Databases) -> DatabaseDriver { let db = PostgresConnectionSource( configuration: configuration ) let pool = EventLoopGroupConnectionPool( source: db, maxConnectionsPerEventLoop: maxConnectionsPerEventLoop, requestTimeout: connectionPoolTimeout, on: databases.eventLoopGroup ) return _FluentPostgresDriver( pool: pool, encoder: encoder, decoder: decoder ) } }
0
// // MocTableCell.swift // CollectionPresenter // // Created by Ravil Khusainov on 10.02.2016. // Copyright © 2016 Moqod. All rights reserved. // import Griddle import UIKit protocol Stringable { var rawValue: String? { get } } class MocTableCell: UITableViewCell, ReusableView { typealias Model = Stringable @IBOutlet weak var titleLabel: UILabel! var model: Stringable! { didSet { titleLabel.text = model.rawValue } } var longPressGesture: UILongPressGestureRecognizer? { didSet { if let gesture = longPressGesture { contentView.addGestureRecognizer(gesture) } } } static func size(for model: Model, container: UIView) -> CGSize? { return CGSize(width: container.frame.width, height: 44) } static func estimatedSize(for model: Model, container: UIView) -> CGSize? { return CGSize(width: container.frame.width, height: 44) } }
0
// // Tag+CoreDataProperties.swift // // // Created by Chien on 2017/7/4. // // import Foundation import CoreData extension Tag { @nonobjc public class func fetchRequest() -> NSFetchRequest<Tag> { return NSFetchRequest<Tag>(entityName: "Tag") } @NSManaged public var name: String? @NSManaged public var time: Double? }
0
// // Photo.swift // JSONSerialization // // Created by Brendan Krekeler on 2/20/19. // Copyright © 2019 Brendan Krekeler. All rights reserved. // import Foundation struct Photo { let image: String let title: String let description: String let latitude: Double let longitude: Double let date: String }
0
// // DynamicDescriptorParams.swift // GenesisSwift // import Foundation struct DynamicDescriptorParams { let merchantName: String? let merchantCity: String? var description: String { var xmlString = "" if (merchantName != nil) { xmlString += "<merchant_name>" + merchantName! + "</merchant_name name>" } if (merchantCity != nil) { xmlString += "<merchant_city>" + merchantCity! + "</merchant_city>" } return xmlString } }