label
int64
0
1
text
stringlengths
0
2.8M
0
// // PaintingPreview.swift // MaLiang_Example // // Created by Harley.xk on 2018/5/6. // Copyright © 2018年 Harley-xk. All rights reserved. // import UIKit class PaintingPreview: UIViewController { var image: UIImage? @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imageView.image = image } 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
// // GalleryUITests.swift // FarlakeUITests // // Created by Boy van Amstel on 04/07/2020. // Copyright © 2020 Boy van Amstel. All rights reserved. // import XCTest class GalleryDetailUITests: XCTestCase { private var app: XCUIApplication! // MARK: - XCTestCase override func setUp() { super.setUp() continueAfterFailure = false app = XCUIApplication() app.launchArguments = ["-ui-testing", "-test-entry-point", "gallery"] app.launch() } // MARK: - Tests func testGalleryDisplayed() { // Check if we're displaying the gallery view XCTAssertTrue(app.isDisplayingGallery) // Verify item count XCTAssertEqual(app.collectionViews.cells.count, 3) // Verify content let cell = app.collectionViews.cells.firstMatch XCTAssertTrue(cell.images["exclamationmark.triangle"].exists) XCTAssertTrue(cell.staticTexts["Title 1"].exists) } }
0
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import Foundation import NIO /// A ``Request`` is a generalized wrapper around an ``InterfaceExporter``'s internal request type. /// /// The information provided on the request is used by the Apodini framework to retrieve values for /// ``Parameter``s. Furthermore, many of the request's properties are reflected on ``Connection`` /// where they are exposed to the user. public protocol Request: CustomStringConvertible, CustomDebugStringConvertible { /// The `EventLoop` this request is to be handled on. var eventLoop: EventLoop { get } /// The remote address associated with this request. var remoteAddress: SocketAddress? { get } /// A set of arbitrary information that is associated with this request. var information: InformationSet { get } /// A function for obtaining the value for a ``Parameter`` from this request. func retrieveParameter<Element: Codable>(_ parameter: Parameter<Element>) throws -> Element }
0
// // CompareInput.swift // Shared // // Created by Joachim Kret on 05/07/2019. // Copyright © 2019 Joachim Kret. All rights reserved. // import Foundation public enum CompareInputError: Swift.Error { case isLess(than: String) case isLessOrNotEqual(to: String) case isGreater(than: String) case isGreaterOrNotEqual(to: String) }
0
// // AppIconActionController.swift // MacTemplet // // Created by Bin Shang on 2020/3/29. // Copyright © 2020 Bin Shang. All rights reserved. // import Cocoa import SwiftExpand class AppIconActionController: NSViewController { var itemList: [NSButton] = [] // MARK: -lifecycle override func viewDidLoad() { super.viewDidLoad() view.layer?.backgroundColor = NSColor.lightBlue.cgColor // Do any additional setup after loading the view. let list: [String] = ["退出应用", "显示未读信息数量", "跳转", "隐藏dock栏Icon", "显示dock栏Icon", "Button", ] itemList = list.enumerated().map({ (e) -> NSButton in let sender = NSButton(title: e.element, target: self, action: #selector(handleAction(_:))) sender.bezelStyle = .regularSquare sender.lineBreakMode = .byCharWrapping sender.tag = e.offset return sender }) itemList.forEach { (e) in view.addSubview(e) } // DDLog(view.frame, view.bounds) // view.getViewLayer() } override func viewDidLayout() { super.viewDidLayout() let frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height*0.1) itemList.updateItemsConstraint(frame, numberOfRow: 6) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } // MARK: -funtions @objc func handleAction(_ sender: NNButton) { DDLog("\(sender.tag)") switch sender.tag { case 0: closeApp(sender) case 1: showAppNumber(sender) case 2: jump(sender) case 3: hideDockIcon(sender) case 4: showDockIcon(sender) default: break } } // 关闭应用 @objc func closeApp(_ sender: Any) { /** NSApplictiaon的单利可以简写为NSApp*/ NSApplication.shared.terminate(nil) } /**显示App的数字提醒*/ @objc func showAppNumber(_ sender: Any) { NSApp.dockTile.badgeLabel = "20" let showBadge = (NSApp.dockTile.badgeLabel != "0" && NSApp.dockTile.badgeLabel != "") NSApp.dockTile.showsApplicationBadge = showBadge } /** 实现Dock 上的App 图标弹跳 */ @objc func jump(_ sender: Any) { /** criticalRequest // 多次跳动App Dock 上的图标,直到用户选中App为活动状态 informationalRequest // 一次跳动App Dock 上的图标 */ // 这个方法只能在当前App 不是处于非活动时才有效 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { NSApp.requestUserAttention(.informationalRequest) } } // 隐藏Dock 上的App 图标 @objc func hideDockIcon(_ sender: Any) { // 隐藏App 图标,会自动隐藏窗口 NSApp.setActivationPolicy(.accessory) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) { NSApp.unhideWithoutActivation() } } // 显示Dock 上的App 图标 @objc func showDockIcon(_ sender: Any) { NSApp.setActivationPolicy(.regular) } }
1
// MARK: - Element Consumer /// An alternate formation of consumers: Don't bind collection type as we're just /// consuming elements by classification or literal sequencing. protocol ElementConsumer { associatedtype Element func consume<C: Collection>( _ c: C, in: Range<C.Index> ) -> C.Index? where C.Element == Element } protocol CharacterConsumer: ElementConsumer where Element == Character { } protocol ScalarConsumer: ElementConsumer where Element == Unicode.Scalar { } protocol UTF8Consumer: ElementConsumer where Element == UInt8 { } protocol UTF16Consumer: ElementConsumer where Element == UInt16 { } // struct ...LiteralSequence: ...Consumer { ... } // MARK: - Element Classes protocol ElementClass: ElementConsumer { func contains(_ e: Element) -> Bool } extension ElementClass { func consume<C: Collection>( _ c: C, in range: Range<C.Index> ) -> C.Index? where C.Element == Element { // FIXME: empty ranges, etc... let lower = range.lowerBound return contains(c[lower]) ? c.index(after: lower) : nil } } protocol ScalarClass: ElementClass, ScalarConsumer {} protocol CharacterClass: ElementClass, CharacterConsumer {} // MARK: Granularity adapters /// Any higher-granularity consumer can be a lower-granularity /// consumer by just consuming at its higher-granularity struct _CharacterToScalar < Characters: CharacterConsumer >: ScalarConsumer { var characters: Characters func consume<C: Collection>( _ c: C, in range: Range<C.Index> ) -> C.Index? where C.Element == Unicode.Scalar { let str = String(c) let r = c.convertByOffset(range, in: str) guard let idx = characters.consume(str, in: r) else { return nil } return str.convertByOffset(idx, in: c) } } // ... /// Any lower-granularity consumer can be a higher /// granularity consumer by checking if the result falls on a /// boundary. struct _ScalarToCharacter < Scalars: ScalarConsumer >: CharacterConsumer { var scalars: Scalars func _consume( _ str: String, in range: Range<String.Index> ) -> String.Index? { guard let idx = scalars.consume(str.unicodeScalars, in: range), str.isOnGraphemeClusterBoundary(idx) else { return nil } return idx } func consume<C: Collection>( _ c: C, in range: Range<C.Index> ) -> C.Index? where C.Element == Character { let str = String(c) let r = c.convertByOffset(range, in: str) guard let idx = _consume(str, in: r) else { return nil } return str.convertByOffset(idx, in: c) } } /// Any lower-granularity class can be a higher-granularity /// class if we choose a semantic-extension style struct _FirstScalarCharacters< Scalars: ScalarClass >: CharacterClass { var scalars: Scalars func contains(_ c: Character) -> Bool { scalars.contains(c.unicodeScalars.first!) } } struct _SingleScalarCharacters< Scalars: ScalarClass >: CharacterClass { var scalars: Scalars func contains(_ c: Character) -> Bool { let scs = c.unicodeScalars return scs.count == 1 && scalars.contains(scs.first!) } // NOTE: This would be equivalent to _ScalarToCharacter // for any scalar consumer that consumes only one scalar // at a time. } struct _AllScalarCharacters< Scalars: ScalarClass >: CharacterClass { var scalars: Scalars func contains(_ c: Character) -> Bool { c.unicodeScalars.allSatisfy(scalars.contains) } }
0
// MIT License // // Copyright (c) 2017-present qazyn951230 [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. @testable import Core import XCTest import Dispatch extension DispatchQueue { func apply(iterations: Int, work: @escaping (Int) -> Void) { __dispatch_apply(iterations, self, work) } } final class AtomicTests: XCTestCase { func testAtomicIntCreate() { let a = spa_int_create(0) XCTAssertEqual(spa_int_load(a), 0) spa_int_free(a) let b = spa_int_create(42) XCTAssertEqual(spa_int_load(b), 42) spa_int_free(b) } func testAtomicIntLoad() { let a = spa_int_create(0) XCTAssertEqual(spa_int_load_explicit(a, .relaxed), 0) spa_int_free(a) let b = spa_int_create(42) XCTAssertEqual(spa_int_load_explicit(b, .relaxed), 42) spa_int_free(b) let c = spa_int_create(23) XCTAssertEqual(spa_int_load_explicit(c, .sequentiallyConsistent), 23) spa_int_free(c) } func testCAtomicIntAdd() { let value: SPAIntRef = spa_int_create(0) XCTAssertEqual(spa_int_load(value), 0) let group = DispatchGroup() let queue = DispatchQueue(label: "test", qos: .utility, attributes: .concurrent) queue.apply(iterations: 10) { _ in group.enter() for _ in 0 ..< 1000 { spa_int_add(value, 1) } group.leave() } _ = group.wait(timeout: .distantFuture) XCTAssertEqual(spa_int_load(value), 10000) spa_int_free(value) } // https://github.com/ReactiveX/RxSwift/issues/1853 func testCAtomicIntDataRace() { let value = spa_int_create(0) let group = DispatchGroup() for i in 0 ... 100 { DispatchQueue.global(qos: .background).async { if i % 2 == 0 { spa_int_add(value, 1) } else { spa_int_sub(value, 1) } if i == 100 { group.leave() } } } group.enter() _ = group.wait(timeout: .distantFuture) XCTAssertEqual(spa_int_load(value), 1) spa_int_free(value) } // https://github.com/apple/swift-evolution/blob/master/proposals/0282-atomics.md#interaction-with-implicit-pointer-conversions func testConcurrentMutation() { let counter = spa_int_create(0) DispatchQueue.concurrentPerform(iterations: 10) { _ in for _ in 0 ..< 1_000_000 { spa_int_add(counter, 1) } } XCTAssertEqual(spa_int_load(counter), 10_000_000) spa_int_free(counter) } #if ENABLE_PERFORMANCE_TESTS func testCAtomicIntPerformance() { measure { let value = spa_int_create(0) for _ in 0 ..< LockTests.max { spa_int_add(value, 1) } spa_int_free(value) } } #endif // ENABLE_PERFORMANCE_TESTS }
0
// // SFJSONViewController.swift // iOSTips // // Created by brian on 2018/2/4. // Copyright © 2018年 brian. All rights reserved. // import UIKit class SFJSONViewController: SFBaseViewController { override func viewDidLoad() { headers = [""] dataSource = [["JSONSerialization": SFJSONSerializationViewController(), "JSONExample": SFJSONExampleTableViewController()] ] super.viewDidLoad() } }
0
// // UserSetView.swift // Books // // Created by ZL on 16/11/3. // Copyright © 2016年 ZL. All rights reserved. // import UIKit class UserSetView: UIView { //表格 private var tbView:UITableView? override init(frame: CGRect) { super.init(frame: frame) self.frame = CGRect(x: -KScreenW/6*5, y: 0-64, width: KScreenW/6*5, height: KScreenH) let label = UILabel() label.text = "设 置" label.textAlignment = .Center label.font = UIFont.boldSystemFontOfSize(24) addSubview(label) self.backgroundColor=UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1.0) label.snp_makeConstraints { (make) in make.centerX.equalToSuperview() make.top.equalToSuperview().offset(20) make.height.equalTo(44) } //创建表格视图 tbView = UITableView(frame: CGRectZero,style: .Plain) tbView?.delegate=self tbView?.dataSource = self tbView?.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1.0) tbView?.showsVerticalScrollIndicator = false //设置成为没有分割线 tbView!.separatorStyle = .None addSubview(tbView!) //约束 tbView?.snp_makeConstraints(closure: { (make) in make.left.right.bottom.equalToSuperview() make.top.equalToSuperview().offset(64) }) tbView!.registerNib(UINib(nibName: "UserSetCell", bundle: nil), forCellReuseIdentifier: "userCell") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:UITableView代理 extension UserSetView:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return KScreenH } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as! UserSetCell // cell.jumpClosure = jumpClosure cell.selectionStyle = .None return cell } // //设置header样式 // func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // // // // return nil // } // //设置header的高度 // func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // // return 0 // } // //去掉UITableView的粘滞性 // func scrollViewDidScroll(scrollView: UIScrollView) { // let h : CGFloat = 54 // if scrollView.contentOffset.y >= h { // scrollView.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0) // }else if scrollView.contentOffset.y > 0 { // scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0) // } // } }
0
// // StatableToolbarItem.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-05-26. // // --------------------------------------------------------------------------- // // © 2016-2020 1024jp // // 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 // // https://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 Cocoa class StatableToolbarItem: ControlToolbarItem { // MARK: Public Properties final var state: NSControl.StateValue = .on { didSet { guard state != oldValue else { return } let suffix = (state == .on) ? "On" : "Off" guard let base = self.image?.name()?.components(separatedBy: "_").first, let image = NSImage(named: base + "_" + suffix) else { return assertionFailure("StatableToolbarItem must habe an image that has name with \"_On\" and \"_Off\" suffixes.") } self.image = image } } }
0
import UIKit class MSettingsItemSupport:MSettingsItem { private let kCellHeight:CGFloat = 85 init() { let reusableIdentifier:String = VSettingsCellSupport.reusableIdentifier super.init( reusableIdentifier:reusableIdentifier, cellHeight:kCellHeight) } }
0
// // String.swift // CommandLineKit // // Created by Bas van Kuijck on 20/10/2017. // import Foundation import Cryptor infix operator =~ /** Regular expression match let match = ("ABC123" =~ "[A-Z]{3}[0-9]{3}") // true */ func =~ (string: String, regex: String) -> Bool { return string.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil } extension String { var md5: String { let md5 = Digest(using: .md5) _ = md5.update(string: self) return md5.final().map{ String(format: "%02X", $0) }.joined() } func uncapitalizeFirstLetter() -> String { return prefix(1).lowercased() + dropFirst() } func appendIfFirstCharacterIsNumber(with string: String = "") -> String { if let firstChar = self.first, let _ = Int("\(firstChar)") { return "\(string)\(self)" } return self } func tabbed(_ count: Int = 0) -> String { let spacing = " " var tab = "" for _ in 0..<count { tab += spacing } return "\(tab)\(self)" } var predefinedString: String { let value = replacingOccurrences(of: ".", with: "_") return "`\(value)`" } } import Foundation public enum StringCaseFormat { public enum CamelCase { case `default` case capitalized } } public extension String { func caseSplit() -> [String] { var res: [String] = [] let trim = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) let alphanumerics = CharacterSet.alphanumerics let uppercaseLetters = CharacterSet.uppercaseLetters let lowercaseLetters = CharacterSet.lowercaseLetters trim.split(separator: " ").forEach { str in var previousCase = 0 var currentCase = 0 var caseChange = false var scalars = UnicodeScalarView() for scalar in str.unicodeScalars { if alphanumerics.contains(scalar) { if uppercaseLetters.contains(scalar) { currentCase = 1 } else if lowercaseLetters.contains(scalar) { currentCase = 2 } else { currentCase = 0 } let letterInWord = scalars.count if !caseChange && letterInWord > 0 { if currentCase != previousCase { if previousCase == 1 { if letterInWord > 1 { caseChange = true } } else { caseChange = true } } } if caseChange { res.append(String(scalars)) scalars.removeAll() } scalars.append(scalar) caseChange = false previousCase = currentCase } else { caseChange = true } } if scalars.count > 0 { res.append(String(scalars)) } } return res } func camelCased(_ format: StringCaseFormat.CamelCase = .default) -> String { var res: [String] = [] for (i, str) in self.caseSplit().enumerated() { if i == 0 && format == .default { res.append(str.lowercased()) continue } res.append(str.capitalized) } return res.joined().uncapitalizeFirstLetter() } }
0
// // XHNetCourseWareCell.swift // XueHuangEducation // // Created by tsaievan on 2/5/18. // Copyright © 2018年 tsaievan. All rights reserved. // import UIKit enum XHNetCourseWareState: Int{ case free = 0 case charge = 2 } extension UIColor { struct NetCourseWareCell { static let teacherLabel = UIColor(hexColor: "#777777") static let titleLabel = UIColor(hexColor: "#333333") } } extension CGFloat { struct NetCourseWareCell { struct Width { static let iconImageView: CGFloat = 80 static let listenButton: CGFloat = 28 } } } extension String { struct NetCourseWareCell { static let listenButtonImageName = "catalogList_listen_button" static let iconImageName = "image_teach_courseware" static let listenButtonTitle = "试听" static let listenButtonPayTitle = "付费" } } fileprivate let listenButtonImageName = String.NetCourseWareCell.listenButtonImageName fileprivate let iconImageName = String.NetCourseWareCell.iconImageName fileprivate let listenButtonTitleText = String.NetCourseWareCell.listenButtonTitle fileprivate let listenButtonTitlePayText = String.NetCourseWareCell.listenButtonPayTitle fileprivate let iconImageViewWidth = CGFloat.NetCourseWareCell.Width.iconImageView fileprivate let listenButtonWidth = CGFloat.NetCourseWareCell.Width.listenButton class XHNetCourseWareCell: UITableViewCell { var model: XHNetCourseWare? { didSet { guard let modelInfo = model, let titleText = modelInfo.netCoursewareName, let teacherName = modelInfo.teacher else { return } titleLabel.text = titleText teacherLabel.text = "老师: \(teacherName)" if let state = modelInfo.state { if state == XHNetCourseWareState.free.rawValue { listenButton.titleLabel?.text = listenButtonTitleText }else { listenButton.titleLabel?.text = listenButtonTitlePayText } } } } lazy var iconImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: iconImageName) imageView.layer.cornerRadius = CGFloat.commonCornerRadius imageView.layer.masksToBounds = true imageView.sizeToFit() return imageView }() lazy var titleLabel: UILabel = { let lbl = UILabel(text: String.empty, textColor: UIColor.NetCourseWareCell.titleLabel, fontSize: CGFloat.FontSize._15) lbl.font = UIFont.boldSystemFont(ofSize: CGFloat.FontSize._15) lbl.numberOfLines = 2 ///< 防止有些标题过长, 在iPhoneSE等小机型下转到第三行, 跟teacherLabel相冲突 return lbl }() lazy var teacherLabel: UILabel = { let lbl = UILabel(text: String.empty, textColor: UIColor.NetCourseWareCell.teacherLabel, fontSize: CGFloat.FontSize._13) return lbl }() lazy var listenButton: XHButton = { let btn = XHButton(withButtonImage: listenButtonImageName, title: listenButtonTitleText, titleColor: UIColor.Global.skyBlue, titleFont: CGFloat.FontSize._12, gap: CGFloat.zero) btn.addTarget(self, action: #selector(didClickListenButtonAction), for: .touchUpInside) return btn }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension XHNetCourseWareCell { fileprivate func setupUI() { contentView.addSubview(iconImageView) contentView.addSubview(titleLabel) contentView.addSubview(teacherLabel) contentView.addSubview(listenButton) makeConstraints() } fileprivate func makeConstraints() { iconImageView.snp.makeConstraints { (make) in make.top.equalTo(contentView).offset(XHMargin._10) make.left.equalTo(contentView).offset(XHMargin._15) make.bottom.equalTo(contentView).offset(-XHMargin._10) make.width.equalTo(iconImageViewWidth) } listenButton.snp.makeConstraints { (make) in make.centerY.equalTo(iconImageView) make.right.equalTo(contentView).offset(-XHMargin._15) make.width.equalTo(listenButtonWidth) } titleLabel.snp.makeConstraints { (make) in make.top.equalTo(iconImageView) make.left.equalTo(iconImageView.snp.right).offset(XHMargin._10) make.right.equalTo(listenButton.snp.left).offset(-XHMargin._10) } teacherLabel.snp.makeConstraints { (make) in make.leading.equalTo(titleLabel) make.bottom.equalTo(iconImageView) } } } extension XHNetCourseWareCell { @objc fileprivate func didClickListenButtonAction(sender: XHButton) { router(withEventName: EVENT_CLICK_NETCOURSE_WARE_CELL_LISTEN_BUTTON, userInfo: [CELL_FOR_NETCOURSE_WARE_CELL_LISTEN_BUTTON : self]) } }
0
// // CollectionExtensions.swift // SwifterSwift // // Created by Sergey Fedortsov on 19.12.16. // Copyright © 2016 Omar Albeik. All rights reserved. // import Foundation // MARK: - Methods public extension Collection { private func indicesArray() -> [Self.Index] { var indices: [Self.Index] = [] var index = self.startIndex while index != self.endIndex { indices.append(index) index = self.index(after: index) } return indices } /// SwifterSwift: performs `each` closure for each element of collection in parallel. /// /// - Parameter each: closure to run for each element. public func forEachInParallel(_ each: (Self.Iterator.Element) -> ()) { let indices = indicesArray() DispatchQueue.concurrentPerform(iterations: indices.count) { (index) in let elementIndex = indices[index] each(self[elementIndex]) } } } extension Collection where Indices.Iterator.Element == Index { /// SwifterSwift: Safe protects the array from out of bounds by use of optional. /// ///- Parameter index: Index of element to access element. ///- Returns: Optional element at index (if applicable). ///- Usage: array[safe: index] subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } }
0
// Created by B.T. Franklin on 10/27/19. import CoreGraphics import Aesthete public struct LightPanelGreebles: Drawable, Codable, Hashable { static private let LIGHT_INSET: CGFloat = 0.01 static private let LIGHT_PADDING: CGFloat = 0.007 static private let LIGHT_SIZE: CGFloat = 0.02 public let xUnits: CGFloat public let yUnits: CGFloat public let themeColor: HSBAColor public let lightColors: [HSBAColor] public let panelCount: Int public init(xUnits: CGFloat = 1, yUnits: CGFloat = 1, themeColor: HSBAColor, lightColors: [HSBAColor] = [CGColor(#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)).hsbaColor], panelCount: Int) { self.xUnits = xUnits self.yUnits = yUnits self.themeColor = themeColor self.lightColors = lightColors self.panelCount = panelCount } public func draw(on context: CGContext) { context.saveGState() context.setAllowsAntialiasing(true) typealias Panel = (rect: CGRect, columnCount: Int, rowCount: Int) var panels: [Panel] = [] for _ in 1...panelCount { let columnCount = Int.random(in: 2...8) let rowCount = Int.random(in: 2...8) let rectWidth = (CGFloat(columnCount) * LightPanelGreebles.LIGHT_SIZE) + (CGFloat(columnCount-1) * LightPanelGreebles.LIGHT_PADDING) + (LightPanelGreebles.LIGHT_INSET * 2) let rectHeight = (CGFloat(rowCount) * LightPanelGreebles.LIGHT_SIZE) + (CGFloat(rowCount-1) * LightPanelGreebles.LIGHT_PADDING) + (LightPanelGreebles.LIGHT_INSET * 2) let rect = CGRect(x: CGFloat.random(in: 0.0...xUnits - 0.1), y: CGFloat.random(in: 0.0...yUnits - 0.1), width: rectWidth, height: rectHeight) panels.append( (rect: rect, columnCount: columnCount, rowCount: rowCount) ) } let backgroundColor = CGColor.make(hsbaColor: themeColor.withBrightness(adjustedBy: -0.1)) for panel in panels { context.setLineWidth(0.002) context.setStrokeColor(.black) context.setFillColor(backgroundColor) context.fill(panel.rect) context.stroke(panel.rect) context.saveGState() for column in 0..<panel.columnCount { for row in 0..<panel.rowCount { if Bool.random(probability: 0.33) { let lightColor = CGColor.make(hsbaColor: lightColors.randomElement()!) context.setFillColor(lightColor) let lightX = panel.rect.minX + LightPanelGreebles.LIGHT_INSET + (CGFloat(column) * LightPanelGreebles.LIGHT_SIZE) + (CGFloat(column) * LightPanelGreebles.LIGHT_PADDING) let lightY = panel.rect.minY + LightPanelGreebles.LIGHT_INSET + (CGFloat(row) * LightPanelGreebles.LIGHT_SIZE) + (CGFloat(row) * LightPanelGreebles.LIGHT_PADDING) let lightRect = CGRect(x: lightX, y: lightY, width: LightPanelGreebles.LIGHT_SIZE, height: LightPanelGreebles.LIGHT_SIZE) context.fill(lightRect) } } } context.restoreGState() } context.restoreGState() } }
0
// // AppDelegate.swift // ScrapeMESwiftly // // Created by Samuel Barthelemy on 5/25/16. // Copyright © 2016 Samuel Barthelemy. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
0
// // Person.swift // PersonStuff // // Created by Jim Campagno on 1/31/17. // Copyright © 2017 Jim Campagno. All rights reserved. // import Foundation class Person { let firstName: String let lastName: String var happiness: Int = 0 var fullName: String { return "\(firstName) \(lastName)" } init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } func greet(person: Person) -> String { happiness = happiness + 2 person.happiness = person.happiness + 2 return "Hello \(person.fullName)." } func dance(with person: Person) -> String { happiness = happiness + 5 person.happiness = person.happiness + 5 return "💃🏼\(fullName)❤️ ❤️\(person.fullName)💃🏼" } }
0
import Foundation public class Setting : Autoresolveable{ public var name : String public var cached : Bool //Can even be a Dictionary<KeyType, ValueType> public var value : Any /** namespace supports multiple plist files with name collisions **/ public var namespace : String init(name:String, value : AnyObject, cached: Bool = false, namespace:String = ""){ self.name = name self.cached = cached self.value = value self.namespace = namespace super.init() self.customEntityName = name } init(name:String, value : Any,cached : Bool = false, namespace : String = "") { self.name = name self.cached = cached self.value = value self.namespace = namespace super.init() self.customEntityName = name } public required init() { self.name = "" self.cached = false self.value = "" self.namespace = "global" super.init() self.customEntityName = name } }
0
// // FaceView.swift // Happiness // // Created by 张佳圆 on 5/4/16. // Copyright © 2016 Tisoga. All rights reserved. // import UIKit protocol FaceViewDataSource: class { func smilinessForFaceView(sender: FaceView) -> Double? } @IBDesignable class FaceView: UIView { @IBInspectable var lineWidth: CGFloat = 3.0 { didSet { setNeedsDisplay() }} @IBInspectable var color: UIColor = UIColor.blackColor() { didSet { setNeedsDisplay() }} @IBInspectable var scale: CGFloat = 0.90 { didSet { setNeedsDisplay() }} var faceCenter: CGPoint { return convertPoint(center, toView: superview) } var faceRadius: CGFloat { return min(bounds.size.width, bounds.size.height) / 2 * scale } weak var dataSource: FaceViewDataSource? func scale(gesture: UIPinchGestureRecognizer) { if gesture.state == .Changed { scale *= gesture.scale gesture.scale = 1 } } private struct Scaling { static let FaceRadiusToEyeRadiusRatio: CGFloat = 10 static let FaceRadiusToEyeOffsetRatio: CGFloat = 3 static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5 static let FaceRadiusToMouthWidthRatio: CGFloat = 1 static let FaceRadiusToMouthHeightRatio: CGFloat = 3 static let FaceRadiusToMouthOffsetRatio: CGFloat = 3 } private enum Eye { case Left, Right } private func bezierPathForEye(whichEye: Eye) -> UIBezierPath { let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio var eyeCenter = faceCenter eyeCenter.y -= eyeVerticalOffset switch whichEye { case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2 case .Right: eyeCenter.x += eyeHorizontalSeparation / 2 } let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true) path.lineWidth = lineWidth return path } private func bezierPathForSmile(fractionOfMaxSime: Double) -> UIBezierPath { let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio let mouthVerticalOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio let smileHeight = CGFloat(max(min(fractionOfMaxSime, 1), -1)) * mouthHeight let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticalOffset) let end = CGPoint(x: start.x + mouthWidth, y: start.y) let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight) let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y) let path = UIBezierPath() path.moveToPoint(start) path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } override func drawRect(rect: CGRect) { let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*M_PI), clockwise: true) facePath.lineWidth = lineWidth color.set() facePath.stroke() bezierPathForEye(.Left).stroke() bezierPathForEye(.Right).stroke() let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0 let smilePath = bezierPathForSmile(smiliness) smilePath.stroke() } }
0
// // MenuCell.swift // Twitter // // Created by Prachie Banthia on 11/6/16. // Copyright © 2016 Prachie Banthia. All rights reserved. // import UIKit class MenuCell: UITableViewCell { @IBOutlet weak var menuItem: UILabel! 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
// // StoreFrontKitTests.swift // StoreFrontKitTests // // Created by Afraz Siddiqui on 12/13/20. // import XCTest @testable import StoreFrontKit class StoreFrontKitTests: XCTestCase {}
0
// // ProductListCellViewModel.swift // MiniPedia // // Created by Agus Cahyono on 12/10/20. // Copyright © 2020 Agus Cahyono. All rights reserved. // import RxSwift struct ProductListCellViewModel { var product: DataProducts? var productName: String? var productPrice: String? var productImage: String? var productStarCount: String? init(product: DataProducts) { self.productName = product.name ?? "" self.productPrice = product.price ?? "" self.productImage = product.imageURI ?? "" self.productStarCount = product.getCountStar self.product = product } init(storage: ProductStorage) { self.productName = storage.name self.productPrice = storage.price self.productImage = storage.imageURI self.productStarCount = "\(storage.rating)" self.product = storage.toDataProduct() } init() { } }
0
// // ScheduleController.swift // TrolleyTracker // // Created by Austin Younts on 7/30/17. // Copyright © 2017 Code For Greenville. All rights reserved. // import UIKit class ScheduleController: FunctionController { enum DisplayType: Int { case route, day static var all: [DisplayType] { return [.route, .day] } static var `default`: DisplayType { return .route } } typealias Dependencies = HasModelController private let dependencies: Dependencies private let viewController: ScheduleViewController private let dataSource: ScheduleDataSource private var routeController: RouteController? private var lastFetchRequestDate: Date? init(dependencies: Dependencies) { self.dependencies = dependencies self.dataSource = ScheduleDataSource() self.viewController = ScheduleViewController() } func prepare() -> UIViewController { let type = DisplayType.default dataSource.displayType = type viewController.displayTypeControl.selectedSegmentIndex = type.rawValue dataSource.displayRouteAction = displayRoute(_:) viewController.tabBarItem.image = #imageLiteral(resourceName: "Schedule") viewController.tabBarItem.title = LS.scheduleTitle viewController.delegate = self let nav = UINavigationController(rootViewController: viewController) viewController.tableView.dataSource = dataSource viewController.tableView.delegate = dataSource loadSchedules() return nav } private func loadSchedulesIfNeeded() { guard let lastDate = lastFetchRequestDate else { loadSchedules() return } guard lastDate.isAcrossQuarterHourBoundryFromNow else { return } loadSchedules() } private func loadSchedules() { lastFetchRequestDate = Date() dependencies.modelController.loadTrolleySchedules(handleNewSchedules(_:)) } private func handleNewSchedules(_ schedules: [RouteSchedule]) { dataSource.set(schedules: schedules) viewController.tableView.reloadData() } private func displayRoute(_ routeID: Int) { routeController = RouteController(routeID: routeID, presentationContext: viewController, dependencies: dependencies) routeController?.present() } } extension ScheduleController: ScheduleVCDelegate { func viewDidAppear() { loadSchedulesIfNeeded() } func didSelectScheduleTypeIndex(_ index: Int) { let displayType = ScheduleController.DisplayType(rawValue: index)! dataSource.displayType = displayType viewController.tableView.reloadData() } }
0
// // GameWithCheat.swift // PVSupport // import Foundation @objc public protocol GameWithCheat { @objc(setCheatWithCode:type:enabled:) func setCheat( code: String, type: String, enabled: Bool ) -> Bool @objc(supportsCheatCode) func supportsCheatCode() -> Bool }
0
#if os(macOS) // Fashion Mac Playground import Cocoa import Fashion var str = "Hello, playground" #endif
0
// // BolusEntryViewModel.swift // Loop // // Created by Michael Pangburn on 7/17/20. // Copyright © 2020 LoopKit Authors. All rights reserved. // import Combine import HealthKit import LocalAuthentication import Intents import os.log import LoopCore import LoopKit import LoopKitUI import LoopUI import SwiftUI protocol BolusEntryViewModelDelegate: class { func withLoopState(do block: @escaping (LoopState) -> Void) func addGlucoseSamples(_ samples: [NewGlucoseSample], completion: ((_ result: Swift.Result<[StoredGlucoseSample], Error>) -> Void)?) func addCarbEntry(_ carbEntry: NewCarbEntry, replacing replacingEntry: StoredCarbEntry? , completion: @escaping (_ result: Result<StoredCarbEntry>) -> Void) func storeBolusDosingDecision(_ bolusDosingDecision: BolusDosingDecision, withDate date: Date) func enactBolus(units: Double, automatic: Bool, completion: @escaping (_ error: Error?) -> Void) func logOutsideInsulinDose(startDate: Date, units: Double, insulinType: InsulinType?) func getGlucoseSamples(start: Date?, end: Date?, completion: @escaping (_ samples: Swift.Result<[StoredGlucoseSample], Error>) -> Void) func insulinOnBoard(at date: Date, completion: @escaping (_ result: DoseStoreResult<InsulinValue>) -> Void) func carbsOnBoard(at date: Date, effectVelocities: [GlucoseEffectVelocity]?, completion: @escaping (_ result: CarbStoreResult<CarbValue>) -> Void) func ensureCurrentPumpData(completion: @escaping () -> Void) func insulinActivityDuration(for type: InsulinType?) -> TimeInterval var mostRecentGlucoseDataDate: Date? { get } var mostRecentPumpDataDate: Date? { get } var isPumpConfigured: Bool { get } var preferredGlucoseUnit: HKUnit { get } var pumpInsulinType: InsulinType? { get } var settings: LoopSettings { get } } final class BolusEntryViewModel: ObservableObject { enum Alert: Int { case recommendationChanged case maxBolusExceeded case noPumpManagerConfigured case noMaxBolusConfigured case carbEntryPersistenceFailure case manualGlucoseEntryOutOfAcceptableRange case manualGlucoseEntryPersistenceFailure case glucoseNoLongerStale } enum Notice: Equatable { case predictedGlucoseBelowSuspendThreshold(suspendThreshold: HKQuantity) case staleGlucoseData case stalePumpData } var authenticate: AuthenticationChallenge = LocalAuthentication.deviceOwnerCheck // MARK: - State @Published var glucoseValues: [GlucoseValue] = [] // stored glucose values + manual glucose entry private var storedGlucoseValues: [GlucoseValue] = [] @Published var predictedGlucoseValues: [GlucoseValue] = [] @Published var glucoseUnit: HKUnit = .milligramsPerDeciliter @Published var chartDateInterval: DateInterval @Published var activeCarbs: HKQuantity? @Published var activeInsulin: HKQuantity? @Published var targetGlucoseSchedule: GlucoseRangeSchedule? @Published var preMealOverride: TemporaryScheduleOverride? private var savedPreMealOverride: TemporaryScheduleOverride? @Published var scheduleOverride: TemporaryScheduleOverride? var maximumBolus: HKQuantity? let originalCarbEntry: StoredCarbEntry? let potentialCarbEntry: NewCarbEntry? let selectedCarbAbsorptionTimeEmoji: String? @Published var isManualGlucoseEntryEnabled = false @Published var enteredManualGlucose: HKQuantity? private var manualGlucoseSample: NewGlucoseSample? // derived from `enteredManualGlucose`, but stored to ensure timestamp consistency @Published var recommendedBolus: HKQuantity? @Published var enteredBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 0) private var isInitiatingSaveOrBolus = false private var dosingDecision = BolusDosingDecision() @Published var activeAlert: Alert? @Published var activeNotice: Notice? private let log = OSLog(category: "BolusEntryViewModel") private var cancellables: Set<AnyCancellable> = [] @Published var isRefreshingPump: Bool = false let chartManager: ChartsManager = { let predictedGlucoseChart = PredictedGlucoseChart(predictedGlucoseBounds: FeatureFlags.predictedGlucoseChartClampEnabled ? .default : nil, yAxisStepSizeMGDLOverride: FeatureFlags.predictedGlucoseChartClampEnabled ? 40 : nil) predictedGlucoseChart.glucoseDisplayRange = LoopConstants.glucoseChartDefaultDisplayRangeWide return ChartsManager(colors: .primary, settings: .default, charts: [predictedGlucoseChart], traitCollection: .current) }() // MARK: - Seams private weak var delegate: BolusEntryViewModelDelegate? private let now: () -> Date private let screenWidth: CGFloat private let debounceIntervalMilliseconds: Int private let uuidProvider: () -> String private let carbEntryDateFormatter: DateFormatter // MARK: - Initialization init( delegate: BolusEntryViewModelDelegate, now: @escaping () -> Date = { Date() }, screenWidth: CGFloat = UIScreen.main.bounds.width, debounceIntervalMilliseconds: Int = 400, uuidProvider: @escaping () -> String = { UUID().uuidString }, timeZone: TimeZone? = nil, originalCarbEntry: StoredCarbEntry? = nil, potentialCarbEntry: NewCarbEntry? = nil, selectedCarbAbsorptionTimeEmoji: String? = nil, isManualGlucoseEntryEnabled: Bool = false ) { self.delegate = delegate self.now = now self.screenWidth = screenWidth self.debounceIntervalMilliseconds = debounceIntervalMilliseconds self.uuidProvider = uuidProvider self.carbEntryDateFormatter = DateFormatter() self.carbEntryDateFormatter.dateStyle = .none self.carbEntryDateFormatter.timeStyle = .short if let timeZone = timeZone { self.carbEntryDateFormatter.timeZone = timeZone } self.originalCarbEntry = originalCarbEntry self.potentialCarbEntry = potentialCarbEntry self.selectedCarbAbsorptionTimeEmoji = selectedCarbAbsorptionTimeEmoji self.isManualGlucoseEntryEnabled = isManualGlucoseEntryEnabled self.chartDateInterval = DateInterval(start: Date(timeInterval: .hours(-1), since: now()), duration: .hours(7)) self.dosingDecision.originalCarbEntry = originalCarbEntry observeLoopUpdates() observeEnteredBolusChanges() observeEnteredManualGlucoseChanges() observeElapsedTime() observeRecommendedBolusChanges() update() } private func observeLoopUpdates() { NotificationCenter.default .publisher(for: .LoopDataUpdated) .receive(on: DispatchQueue.main) .sink { [weak self] _ in self?.update() } .store(in: &cancellables) } private func observeEnteredBolusChanges() { $enteredBolus .removeDuplicates() .debounce(for: .milliseconds(debounceIntervalMilliseconds), scheduler: RunLoop.main) .sink { [weak self] _ in self?.delegate?.withLoopState { [weak self] state in self?.updatePredictedGlucoseValues(from: state) } } .store(in: &cancellables) } private func observeRecommendedBolusChanges() { $recommendedBolus .removeDuplicates() .debounce(for: .milliseconds(debounceIntervalMilliseconds), scheduler: RunLoop.main) .sink { [weak self] _ in self?.setRecommendedBolus() } .store(in: &cancellables) } private func observeEnteredManualGlucoseChanges() { $enteredManualGlucose .debounce(for: .milliseconds(debounceIntervalMilliseconds), scheduler: RunLoop.main) .sink { [weak self] enteredManualGlucose in guard let self = self else { return } self.updateManualGlucoseSample(enteredAt: self.now()) // Clear out any entered bolus whenever the manual entry changes self.enteredBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 0) self.delegate?.withLoopState { [weak self] state in self?.updatePredictedGlucoseValues(from: state, completion: { // Ensure the manual glucose entry appears on the chart at the same time as the updated prediction self?.updateGlucoseChartValues() }) self?.ensurePumpDataIsFresh { [weak self] in self?.updateRecommendedBolusAndNotice(from: state, isUpdatingFromUserInput: true) } } } .store(in: &cancellables) } private func observeElapsedTime() { // If glucose data is stale, loop status updates cannot be expected to keep presented data fresh. // Periodically update the UI to ensure recommendations do not go stale. Timer.publish(every: .minutes(5), tolerance: .seconds(15), on: .main, in: .default) .autoconnect() .receive(on: DispatchQueue.main) .sink { [weak self] _ in guard let self = self else { return } self.log.default("5 minutes elapsed on bolus screen; refreshing UI") // Update the manual glucose sample's timestamp, which should always be "now" self.updateManualGlucoseSample(enteredAt: self.now()) self.update() } .store(in: &cancellables) } // MARK: - View API var isBolusRecommended: Bool { guard let recommendedBolus = recommendedBolus else { return false } return recommendedBolus.doubleValue(for: .internationalUnit()) > 0 } func setRecommendedBolus() { guard isBolusRecommended else { return } enteredBolus = recommendedBolus! isRefreshingPump = false delegate?.withLoopState { [weak self] state in self?.updatePredictedGlucoseValues(from: state) } } func saveAndDeliver(onSuccess completion: @escaping () -> Void) { guard delegate?.isPumpConfigured ?? false else { presentAlert(.noPumpManagerConfigured) return } guard let maximumBolus = maximumBolus else { presentAlert(.noMaxBolusConfigured) return } guard enteredBolus <= maximumBolus else { presentAlert(.maxBolusExceeded) return } if let manualGlucoseSample = manualGlucoseSample { guard LoopConstants.validManualGlucoseEntryRange.contains(manualGlucoseSample.quantity) else { presentAlert(.manualGlucoseEntryOutOfAcceptableRange) return } } // Authenticate the bolus before saving anything if enteredBolus.doubleValue(for: .internationalUnit()) > 0 { let message = String(format: NSLocalizedString("Authenticate to Bolus %@ Units", comment: "The message displayed during a device authentication prompt for bolus specification"), enteredBolusAmountString) authenticate(message) { [weak self] in switch $0 { case .success: self?.continueSaving(onSuccess: completion) case .failure: break } } } else if potentialCarbEntry != nil { // Allow user to save carbs without bolusing continueSaving(onSuccess: completion) } else if manualGlucoseSample != nil { // Allow user to save the manual glucose sample without bolusing continueSaving(onSuccess: completion) } else { completion() } } private func continueSaving(onSuccess completion: @escaping () -> Void) { if let manualGlucoseSample = manualGlucoseSample { isInitiatingSaveOrBolus = true delegate?.addGlucoseSamples([manualGlucoseSample]) { result in DispatchQueue.main.async { switch result { case .success(let glucoseValues): self.dosingDecision.manualGlucose = glucoseValues.first self.saveCarbsAndDeliverBolus(onSuccess: completion) case .failure(let error): self.isInitiatingSaveOrBolus = false self.presentAlert(.manualGlucoseEntryPersistenceFailure) self.log.error("Failed to add manual glucose entry: %{public}@", String(describing: error)) } } } } else { self.dosingDecision.manualGlucose = nil saveCarbsAndDeliverBolus(onSuccess: completion) } } private func saveCarbsAndDeliverBolus(onSuccess completion: @escaping () -> Void) { guard let carbEntry = potentialCarbEntry else { dosingDecision.carbEntry = nil deliverBolus(onSuccess: completion) return } if originalCarbEntry == nil { let interaction = INInteraction(intent: NewCarbEntryIntent(), response: nil) interaction.donate { [weak self] (error) in if let error = error { self?.log.error("Failed to donate intent: %{public}@", String(describing: error)) } } } isInitiatingSaveOrBolus = true delegate?.addCarbEntry(carbEntry, replacing: originalCarbEntry) { result in DispatchQueue.main.async { switch result { case .success(let storedCarbEntry): self.dosingDecision.carbEntry = storedCarbEntry self.deliverBolus(onSuccess: completion) case .failure(let error): self.isInitiatingSaveOrBolus = false self.presentAlert(.carbEntryPersistenceFailure) self.log.error("Failed to add carb entry: %{public}@", String(describing: error)) } } } } private func deliverBolus(onSuccess completion: @escaping () -> Void) { let now = self.now() let bolusVolume = enteredBolus.doubleValue(for: .internationalUnit()) dosingDecision.requestedBolus = bolusVolume delegate?.storeBolusDosingDecision(dosingDecision, withDate: now) guard bolusVolume > 0 else { completion() return } isInitiatingSaveOrBolus = true savedPreMealOverride = nil // TODO: should we pass along completion or not??? delegate?.enactBolus(units: bolusVolume, automatic: false, completion: { _ in }) completion() } private func presentAlert(_ alert: Alert) { dispatchPrecondition(condition: .onQueue(.main)) // As of iOS 13.6 / Xcode 11.6, swapping out an alert while one is active crashes SwiftUI. guard activeAlert == nil else { return } activeAlert = alert } private lazy var bolusVolumeFormatter = QuantityFormatter(for: .internationalUnit()) private lazy var absorptionTimeFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.collapsesLargestUnit = true formatter.unitsStyle = .abbreviated formatter.allowsFractionalUnits = true formatter.allowedUnits = [.hour, .minute] return formatter }() var enteredBolusAmountString: String { let bolusVolume = enteredBolus.doubleValue(for: .internationalUnit()) return bolusVolumeFormatter.numberFormatter.string(from: bolusVolume) ?? String(bolusVolume) } var maximumBolusAmountString: String? { guard let maxBolusVolume = maximumBolus?.doubleValue(for: .internationalUnit()) else { return nil } return bolusVolumeFormatter.numberFormatter.string(from: maxBolusVolume) ?? String(maxBolusVolume) } var carbEntryAmountAndEmojiString: String? { guard let potentialCarbEntry = potentialCarbEntry, let carbAmountString = QuantityFormatter(for: .gram()).string(from: potentialCarbEntry.quantity, for: .gram()) else { return nil } if let emoji = potentialCarbEntry.foodType ?? selectedCarbAbsorptionTimeEmoji { return String(format: NSLocalizedString("%1$@ %2$@", comment: "Format string combining carb entry quantity and absorption time emoji"), carbAmountString, emoji) } else { return carbAmountString } } var carbEntryDateAndAbsorptionTimeString: String? { guard let potentialCarbEntry = potentialCarbEntry else { return nil } let entryTimeString = carbEntryDateFormatter.string(from: potentialCarbEntry.startDate) if let absorptionTime = potentialCarbEntry.absorptionTime, let absorptionTimeString = absorptionTimeFormatter.string(from: absorptionTime) { return String(format: NSLocalizedString("%1$@ + %2$@", comment: "Format string combining carb entry time and absorption time"), entryTimeString, absorptionTimeString) } else { return entryTimeString } } // MARK: - Data upkeep private func updateManualGlucoseSample(enteredAt entryDate: Date) { dispatchPrecondition(condition: .onQueue(.main)) manualGlucoseSample = enteredManualGlucose.map { quantity in NewGlucoseSample( date: entryDate, quantity: quantity, isDisplayOnly: false, wasUserEntered: true, syncIdentifier: uuidProvider() ) } } private func update() { dispatchPrecondition(condition: .onQueue(.main)) // Prevent any UI updates after a bolus has been initiated. guard !isInitiatingSaveOrBolus else { return } disableManualGlucoseEntryIfNecessary() updateChartDateInterval() updateStoredGlucoseValues() updateFromLoopState() updateActiveInsulin() } private func disableManualGlucoseEntryIfNecessary() { dispatchPrecondition(condition: .onQueue(.main)) if isManualGlucoseEntryEnabled, !isGlucoseDataStale { isManualGlucoseEntryEnabled = false enteredManualGlucose = nil manualGlucoseSample = nil presentAlert(.glucoseNoLongerStale) } } private func updateStoredGlucoseValues() { delegate?.getGlucoseSamples(start: chartDateInterval.start, end: nil) { [weak self] result in DispatchQueue.main.async { guard let self = self else { return } switch result { case .failure(let error): self.log.error("Failure getting glucose samples: %{public}@", String(describing: error)) self.storedGlucoseValues = [] case .success(let samples): self.storedGlucoseValues = samples } self.updateGlucoseChartValues() } } } private func updateGlucoseChartValues() { dispatchPrecondition(condition: .onQueue(.main)) var chartGlucoseValues = storedGlucoseValues if let manualGlucoseSample = manualGlucoseSample { chartGlucoseValues.append(manualGlucoseSample.quantitySample) } self.glucoseValues = chartGlucoseValues } /// - NOTE: `completion` is invoked on the main queue after predicted glucose values are updated private func updatePredictedGlucoseValues(from state: LoopState, completion: @escaping () -> Void = {}) { dispatchPrecondition(condition: .notOnQueue(.main)) let (manualGlucoseSample, enteredBolus, insulinType) = DispatchQueue.main.sync { (self.manualGlucoseSample, self.enteredBolus, delegate?.pumpInsulinType) } let enteredBolusDose = DoseEntry(type: .bolus, startDate: Date(), value: enteredBolus.doubleValue(for: .internationalUnit()), unit: .units, insulinType: insulinType) let predictedGlucoseValues: [PredictedGlucoseValue] do { if let manualGlucoseEntry = manualGlucoseSample { predictedGlucoseValues = try state.predictGlucoseFromManualGlucose( manualGlucoseEntry, potentialBolus: enteredBolusDose, potentialCarbEntry: potentialCarbEntry, replacingCarbEntry: originalCarbEntry, includingPendingInsulin: true ) } else { predictedGlucoseValues = try state.predictGlucose( using: .all, potentialBolus: enteredBolusDose, potentialCarbEntry: potentialCarbEntry, replacingCarbEntry: originalCarbEntry, includingPendingInsulin: true ) } } catch { predictedGlucoseValues = [] } DispatchQueue.main.async { self.predictedGlucoseValues = predictedGlucoseValues self.dosingDecision.predictedGlucoseIncludingPendingInsulin = predictedGlucoseValues completion() } } private func updateActiveInsulin() { delegate?.insulinOnBoard(at: Date()) { [weak self] result in guard let self = self else { return } DispatchQueue.main.async { switch result { case .success(let iob): self.activeInsulin = HKQuantity(unit: .internationalUnit(), doubleValue: iob.value) self.dosingDecision.insulinOnBoard = iob case .failure: self.activeInsulin = nil self.dosingDecision.insulinOnBoard = nil } } } } private func updateFromLoopState() { delegate?.withLoopState { [weak self] state in self?.updatePredictedGlucoseValues(from: state) self?.updateCarbsOnBoard(from: state) self?.ensurePumpDataIsFresh { [weak self] in self?.updateRecommendedBolusAndNotice(from: state, isUpdatingFromUserInput: false) DispatchQueue.main.async { self?.updateSettings() } } } } private func updateCarbsOnBoard(from state: LoopState) { delegate?.carbsOnBoard(at: Date(), effectVelocities: state.insulinCounteractionEffects) { result in DispatchQueue.main.async { switch result { case .success(let carbValue): self.activeCarbs = carbValue.quantity self.dosingDecision.carbsOnBoard = carbValue case .failure: self.activeCarbs = nil self.dosingDecision.carbsOnBoard = nil } } } } private func ensurePumpDataIsFresh(then completion: @escaping () -> Void) { if !isPumpDataStale { completion() return } DispatchQueue.main.async { // v-- This needs to happen on the main queue self.isRefreshingPump = true let wrappedCompletion: () -> Void = { [weak self] in self?.delegate?.withLoopState { [weak self] _ in // v-- This needs to happen in LoopDataManager's dataQueue completion() // ^v-- Unfortunately, these two things might happen concurrently, so in theory the // completion above may not "complete" by the time we clear isRefreshingPump. To fix that // would require some very confusing wiring, but I think it is a minor issue. DispatchQueue.main.async { // v-- This needs to happen on the main queue self?.isRefreshingPump = false } } } self.delegate?.ensureCurrentPumpData(completion: wrappedCompletion) } } private func updateRecommendedBolusAndNotice(from state: LoopState, isUpdatingFromUserInput: Bool) { dispatchPrecondition(condition: .notOnQueue(.main)) var recommendation: ManualBolusRecommendation? let recommendedBolus: HKQuantity? let notice: Notice? do { recommendation = try computeBolusRecommendation(from: state) if let recommendation = recommendation { recommendedBolus = HKQuantity(unit: .internationalUnit(), doubleValue: recommendation.amount) switch recommendation.notice { case .glucoseBelowSuspendThreshold: if let suspendThreshold = delegate?.settings.suspendThreshold { notice = .predictedGlucoseBelowSuspendThreshold(suspendThreshold: suspendThreshold.quantity) } else { notice = nil } default: notice = nil } } else { recommendedBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 0) notice = nil } } catch { recommendedBolus = nil switch error { case LoopError.missingDataError(.glucose), LoopError.glucoseTooOld: notice = .staleGlucoseData case LoopError.pumpDataTooOld: notice = .stalePumpData default: notice = nil } } DispatchQueue.main.async { let priorRecommendedBolus = self.recommendedBolus self.recommendedBolus = recommendedBolus self.dosingDecision.recommendedBolus = recommendation self.activeNotice = notice if priorRecommendedBolus != recommendedBolus, self.enteredBolus.doubleValue(for: .internationalUnit()) > 0, !self.isInitiatingSaveOrBolus { self.enteredBolus = HKQuantity(unit: .internationalUnit(), doubleValue: 0) if !isUpdatingFromUserInput { self.presentAlert(.recommendationChanged) } } } } private func computeBolusRecommendation(from state: LoopState) throws -> ManualBolusRecommendation? { dispatchPrecondition(condition: .notOnQueue(.main)) let manualGlucoseSample = DispatchQueue.main.sync { self.manualGlucoseSample } if manualGlucoseSample != nil { return try state.recommendBolusForManualGlucose( manualGlucoseSample!, consideringPotentialCarbEntry: potentialCarbEntry, replacingCarbEntry: originalCarbEntry ) } else { return try state.recommendBolus( consideringPotentialCarbEntry: potentialCarbEntry, replacingCarbEntry: originalCarbEntry ) } } private func updateSettings() { dispatchPrecondition(condition: .onQueue(.main)) guard let delegate = delegate else { return } glucoseUnit = delegate.preferredGlucoseUnit targetGlucoseSchedule = delegate.settings.glucoseTargetRangeSchedule // Pre-meal override should be ignored if we have carbs (LOOP-1964) preMealOverride = potentialCarbEntry == nil ? delegate.settings.preMealOverride : nil scheduleOverride = delegate.settings.scheduleOverride if preMealOverride?.hasFinished() == true { preMealOverride = nil } if scheduleOverride?.hasFinished() == true { scheduleOverride = nil } maximumBolus = delegate.settings.maximumBolus.map { maxBolusAmount in HKQuantity(unit: .internationalUnit(), doubleValue: maxBolusAmount) } dosingDecision.scheduleOverride = preMealOverride ?? scheduleOverride dosingDecision.glucoseTargetRangeSchedule = targetGlucoseSchedule if scheduleOverride != nil || preMealOverride != nil { dosingDecision.effectiveGlucoseTargetRangeSchedule = delegate.settings.effectiveGlucoseTargetRangeSchedule(presumingMealEntry: potentialCarbEntry != nil) } else { dosingDecision.effectiveGlucoseTargetRangeSchedule = nil } } private func updateChartDateInterval() { dispatchPrecondition(condition: .onQueue(.main)) // How far back should we show data? Use the screen size as a guide. let viewMarginInset: CGFloat = 14 let availableWidth = screenWidth - chartManager.fixedHorizontalMargin - 2 * viewMarginInset let totalHours = floor(Double(availableWidth / LoopConstants.minimumChartWidthPerHour)) let futureHours = ceil((delegate?.insulinActivityDuration(for: delegate?.pumpInsulinType) ?? .hours(4)).hours) let historyHours = max(LoopConstants.statusChartMinimumHistoryDisplay.hours, totalHours - futureHours) let date = Date(timeInterval: -TimeInterval(hours: historyHours), since: now()) let chartStartDate = Calendar.current.nextDate( after: date, matching: DateComponents(minute: 0), matchingPolicy: .strict, direction: .backward ) ?? date chartDateInterval = DateInterval(start: chartStartDate, duration: .hours(totalHours)) } } extension BolusEntryViewModel.Alert: Identifiable { var id: Self { self } } // MARK: Helpers extension BolusEntryViewModel { var isGlucoseDataStale: Bool { guard let latestGlucoseDataDate = delegate?.mostRecentGlucoseDataDate else { return true } return now().timeIntervalSince(latestGlucoseDataDate) > LoopCoreConstants.inputDataRecencyInterval } var isPumpDataStale: Bool { guard let latestPumpDataDate = delegate?.mostRecentPumpDataDate else { return true } return now().timeIntervalSince(latestPumpDataDate) > LoopCoreConstants.inputDataRecencyInterval } var isManualGlucosePromptVisible: Bool { activeNotice == .staleGlucoseData && !isManualGlucoseEntryEnabled } var isNoticeVisible: Bool { if activeNotice == nil { return false } else if activeNotice != .staleGlucoseData { return true } else { return !isManualGlucoseEntryEnabled } } private var hasBolusEntryReadyToDeliver: Bool { enteredBolus.doubleValue(for: .internationalUnit()) != 0 } private var hasDataToSave: Bool { enteredManualGlucose != nil || potentialCarbEntry != nil } enum ButtonChoice { case manualGlucoseEntry, actionButton } var primaryButton: ButtonChoice { if !isManualGlucosePromptVisible { return .actionButton } if hasBolusEntryReadyToDeliver { return .actionButton } return .manualGlucoseEntry } enum ActionButtonAction { case saveWithoutBolusing case saveAndDeliver case enterBolus case deliver } var actionButtonAction: ActionButtonAction { switch (hasDataToSave, hasBolusEntryReadyToDeliver) { case (true, true): return .saveAndDeliver case (true, false): return .saveWithoutBolusing case (false, true): return .deliver case (false, false): return .enterBolus } } }
0
// // MagneticNotchContentModeTests.swift // DynamicOverlay // // Created by Gaétan Zanella on 07/05/2022. // Copyright © 2022 Fabernovel. All rights reserved. // import Foundation import XCTest import SwiftUI import DynamicOverlay private enum Notch: CaseIterable, Equatable { case min case max } private struct NotchDimensionView: View { let behavior: MagneticNotchOverlayBehavior<Notch> let onHeightChange: (CGFloat) -> Void var body: some View { Color.red .dynamicOverlay(Color.green.onHeightChange(onHeightChange)) .dynamicOverlayBehavior(behavior) } } class MagneticNotchContentModeTests: XCTestCase { func testAdjustmentContentModes() { let resultByMode: [MagneticNotchOverlayBehavior<Notch>.ContentAdjustmentMode: CGFloat] = [ .none: 200, .stretch: 100 ] let behavior = MagneticNotchOverlayBehavior<Notch> { notch in switch notch { case .max: return .absolute(200) case .min: return .absolute(100) } } resultByMode.forEach { mode, result in let expectation = XCTestExpectation() let view = NotchDimensionView( behavior: behavior.contentAdjustmentMode(mode).notchChange(.constant(.min)) ) { height in XCTAssertEqual(height, result) expectation.fulfill() } ViewRenderer(view: view).render() wait(for: [expectation], timeout: 0.3) } } }
0
// // BaseTableViewController.swift // SinaWeiBoProject // // Created by 房城鸿 on 15/10/6. // Copyright © 2015年 房兰峰. All rights reserved. import UIKit class BaseTableViewController: UITableViewController { //用户登录标记 var userLogin = UserAccountViewModel.sharedUserAccount.userLogin // var userLogin = false //用户登陆视图 - 每个控制器各自拥有自己的 visitorView // 提示:如果使用懒加载,会在用户登陆成功之后,视图仍然被创建,虽然不会影响程序执行,但是会消耗内存 var visitorView:VisitorLoginView? // lazy var visitorView:VisitorLoginView = VisitorLoginView() /** 如果view不存在,系统会再次调用loadView */ override func loadView() { userLogin ? super.loadView() : setupVistorView() } override func viewDidLoad() { super.viewDidLoad() } /** 设置访客视图 */ private func setupVistorView(){ visitorView = VisitorLoginView() //替换视图 view = visitorView //设置导航栏 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "VisitorLoginViewWillRigester") self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Plain, target: self , action: "VisitorLoginViewWillLogin") visitorView?.registerButton.addTarget(self, action: "VisitorLoginViewWillRigester", forControlEvents: UIControlEvents.TouchUpInside) visitorView?.loginButton.addTarget(self, action: "VisitorLoginViewWillLogin", forControlEvents: UIControlEvents.TouchUpInside) } //MARK: - VisitorLoginViewDelegate @objc private func VisitorLoginViewWillRigester() { print("注册") } @objc private func VisitorLoginViewWillLogin() { let nav = UINavigationController(rootViewController: OAuthViewController()) presentViewController(nav, animated:true, completion: nil) } //是专门为手写代码准备的,一旦实现此方法,所有的xib/sb 都会失效 //当试图控制器被初始化后,它会自动检测View是否为空,如果为空,会自动盗用此方法 // 在view没有被初始化之前,不要跟踪view /* override func loadView() { vistorLoginView = NSBundle.mainBundle().loadNibNamed("VistorLoginView", owner: nil, options: nil).last as? VistorLoginView // myView.backgroundColor = UIColor.redColor() // vistorLoginView.vis view = vistorLoginView //添加导航栏的barButtonItem self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "") self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: "") // appearance.tintColor 相当于将颜色作为全局文件存储, // 修改它,一定要趁早设置,否则完了 UINavigationBar.appearance().tintColor = UIColor.orangeColor() } */ }
0
// // NSView+Constraints.swift // NXKit // // Created by Austin Chen on 2018-08-15. // import AppKit public extension NSEdgeInsets { public init(uniform: CGFloat) { self.init(top: uniform, left: uniform, bottom: uniform, right: uniform) } } public enum SnapOption { case uniformInset(CGFloat) case insets(NSEdgeInsets) } private extension SnapOption { var resultInsets: NSEdgeInsets { switch self { case .uniformInset(let n): return NSEdgeInsets.init(top: n, left: n, bottom: n, right: n) case .insets(let insets): return insets } } } public extension NSView { public func snapTopBottom(toView view: NSView, option: SnapOption = .uniformInset(0)) { NSLayoutConstraint.activate([ topAnchor.constraint(equalTo: view.topAnchor, constant: option.resultInsets.top), bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -option.resultInsets.bottom) ]) } public func snapLeadTrail(toView view: NSView, option: SnapOption = .uniformInset(0)) { NSLayoutConstraint.activate([ leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: option.resultInsets.left), trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -option.resultInsets.right) ]) } public func snapAll(toView view: NSView, option: SnapOption = .uniformInset(0)) { snapTopBottom(toView: view, option: option) snapLeadTrail(toView: view, option: option) } public func snapTopBottomToSuperview() { guard let sv = self.superview else { return } snapTopBottom(toView: sv) } public func snapLeadTrailToSuperview() { guard let sv = self.superview else { return } snapLeadTrail(toView: sv) } public func snapAllToSuperview() { snapTopBottomToSuperview() snapLeadTrailToSuperview() } }
0
// // PersistenceStore+MovieSearch.swift // CoreDataInfrastructure // // Created by Bheem Singh on 3/4/19. // Copyright © 2019 Bheem Singh. All rights reserved. // extension PersistenceStore where Entity == CDMovieSearch { func saveMovieSearch(with searchText: String, completion: ((Bool) -> Void)? = nil) { managedObjectContext.performChanges { _ = CDMovieSearch.insert(into: self.managedObjectContext, searchText: searchText) completion?(true) } } }
0
// // CSVParser.swift // ESCSVParser // // Created by Tomohiro Kumagai on H27/07/15. // Copyright © 2015 EasyStyle G.K. All rights reserved. // import Foundation /// This class is a CSV parser. internal class CSVParser { /// load a csv file from 'path'. /// This method returns an array of the csv data parsed by each line. static func loadFromPath<Row:CSVRowRepresentable>(path:String, skipHeader:Bool) throws -> [Row] { var results = [Row]() let rawData = try String(contentsOfFile: path) let lines = rawData.componentsSeparatedByString(self.Newline) for line in lines.enumerate() { guard !line.element.isEmpty else { continue } if skipHeader && line.index == 0 { continue } results += try [ Row.fromRawLine(self.parseRawLine(line.element)) ] } return results } } extension CSVParser { static let Quote:Character = "\u{0022}" static let Comma:Character = "\u{002C}" static let Newline:String = "\u{000D}\u{000A}" typealias ParseIndex = String.CharacterView.Index typealias ParseCharacter = String.CharacterView.Generator.Element typealias ColumnLocation = (column:RawColumn, start:ParseIndex,end:ParseIndex,next:ParseIndex?) static func parseRawLine(line:String) throws -> RawLine { guard !line.isEmpty else { return RawLine(columns: []) } var results = [RawColumn]() var location:ParseIndex = line.startIndex while let found = try self.parseRawColumn(line, location: location) { results += [found.column] guard found.next != nil else { break } location = found.next! } return RawLine(columns: results) } static func isQuoteCharacter(line:String, atIndex index:ParseIndex) -> Bool { guard index != line.endIndex else { return false } return line[index] == self.Quote } static func isCommaCharacter(line:String, atIndex index:ParseIndex) -> Bool { guard index != line.endIndex else { return false } return line[index] == self.Comma } static func parseRawColumn(line:String, location:ParseIndex) throws -> ColumnLocation? { guard location != line.endIndex else { return ColumnLocation(column: RawColumn(), start: line.endIndex, end: line.endIndex, next: nil) } if self.isQuoteCharacter(line, atIndex: location) { return try self.parseRawQuotedColumn(line, location: location) } else { return try self.parseRawNonQuotedColumn(line, location: location) } } static func parseRawQuotedColumn(line:String, location sourceLocation:ParseIndex) throws -> ColumnLocation { let start = sourceLocation.successor() for var location = start; location != line.endIndex; ++location { if self.isQuoteCharacter(line, atIndex: location) { guard self.isQuoteCharacter(line, atIndex: location.successor()) else { let end = location let next = location.successor() let column = RawColumn((line[start..<end] as NSString).stringByReplacingOccurrencesOfString("\"\"", withString: "\"")) if next == line.endIndex { return (column: column, start:start, end:end, next:nil) } else if self.isCommaCharacter(line, atIndex: next) { return (column: column, start:start, end:end, next:next.successor()) } else { throw CSVParserError.ParseError("Comma not found at \(next)") } } ++location } } throw CSVParserError.ParseError("Invalid quote character found at \(sourceLocation)") } static func parseRawNonQuotedColumn(line:String, location sourceLocation:ParseIndex) throws -> ColumnLocation { let start = sourceLocation guard !self.isCommaCharacter(line, atIndex: start) else { return (column: RawColumn(), start: start, end:start, next: start.successor()) } for var location = start; location != line.endIndex; ++location { guard !self.isCommaCharacter(line, atIndex: location) else { let end = location let column = RawColumn.fromString(line, ofRange: start ..< end) return (column: column, start:start, end:end, next:location.successor()) } } return (column: RawColumn.fromString(line, ofRange: start ..< line.endIndex), start:start, end:line.endIndex, next:nil) } }
0
// // SideMenuTableViewController.swift // Swift_MVVM_Boilerplate // // Created by Ravi on 10/01/20. // Copyright © 2020 Systango. All rights reserved. // import UIKit class SideMenuTableViewController: UITableViewController { @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var labelFullname: UILabel! @IBOutlet weak var labelDescription: UILabel! override func viewDidLoad() { super.viewDidLoad() logoutButton.layer.cornerRadius = 4.0 logoutButton.layer.borderWidth = 1 logoutButton.layer.borderColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) imageView.layer.cornerRadius = 45.0 imageView.layer.masksToBounds = true imageView.layer.borderWidth = 1 imageView.layer.borderColor = #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1) } @IBAction func logoutAction(_ sender: Any) { self.showAlert("Logout", message: Constants.Message.logoutWarning, actions: ["Cancel", "Logout"]) { (actionTitle) in if actionTitle == "Logout" { RedirectionHelper.redirectToLogin() } } } }
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func k<g { enum k { func l var _ = l extension NSSet { struct c<e> { } func f<o>() -> (o, o -> o) -> o { o m o.j = { } func j<d { enum j { class j { func y((Any, j))(v: (Any, AnyObject)) { y(v) }
0
// // OptionsViewController.swift // First // // Created by dengjiangzhou on 2018/6/7. // Copyright © 2018年 dengjiangzhou. All rights reserved. // import UIKit protocol OptionsViewControllerDelegate: class{ func play() func toSetVolumn(value: Float) func toSetPan(value: Float) func toSetRate(value: Float) func toSetLoopPlayback(loop: Bool) } let kVolume = "Volume" class OptionsViewController: UIViewController { @IBOutlet weak var volumeSlider: UISlider! @IBOutlet weak var panSlider: UISlider! @IBOutlet weak var rateSlider: UISlider! @IBOutlet weak var loopSwitch: UISwitch! weak var delegateOptionsViewController: OptionsViewControllerDelegate? let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. volumeSlider.value = defaults.float(forKey: kVolume) panSlider.value = defaults.float(forKey: "Pan") rateSlider.value = defaults.float(forKey: "Rate") loopSwitch.isOn = defaults.bool(forKey: "Loop Audio") } override var prefersStatusBarHidden: Bool{ return true } // MARK:- 右边的仪表盘 IBActions @IBAction func toSetVolume(_ sender: UISlider) { defaults.set(sender.value, forKey: "Volume") delegateOptionsViewController?.toSetVolumn(value: sender.value) } @IBAction func toSetPan(_ sender: UISlider) { defaults.set(sender.value, forKey: "Pan") delegateOptionsViewController?.toSetPan(value: sender.value) } @IBAction func toSetRate(_ sender: UISlider) { defaults.set(sender.value, forKey: "Rate") delegateOptionsViewController?.toSetRate(value: sender.value) } @IBAction func loopAudio(_ sender: UISwitch) { defaults.set(sender.isOn, forKey: "Loop Audio") delegateOptionsViewController?.toSetLoopPlayback(loop: sender.isOn) } // MARK:- 下面的 Button Actions @IBAction func closeOptions(_ sender: UIButton) { dismiss(animated: true){} } @IBAction func previewAudio(_ sender: UIButton) { delegateOptionsViewController?.play() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
0
// // ConversationsLoginManager.swift // ConversationsApp // // Copyright © Twilio, Inc. All rights reserved. // import Foundation class ConversationsLoginManager: LoginManager { // MARK: Properties private var conversationsProvider: ConversationsProvider private var conversationsCredentialStorage: CredentialStorage // MARK: Intialization init(conversationsProvider: ConversationsProvider = ConversationsClientWrapper.wrapper, credentialStorage: CredentialStorage = ConversationsCredentialStorage.shared) { self.conversationsProvider = conversationsProvider self.conversationsCredentialStorage = credentialStorage } // MARK: Sign in logic func signIn(identity: String, password: String, completion: @escaping (LoginResult) -> Void) { conversationsProvider.create(login: identity, password: password) { [weak self] result in if case .success = result { // Save credentials do { try self?.conversationsCredentialStorage.saveCredentials(identity: identity, password: password) } catch (let error){ print(error.localizedDescription) return completion(.failure(LoginError.unableToStoreCredentials)) } } completion(result) } } func signInUsingStoredCredentials(completion: @escaping (LoginResult) -> Void) { guard let latestCredentials = try? conversationsCredentialStorage.loadLatestCredentials(), let pass = try? latestCredentials.readPassword() else { print("Saved credentials failed, erasing") try? conversationsCredentialStorage.deleteCredentials() completion(.failure(LoginError.accessDenied)) return } print("Signing in using saved credentials") signIn(identity: latestCredentials.account, password: pass) { [weak self] result in if case .failure(LoginError.accessDenied) = result { try? self?.conversationsCredentialStorage.deleteCredentials() } completion(result) } } }
0
import BowLiteCore import BowLiteLaws extension Store: Equatable where View: Equatable { public static func ==(lhs: Store<State, View>, rhs: Store<State, View>) -> Bool { lhs.extract() == rhs.extract() } }
0
import Vapor import MongoKitten import MeowVapor /// Called before your application initializes. public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws { // Register providers first // Register routes to the router let router = EngineRouter.default() try routes(router) services.register(router, as: Router.self) // Register middleware var middlewares = MiddlewareConfig() // Create _empty_ middleware config middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response middlewares.use(SessionsMiddleware.self) services.register(middlewares) // db because it is connected to mongo container let connectionURI = "mongodb://db:27017/test" let meow = try MeowProvider(uri: connectionURI) try services.register(meow) // services.register { container -> MongoKitten.Database in // return try MongoKitten.Database.lazyConnect(connectionURI, on: container.eventLoop) // } config.prefer(MemoryKeyedCache.self, for: KeyedCache.self) } extension MongoKitten.Database: Service {}
0
// // WidgetViews.swift // DuckDuckGo // // Copyright © 2020 DuckDuckGo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import WidgetKit import SwiftUI struct FavoriteView: View { var favorite: Favorite? var isPreview: Bool var body: some View { ZStack { RoundedRectangle(cornerRadius: 10) .fill(Color.widgetFavoritesBackground) if let favorite = favorite { Link(destination: favorite.url) { RoundedRectangle(cornerRadius: 10) .fill(favorite.needsColorBackground ? Color.forDomain(favorite.domain) : Color.widgetFavoritesBackground) .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2) if let image = favorite.favicon { Image(uiImage: image) .scaleDown(image.size.width > 60) .cornerRadius(10) } else if favorite.isDuckDuckGo { Image("WidgetDaxLogo") .resizable() .frame(width: 45, height: 45, alignment: .center) } else { Text(favorite.domain.first?.uppercased() ?? "") .foregroundColor(Color.widgetFavoriteLetter) .font(.system(size: 42)) } } .accessibilityLabel(Text(favorite.title)) } } .frame(width: 60, height: 60, alignment: .center) } } struct LargeSearchFieldView: View { var body: some View { Link(destination: DeepLinks.newSearch) { ZStack { Capsule(style: .circular) .fill(Color.widgetSearchFieldBackground) .frame(minHeight: 46, maxHeight: 46) .padding(16) HStack { Image("WidgetDaxLogo") .resizable() .frame(width: 24, height: 24, alignment: .leading) Text(UserText.searchDuckDuckGo) .foregroundColor(Color.widgetSearchFieldText) Spacer() Image("WidgetSearchLoupe") }.padding(EdgeInsets(top: 0, leading: 27, bottom: 0, trailing: 27)) }.unredacted() } } } struct FavoritesRowView: View { var entry: Provider.Entry var start: Int var end: Int var body: some View { HStack { ForEach(start...end, id: \.self) { FavoriteView(favorite: entry.favoriteAt(index: $0), isPreview: entry.isPreview) if $0 < end { Spacer() } } } .padding(.horizontal, 16) } } struct FavoritesGridView: View { @Environment(\.widgetFamily) var widgetFamily var entry: Provider.Entry var body: some View { FavoritesRowView(entry: entry, start: 0, end: 3) Spacer() if widgetFamily == .systemLarge { FavoritesRowView(entry: entry, start: 4, end: 7) Spacer() FavoritesRowView(entry: entry, start: 8, end: 11) Spacer() } } } struct FavoritesWidgetView: View { @Environment(\.widgetFamily) var widgetFamily var entry: Provider.Entry var body: some View { ZStack { Rectangle().fill(Color.widgetBackground) VStack(alignment: .center, spacing: 0) { LargeSearchFieldView() if entry.favorites.isEmpty, !entry.isPreview { Link(destination: DeepLinks.addFavorite) { FavoritesGridView(entry: entry).accessibilityLabel(Text(UserText.noFavoritesCTA)) } } else { FavoritesGridView(entry: entry) } }.padding(.bottom, 8) VStack(spacing: 8) { Text(UserText.noFavoritesMessage) .font(.system(size: 15)) .multilineTextAlignment(.center) .foregroundColor(.widgetAddFavoriteMessage) .padding(.horizontal) .accessibilityHidden(true) HStack { Text(UserText.noFavoritesCTA) .bold() .font(.system(size: 15)) .foregroundColor(.widgetAddFavoriteCTA) Image(systemName: "chevron.right") .imageScale(.medium) .foregroundColor(.widgetAddFavoriteCTA) }.accessibilityHidden(true) } .isVisible(entry.favorites.isEmpty && !entry.isPreview) .padding(EdgeInsets(top: widgetFamily == .systemLarge ? 48 : 60, leading: 0, bottom: 0, trailing: 0)) } } } struct SearchWidgetView: View { var entry: Provider.Entry var body: some View { ZStack { Rectangle() .fill(Color.widgetBackground) .accessibilityLabel(Text(UserText.searchDuckDuckGo)) VStack(alignment: .center, spacing: 15) { Image("WidgetDaxLogo") .resizable() .frame(width: 46, height: 46, alignment: .center) .isHidden(false) .accessibilityHidden(true) ZStack(alignment: Alignment(horizontal: .trailing, vertical: .center)) { Capsule(style: .circular) .fill(Color.widgetSearchFieldBackground) .frame(width: 123, height: 46) Image("WidgetSearchLoupe") .padding(.trailing) .isHidden(false) } }.accessibilityHidden(true) } } } // See https://stackoverflow.com/a/59228385/73479 extension View { /// Hide or show the view based on a boolean value. /// /// Example for visibility: /// ``` /// Text("Label") /// .isHidden(true) /// ``` /// /// Example for complete removal: /// ``` /// Text("Label") /// .isHidden(true, remove: true) /// ``` /// /// - Parameters: /// - hidden: Set to `false` to show the view. Set to `true` to hide the view. /// - remove: Boolean value indicating whether or not to remove the view. @ViewBuilder func isHidden(_ hidden: Bool, remove: Bool = false) -> some View { if hidden { if !remove { self.hidden() } } else { self } } /// Logically inverse of `isHidden` @ViewBuilder func isVisible(_ visible: Bool, remove: Bool = false) -> some View { self.isHidden(!visible, remove: remove) } } extension Image { @ViewBuilder func scaleDown(_ shouldScale: Bool) -> some View { if shouldScale { self.resizable().aspectRatio(contentMode: .fit) } else { self } } } struct WidgetViews_Previews: PreviewProvider { static let mockFavorites: [Favorite] = { let duckDuckGoFavorite = Favorite(url: URL(string: "https://duckduckgo.com/")!, domain: "duckduckgo.com", title: "title", favicon: nil) let favorites = "abcdefghijk".map { Favorite(url: URL(string: "https://\($0).com/")!, domain: "\($0).com", title: "title", favicon: nil) } return [duckDuckGoFavorite] + favorites }() static let withFavorites = FavoritesEntry(date: Date(), favorites: mockFavorites, isPreview: false) static let previewWithFavorites = FavoritesEntry(date: Date(), favorites: mockFavorites, isPreview: true) static let emptyState = FavoritesEntry(date: Date(), favorites: [], isPreview: false) static let previewEmptyState = FavoritesEntry(date: Date(), favorites: [], isPreview: true) static var previews: some View { SearchWidgetView(entry: emptyState) .previewContext(WidgetPreviewContext(family: .systemSmall)) .environment(\.colorScheme, .light) SearchWidgetView(entry: emptyState) .previewContext(WidgetPreviewContext(family: .systemSmall)) .environment(\.colorScheme, .dark) // Medium size: FavoritesWidgetView(entry: previewWithFavorites) .previewContext(WidgetPreviewContext(family: .systemMedium)) .environment(\.colorScheme, .light) FavoritesWidgetView(entry: withFavorites) .previewContext(WidgetPreviewContext(family: .systemMedium)) .environment(\.colorScheme, .light) FavoritesWidgetView(entry: previewEmptyState) .previewContext(WidgetPreviewContext(family: .systemMedium)) .environment(\.colorScheme, .dark) FavoritesWidgetView(entry: emptyState) .previewContext(WidgetPreviewContext(family: .systemMedium)) .environment(\.colorScheme, .dark) // Large size: FavoritesWidgetView(entry: previewWithFavorites) .previewContext(WidgetPreviewContext(family: .systemLarge)) .environment(\.colorScheme, .light) FavoritesWidgetView(entry: withFavorites) .previewContext(WidgetPreviewContext(family: .systemLarge)) .environment(\.colorScheme, .light) FavoritesWidgetView(entry: previewEmptyState) .previewContext(WidgetPreviewContext(family: .systemLarge)) .environment(\.colorScheme, .dark) FavoritesWidgetView(entry: emptyState) .previewContext(WidgetPreviewContext(family: .systemLarge)) .environment(\.colorScheme, .dark) } }
0
// // AddressBookRepository.swift // VergeiOS // // Created by Swen van Zanten on 10-09-18. // Copyright © 2018 Verge Currency. All rights reserved. // import Foundation import CoreStore import Logging class AddressBookRepository { private let dataStack: DataStack private let log: Logger init(dataStack: DataStack, log: Logger) { self.dataStack = dataStack self.log = log } func name(byAddress address: String) -> String? { guard let entity = ((try? self.dataStack.fetchOne(From<AddressType>().where(\.address == address))) as AddressType??) else { return nil } return entity?.name } func get(byName name: String) -> Contact? { guard let entity = ((try? self.dataStack.fetchOne(From<AddressType>().where(\.name == name))) as AddressType??) else { return nil } return transform(entity: entity) } func get(byAddress address: String) -> Contact? { guard let entity = ((try? self.dataStack.fetchOne(From<AddressType>().where(\.address == address))) as AddressType??) else { return nil } return transform(entity: entity) } func all() -> [Contact] { let entities = try? self.dataStack.fetchAll(From<AddressType>()) var addresses: [Contact] = [] for entity in entities ?? [] { addresses.append(transform(entity: entity)) } return addresses } func put(address: Contact) { var entity: AddressType? if let existingEntity = ((try? self.dataStack.fetchOne(From<AddressType>().where(\.address == address.address))) as AddressType??) { entity = existingEntity } do { _ = try self.dataStack.perform(synchronous: { transaction -> Bool in if entity == nil { entity = transaction.create(Into<AddressType>()) } else { entity = transaction.edit(entity) } entity?.name = address.name entity?.address = address.address return transaction.hasChanges }) } catch { self.log.error("address book repository error while adding contact: \(error.localizedDescription)") } } func remove(address: Contact) { guard let entity = ((try? self.dataStack.fetchOne(From<AddressType>().where(\.name == address.name))) as AddressType??) else { return } do { _ = try self.dataStack.perform(synchronous: { transaction -> Bool in transaction.delete(entity) return transaction.hasChanges }) } catch { self.log.error("address book repository error while removing contact: \(error.localizedDescription)") } } func isEmpty() -> Bool { all().count == 0 } private func transform(entity: AddressType?) -> Contact { var address = Contact() address.name = entity?.name ?? "" address.address = entity?.address ?? "" return address } }
0
// // AppDelegate.swift // SAHistoryNavigationViewControllerSample // // Created by 鈴木大貴 on 2015/03/26. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit import SAHistoryNavigationViewController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().barTintColor = UIColor(red: 0.0, green: 0.549, blue: 0.89, alpha: 1.0) UINavigationBar.appearance().tintColor = .whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false) (window?.rootViewController as? UINavigationController)?.historyDelegate = self return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } extension AppDelegate: SAHistoryNavigationViewControllerDelegate { func historyControllerDidShowHistory(controller: SAHistoryNavigationViewController, viewController: UIViewController) { print("did show history") } }
0
// // BoolValue.swift // Formulitic // // Copyright (c) 2016-2018 Hironori Ichimiya <[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 /// A calculated value which represents a boolean value. public struct BoolValue: BooleanableValue, Hashable { /// A raw value. public let bool: Bool /// Initializes the object. /// - Parameters: /// - bool: A raw value. public init(bool: Bool) { self.bool = bool } public func cast(to capability: ValueCapability, context: EvaluateContext) -> Value { switch capability { case .booleanable: return self case .numerable: return DoubleValue(number: bool ? 1.0 : 0.0) case .stringable: return StringValue(string: bool ? "1" : "0") } } /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: BoolValue, rhs: BoolValue) -> Bool { return lhs.bool == rhs.bool } /// The hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { get { return bool.hashValue } } } extension BoolValue: CustomDebugStringConvertible { public var debugDescription: String { return "BoolValue(\(bool))" } }
0
internal enum _Corner { case topLeft case topRight case bottomLeft case bottomRight } internal extension Corner { func toInternal(_ view: Frameable) -> _Corner { switch self { case .topLeft: return .topLeft case .topRight: return .topRight case .bottomLeft: return .bottomLeft case .bottomRight: return .bottomRight case .topLeading: return view.isRightToLeft ? .topRight : .topLeft case .topTrailing: return view.isRightToLeft ? .topLeft : .topRight case .bottomLeading: return view.isRightToLeft ? .bottomRight : .bottomLeft case .bottomTrailing: return view.isRightToLeft ? .bottomLeft : .bottomRight } } } internal enum _Edge { case top case left case bottom case right } internal extension Edge { func toInternal(_ view: Frameable) -> _Edge { switch self { case .top: return .top case .left: return .left case .bottom: return .bottom case .right: return .right case .leading: return view.isRightToLeft ? .right : .left case .trailing: return view.isRightToLeft ? .left : .right } } } internal enum _Align { case toTheRightMatchingTop case toTheRightMatchingBottom case toTheRightCentered case toTheLeftMatchingTop case toTheLeftMatchingBottom case toTheLeftCentered case underMatchingLeft case underMatchingRight case underCentered case aboveMatchingLeft case aboveMatchingRight case aboveCentered } internal extension Align { func toInternal(_ view: Frameable) -> _Align { switch self { case .toTheRightMatchingTop: return .toTheRightMatchingTop case .toTheRightMatchingBottom: return .toTheRightMatchingBottom case .toTheRightCentered: return .toTheRightCentered case .toTheLeftMatchingTop: return .toTheLeftMatchingTop case .toTheLeftMatchingBottom: return .toTheLeftMatchingBottom case .toTheLeftCentered: return .toTheLeftCentered case .underMatchingLeft: return .underMatchingLeft case .underMatchingRight: return .underMatchingRight case .underCentered: return .underCentered case .aboveMatchingLeft: return .aboveMatchingLeft case .aboveMatchingRight: return .aboveMatchingRight case .aboveCentered: return .aboveCentered case .toTheLeadingMatchingTop: return view.isRightToLeft ? .toTheRightMatchingTop : .toTheLeftMatchingTop case .toTheTrailingMatchingTop: return view.isRightToLeft ? .toTheLeftMatchingTop : .toTheRightMatchingTop case .toTheLeadingMatchingBottom: return view.isRightToLeft ? .toTheRightMatchingBottom : .toTheLeftMatchingBottom case .toTheTrailingMatchingBottom: return view.isRightToLeft ? .toTheLeftMatchingBottom : .toTheRightMatchingBottom case .toTheLeadingCentered: return view.isRightToLeft ? .toTheRightCentered : .toTheLeftCentered case .toTheTrailingCentered: return view.isRightToLeft ? .toTheLeftCentered : .toTheRightCentered case .underMatchingLeading: return view.isRightToLeft ? .underMatchingRight : .underMatchingLeft case .underMatchingTrailing: return view.isRightToLeft ? .underMatchingLeft : .underMatchingRight case .aboveMatchingLeading: return view.isRightToLeft ? .aboveMatchingRight : .aboveMatchingLeft case .aboveMatchingTrailing: return view.isRightToLeft ? .aboveMatchingLeft : .aboveMatchingRight } } }
0
// // Buildings.swift // OGame // // Created by Subvert on 22.05.2021. // import UIKit struct Building { let name: String let metal: Int let crystal: Int let deuterium: Int let image: ImageBundle let buildingsID: Int var levelOrAmount: Int let condition: String let timeToBuild: String } struct Buildings { // MARK: - Supplies static let metalMine = (1, 1, "supplies") static let crystalMine = (2, 1, "supplies") static let deuteriumMine = (3, 1, "supplies") static let solarPlant = (4, 1, "supplies") static let fusionPlant = (12, 1, "supplies") static let metalStorage = (22, 1, "supplies") static let crystalStorage = (23, 1, "supplies") static let deuteriumStorage = (24, 1, "supplies") // MARK: - Facilities static let roboticsFactory = (14, 1, "facilities") static let shipyard = (21, 1, "facilities") static let researchLaboratory = (31, 1, "facilities") static let allianceDepot = (34, 1, "facilities") static let missileSilo = (44, 1, "facilities") static let naniteFactory = (15, 1, "facilities") static let terraformer = (33, 1, "facilities") static let repairDock = (36, 1, "facilities") static let moonBase = (41, 1, "facilities") static let sensorPhalanx = (42, 1, "facilities") static let jumpGate = (43, 1, "facilities") // MARK: - Researches static let energy = (113, 1, "research") static let laser = (120, 1, "research") static let ion = (121, 1, "research") static let hyperspace = (114, 1, "research") static let plasma = (122, 1, "research") static let combustionDrive = (115, 1, "research") static let impulseDrive = (117, 1, "research") static let hyperspaceDrive = (118, 1, "research") static let espionage = (106, 1, "research") static let computer = (108, 1, "research") static let astrophysics = (124, 1, "research") static let researchNetwork = (123, 1, "research") static let graviton = (199, 1, "research") static let weapons = (109, 1, "research") static let shielding = (110, 1, "research") static let armour = (111, 1, "research") // MARK: - Ships static func lightFighter(_ amount: Int = 1) -> (Int, Int, String) { return (204, amount, "shipyard") } static func heavyFighter(_ amount: Int = 1) -> (Int, Int, String) { return (205, amount, "shipyard") } static func cruiser(_ amount: Int = 1) -> (Int, Int, String) { return (206, amount, "shipyard") } static func battleship(_ amount: Int = 1) -> (Int, Int, String) { return (207, amount, "shipyard") } static func battlecruiser(_ amount: Int = 1) -> (Int, Int, String) { return (215, amount, "shipyard") } static func bomber(_ amount: Int = 1) -> (Int, Int, String) { return (211, amount, "shipyard") } static func destroyer(_ amount: Int = 1) -> (Int, Int, String) { return (213, amount, "shipyard") } static func deathstar(_ amount: Int = 1) -> (Int, Int, String) { return (214, amount, "shipyard") } static func reaper(_ amount: Int = 1) -> (Int, Int, String) { return (218, amount, "shipyard") } static func pathfinder(_ amount: Int = 1) -> (Int, Int, String) { return (219, amount, "shipyard") } static func smallCargo(_ amount: Int = 1) -> (Int, Int, String) { return (202, amount, "shipyard") } static func largeCargo(_ amount: Int = 1) -> (Int, Int, String) { return (203, amount, "shipyard") } static func colonyShip(_ amount: Int = 1) -> (Int, Int, String) { return (208, amount, "shipyard") } static func recycler(_ amount: Int = 1) -> (Int, Int, String) { return (209, amount, "shipyard") } static func espionageProbe(_ amount: Int = 1) -> (Int, Int, String) { return (210, amount, "shipyard") } static func solarSatellite(_ amount: Int = 1) -> (Int, Int, String) { return (212, amount, "shipyard") } static func crawler(_ amount: Int = 1) -> (Int, Int, String) { return (217, amount, "shipyard") } // MARK: - Defences static func rocketLauncher(amount: Int = 1) -> (Int, Int, String) { return (401, amount, "defenses") } static func lightLaser(amount: Int = 1) -> (Int, Int, String) { return (402, amount, "defenses") } static func heavyLaser(amount: Int = 1) -> (Int, Int, String) { return (403, amount, "defenses") } static func gaussCannon(amount: Int = 1) -> (Int, Int, String) { return (404, amount, "defenses") } static func ionCannon(amount: Int = 1) -> (Int, Int, String) { return (405, amount, "defenses") } static func plasmaCannon(amount: Int = 1) -> (Int, Int, String) { return (406, amount, "defenses") } static func smallShieldDome(amount: Int = 1) -> (Int, Int, String) { return (407, amount, "defenses") } static func largeShieldDome(amount: Int = 1) -> (Int, Int, String) { return (408, amount, "defenses") } static func antiBallisticMissiles(amount: Int = 1) -> (Int, Int, String) { return (502, amount, "defenses") } static func interplanetaryMissiles(amount: Int = 1) -> (Int, Int, String) { return (503, amount, "defenses") } }
0
public struct TMDBTVEpisodeAccountStates: Codable { public let id: Int public let rated: TMDBBool }
0
// // IssueRequestModel.swift // Freetime // // Created by Ryan Nystrom on 7/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class IssueRequestModel: ListDiffable { enum Event { case assigned case unassigned case reviewRequested case reviewRequestRemoved } let id: String let actor: String let user: String let date: Date let event: Event let attributedText: NSAttributedStringSizing init(id: String, actor: String, user: String, date: Date, event: Event, width: CGFloat) { self.id = id self.actor = actor self.user = user self.date = date self.event = event let attributedText = NSMutableAttributedString() attributedText.append(NSAttributedString( string: actor, attributes: [ .font: Styles.Fonts.secondaryBold, .foregroundColor: Styles.Colors.Gray.dark.color, MarkdownAttribute.username: actor ] )) let phrase: String switch event { case .assigned: phrase = NSLocalizedString(" assigned", comment: "") case .unassigned: phrase = NSLocalizedString(" unassigned", comment: "") case .reviewRequested: phrase = NSLocalizedString(" requested", comment: "") case .reviewRequestRemoved: phrase = NSLocalizedString(" removed", comment: "") } attributedText.append(NSAttributedString( string: phrase, attributes: [ .font: Styles.Fonts.secondary, .foregroundColor: Styles.Colors.Gray.medium.color ] )) attributedText.append(NSAttributedString( string: " \(user)", attributes: [ .font: Styles.Fonts.secondaryBold, .foregroundColor: Styles.Colors.Gray.dark.color, MarkdownAttribute.username: user ] )) attributedText.append(NSAttributedString( string: " \(date.agoString)", attributes: [ .font: Styles.Fonts.secondary, .foregroundColor: Styles.Colors.Gray.medium.color, MarkdownAttribute.details: DateDetailsFormatter().string(from: date) ] )) self.attributedText = NSAttributedStringSizing( containerWidth: width, attributedText: attributedText, inset: UIEdgeInsets( top: Styles.Sizes.inlineSpacing, left: Styles.Sizes.eventGutter, bottom: Styles.Sizes.inlineSpacing, right: Styles.Sizes.eventGutter ), backgroundColor: Styles.Colors.background ) } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return id as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } }
0
import UIKit import PhotosUI import LPLivePhotoGenerator class MainViewController: UIViewController { var createButton: UIButton! var createActivityIndicatorView: UIActivityIndicatorView! var viewButton: UIButton! var saveButton: UIButton! var imagePath: String! var videoPath: String! var livePhoto: LPLivePhoto? override func viewDidLoad() { super.viewDidLoad() imagePath = Bundle.main.path(forResource: "image", ofType: "JPEG") videoPath = Bundle.main.path(forResource: "video", ofType: "MOV") view.backgroundColor = UIColor.black let height = view.frame.height / 4 let width = view.frame.width * 0.8 let spaceBetween = height / 4 createButton = ActionButton(frame: CGRect(x: 0, y: spaceBetween, width: width, height: height), title: "Create Live Photo", hidden: false) createButton.center.x = view.center.x createButton.addTarget(self, action: #selector(createButtonWasPressed), for: .touchUpInside) viewButton = ActionButton(frame: CGRect(x: 0, y: createButton.frame.maxY + spaceBetween, width: width, height: height), title: "View Live Photo", hidden: true) viewButton.center.x = view.center.x viewButton.addTarget(self, action: #selector(viewButtonWasPressed), for: .touchUpInside) createActivityIndicatorView = UIActivityIndicatorView(style: .whiteLarge) createActivityIndicatorView.center = viewButton.center saveButton = ActionButton(frame: CGRect(x: 0, y: viewButton.frame.maxY + spaceBetween, width: width, height: height), title: "Save Live Photo", hidden: true) saveButton.center.x = view.center.x saveButton.addTarget(self, action: #selector(saveButtonWasPressed), for: .touchUpInside) view.addSubview(createButton) view.addSubview(createActivityIndicatorView) view.addSubview(viewButton) view.addSubview(saveButton) } @objc func createButtonWasPressed() { self.viewButton.isHidden = true self.saveButton.isHidden = true self.saveButton.isUserInteractionEnabled = true self.saveButton.setTitle("Save Live Photo", for: .normal) self.saveButton.setTitleColor(UIColor.white, for: .normal) createActivityIndicatorView.startAnimating() LPLivePhotoGenerator.create(inputImagePath: self.imagePath, inputVideoPath: self.videoPath) { (livePhoto: LPLivePhoto?, error: Error?) in if let livePhoto = livePhoto { self.livePhoto = livePhoto self.createActivityIndicatorView.stopAnimating() self.viewButton.isHidden = false return } if let error = error { print(error) } } } @objc func viewButtonWasPressed() { let livePhotoViewController = LivePhotoViewController() livePhotoViewController.phLivePhoto = livePhoto?.phLivePhoto self.present(livePhotoViewController, animated: true) { self.saveButton.isHidden = false } } @objc func saveButtonWasPressed() { self.saveButton.isUserInteractionEnabled = false livePhoto?.writeToPhotoLibrary(completion: { (livePhoto: LPLivePhoto, error: Error?) in DispatchQueue.main.sync { if let error = error { print(error) } else { self.saveButton.setTitle("Saved", for: .normal) self.saveButton.setTitleColor(UIColor.green, for: .normal) } } }) } }
0
// // SchedulerTimeIntervalConvertible.swift // iCombine // // Created by Adamas Zhu on 5/8/21. // import RxCocoa import RxSwift /// A protocol that provides a scheduler with an expression for relative time. // public protocol SchedulerTimeIntervalConvertible { // static func seconds(_ s: Int) -> Self // static func seconds(_ s: Double) -> Self // static func milliseconds(_ ms: Int) -> Self // static func microseconds(_ us: Int) -> Self // static func nanoseconds(_ ns: Int) -> Self //}
0
// // RoundImageView.swift // SwiftProject // // Created by 王云鹏 on 16/3/7. // Copyright © 2016年 王涛. All rights reserved. // import UIKit class RoundImageView: UIImageView { override init(frame: CGRect) { super.init(frame: frame) addCover() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addCover() } init (){ super.init(frame:CGRect.zero) addCover() } func addCover(){ let imageView = UIImageView() //FIXME:图片有点不合适咯 imageView.image = UIImage(named: "roundCoverer") self.addSubview(imageView) // imageView.snp_makeConstraints { (make) -> Void in // make.edges.equalTo(self).inset(UIEdgeInsetsMake(0, 0, 0, 0)) // } } }
0
// // CertificatePinnerTestsHelpers.swift // QuickHatch // // Created by Daniel Koster on 8/13/20. // Copyright © 2020 DaVinci Labs. All rights reserved. // import QuickHatch class CertificatePinnerTestHelpers { class func fakeChallenge(with certificate: SecCertificate?) -> URLAuthenticationChallenge { var serverTrust: SecTrust? SecTrustCreateWithCertificates([certificate] as CFArray, SecPolicyCreateBasicX509(), &serverTrust) let space = MockURLProtectionSpace(serverTrust: serverTrust, host: "nobody", port: 8080) return URLAuthenticationChallenge(protectionSpace: space, proposedCredential: nil, previousFailureCount: 0, failureResponse: nil, error: nil, sender: MockAuthenticationChallengeSender()) } class func fakeChallenge(with certificate: SecCertificate?, host: String, authType: String = NSURLAuthenticationMethodServerTrust) -> URLAuthenticationChallenge { var serverTrust: SecTrust? SecTrustCreateWithCertificates([certificate] as CFArray, SecPolicyCreateBasicX509(), &serverTrust) let space = MockURLProtectionSpace(serverTrust: serverTrust, host: host, port: 8080, authenticationMethod: authType) return URLAuthenticationChallenge(protectionSpace: space, proposedCredential: nil, previousFailureCount: 0, failureResponse: nil, error: nil, sender: MockAuthenticationChallengeSender()) } static let bundle = Bundle.init(for: CertificateBuilderTests.self) class var certificate: SecCertificate? { return QHCertificateBuilder.default.openDer(name: "certificate", type: "der", bundle: bundle) } class var davinciCertificate: SecCertificate? { return QHCertificateBuilder.default.openDer(name: "davinci.com", type: "der", bundle: bundle) } } class MockAuthenticationChallengeSender: NSObject, URLAuthenticationChallengeSender { func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge) { } func continueWithoutCredential(for challenge: URLAuthenticationChallenge) { } func cancel(_ challenge: URLAuthenticationChallenge) { } } class MockURLProtectionSpace: URLProtectionSpace { private let trust: SecTrust? init(serverTrust: SecTrust?,host: String, port: Int, authenticationMethod: String? = nil) { self.trust = serverTrust super.init(host: host, port: port, protocol: nil, realm: nil, authenticationMethod: authenticationMethod) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var serverTrust: SecTrust? { return trust } }
0
// // MSExpenseItem+Convertible.swift // MoyskladiOSRemapSDK // // Created by Vladislav on 30.08.17. // Copyright © 2017 Andrey Parshakov. All rights reserved. // import Foundation extension MSExpenseItem: DictConvertable { public func dictionary(metaOnly: Bool) -> Dictionary<String, Any> { var dict = [String: Any]() dict["meta"] = meta.dictionary() guard !metaOnly else { return dict } // тут должны быть остальные поля объекта, если они понадобятся return dict } public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSExpenseItem>? { guard let meta = MSMeta.from(dict: dict.msValue("meta"), parent: dict) else { return nil } return MSEntity.entity(MSExpenseItem(id: MSID(dict: dict), meta: meta, info: MSInfo(dict: dict))) } }
0
//=----------------------------------------------------------------------------= // This source file is part of the DiffableTextViews open source project. // // Copyright (c) 2022 Oscar Byström Ericsson // Licensed under Apache License, Version 2.0 // // See http://www.apache.org/licenses/LICENSE-2.0 for license information. //=----------------------------------------------------------------------------= #if DEBUG @testable import DiffableTextKit import XCTest //*============================================================================* // MARK: * Status x Tests //*============================================================================* final class StatusTests: XCTestCase { //=------------------------------------------------------------------------= // MARK: State //=------------------------------------------------------------------------= let en_US = Mock(locale: Locale(identifier: "en_US")) let sv_SE = Mock(locale: Locale(identifier: "sv_SE")) //=------------------------------------------------------------------------= // MARK: Tests x Transformations //=------------------------------------------------------------------------= func testMergeReplacesInequalValues() { var status = Status(en_US, "0", false) let changes = status.merge(Status(sv_SE, "1", true)) let result = Status(sv_SE, "1", true) XCTAssertEqual(status, result) XCTAssertEqual(changes, [.style, .value, .focus]) } func testMergeDiscardsEqualValues() { let en_US = en_US.equals(()) let sv_SE = sv_SE.equals(()) var status0 = Status(en_US, "0", false) let status1 = Status(sv_SE, "1", true) let changes = status0.merge( status1) XCTAssertEqual(status0, status1) XCTAssertEqual(status0.style.base.locale, en_US.base.locale) XCTAssertEqual(changes, Changes([.value, .focus])) } //=------------------------------------------------------------------------= // MARK: Tests x Utilities //=------------------------------------------------------------------------= func testMemberWiseInequal() { XCTAssertEqual( Status(en_US, "0", false) .!= Status(en_US, "0", false), []) XCTAssertEqual( Status(en_US, "0", false) .!= Status(sv_SE, "0", false), [.style]) XCTAssertEqual( Status(en_US, "0", false) .!= Status(en_US, "1", false), [.value]) XCTAssertEqual( Status(en_US, "0", false) .!= Status(en_US, "0", true), [.focus]) XCTAssertEqual( Status(en_US, "0", false) .!= Status(sv_SE, "1", true), [.style, .value, .focus]) } } #endif
0
// // ViewController.swift // Alamofire_Practice // // Created by CoderDream on 2018/11/12. // Copyright © 2018 CoderDream. 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. } }
0
// // Update.swift // SQLiteORM // // Created by Valo on 2022/9/28. // import AnyCoder import Foundation open class Update<T>: CURD { public enum Method { case insert, upsert, update } private let orm: Orm<T> private var method: Method = .insert private var items: [Any] = [] private var fields: [String] = [] public required init(_ orm: Orm<T>) { self.orm = orm super.init() self.orm { orm } } private lazy var validKeys: [String] = { var keys = orm.config.columns if method == .insert, let config = orm.config as? PlainConfig, config.primaries.count == 1, config.pkAutoInc { keys.removeAll { config.primaries.first! == $0 } } return keys }() fileprivate func keyValue(of item: Any) throws -> [String: Primitive] { let dic = try encodeToKeyValue(item) var filtered = dic.filter { validKeys.contains($0.key) } if let config = orm.config as? PlainConfig, config.logAt { let now = Date().timeIntervalSinceReferenceDate if method != .update { filtered[Config.createAt] = now } filtered[Config.updateAt] = now } return filtered } private func prepare(_ keyValue: [String: Primitive]) -> (sql: String, values: [Primitive]) { var sql = "" var keys: Dictionary<String, any Primitive>.Keys var values: [Primitive] switch method { case .insert, .upsert: keys = keyValue.keys values = keys.map { keyValue[$0] } as! [Primitive] let keysString = keys.map { $0.quoted }.joined(separator: ",") let marksString = Array(repeating: "?", count: keyValue.count).joined(separator: ",") sql = ((method == .upsert) ? "INSERT OR REPLACE" : "INSERT") + " INTO \(table.quoted) (\(keysString)) VALUES (\(marksString))" case .update: let kv = fields.count == 0 ? keyValue : keyValue.filter { (fields + [Config.updateAt]).contains($0.key) } keys = kv.keys values = keys.map { kv[$0] } as! [Primitive] let setsString = keys.map { $0.quoted + "=?" }.joined(separator: ",") let condition = self.where.count > 0 ? self.where : constraint(of: keyValue, orm.config).toWhere() let whereClause = condition.count > 0 ? "WHERE \(condition)" : "" sql = "UPDATE \(table.quoted) SET \(setsString) \(whereClause)" } return (sql, values) } private func run(_ tuple: (sql: String, values: [Primitive])) -> Bool { do { try orm.db.prepare(tuple.sql, bind: tuple.values).run() } catch _ { return false } return true } @discardableResult public func method(_ closure: () -> Method) -> Self { method = closure() return self } @discardableResult public func items(_ closure: () -> [Any]) -> Self { items = closure() return self } @discardableResult public func fields(_ closure: () -> [String]) -> Self { fields = closure() return self } public func execute() -> Int64 { let array = items.map { try? keyValue(of: $0) }.filter { $0 != nil } guard array.count > 0 else { return 0 } let tuples = array.map { prepare($0!) } if tuples.count == 1 { return run(tuples.first!) ? 1 : 0 } var count: Int64 = 0 do { try orm.db.transaction(.immediate) { for tuple in tuples { let ret = run(tuple) count += ret ? 1 : 0 } } } catch _ { return count } return count } } // MARK: - insert public extension Orm { /// insert a item @discardableResult func insert(_ item: T) -> Bool { Update(self).method { .insert }.items { [item] }.execute() == 1 } @discardableResult func insert(keyValues: [String: Primitive]) -> Bool { Update(self).method { .insert }.items { [keyValues] }.execute() == 1 } /// insert multiple items /// /// - Returns: number of successes @discardableResult func insert(multi items: [T]) -> Int64 { Update(self).method { .insert }.items { items }.execute() } @discardableResult func insert(multiKeyValues: [[String: Primitive]]) -> Int64 { Update(self).method { .insert }.items { multiKeyValues }.execute() } } // MARK: - upsert public extension Orm { /// insert or update a item @discardableResult func upsert(_ item: T) -> Bool { Update(self).method { .upsert }.items { [item] }.execute() == 1 } @discardableResult func upsert(keyValues: [String: Primitive]) -> Bool { Update(self).method { .upsert }.items { [keyValues] }.execute() == 1 } /// insert or update multiple records /// /// - Returns: number of successes @discardableResult func upsert(multi items: [T]) -> Int64 { Update(self).method { .upsert }.items { items }.execute() } @discardableResult func upsert(multiKeyValues: [[String: Primitive]]) -> Int64 { Update(self).method { .upsert }.items { multiKeyValues }.execute() } } // MARK: - update public extension Orm { /// update datas /// /// - Parameters: /// - condition: condit /// - bindings: [filed:data] @discardableResult func update(with bindings: [String: Primitive], condition: (() -> String)? = nil) -> Bool { let up = Update(self).method { .update }.items { [bindings] } if let condition = condition { up.where(condition) } return up.execute() == 1 } /// update a item @discardableResult func update(_ item: T) -> Bool { return Update(self).method { .update }.items { [item] }.execute() == 1 } /// update a item, special the fields @discardableResult func update(_ item: T, fields: [String]) -> Bool { return Update(self).method { .update }.items { [item] }.fields { fields }.execute() == 1 } /// update multple items /// /// - Returns: number of successes @discardableResult func update(multi items: [T]) -> Int64 { return Update(self).method { .update }.items { items }.execute() } /// update multple items, special the fileds /// /// - Returns: number of successes @discardableResult func update(multi items: [T], fields: [String]) -> Int64 { return Update(self).method { .update }.items { items }.fields { fields }.execute() } /// plus / minus on the specified field /// /// - Parameters: /// - value: update value, example: 2 means plus 2, -2 means minus 2 @discardableResult func increase(_ field: String, value: Int, condition: (() -> String)? = nil) -> Bool { guard value != 0 else { return true } let val = field + (value > 0 ? "+\(value)" : "\(value)") return update(with: [field: val], condition: condition) } }
0
// // ViewController.swift // UICircleSegmentSample // // Created by Murawaki on 7/21/16. // Copyright © 2016 Murawaki. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let segmentView = UICircleSegmentView(frame: CGRectMake(50, 200, self.view.frame.width-100, 200), CircleNum: 3, CircleSize: 100, sCircleSize: 40); segmentView.value = ["ツイート", "フォロー", "フォロワー"]; segmentView.sValue = ["120", "92", "91"]; segmentView.addTarget(self, action: #selector(self.didChanged)); self.view.addSubview(segmentView); } func didChanged(){ print("changedValue"); } }
0
// // UIViewControllerExtension.swift // ask-user_ios // // Created by iMac on 2019/04/08. // Copyright © 2019 iMac. All rights reserved. // import Foundation import UIKit extension UIViewController { // MARK:画面遷移 public func changeViewPresent(storyboard: String, crossDissolve: Bool = false) { // let sb = UIStoryboard(name: storyboard, bundle: nil) // let vc = sb.instantiateInitialViewController()! // if crossDissolve { // vc.modalTransitionStyle = .crossDissolve // } // present(vc, animated: true, completion: nil) } public func changeViewPush(storyboard: String) { // let sb = UIStoryboard(name: storyboard, bundle: nil) // let vc = sb.instantiateInitialViewController()! // self.navigationController?.pushViewController(vc, animated: true) } public func changeViewShow(storyboard: String) { // let sb = UIStoryboard(name: storyboard, bundle: nil) // let vc = sb.instantiateInitialViewController()! // show(vc, sender: nil) } // MARK:アラート関連 /* * アラート * @param message = アラートに表示するメッセージ */ public func showAlertMessage(_ message: String) { // let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) // alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) // present(alert, animated: true, completion:{ // alert.view.superview?.isUserInteractionEnabled = true // alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dissmissAlert))) // }) } /* * ↑のアラートを消す */ @objc public func dissmissAlert() { self.dismiss(animated: true, completion: nil) } // MARK:インジケーター public func setUpIndicator(vc: UIViewController) -> (UIActivityIndicatorView) { let activeIndicator = UIActivityIndicatorView() // activeIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50) // activeIndicator.center = vc.view.center // activeIndicator.hidesWhenStopped = true // activeIndicator.style = UIActivityIndicatorView.Style.gray // vc.view.addSubview(activeIndicator) // activeIndicator.startAnimating() return activeIndicator } // MARK:UserDefault public func getUserString(key:String) -> String { let value = UserDefaults.standard.string(forKey: key) if value != nil { return value! } else { return "" } } public func getUserInteger(key:String) -> Int { let value = UserDefaults.standard.integer(forKey: key) return value } public func getUserDefault_S(key:String) -> String { let value = UserDefaults.standard.string(forKey: key) if value != nil { return value! } else { return "" } } public func setUserDefault(key:String,value:Any) { UserDefaults.standard.set(value, forKey: key) } /* * 高さがキーボードに被る場合スクロールさせる。 */ public func moveUpViewPosition(textField: UITextField, vc: UIViewController) { var bounceHeight: CGFloat = 0.0 if textField.frame.origin.y < 240 { bounceHeight = -130 } else { bounceHeight = -210 } UIView.animate(withDuration: 0.25, animations: { () in let transform = CGAffineTransform(translationX: 0, y: bounceHeight) vc.view.transform = transform }) } /* * キーボード非表示時に上に上がっている画面を元に戻す */ public func moveDownViewPosition(vc: UIViewController) { UIView.animate(withDuration: 0.25, animations: { () in vc.view.transform = .identity }) } }
0
// // Copyright (C) 2021 Curity AB. // // 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 SwiftUI struct AuthenticatorButton: View { @Environment(\.colorScheme) var colorScheme private let imageName: String? private let title: LocalizedStringKey private let actionHandler: (Resettable) -> Void @State private var isSelected = false init(imageName: String?, title: LocalizedStringKey, actionHandler: @escaping (Resettable) -> Void) { self.imageName = imageName self.title = title self.actionHandler = actionHandler } var body: some View { Button(action: didSelect) { HStack (spacing: 11.0) { if !isSelected { Image(imageName ?? "") .resizable() .frame(width: 26.0, height: 26.0, alignment: .center) Text(title) .lineLimit(2) .minimumScaleFactor(0.5) } else { ArcSpinner(color: Color.primaryRegular) } } } .buttonStyle(ColorButtonStyle(buttonTheme: ButtonTheme.authenticatorButton(for: colorScheme))) } func didSelect() { isSelected = true actionHandler(self) } } extension AuthenticatorButton: Resettable { func reset() { isSelected = false } } struct AuthenticatorButton_Previews: PreviewProvider { static var previews: some View { LazyVStack { AuthenticatorButton(imageName: "icon-twitter", title: "Continue with Google", actionHandler: { _ in }) AuthenticatorButton(imageName: "icon-user", title: "A Standard Active Directory backed Authenticator", actionHandler: { _ in }) } .preferredColorScheme(.dark) .padding() .previewDevice("iPod touch (7th generation)") } } private extension ButtonTheme { static func authenticatorButton(for colorScheme: ColorScheme) -> ButtonTheme { return ButtonTheme(foregroundColor: .black, backgroundColor: .white, borderColor: colorScheme == .light ? .buttonBorder : .clear, font: .actionText, cornerRadius: UIConstants.cornerRadius, minHeight: UIConstants.buttonHeight) } }
0
// // SwiftIconTests.swift // SwiftIconTests // // Created by Eric Yang on 1/8/19. // Copyright © 2019 EricYang. All rights reserved. // import XCTest @testable import SwiftIcon class SwiftIconTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // Configuration.swift // MobiWeather // // Created by Parth Adroja on 10/10/18. // Copyright © 2018 Parth Adroja. All rights reserved. // import Foundation struct Configuration { lazy var environment: Environment = { if let configuration = Bundle.main.object(forInfoDictionaryKey: "Configuration") as? String { if configuration.range(of: "Dev") != nil { return .dev } else if configuration.range(of: "Stage") != nil { return .stage } } return .release }() }
0
// // GameListLocalDataManager.swift // Games // // Created on 05/04/20. // Copyright © 2020 redspark. All rights reserved. // import Foundation final class GameListLocalDataManager: GameListLocalDataManagerProtocol { private enum Constants { static let gameListDataKey = "gameList" } weak var output: GameListLocalDataManagerOutput! private lazy var userDefault = UserDefaults.standard func saveGameList(_ gameList: [Game]) { let gameListData = NSKeyedArchiver.archivedData(withRootObject: gameList) userDefault.setValue(gameListData, forKey: Constants.gameListDataKey) userDefault.synchronize() } func getGameList() -> [Game]? { if let gameListData = userDefault.object(forKey: Constants.gameListDataKey) as? Data, let gameList = NSKeyedUnarchiver.unarchiveObject(with: gameListData) as? [Game] { return gameList } return nil } }
0
import Foundation import UIKit // Used for network indicator in the UI // Basic HTTP Client that offers support for basic HTTP verbs. // Authentication (user/password) is supported in case a reverse proxy // is configured properly in front of the OctoPrint server. // Requests will include the 'X-Api-Key' header that will be processed by // the OctoPrint server. class HTTPClient: NSObject, URLSessionTaskDelegate { var serverURL: String! var apiKey: String! var username: String? var password: String? var timeoutIntervalForRequest = 10.0 var timeoutIntervalForResource = 16.0 var preRequest: (() -> Void)? var postRequest: (() -> Void)? init(serverURL: String, apiKey: String, username: String?, password: String?) { super.init() self.serverURL = serverURL self.apiKey = apiKey self.username = username self.password = password } // MARK: HTTP operations (GET/POST/PUT/DELETE) func get(_ service: String, callback: @escaping (NSObject?, Error?, HTTPURLResponse) -> Void) { let url: URL = URL(string: serverURL + service)! // Get session with the provided configuration let session = Foundation.URLSession(configuration: getConfiguration(false), delegate: self, delegateQueue: nil) // Create background task that will perform the HTTP request var request = URLRequest(url: url) // Add API Key header request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in self.postRequest?() if let httpRes = response as? HTTPURLResponse { if error != nil { callback(nil, error, httpRes) } else { if httpRes.statusCode == 200 { // Parse string into JSON object let result = String(data: data!, encoding: String.Encoding.utf8)! do { let json = try JSONSerialization.jsonObject(with: result.data(using: String.Encoding.utf8)!, options: [.mutableLeaves, .mutableContainers]) as? NSObject callback(json, nil, httpRes) } catch let err as NSError { callback(nil, err, httpRes) } } else { callback(nil, nil, httpRes) } } } else { callback(nil, error, HTTPURLResponse(url: url, statusCode: (error! as NSError).code, httpVersion: nil, headerFields: nil)!) } }) self.preRequest?() task.resume() } func delete(_ service: String, callback: @escaping (Bool, Error?, HTTPURLResponse) -> Void) { let url: URL = URL(string: serverURL + service)! // Get session with the provided configuration let session = Foundation.URLSession(configuration: getConfiguration(false), delegate: self, delegateQueue: nil) // Create background task that will perform the HTTP request var request = URLRequest(url: url) request.httpMethod = "DELETE" // Add API Key header request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in self.postRequest?() if let httpRes = response as? HTTPURLResponse { callback(httpRes.statusCode == 204, error, httpRes) } else { callback(false, error, HTTPURLResponse(url: url, statusCode: (error! as NSError).code, httpVersion: nil, headerFields: nil)!) } }) self.preRequest?() task.resume() } func post(_ service: String, callback: @escaping (Bool, Error?, HTTPURLResponse) -> Void) { if let url: URL = URL(string: serverURL! + service) { // Get session with the provided configuration let session = Foundation.URLSession(configuration: getConfiguration(false), delegate: self, delegateQueue: nil) // Create background task that will perform the HTTP request var request = URLRequest(url: url) request.httpMethod = "POST" // Add API Key header request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in self.postRequest?() if let httpRes = response as? HTTPURLResponse { callback(httpRes.statusCode == 204, error, httpRes) } else { callback(false, error, HTTPURLResponse(url: url, statusCode: (error! as NSError).code, httpVersion: nil, headerFields: nil)!) } }) self.preRequest?() task.resume() } else { NSLog("POST not possible. Invalid URL found. Server: \(serverURL!). Service: \(service)") if let serverURL = URL(string: serverURL!) { if let response = HTTPURLResponse(url: serverURL, statusCode: 404, httpVersion: nil, headerFields: nil) { callback(false, nil, response) } } } } func post(_ service: String, json: NSObject, expected: Int, callback: @escaping (NSObject?, Error?, HTTPURLResponse) -> Void) { if let url: URL = URL(string: serverURL! + service) { requestWithBody(url, verb: "POST", expected: expected, json: json, callback: callback) } else { NSLog("POST not possible. Invalid URL found. Server: \(serverURL!). Service: \(service)") if let serverURL = URL(string: serverURL!) { if let response = HTTPURLResponse(url: serverURL, statusCode: 404, httpVersion: nil, headerFields: nil) { callback(nil, nil, response) } } } } func upload(_ service: String, parameters: [String: String]?, filename: String, fileContent: Data, expected: Int, callback: @escaping (Bool, Error?, HTTPURLResponse) -> Void) { let url: URL = URL(string: serverURL! + service)! // Get session with the provided configuration let session = Foundation.URLSession(configuration: getConfiguration(false), delegate: self, delegateQueue: nil) // Create background task that will perform the HTTP request var request = URLRequest(url: url) request.httpMethod = "POST" // Set multipart boundary let boundary = "Boundary-\(UUID().uuidString)" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") // Add API Key header request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") // Create multipart that includes file request.httpBody = createMultiPartBody(parameters: parameters, boundary: boundary, data: fileContent, mimeType: "application/octet-stream", filename: filename) // Send request let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in self.postRequest?() if let httpRes = response as? HTTPURLResponse { callback(httpRes.statusCode == 201, error, httpRes) } else { callback(false, error, HTTPURLResponse(url: url, statusCode: (error! as NSError).code, httpVersion: nil, headerFields: nil)!) } }) self.preRequest?() task.resume() } // MARK: Private functions fileprivate func requestWithBody(_ url: URL, verb: String, expected: Int, json: NSObject?, callback: @escaping (NSObject?, Error?, HTTPURLResponse) -> Void) { // Get session with the provided configuration let session = Foundation.URLSession(configuration: getConfiguration(false), delegate: self, delegateQueue: nil) var request = URLRequest(url: url) // Add API Key header request.addValue(apiKey, forHTTPHeaderField: "X-Api-Key") request.httpMethod = verb var err: NSError? do { if let data = json { let postBody = try JSONSerialization.data(withJSONObject: data, options:JSONSerialization.WritingOptions(rawValue: 0)) request.httpBody = postBody request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") } // Create background task that will perform the HTTP request let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in self.postRequest?() if let httpRes = response as? HTTPURLResponse { if error != nil { callback(nil, error, httpRes) } else { if httpRes.statusCode == expected { if expected == 204 { // No content so nothing to parse callback(nil, nil, httpRes) return } // Parse string into JSON object let result = String(data: data!, encoding: String.Encoding.utf8)! do { let json = try JSONSerialization.jsonObject(with: result.data(using: String.Encoding.utf8)!, options: [.mutableLeaves, .mutableContainers]) as? NSObject callback(json, nil, httpRes) } catch let err as NSError { callback(nil, err, httpRes) } } else { callback(nil, nil, httpRes) } } } else { callback(nil, error, HTTPURLResponse(url: url, statusCode: (error! as NSError).code, httpVersion: nil, headerFields: nil)!) } }) self.preRequest?() task.resume() } catch let error as NSError { err = error // Fail to convert NSObject into JSON callback(nil, err, HTTPURLResponse(url: url, statusCode: 400, httpVersion: nil, headerFields: nil)!) } } fileprivate func createMultiPartBody(parameters: [String: String]?, boundary: String, data: Data, mimeType: String, filename: String) -> Data { var body = Data() let boundaryPrefix = "--\(boundary)\r\n" if let params = parameters { for (key, value) in params { body.append(Data(boundaryPrefix.utf8)) body.append(Data("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".utf8)) body.append(Data("\(value)\r\n".utf8)) } } body.append(Data(boundaryPrefix.utf8)) body.append(Data("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n".utf8)) body.append(Data("Content-Type: \(mimeType)\r\n\r\n".utf8)) body.append(data) body.append(Data("\r\n".utf8)) body.append(Data("--".appending(boundary.appending("--")).utf8)) return body } fileprivate func getConfiguration(_ preemptive: Bool) -> URLSessionConfiguration { let config = URLSessionConfiguration.default if preemptive && username != nil && password != nil { let userPasswordString = username! + ":" + password! let userPasswordData = userPasswordString.data(using: String.Encoding.utf8) let base64EncodedCredential = userPasswordData!.base64EncodedString(options: []) let authString = "Basic \(base64EncodedCredential)" config.httpAdditionalHeaders = ["Authorization" : authString] } // Timeout to start transmitting config.timeoutIntervalForRequest = timeoutIntervalForRequest // Timeout to receive data config.timeoutIntervalForResource = timeoutIntervalForResource return config } func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.previousFailureCount > 0 { NSLog("Alert Please check the credential") completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } else { let credential = URLCredential(user: self.username ?? "", password: self.password ?? "", persistence: .forSession) completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, credential) } } }
0
// Copyright © 2020 Stormbird PTE. LTD. import Foundation import BigInt import PromiseKit import web3swift class GetBlockTimestampCoordinator { //TODO persist? private static var blockTimestampCache: [RPCServer: [BigUInt: Promise<Date>]] = .init() func getBlockTimestamp(_ blockNumber: BigUInt, onServer server: RPCServer) -> Promise<Date> { var cacheForServer = Self.blockTimestampCache[server] ?? .init() if let datePromise = cacheForServer[blockNumber] { return datePromise } guard let web3 = try? getCachedWeb3(forServer: server, timeout: 6) else { return Promise(error: Web3Error(description: "Error creating web3 for: \(server.rpcURL) + \(server.web3Network)")) } let promise: Promise<Date> = Promise { seal in firstly { web3.eth.getBlockByNumberPromise(blockNumber) }.map { $0.timestamp }.done { seal.fulfill($0) }.catch { seal.reject($0) } } cacheForServer[blockNumber] = promise Self.blockTimestampCache[server] = cacheForServer return promise } }
0
// // ProgressBar.swift // SupportDocsSwiftUI // // Created by Zheng on 10/17/20. // import SwiftUI /** The progress bar used as the loading indicator. - Fades out at 0.0 and 1.0. # Customizable parts: - `foregroundColor` - color of the loading bar. - `foregroundColor` - color of the bar's background. Source: [https://www.simpleswiftguide.com/how-to-build-linear-progress-bar-in-swiftui/]( https://www.simpleswiftguide.com/how-to-build-linear-progress-bar-in-swiftui/). */ internal struct ProgressBar: View { /// From 0.0 to 1.0 @Binding var value: Float /// Stores the background and foreground color. var progressBarOptions: SupportOptions.ProgressBar var body: some View { GeometryReader { geometry in ZStack(alignment: .leading) { Rectangle().frame(width: geometry.size.width, height: geometry.size.height) .opacity(0.3) .foregroundColor((value == 0.0 || value == 1.0) ? Color.clear : Color(progressBarOptions.backgroundColor)) /// If progress is at 0 or 1, hide the progress bar background. Rectangle().frame(width: min(CGFloat(self.value) * geometry.size.width, geometry.size.width), height: geometry.size.height) .foregroundColor((value == 0.0 || value == 1.0) ? Color.clear : Color(progressBarOptions.foregroundColor)) /// If progress is at 0 or 1, hide the progress bar foreground. .animation(.easeOut) } } } }
0
// // String+LPK.swift // LPIM // // Created by lipeng on 2017/6/26. // Copyright © 2017年 lipeng. All rights reserved. // import UIKit extension String { func lp_stringByDeletingPictureResolution() -> String { let doubleResolution = "@2x" let tribleResolution = "@3x" let fileName = (self as NSString).deletingPathExtension var res = self if fileName.hasSuffix(doubleResolution) || fileName.hasSuffix(tribleResolution) { res = fileName.substring(to: fileName.characters.index(fileName.endIndex, offsetBy: -3)) let pathExtension = (self as NSString).pathExtension if pathExtension.characters.count > 0 { res = (self as NSString).appendingPathExtension(pathExtension)! } } return res } }
0
// // CGParallaxFlowLayout.swift // CGParllaxCollectionView-Final // // Created by CocoaGarage on 04/06/14. // Copyright (c) 2014 CocoaGarage. All rights reserved. // import Foundation import UIKit class CGParallaxFlowLayout: UICollectionViewFlowLayout { let maxParallaxOffset : CGFloat = 30.0 // A constant // Overriden Methods override class func layoutAttributesClass() -> AnyClass! { return CGParallaxLayoutAttributes.self } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> AnyObject[]! { var layoutAttrArr : Array<AnyObject> = super.layoutAttributesForElementsInRect(rect) for layoutAttr : AnyObject in layoutAttrArr { if layoutAttr.isKindOfClass(CGParallaxLayoutAttributes.self) { var paralaxLayoutAttr: CGParallaxLayoutAttributes = layoutAttr as CGParallaxLayoutAttributes if paralaxLayoutAttr.representedElementCategory == UICollectionElementCategory.Cell { paralaxLayoutAttr.parallaxOffset = self.parallaxOffsetForLayoutAttribtues(paralaxLayoutAttr) } } } return layoutAttrArr } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath!) -> UICollectionViewLayoutAttributes! { var layoutAttributes : CGParallaxLayoutAttributes = super.layoutAttributesForItemAtIndexPath(indexPath) as CGParallaxLayoutAttributes layoutAttributes.parallaxOffset = self.parallaxOffsetForLayoutAttribtues(layoutAttributes) return layoutAttributes } func parallaxOffsetForLayoutAttribtues(layoutAttributes: CGParallaxLayoutAttributes) -> CGPoint { if layoutAttributes == nil { return CGPointZero } if (!layoutAttributes.isKindOfClass(CGParallaxLayoutAttributes.self)) { return CGPointZero } var bounds: CGRect = self.collectionView.bounds var boundsCenter : CGPoint = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) var cellCenter : CGPoint = layoutAttributes.center var offsetFromCenter : CGPoint = CGPointMake(boundsCenter.x - cellCenter.x, boundsCenter.y - cellCenter.y) var cellSize: CGSize = layoutAttributes.size var maxVerticalOffsetVisible: CGFloat = bounds.size.height/2 + cellSize.height/2 var scaleFactor: CGFloat = self.maxParallaxOffset / maxVerticalOffsetVisible var parallaxOffset: CGPoint = CGPointMake(0.0, offsetFromCenter.y * scaleFactor) return parallaxOffset } }
0
import Foundation public struct JSONTextModel: Codable { public var id: String? public var zPosition: CGFloat public var origin: AnnotationPoint public var to: AnnotationPoint? public var text: String public var style: TextParams public var legibilityEffectEnabled: Bool }
0
// // ActionSheetCustomViewTableViewCell.swift // CustomAlertController // // Created by Mojisola Adebiyi on 24/07/2021. // import UIKit class ActionSheetCustomViewTableViewCell: UITableViewCell { var onCellTappedAction: (()->())? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private let containerView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private func setupView() { selectionStyle = .none backgroundColor = .clear contentView.backgroundColor = .clear contentView.addSubview(containerView) containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 16).isActive = true containerView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 8).isActive = true containerView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -8).isActive = true containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -16).isActive = true } private func constrainCustom(_ view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false let tempContainer: UIView = { let tempContainer = UIView() tempContainer.addSubview(view) tempContainer.translatesAutoresizingMaskIntoConstraints = false if view.frame.isEmpty { view.topAnchor.constraint(equalTo: tempContainer.topAnchor).isActive = true view.centerXAnchor.constraint(equalTo: tempContainer.centerXAnchor).isActive = true view.bottomAnchor.constraint(equalTo: tempContainer.bottomAnchor).isActive = true }else { view.centerXAnchor.constraint(equalTo: tempContainer.centerXAnchor).isActive = true view.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true view.heightAnchor.constraint(equalToConstant: view.frame.height).isActive = true view.widthAnchor.constraint(equalToConstant: view.frame.height).isActive = true } return view }() containerView.addSubview(tempContainer) tempContainer.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true tempContainer.centerXAnchor.constraint(equalTo: containerView.centerXAnchor).isActive = true tempContainer.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true } func configureView(with type: ActionSheetCellType) { switch type { case .custom(let view): self.constrainCustom(view) default: break } } }
0
// // NamedBezierPathViews.swift // Brickout // // Created by 诸葛俊伟 on 6/17/16. // Copyright © 2016 Stanford University. All rights reserved. // import UIKit class NamedBezierPathViews: UIView { var bezierPath = [Int:UIBezierPath]() { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { for (int, path) in bezierPath { if int == 36 { UIColor.red.setFill() path.fill() UIColor.cyan.setStroke() path.stroke() } else { UIColor.random.setFill() path.fill() UIColor.darkGray.setStroke() path.stroke() } } } }
0
import Foundation import ARKit func createWorldTrackingConfiguration(_ arguments: Dictionary<String, Any>) -> ARWorldTrackingConfiguration? { if(ARWorldTrackingConfiguration.isSupported) { let worldTrackingConfiguration = ARWorldTrackingConfiguration() if let planeDetection = arguments["planeDetection"] as? Int { if planeDetection == 1 { worldTrackingConfiguration.planeDetection = .horizontal } if planeDetection == 2 { if #available(iOS 11.3, *) { worldTrackingConfiguration.planeDetection = .vertical } } if planeDetection == 3 { if #available(iOS 11.3, *) { worldTrackingConfiguration.planeDetection = [.horizontal, .vertical] } } } if #available(iOS 11.3, *) { if let detectionImagesGroupName = arguments["detectionImagesGroupName"] as? String { worldTrackingConfiguration.detectionImages = ARReferenceImage.referenceImages(inGroupNamed: detectionImagesGroupName, bundle: nil) } if let detectionImages = arguments["detectionImages"] as? Array<Dictionary<String, Any>> { worldTrackingConfiguration.detectionImages = parseReferenceImagesSet(detectionImages) } } if #available(iOS 12.0, *) { if let maximumNumberOfTrackedImages = arguments["maximumNumberOfTrackedImages"] as? Int { worldTrackingConfiguration.maximumNumberOfTrackedImages = maximumNumberOfTrackedImages } } return worldTrackingConfiguration } return nil }
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 e { var d { { { func a< > ( = [ { { { } func a { func a func d case } class case c, case
0
// // File.swift // // // Created by Lakr Aream on 2021/8/10. // import Foundation public extension RepositoryCenter { /// post notification with this object struct UpdateNotification { public let representedRepo: URL public let progress: Progress? public let complete: Bool public let success: Bool public let queueLeft: Int } }
0
//: Playground - noun: a place where people can play import Cocoa import SwiftUtilities enum Contains { case False case Maybe } struct BloomFilter <Element: Hashable> { var data: Array <UInt8> let count: Int init(count: Int) { self.count = count self.data = Array <UInt8> (count: Int(ceil(Double(count) / 8)), repeatedValue: 0) } mutating func add(value: Element) { let hash = value.hashValue let position = Int(unsafeBitCast(hash, UInt.self) % UInt(count)) data.withUnsafeMutableBufferPointer() { (buffer) in bitSet(buffer, start: position, length: 1, newValue: 1) return } } func contains(value: Element) -> Contains { let hash = value.hashValue let position = Int(unsafeBitCast(hash, UInt.self) % UInt(count)) return data.withUnsafeBufferPointer() { (buffer) in return bitRange(buffer, start: position, length: 1) == 0 ? Contains.False : Contains.Maybe } } } var filter = BloomFilter <String>(count: 100) filter.data filter.add("hello world") filter.data filter.add("girafe") filter.data filter.contains("hello world") filter.contains("donkey")
0
// // UITableViewExtension.swift // LetSwift // // Created by Kinga Wilczek, Marcin Chojnacki on 30.04.2017. // Copyright © 2017 Droids On Roids. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import ESPullToRefresh extension UITableView: NibPresentable { func item<Cell: UITableViewCell, T, S: Sequence>(with identifier: String, cellType: Cell.Type = Cell.self) -> (@escaping (Int, T, Cell) -> ()) -> (_ source: S) -> () where T == S.Iterator.Element { return { cellFormer in return { source in let delegate = ReactiveTableViewDataSource<S> { tableView, index, element in let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: IndexPath(row: index, section: 0)) as! Cell cellFormer(index, element, cell) return cell } ReactiveTableViewDataSourceProxy.subscribeToProxy(tableView: self, datasource: delegate) { _ in delegate.tableView(self, observedElements: source) } } } } func items<S: Sequence>() -> (@escaping (UITableView, Int, S.Iterator.Element) -> UITableViewCell) -> (_ source: S, _ updated: Bool) -> () { return { cellFormer in return { source, shouldUpdate in let delegate = ReactiveTableViewDataSource<S>(cellFormer: cellFormer) ReactiveTableViewDataSourceProxy.subscribeToProxy(tableView: self, datasource: delegate) { _ in delegate.tableView(self, observedElements: source, updated: shouldUpdate) } } } } func createDataSourceProxy() -> ReactiveTableViewDataSourceProxy { return ReactiveTableViewDataSourceProxy() } func createDelegateProxy() -> ReactiveTableViewDelegateProxy { return ReactiveTableViewDelegateProxy() } var delegateProxy: ReactiveTableViewDelegateProxy { return ReactiveTableViewDelegateProxy.proxyForObject(self) } var itemDidSelectObservable: ObservableEvent<IndexPath> { return ObservableEvent(event: delegateProxy.itemDidSelectObservable) } // MARK: Header and footer static var emptyFooter: UIView { return UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 1.0)) } private func createHeaderFooterView(_ color: UIColor, negativeOffset: Bool) -> UIView { let offset: CGFloat = 1000.0 let offsetView = UIView() let colorView = UIView(frame: CGRect(x: 0.0, y: negativeOffset ? -offset : 0.0, width: max(bounds.width, bounds.height), height: offset)) colorView.backgroundColor = color offsetView.addSubview(colorView) return offsetView } func setHeaderColor(_ color: UIColor) { tableHeaderView = createHeaderFooterView(color, negativeOffset: true) } func setFooterColor(_ color: UIColor) { let footerView = createHeaderFooterView(color, negativeOffset: false) tableFooterView = footerView sendSubview(toBack: footerView) } override open var delaysContentTouches: Bool { didSet { changeChildDelaysContentTouches() } } override open func awakeFromNib() { super.awakeFromNib() changeChildDelaysContentTouches() } private func changeChildDelaysContentTouches() { subviews.forEach { ($0 as? UIScrollView)?.delaysContentTouches = delaysContentTouches } } var scrollViewWillEndDraggingObservable: ObservableEvent<UIScrollView?> { return ObservableEvent(event: delegateProxy.scrollViewWillEndDraggingObservable) } var scrollViewDidScrollObservable: ObservableEvent<UIScrollView?> { return ObservableEvent(event: delegateProxy.scrollViewDidScrollObservable) } var isTableHeaderViewVisible: Bool { guard let tableHeaderView = tableHeaderView else { return false } return contentOffset.y < tableHeaderView.frame.size.height } func scrollToTop() { let firstIndex = IndexPath(row: 0, section: 0) guard numberOfRows(inSection: firstIndex.section) > 0 else { return } scrollToRow(at: firstIndex, at: .bottom, animated: true) } }
0
// The MIT License (MIT) // // Copyright (c) 2017-2018 Alexander Grebenyuk (github.com/kean). import XCTest import Yalta class AnchorTests: XCTestCase { let container = UIView() let view = UIView() override func setUp() { super.setUp() container.addSubview(view) } func testConstraintsCreatedByAnchorsAreInstalledAutomatically() { let constraint = view.al.top.align(with: container.al.top) XCTAssertEqual(constraint.isActive, true) } func testFirstViewSetToTranslatesAutoresizingMaskIntoConstraints() { // make sure that the precndition is always true view.translatesAutoresizingMaskIntoConstraints = true container.translatesAutoresizingMaskIntoConstraints = true XCTAssertTrue(view.translatesAutoresizingMaskIntoConstraints) XCTAssertTrue(container.translatesAutoresizingMaskIntoConstraints) view.al.top.align(with: container.al.top) XCTAssertFalse(view.translatesAutoresizingMaskIntoConstraints) XCTAssertTrue(container.translatesAutoresizingMaskIntoConstraints) view.translatesAutoresizingMaskIntoConstraints = true container.al.top.align(with: view.al.top) XCTAssertTrue(view.translatesAutoresizingMaskIntoConstraints) XCTAssertFalse(container.translatesAutoresizingMaskIntoConstraints) } // MARK: Offsetting func testOffsettingTopAnchor() { let anchor = container.al.top + 10 XCTAssertEqualConstraints( view.al.top.align(with: anchor), NSLayoutConstraint(item: view, attribute: .top, toItem: container, attribute: .top, constant: 10) ) XCTAssertEqualConstraints( view.al.top.align(with: anchor + 10), NSLayoutConstraint(item: view, attribute: .top, toItem: container, attribute: .top, constant: 20) ) XCTAssertEqualConstraints( // test that works both ways anchor.align(with: view.al.top), NSLayoutConstraint(item: container, attribute: .top, toItem: view, attribute: .top, constant: -10) ) } func testOffsettingUsingOperators() { XCTAssertEqualConstraints( view.al.top.align(with: container.al.top + 10), NSLayoutConstraint(item: view, attribute: .top, toItem: container, attribute: .top, constant: 10) ) XCTAssertEqualConstraints( view.al.top.align(with: container.al.top - 10), NSLayoutConstraint(item: view, attribute: .top, toItem: container, attribute: .top, constant: -10) ) } func testOffsettingRightAnchor() { let anchor = container.al.right - 10 XCTAssertEqualConstraints( view.al.right.align(with: anchor), NSLayoutConstraint(item: view, attribute: .right, toItem: container, attribute: .right, constant: -10) ) XCTAssertEqualConstraints( // test that works both ways anchor.align(with: view.al.right), NSLayoutConstraint(item: container, attribute: .right, toItem: view, attribute: .right, constant: 10) ) } func testAligningTwoOffsetAnchors() { let containerTop = container.al.top + 10 let viewTop = view.al.top + 10 XCTAssertEqualConstraints( viewTop.align(with: containerTop), // nobody's going to do that, but it's nice it's their NSLayoutConstraint(item: view, attribute: .top, toItem: container, attribute: .top, constant: 0) ) } func testOffsettingWidth() { XCTAssertEqualConstraints( view.al.height.match(container.al.width + 10), NSLayoutConstraint(item: view, attribute: .height, toItem: container, attribute: .width, constant: 10) ) XCTAssertEqualConstraints( view.al.height.match(container.al.width - 10), NSLayoutConstraint(item: view, attribute: .height, toItem: container, attribute: .width, constant: -10) ) } func testOffsetingMultipleTimes() { XCTAssertEqualConstraints( view.al.height.match((container.al.width + 10) + 10), NSLayoutConstraint(item: view, attribute: .height, toItem: container, attribute: .width, constant: 20) ) } // MARK: Multiplying func testMultiplyingWidth() { XCTAssertEqualConstraints( view.al.width.match(container.al.width * 0.5), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.5) ) XCTAssertEqualConstraints( (view.al.width * 2).match(container.al.width), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.5) ) } func testMultiplyingMultipleTimes() { XCTAssertEqualConstraints( view.al.width.match((container.al.width * 0.5) * 0.5), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.25) ) XCTAssertEqualConstraints( ((view.al.width * 2) * 2).match(container.al.width), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.25) ) } func testMultiplyingBothAnchors() { XCTAssertEqualConstraints( (view.al.width * 0.5).match(container.al.width * 0.5), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 1) ) } // MARK: Mixing Multiplier and Offset func testMixingMultiplierAndOffset() { XCTAssertEqualConstraints( view.al.width.match(container.al.width * 0.5 + 10), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.5, constant: 10) ) XCTAssertEqualConstraints( view.al.width.match((container.al.width + 10) * 0.5), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.5, constant: 5) ) XCTAssertEqualConstraints( view.al.width.match((container.al.width + 10) * 0.5 + 7), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 0.5, constant: 12) ) XCTAssertEqualConstraints( view.al.width.match(((container.al.width + 10) * 0.5 + 7) * 2), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 1, constant: 24) ) XCTAssertEqualConstraints( view.al.width.match(container.al.width + 10 * 0.5), NSLayoutConstraint(item: view, attribute: .width, toItem: container, attribute: .width, multiplier: 1, constant: 5) ) } }
0
// // UITextField+Observer.swift // UITextField-Mask // // Created by Rafael on 17/12/18. // Copyright © 2018 Rafael Ribeiro da Silva. All rights reserved. // import Foundation extension UITextField { /** A simple class that uses `NSKeyValueObserving` to observer object value changes */ final class Observer: NSObject { /** Boolean value indicating whether or not to execute handler */ private var observing = true /** Handler to execute when observed object value changes */ private var changeHandler: (() -> Void)? /** Creates an instance of observer passing a handler to execute when observed object value changes - Parameter handler: Handler to execute when observed object value changes */ init(_ handler: @escaping () -> Void) { changeHandler = handler } /** Start value observing */ func startObserving() { observing = true } /** Stop value observing */ func stopObserving() { observing = false } //MARK: - NSKeyValueObserving public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if observing { changeHandler?() } } } }
0
// // RangeValidator.swift // // // Created by Michael Housh on 5/2/20. // import Foundation extension Validator where T: Comparable { /// Validates that the data's count is within the supplied `ClosedRange`. /// /// let validator = Validator<Int>.range(5...10) /// /// - errorText: `between 5 and 10` public static func range(_ range: ClosedRange<T>) -> Validator<T> { RangeValidator(.closedRange(min: range.lowerBound, max: range.upperBound)).validator() } /// Validates that the data's count is less than the supplied upper bound using `PartialRangeThrough`. /// /// let validator = Validator<Int>.range(...10) /// /// - errorText: `at most 10` public static func range(_ range: PartialRangeThrough<T>) -> Validator<T> { RangeValidator(.partialRangeMax(max: range.upperBound)).validator() } /// Validates that the data's count is less than the supplied lower bound using `PartialRangeFrom`. /// /// let validator = Validator<Int>.range(5...) /// /// - errorText: `at least 5` public static func range(_ range: PartialRangeFrom<T>) -> Validator<T> { RangeValidator(.partialRangeMin(min: range.lowerBound)).validator() } } extension Validator where T: Comparable & Strideable { /// Validates that the data's count is within the supplied `Range`. /// /// let validator = Validator<Int>.range(5..<10) /// /// - errorText: `between 5 and 9` public static func range(_ range: Range<T>) -> Validator<T> { RangeValidator(.range(min: range.lowerBound, max: range.upperBound.advanced(by: -1))).validator() } } // MARK: Private /// Validates whether the item's count is within a supplied int range. private struct RangeValidator<T>: ValidatorType where T: Comparable { let countType: RangeType<T> /// See `ValidatorType`. var errorText: String { "\(countType.readable())" } init(_ type: RangeType<T>) { self.countType = type } /// See `ValidatorType`. func validate(_ data: T) throws { if let min = self.countType.min { guard data >= min else { throw BasicValidationError(errorText) } } if let max = self.countType.max { guard data <= max else { throw BasicValidationError(errorText) } } } }
0
// // MySQLMigration.swift // MySQLBridge // // Created by Mihael Isaev on 30.01.2020. // import Bridges import MySQLNIO public protocol MySQLMigration: Migration { associatedtype Connection = MySQLConnection }
0
// // PhotoWallUploadViewController.swift // viossvc // // Created by 陈奕涛 on 16/12/1. // Copyright © 2016年 com.yundian. All rights reserved. // import Foundation import SVProgressHUD class PhotoWallUploadViewController: UICollectionViewController, PhotoSelectorViewControllerDelegate, PhotoCollectionCellDelegate { @IBOutlet weak var layout: UICollectionViewFlowLayout! var photosArray:[UIImage]? = [] var seletedPhotosArray:[Int] = [] var uploaded:[Int: [String: String]] = [:] var doneIndex:[Int] = [] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() collectionView?.backgroundColor = UIColor.whiteColor() let screenWidth = UIScreen.mainScreen().bounds.width let width = (screenWidth - 75.0) / 4.0 layout.estimatedItemSize = CGSizeMake(width, width) layout.sectionInset.left = 20 layout.sectionInset.top = 20 layout.sectionInset.right = 20 layout.sectionInset.bottom = 20 layout.headerReferenceSize = CGSizeMake(screenWidth, 30) collectionView?.registerClass(PhotoCollectionCell.self, forCellWithReuseIdentifier: "PhotoCollectionCell") collectionView?.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "PhotoCollectionHeader") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) initNav() collectionView?.reloadData() } func initNav() { if navigationItem.rightBarButtonItem == nil { navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "确定", style: .Plain, target: self, action: #selector(rightItemTapped)) } } func rightItemTapped() { MobClick.event(AppConst.Event.server_addPicture) if photosArray?.count > 0 { SVProgressHUD.showProgressMessage(ProgressMessage: "照片上传中...") let uid = CurrentUserHelper.shared.userInfo.uid var reUp = true for (index, img) in photosArray!.enumerate() { let done = doneIndex.indexOf(index) if done == nil { qiniuUploadImage(img, imagePath: "\(uid)/PhotoWall/", imageName: "photo", tags: ["index": index], complete: { [weak self] (response) in self!.upload2Server(response) }) reUp = false } } if reUp { SVProgressHUD.dismiss() } } } func upload2Server(response: AnyObject?) { if let resp = response as? [AnyObject] { let uid = CurrentUserHelper.shared.userInfo.uid let imageUrl = resp[1] as! String let tags = resp[0] as? [String: Int] let index = tags!["index"]! if imageUrl != "failed" { uploaded[index] = ["thumbnail_url_": imageUrl + AppConst.Network.qiniuImgStyle] uploaded[index]?.updateValue(imageUrl, forKey: "photo_url_") doneIndex.append(index) let dict:[String: AnyObject] = ["uid_": uid, "photo_list_": [uploaded[index] as! AnyObject]] AppAPIHelper.userAPI().uploadPhoto2Wall(dict, complete: completeBlockFunc(), error: { (error) in NSLog("\(error)") }) } else { SVProgressHUD.showErrorMessage(ErrorMessage: "图片 \(index) 上传出错,请重试", ForDuration: 1, completion: nil) } } } func completeBlockFunc()->CompleteBlock { return { [weak self] (obj) in self?.didRequestComplete(obj) } } func didRequestComplete(data:AnyObject?) { collectionView?.reloadData() if doneIndex.count == seletedPhotosArray.count { SVProgressHUD.showSuccessMessage(SuccessMessage: "照片上传成功", ForDuration: 1.0, completion: nil) weak var weakSelf = self dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.5)), dispatch_get_main_queue(), { () in weakSelf?.navigationController?.popViewControllerAnimated(true) }) } } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "PhotoCollectionHeader", forIndexPath: indexPath) var title = header.viewWithTag(1001) as? UILabel if title == nil { title = UILabel() title?.frame = CGRectMake(20, 15, 300, 15) title?.tag = 1001 title?.backgroundColor = UIColor.clearColor() title?.text = "最多只能同时上传8张照片" title?.textColor = UIColor.grayColor() title?.font = UIFont.systemFontOfSize(15) header.addSubview(title!) } return header } override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photosArray!.count + 1 } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCollectionCell" ,forIndexPath: indexPath) as? PhotoCollectionCell { cell.delegate = self if indexPath.row < photosArray!.count { if let _ = doneIndex.indexOf(indexPath.row) { cell.type = .Selected } else { cell.type = .CanRemove } cell.updateWithImage(photosArray![indexPath.row], indexPath: indexPath) } else { cell.updateWithImage(UIImage.init(named: "tianjia")!, indexPath: indexPath) cell.type = .Normal } cell.update() return cell } return UICollectionViewCell() } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { NSLog("%d", indexPath.row) if indexPath.row == photosArray!.count { if let photoSelector = storyboard?.instantiateViewControllerWithIdentifier("PhotoSelectorViewController") as? PhotoSelectorViewController { photoSelector.delegate = self photoSelector.seletedPhotosArray = self.seletedPhotosArray navigationController?.pushViewController(photoSelector, animated: true) } } } //MARK: - PhotoCollectionCellDelegate func rightTopButtonAction(indexPath: NSIndexPath?) { if indexPath != nil { if let cell = collectionView?.cellForItemAtIndexPath(indexPath!) as? PhotoCollectionCell { if cell.type == .CanRemove { seletedPhotosArray.removeAtIndex(indexPath!.row) photosArray?.removeAtIndex(indexPath!.row) collectionView?.reloadData() } } } } //MARK: - PhotoSelectorViewController func selected(thumb: [UIImage]?, src: [UIImage]?, seletedIndex: [Int]) { photosArray = thumb seletedPhotosArray = seletedIndex } deinit { SVProgressHUD.dismiss() } }
0
// // StandardLocationService.swift // RxLocationManager // // Created by Hao Yu on 16/7/6. // Copyright © 2016年 GFWGTH. All rights reserved. // import Foundation import CoreLocation import RxSwift //MARK: StandardLocationServiceConfigurable public protocol StandardLocationServiceConfigurable{ /** Set distance filter - parameter distance - returns: self for chaining call */ func distanceFilter(_ distance: CLLocationDistance) -> StandardLocationService /** Set desired accuracy - parameter desiredAccuracy - returns: self for chaining call */ func desiredAccuracy(_ desiredAccuracy: CLLocationAccuracy) -> StandardLocationService #if os(iOS) /** Refer description in official [document](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instm/CLLocationManager/allowDeferredLocationUpdatesUntilTraveled:timeout:) - parameter distance - parameter timeout - returns: self for chaining call */ func allowDeferredLocationUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval) -> StandardLocationService /** Refer description in official [document](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instm/CLLocationManager/disallowDeferredLocationUpdates) - returns: self for chaining call */ func disallowDeferredLocationUpdates() -> StandardLocationService /** Set Boolean value to [pausesLocationUpdatesAutomatically](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instp/CLLocationManager/pausesLocationUpdatesAutomatically) - parameter pause: Boolean value - returns: self for chaining call */ func pausesLocationUpdatesAutomatically(_ pause : Bool) -> StandardLocationService /** Set Boolean value to [allowsBackgroundLocationUpdates](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instp/CLLocationManager/allowsBackgroundLocationUpdates) - parameter allow: Boolean value - returns: self for chaining call */ @available(iOS 9.0, *) func allowsBackgroundLocationUpdates(_ allow : Bool) -> StandardLocationService /** Set value to [activityType](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instp/CLLocationManager/activityType) - parameter type - returns: self for chaining call */ func activityType(_ type: CLActivityType) -> StandardLocationService #endif /// Current distance filter value var distanceFilter: CLLocationDistance {get} /// Current desired accuracy value var desiredAccuracy: CLLocationAccuracy {get} #if os(iOS) /// Current pausesLocationUpdatesAutomatically value var pausesLocationUpdatesAutomatically: Bool {get} @available(iOS 9.0, *) /// Current allowsBackgroundLocationUpdates var allowsBackgroundLocationUpdates: Bool {get} /// Current activityType var activityType: CLActivityType {get} #endif } //MARK: StandardLocationService public protocol StandardLocationService: StandardLocationServiceConfigurable{ #if os(iOS) || os(OSX) || os(watchOS) /// Observable of current changing location, series of CLLocation objects will be reported, intermittent LocationUnknown error will be ignored and not stop subscriptions on this observable, other errors are reported as usual @available(watchOS 3.0, *) var locating: Observable<[CLLocation]>{get} #endif #if os(iOS) || os(watchOS) || os(tvOS) /// Observable of current location, only report one CLLocation object and complete, or error if underlying CLLocationManager reports error var located: Observable<CLLocation>{get} #endif #if os(iOS) /// Observable of possible error when calling allowDeferredLocationUpdates method var deferredUpdateFinished: Observable<NSError?>{get} /// Observable of pause status var isPaused: Observable<Bool>{get} #endif /** Return cloned instance - returns: cloned standard location service */ func clone() -> StandardLocationService } //MARK: DefaultStandardLocationService class DefaultStandardLocationService: StandardLocationService{ private let bridgeClass: CLLocationManagerBridge.Type #if os(iOS) || os(watchOS) || os(tvOS) var locMgrForLocation:CLLocationManagerBridge! private var locatedObservers = [(id: Int, observer: AnyObserver<CLLocation>)]() #endif #if os(iOS) || os(OSX) || os(watchOS) var locMgrForLocating:CLLocationManagerBridge! private var locatingObservers = [(id: Int, observer: AnyObserver<[CLLocation]>)]() #endif #if os(iOS) private var deferredUpdateErrorObservers = [(id: Int, observer: AnyObserver<NSError?>)]() private var isPausedObservers = [(id: Int, observer: AnyObserver<Bool>)]() #endif var distanceFilter:CLLocationDistance{ get{ #if os(OSX) return locMgrForLocating.distanceFilter #else return locMgrForLocation.distanceFilter #endif } } var desiredAccuracy: CLLocationAccuracy{ get{ #if os(OSX) return locMgrForLocating.desiredAccuracy #else return locMgrForLocation.desiredAccuracy #endif } } #if os(iOS) var pausesLocationUpdatesAutomatically: Bool{ get{ return locMgrForLocating.pausesLocationUpdatesAutomatically } } @available(iOS 9.0, *) var allowsBackgroundLocationUpdates: Bool{ get{ return locMgrForLocating.allowsBackgroundLocationUpdates } } var activityType: CLActivityType{ get{ return locMgrForLocating.activityType } } #endif #if os(iOS) || os(watchOS) || os(tvOS) var located:Observable<CLLocation> { get{ if self.locMgrForLocation.location != nil{ return Observable.just(self.locMgrForLocation.location!) }else{ return Observable.create{ observer in var ownerService: DefaultStandardLocationService! = self let id = nextId() ownerService.locatedObservers.append((id, observer)) if #available(iOS 9.0, *) { ownerService.locMgrForLocation.requestLocation() } else { #if os(iOS) ownerService.locMgrForLocation.startUpdatingLocation() #endif } return Disposables.create { ownerService.locatedObservers.remove(at: ownerService.locatedObservers.index(where: {$0.id == id})!) if(ownerService.locatedObservers.count == 0){ ownerService.locMgrForLocation.stopUpdatingLocation() } ownerService = nil } } } } } #endif #if os(iOS) var isPaused:Observable<Bool>{ get{ return Observable.create { observer in var ownerService: DefaultStandardLocationService! = self let id = nextId() ownerService.isPausedObservers.append((id, observer)) return Disposables.create { ownerService.isPausedObservers.remove(at: ownerService.isPausedObservers.index(where: {$0.id == id})!) ownerService = nil } } } } var deferredUpdateFinished:Observable<NSError?>{ get{ return Observable.create { observer in var ownerService: DefaultStandardLocationService! = self let id = nextId() ownerService.deferredUpdateErrorObservers.append((id, observer)) return Disposables.create { ownerService.deferredUpdateErrorObservers.remove(at: ownerService.deferredUpdateErrorObservers.index(where: {$0.id == id})!) ownerService = nil } } } } #endif #if os(iOS) || os(OSX) || os(watchOS) @available(watchOS 3.0, *) var locating:Observable<[CLLocation]> { get{ return Observable.create { observer in var ownerService: DefaultStandardLocationService! = self let id = nextId() ownerService.locatingObservers.append((id, observer)) //calling this method to start updating location anyway, it's no harm according to the doc ownerService.locMgrForLocating.startUpdatingLocation() return Disposables.create { ownerService.locatingObservers.remove(at: ownerService.locatingObservers.index(where: {$0.id == id})!) if(ownerService.locatingObservers.count == 0){ ownerService.locMgrForLocating.stopUpdatingLocation() } ownerService = nil } } } } #endif init(bridgeClass: CLLocationManagerBridge.Type){ self.bridgeClass = bridgeClass #if os(iOS) || os(watchOS) || os(tvOS) locMgrForLocation = bridgeClass.init() #endif #if os(iOS) || os(OSX) || os(watchOS) if #available(watchOS 3.0, *) { locMgrForLocating = bridgeClass.init() } #endif #if os(iOS) || os(watchOS) || os(tvOS) locMgrForLocation.didUpdateLocations = { [weak self] mgr, locations in if let copyOfLocatedObservers = self?.locatedObservers{ for (_, observer) in copyOfLocatedObservers{ observer.onNext(locations.last!) observer.onCompleted() } guard #available(iOS 9.0, *) else { self?.locMgrForLocation.stopUpdatingLocation() return } } } locMgrForLocation.didFailWithError = { [weak self] mgr, err in if let copyOfLocatedObservers = self?.locatedObservers{ for (_, observer) in copyOfLocatedObservers{ observer.onError(err) } } } #endif #if os(iOS) || os(OSX) || os(watchOS) if #available(watchOS 3.0, *){ locMgrForLocating.didUpdateLocations = { [weak self] mgr, locations in if let copyOfLocatingObservers = self?.locatingObservers{ for (_, observer) in copyOfLocatingObservers{ observer.onNext(locations) } } } locMgrForLocating.didFailWithError = { [weak self] mgr, err in if err.domain == "kCLErrorDomain" && CLError.locationUnknown.rawValue == err.code{ //ignore location update error, since new update event may come return } if let copyOfLocatingObservers = self?.locatingObservers{ for (_, observer) in copyOfLocatingObservers{ observer.onError(err) } } } } #endif #if os(iOS) locMgrForLocating.didFinishDeferredUpdatesWithError = { [weak self] mgr, error in if let copyOfdeferredUpdateErrorObservers = self?.deferredUpdateErrorObservers{ for (_, observer) in copyOfdeferredUpdateErrorObservers{ observer.onNext(error) } } } locMgrForLocating.didPausedUpdate = { [weak self] mgr in if let copyOfIsPausedObservers = self?.isPausedObservers{ for(_, observer) in copyOfIsPausedObservers{ observer.onNext(true) } } } locMgrForLocating.didResumeUpdate = { [weak self] mgr in if let copyOfIsPausedObservers = self?.isPausedObservers{ for(_, observer) in copyOfIsPausedObservers{ observer.onNext(false) } } } #endif } #if os(iOS) func allowDeferredLocationUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval) -> StandardLocationService{ locMgrForLocating.allowDeferredLocationUpdates(untilTraveled: distance, timeout: timeout) return self } func disallowDeferredLocationUpdates() -> StandardLocationService{ locMgrForLocating.disallowDeferredLocationUpdates() return self } func pausesLocationUpdatesAutomatically(_ pause: Bool) -> StandardLocationService { locMgrForLocating.pausesLocationUpdatesAutomatically = pause return self } @available(iOS 9.0, *) func allowsBackgroundLocationUpdates(_ allow: Bool) -> StandardLocationService { locMgrForLocating.allowsBackgroundLocationUpdates = allow return self } func activityType(_ type: CLActivityType) -> StandardLocationService { locMgrForLocating.activityType = type return self } #endif func distanceFilter(_ distance: CLLocationDistance) -> StandardLocationService { #if os(iOS) || os(watchOS) || os(tvOS) locMgrForLocation.distanceFilter = distance #endif #if os(iOS) || os(OSX) locMgrForLocating.distanceFilter = distance #endif return self } func desiredAccuracy(_ desiredAccuracy: CLLocationAccuracy) -> StandardLocationService { #if os(iOS) || os(watchOS) || os(tvOS) locMgrForLocation.desiredAccuracy = desiredAccuracy #endif #if os(iOS) || os(OSX) locMgrForLocating.desiredAccuracy = desiredAccuracy #endif return self } func clone() -> StandardLocationService { let cloned = DefaultStandardLocationService(bridgeClass: bridgeClass) #if os(iOS) _ = cloned.activityType(self.activityType) if #available(iOS 9.0, *) { _ = cloned.allowsBackgroundLocationUpdates(self.allowsBackgroundLocationUpdates) } _ = cloned.pausesLocationUpdatesAutomatically(self.pausesLocationUpdatesAutomatically) #endif _ = cloned.desiredAccuracy(self.desiredAccuracy) _ = cloned.distanceFilter(self.distanceFilter) return cloned } }
0
import AsyncDisplayKit open class HighlightCellNode<D: ASDisplayNode>: NamedDisplayCellNodeBase { public typealias BodyNode = D open override var supportsLayerBacking: Bool { return false } public let overlayNode: ASDisplayNode? public let bodyNode: D private let animationTargetNode: ASDisplayNode private let highlightAnimation: HighlightAnimationDescriptor private let haptics: HapticsDescriptor? private var onTapClosure: () -> Void = {} // MARK: - Initializers public init( animation: HighlightAnimationDescriptor, haptics: HapticsDescriptor? = nil, _ bodyNode: () -> D ) { self.haptics = haptics self.overlayNode = animation.overlayNode let body = bodyNode() self.bodyNode = body if body.isLayerBacked { /** If body uses layer-backing, it can't take a view to animate by UIView based animation. With wrapping another node, it enables body-node can be animatable. */ self.animationTargetNode = AnyWrapperNode { body } } else { self.animationTargetNode = body } self.highlightAnimation = animation super.init() clipsToBounds = false addSubnode(animationTargetNode) self.overlayNode.map { addSubnode($0) } } open override func layoutSpecThatFits( _ constrainedSize: ASSizeRange ) -> ASLayoutSpec { if let overlayNode = self.overlayNode { return ASOverlayLayoutSpec(child: animationTargetNode, overlay: overlayNode) } else { return ASWrapperLayoutSpec(layoutElement: animationTargetNode) } } open override var isHighlighted: Bool { didSet { highlightAnimation.animation(isHighlighted, self, animationTargetNode) } } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) haptics?.send(event: .onTouchDownInside) } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) haptics?.send(event: .onTouchUpInside) onTapClosure() } @discardableResult public func onTap(_ handler: @escaping () -> Void) -> Self { onTapClosure = handler return self } } /// To avoid runtime error with ObjC open class AnyHighlightCellNode: HighlightCellNode<ASDisplayNode> { }
0
// // SwiftFrameworks.swift // AMDataManager // // Created by Christian Quicano on 12/13/15. // Copyright © 2015 iphone4peru. All rights reserved. // import Foundation public class SwiftFrameworks { public init (){ print("Class has been initialised") } public func doSomething(){ print("Yeah, it works") } }
0
// // KeyboardRowView.swift // AptoSDK // // Created by Takeichi Kanzaki on 19/06/2019. // import SnapKit import UIKit protocol KeyboardRowViewDelegate: AnyObject { func leftButtonTapped(sender: KeyboardButton) func centerButtonTapped(sender: KeyboardButton) func rightButtonTapped(sender: KeyboardButton) } class KeyboardRowView: UIView { private let leftButton: KeyboardButton private let centerButton: KeyboardButton private let rightButton: KeyboardButton weak var delegate: KeyboardRowViewDelegate? init(leftButton: KeyboardButton, centerButton: KeyboardButton, rightButton: KeyboardButton) { self.leftButton = leftButton self.centerButton = centerButton self.rightButton = rightButton super.init(frame: .zero) setUpUI() } @available(*, unavailable) public required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpUI() { backgroundColor = .clear setUpCenterButton() setUpLeftButton() setUpRightButton() } private func setUpCenterButton() { centerButton.action = { [unowned self] _ in self.delegate?.centerButtonTapped(sender: self.centerButton) } addSubview(centerButton) centerButton.snp.makeConstraints { make in make.top.equalToSuperview() make.centerX.equalToSuperview() make.bottom.equalToSuperview() } } private func setUpLeftButton() { leftButton.action = { [unowned self] _ in self.delegate?.leftButtonTapped(sender: self.leftButton) } addSubview(leftButton) leftButton.snp.makeConstraints { make in make.top.equalTo(centerButton) make.right.equalTo(centerButton.snp.left).offset(-44) } } private func setUpRightButton() { rightButton.action = { [unowned self] _ in self.delegate?.rightButtonTapped(sender: self.rightButton) } addSubview(rightButton) rightButton.snp.makeConstraints { make in make.top.equalTo(centerButton) make.left.equalTo(centerButton.snp.right).offset(44) } } }
0
// // AddNewVC.swift // Demo // // Created by Shashikant's_Macmini on 26/02/20. // Copyright © 2020 redbytes. All rights reserved. // import UIKit import CoreData final class AddNewVC: UITableViewController { // MARK:- Outlets @IBOutlet private weak var lblID : UILabel! @IBOutlet private weak var txtfName : UITextField! @IBOutlet private weak var txtfSubDetails : UITextField! // MARK:- Variables private var id = 0 var isUser = true // MARK:- View Life Cycle override func viewDidLoad() { super.viewDidLoad() setUpView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = false } // MARK:- SetUpView private func setUpView() { self.title = isUser ? "Add New User" : "Add New Product" txtfSubDetails.placeholder = isUser ? "Bio" : "Price" if isUser { id = User.fetchAll().count } else { id = Product.fetchAll().count } lblID.text = "\(id)" } // MARK:- Button Actions @IBAction private func btnSavePressed(_ sender: UIBarButtonItem) { switch isUser { case true: saveUser() case false: saveProduct() } } // MARK:- Custom Methods private func saveUser() { let entity = NSEntityDescription.entity(forEntityName: "User", in: CoreData.context!)! let newUser = User(entity: entity, insertInto: CoreData.context!) newUser.id = Int64(id) newUser.name = txtfName.text ?? "" newUser.bio = txtfSubDetails.text ?? "" do { try CoreData.context?.save() } catch { print("Failed saveUser") } guard let vc = self.navigationController?.viewControllers.first as? UserListVC else { return } vc.refreshData() DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) } } private func saveProduct() { let entity = NSEntityDescription.entity(forEntityName: "Product", in: CoreData.context!)! let newProduct = Product(entity: entity, insertInto: CoreData.context!) newProduct.id = Int64(id) newProduct.name = txtfName.text ?? "" newProduct.price = txtfSubDetails.text ?? "" do { try CoreData.context?.save() } catch { print("Failed saveProduct") } guard let vcCount = self.navigationController?.viewControllers.count, vcCount > 2, let vc = self.navigationController?.viewControllers[1] as? ProductListVC else { return } vc.refreshData() DispatchQueue.main.async { self.navigationController?.popViewController(animated: true) } } // MARK:- ReceiveMemoryWarning override func didReceiveMemoryWarning() { debugPrint("⚠️🤦‍♂️⚠️ Receive Memory Warning on \(self) ⚠️🤦‍♂️⚠️") } // MARK:- deinit { debugPrint("🏹 Controller is removed from memory \(self) 🎯 🏆") } } //class
0
// // OpenWeatherMapAPIClient.swift // WeatherYARCH // // Created by Филипп on 31/05/2019. // Copyright © 2019 Filipp Lebedev. All rights reserved. // import Foundation import Alamofire import CodableAlamofire class OpenWeatherMapAPIClient: APIClient { let baseURL = "http://api.openweathermap.org/data/2.5/" let appID = AppPrivateData.openWeatherMapAPIKey let requestFactory: APIRequestFactory = OpenWeatherMapAPIRequestFactory() func request<T>(for abstractRequest: T) -> T where T : APIRequest { return requestFactory.request(abstractRequest) ?? abstractRequest } func send<T>(_ request: T, completion: @escaping (Result<T.Response>) -> Void) where T : APIRequest { let urlString = absoluteURL(for: request).absoluteString typealias ObjectType = T.Response Alamofire.request(urlString, method: .get, parameters:request.parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in print("REQUEST: \(response.request?.url?.absoluteString ?? "")") if let error = response.result.error { self.analyzeError(error: error) if !self.isErrorIgnored(error: error) { completion(.failure(error)) } } } .responseDecodableObject(keyPath: request.endPoint.keyPath, decoder: JSONDecoder()) { (response: DataResponse<ObjectType>) in guard let result = response.result.value else { if let error = response.error { print("ERROR DECODING: \(error)") } return } print("SUCCESS DECODING") completion(.success(result)) } } func absoluteURL<T>(for request: T) -> URL where T : APIRequest { let path = "\(baseURL)\(request.endPoint.method)?appid=\(appID)".replacingOccurrences(of: " ", with: "%20") return URL(string: path) ?? URL(string: "")! } func cancelAllRequests() { Alamofire.SessionManager.default.session.getAllTasks { (tasks) in tasks.forEach { $0.cancel() } } } private func analyzeError(error: Error?) { if let error = error as? AFError { switch error { case .invalidURL(let url): print("Invalid URL: \(url) - \(error.localizedDescription)") case .parameterEncodingFailed(let reason): print("Parameter encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .multipartEncodingFailed(let reason): print("Multipart encoding failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") case .responseValidationFailed(let reason): print("Response validation failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") switch reason { case .dataFileNil, .dataFileReadFailed: print("Downloaded file could not be read") case .missingContentType(let acceptableContentTypes): print("Content Type Missing: \(acceptableContentTypes)") case .unacceptableContentType(let acceptableContentTypes, let responseContentType): print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)") case .unacceptableStatusCode(let code): print("Response status code was unacceptable: \(code)") } case .responseSerializationFailed(let reason): print("Response serialization failed: \(error.localizedDescription)") print("Failure Reason: \(reason)") default:break } print("Underlying error: \(error.underlyingError)") } else if let error = error as? URLError { print("URLError occurred: \(error)") } else { print("Unknown error: \(error)") } } private func isErrorIgnored(error: Error?) -> Bool { if let error = error as? URLError { switch error.code { case .cancelled: return true default: return false } } return false } }
0
// // UserProfileViewTests.swift // edX // // Created by Michael Katz on 9/28/15. // Copyright © 2015 edX. All rights reserved. // @testable import edX class MockProfilePresenter: UserProfilePresenter { let profileStream: OEXStream<UserProfile> let tabStream: OEXStream<[ProfileTabItem]> weak var delegate: UserProfilePresenterDelegate? init(profile: UserProfile, tabs: [ProfileTabItem]) { profileStream = OEXStream(value: profile) tabStream = OEXStream(value: tabs) } func refresh() { // do nothing } } class MockPaginator<A>: Paginator { typealias Element = A let stream: OEXStream<[A]> init(values : [A]) { self.stream = OEXStream(value: values) } let hasNext: Bool = false func loadMore() { // do nothing } } class UserProfileViewTests: SnapshotTestCase { func profileWithPrivacy(_ privacy : UserProfile.ProfilePrivacy) -> UserProfile { return UserProfile(username: "Test Person", bio: "Hello I am a lorem ipsum dolor sit amet", parentalConsent: false, countryCode: "de", accountPrivacy: privacy) } func snapshotContentWithPrivacy(_ privacy : UserProfile.ProfilePrivacy) { let environment = TestRouterEnvironment().logInTestUser() let presenter = MockProfilePresenter(profile: profileWithPrivacy(privacy), tabs: []) let controller = UserProfileViewController(environment: environment, presenter: presenter, editable: true) inScreenNavigationContext(controller, action: { () -> () in assertSnapshotValidWithContent(controller.navigationController!) }) } func testSnapshotContent() { snapshotContentWithPrivacy(.Public) } func testSnapshotContentPrivateProfile() { snapshotContentWithPrivacy(.Private) } func testVisibleAccomplishments() { let profile = profileWithPrivacy(.Public) let image = RemoteImageJustImage(image: UIImage(testImageNamed: "sample-badge")) let accomplishments = [ Accomplishment(image: image, title: "Some Cool Thing I did", detail: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ", date: NSDate.stableTestDate(), shareURL: NSURL(string:"https://whatever")!), Accomplishment(image: image, title: "Some Other Thing I did", detail: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ", date: NSDate.stableTestDate(), shareURL: NSURL(string:"https://whatever")!) ] let tabs = [{(scrollView: UIScrollView) -> TabItem in let paginator = AnyPaginator(MockPaginator(values:accomplishments)) let view = AccomplishmentsView(paginator: paginator, containingScrollView: scrollView) {_ in } return TabItem(name: Strings.Accomplishments.title, view: view, identifier: "accomplishments")}] let testPresenter = MockProfilePresenter(profile: profile, tabs: tabs) let controller = UserProfileViewController(environment: TestRouterEnvironment(), presenter: testPresenter, editable: false) inScreenNavigationContext(controller) { controller.t_chooseTab(identifier: "accomplishments") assertSnapshotValidWithContent(controller.navigationController!) } } }
0
import Combine import Foundation private final class ShareReplaySubscription<Output, Failure: Error>: Subscription { let capacity: Int var subscriber: AnySubscriber<Output, Failure>? = nil var demand: Subscribers.Demand = .none var buffer: [Output] var completion: Subscribers.Completion<Failure>? = nil // Stores upstream completion event if emitted init<S>(subscriber: S, replay: [Output], capacity: Int, completion: Subscribers.Completion<Failure>?) where S: Subscriber, Failure == S.Failure, Output == S.Input { self.subscriber = AnySubscriber(subscriber) self.buffer = replay self.capacity = capacity self.completion = completion } func request(_ demand: Subscribers.Demand) { if demand != .none { self.demand += demand } emitAsNeeded() } func cancel() { complete(with: .finished) } func receive(_ input: Output) { guard subscriber != nil else { return } buffer.append(input) if buffer.count > capacity { buffer.removeFirst() } emitAsNeeded() } func receive(completion: Subscribers.Completion<Failure>) { guard let subscriber = subscriber else { return } self.subscriber = nil self.buffer.removeAll() subscriber.receive(completion: completion) } private func complete(with completion: Subscribers.Completion<Failure>) { guard let subscriber = subscriber else { return } self.subscriber = nil self.completion = nil self.buffer.removeAll() subscriber.receive(completion: completion) } private func emitAsNeeded() { guard let subscriber = subscriber else { return } // if there is a subscriber while self.demand > .none && !buffer.isEmpty { // send if some demand and we have buffered data self.demand -= .max(1) // decrment demand before send let nextDemand = subscriber.receive(buffer.removeFirst()) // send a ask for a new demand if nextDemand != .none { self.demand += nextDemand // aument new demand } } if let completion = completion { complete(with: completion) } } } extension Publishers { final class ShareReplay<Upstream: Publisher>: Publisher { typealias Output = Upstream.Output typealias Failure = Upstream.Failure private let lock = NSRecursiveLock() private let upstream: Upstream private let capacity: Int private var replay = [Output]() private var subscriptions = [ShareReplaySubscription<Output, Failure>]() private var completion: Subscribers.Completion<Failure>? = nil init(upstream: Upstream, capacity: Int) { self.upstream = upstream self.capacity = capacity } func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { lock.lock() defer { lock.unlock() } let subscription = ShareReplaySubscription(subscriber: subscriber, replay: replay, capacity: capacity, completion: completion) subscriptions.append(subscription) subscriber.receive(subscription: subscription) guard subscriptions.count == 1 else { return } let sink = AnySubscriber<Output, Failure>(receiveSubscription: { (subscription) in subscription.request(.unlimited) }, receiveValue: { [weak self] (value) -> Subscribers.Demand in self?.relay(value) return .none }) { [weak self] (completion) in self?.complete(completion) } upstream.subscribe(sink) } private func relay(_ value: Output) { lock.lock() defer { lock.unlock() } guard completion == nil else { return } replay.append(value) if replay.count > capacity { replay.removeFirst() } subscriptions.forEach({ $0.receive(value) }) } private func complete(_ completion: Subscribers.Completion<Failure>) { lock.lock() defer { lock.unlock() } self.completion = completion subscriptions.forEach { $0.receive(completion: completion) } } } } extension Publisher { func replay(capacity: Int = .max) -> Publishers.ShareReplay<Self> { return Publishers.ShareReplay(upstream: self, capacity: capacity) } } let capacity = 2 let subject = CurrentValueSubject<Int, Never>(0) // for some reason this is sended.. if we use a CurrentValueSubject let publisher = subject .print("REPLAY") // check that the publisher subscription is once .replay(capacity: capacity) //subject.send(1) // Send an initial value through the subject. No subscriber has connected to the shared publisher, so you shouldn’t see any output. var subscriptions = Set<AnyCancellable>() // it will receive subject emitted values after subscription, emitted before won´t be send publisher .sink(receiveCompletion: { print("1.replayCompleted: \($0)") }, receiveValue: { print("1.replay \($0)") }) .store(in: &subscriptions) subject.send(2) subject.send(3) subject.send(4) subject.send(completion: .finished) // it will receive last capacity values and next ones publisher .sink(receiveCompletion: { print("2.replayCompleted: \($0)") }, receiveValue: { print("2.replay \($0)") }) .store(in: &subscriptions) // it will receive last capacity values and finish DispatchQueue.main.asyncAfter(deadline: .now() + 2) { print("Subscribing to replay after upstream completed") publisher .sink(receiveCompletion: { print("3.replayDelayedCompleted: \($0)") }, receiveValue: { print("3.replayDelayed \($0)") }) .store(in: &subscriptions) }
0
// // ChatViewController+Subviews.swift // ChatViewController // // Created by Hoangtaiki on 5/18/18. // Copyright © 2018 toprating. All rights reserved. // import UIKit extension ChatViewController { // Observer keyboard events func observerKeyboardEvents() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } // Remove observer keyboard events func removeObserverKeyboardEvents() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: Notification) { keyboardControl(notification: notification, isShowing: true) } @objc func keyboardWillHide(notification: Notification) { keyboardControl(notification: notification, isShowing: false) } } /// Tableview extension ChatViewController { /// Set up for TableView func initTableView() { let tap = UITapGestureRecognizer() tap.cancelsTouchesInView = false tap.addTarget(self, action: #selector(handleTapTableView(recognizer:))) tableView.addGestureRecognizer(tap) tableView.transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: 0) view.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 11.0, *) { tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true } else { tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true } tableViewBottomConstraint = tableView.bottomAnchor.constraint(equalTo: typingIndicatorView.topAnchor, constant: -8) tableViewBottomConstraint.isActive = true } /// Hide all keyboard and then resignFirstResponse for TextView to call Keyboard appear @objc fileprivate func handleTapTableView(recognizer: UITapGestureRecognizer) { dismissKeyboard() } public func dismissKeyboard() { switch currentKeyboardType { case .default: chatBarView.textView.resignFirstResponderTimeAnimate = 0.25 _ = chatBarView.textView.resignFirstResponder() currentKeyboardType = .none case .image: animateHideImagePicker() currentKeyboardType = .none default: break } } } /// ChatBarView extension ChatViewController { public func showDefaultKeyboard() { switch currentKeyboardType { case .none: currentKeyboardType = .default case .image: chatBarView.textView.becomeFirstResponderTimeAnimate = 0 currentKeyboardType = .default imagePickerView?.isHidden = true default: break } } public func didChangeBarHeight(from: CGFloat, to: CGFloat) { controlExpandableInputView(showExpandable: true, from: from, to: to) } /// Control func controlExpandableInputView(showExpandable: Bool, from: CGFloat, to: CGFloat) { let currentTextHeight = chatBarView.textViewCurrentHeight + chatBarView.getAdditionalHeight() UIView.animate(withDuration: 0.3, animations: { let textHeight = showExpandable ? currentTextHeight : self.minimumChatBarHeight self.chatBarHeightConstraint?.constant = textHeight self.chatBarView.textView.contentOffset = .zero self.view.layoutIfNeeded() self.chatBarView.textView.setContentOffset(.zero, animated: false) }) } /// Animate show ChatBarView then setContentOffset for TableView /// Show keyboard from nothing // Handle keyboard show/hide notification to animation show ChatBarView func animateKeyboard(notification: Notification, isShowing: Bool) { var userInfo = notification.userInfo! let keyboardRect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue let curve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey]! as AnyObject).uint32Value let convertedFrame = view.convert(keyboardRect!, from: nil) var heightOffset = view.bounds.size.height - convertedFrame.origin.y let options = UIView.AnimationOptions(rawValue: UInt(curve!) << 16 | UIView.AnimationOptions.beginFromCurrentState.rawValue) let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue // The height offset we need update constraint for chat bar to make it always above keyboard if isShowing { if #available(iOS 11.0, *) { heightOffset -= view.safeAreaInsets.bottom } } else { heightOffset = 0 } // In case showing image picker view and switch to default keyboard // If image picker and keyboard has same height so that we don't need // animate chatbarview if lastKeyboardType == .image && heightOffset == customKeyboardHeight { return } // In case showing default keyboard and user touch gallery button and need // to show image picker. if currentKeyboardType == .image && !isShowing { return } // Everytime keyboard show. We will check keyboard height change or not to update image picker view size if isShowing && configuration.imagePickerType != .actionSheet { updateHeightForImagePicker(keyboardHeight: heightOffset) } UIView.animate(withDuration: duration!, delay: 0, options: options, animations: { self.chatBarBottomConstraint?.constant = -heightOffset self.view.layoutIfNeeded() }, completion: nil) if isShowing { currentKeyboardType = .default } } } /// ImagePickerView extension ChatViewController { /// Setup for ImagePicker func initImagePickerView() { imagePickerView = ImagePickerView() imagePickerView!.isHidden = true imagePickerView!.pickerDelegate = self imagePickerView!.parentViewController = self imagePickerView!.translatesAutoresizingMaskIntoConstraints = false view.addSubview(imagePickerView!) imagePickerView!.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true imagePickerView!.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true imagePickerTopContraint = imagePickerView!.topAnchor.constraint(equalTo: chatBarView.bottomAnchor) imagePickerTopContraint!.isActive = true imagePickerHeightContraint = imagePickerView!.heightAnchor.constraint(equalToConstant: customKeyboardHeight) imagePickerHeightContraint!.isActive = true } func handleShowImagePicker() { switch currentKeyboardType { case .image: return case .default: break case .none: animateShowImagePicker() } } /// Update image picker height. We always try make image picker has size same with keyboard /// So that we will has different layout for different height /// We will cache keyboard height and update everytime keyboard change height (show/hide predictive bar) /// /// - parameter: keyboardHeight: current keyboard height func updateHeightForImagePicker(keyboardHeight: CGFloat) { // If current keyboard height is equal with last cached keyboard we will not // update image picker height and layout if keyboardHeight == customKeyboardHeight { return } customKeyboardHeight = keyboardHeight /// Store keyboardheight into cache Utils.shared.cacheKeyboardHeight(customKeyboardHeight) DispatchQueue.main.async { /// Temporary update UI for ImagePicker self.imagePickerHeightContraint?.constant = self.customKeyboardHeight self.imagePickerView?.layoutSubviews() self.imagePickerView?.collectionView.updateUI() } } /// Animate show image picker /// /// -parameter isNeedScrollTable: Need update tableview content offset or not func animateShowImagePicker() { tableView.stopScrolling() imagePickerView?.isHidden = false imagePickerView?.collectionView.resetUI() UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(), animations: { self.chatBarBottomConstraint.constant = -self.customKeyboardHeight self.view.layoutIfNeeded() }, completion: nil) } func animateHideImagePicker() { tableView.stopScrolling() UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions(), animations: { self.chatBarBottomConstraint.constant = 0 self.imagePickerView?.alpha = 0.0 self.view.layoutIfNeeded() }, completion: { _ in self.imagePickerView?.isHidden = true self.imagePickerView?.alpha = 1.0 }) } } /// TypingIndicator extension ChatViewController { /// Setup TypingIndicator func setupTypingIndicator() { view.addSubview(typingIndicatorView) typingIndicatorView.isHidden = true observation = typingIndicatorView.observe(\TypingIndicatorView.isVisible) { [weak self] object, change in self?.animateTypeIndicatorView() } typingIndicatorView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true typingIndicatorView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true typingIndicatorView.bottomAnchor.constraint(equalTo: chatBarView.topAnchor).isActive = true typingIndicatorHeightConstraint = typingIndicatorView.heightAnchor.constraint(equalToConstant: 0.0) typingIndicatorHeightConstraint?.isActive = true } func animateTypeIndicatorView() { let height = typingIndicatorView.isVisible ? typingIndicatorView.viewHeight : 0.0 typingIndicatorHeightConstraint.constant = height if typingIndicatorView.isVisible { typingIndicatorView.isHidden = false } UIView.animate(withDuration: 0.3, animations: { if !self.typingIndicatorView.isVisible { self.typingIndicatorView.isHidden = true } self.view.layoutIfNeeded() }) } }
0
// // XCResultFile.swift // // // Created by David House on 7/6/19. // import Foundation public class XCResultFile { let url: URL public init(url: URL) { self.url = url } public func getInvocationRecord() -> ActionsInvocationRecord? { guard let data = xcrun(["xcresulttool", "get", "--path", url.path, "--format", "json"]) else { return nil } do { guard let rootJSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { logError("Expecting top level dictionary but didn't find one") return nil } let invocation = ActionsInvocationRecord(rootJSON) return invocation } catch { logError("Error deserializing JSON: \(error)") return nil } } public func getTestPlanRunSummaries(id: String) -> ActionTestPlanRunSummaries? { guard let data = xcrun(["xcresulttool", "get", "--path", url.path, "--id", id, "--format", "json"]) else { return nil } do { guard let rootJSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { logError("Expecting top level dictionary but didn't find one") return nil } let runSummaries = ActionTestPlanRunSummaries(rootJSON) return runSummaries } catch { logError("Error deserializing JSON: \(error)") return nil } } public func getLogs(id: String) -> ActivityLogSection? { guard let data = xcrun(["xcresulttool", "get", "--path", url.path, "--id", id, "--format", "json"]) else { return nil } do { guard let rootJSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { logError("Expecting top level dictionary but didn't find one") return nil } return ActivityLogSection(rootJSON) } catch { logError("Error deserializing JSON: \(error)") return nil } } public func getActionTestSummary(id: String) -> ActionTestSummary? { guard let data = xcrun(["xcresulttool", "get", "--path", url.path, "--id", id, "--format", "json"]) else { return nil } do { guard let rootJSON = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { logError("Expecting top level dictionary but didn't find one") return nil } let summary = ActionTestSummary(rootJSON) return summary } catch { logError("Error deserializing JSON: \(error)") return nil } } public func getPayload(id: String) -> Data? { guard let data = xcrun(["xcresulttool", "get", "--path", url.path, "--id", id]) else { return nil } return data } public func exportPayload(id: String) -> URL? { let tempPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(id) _ = xcrun(["xcresulttool", "export", "--type", "file", "--path", url.path, "--id", id, "--output-path", tempPath.path]) return tempPath } public func getCodeCoverage() -> CodeCoverage? { guard let data = xcrun(["xccov", "view", "--report", "--json", url.path]) else { return nil } do { let decoded = try JSONDecoder().decode(CodeCoverage.self, from: data) return decoded } catch { logError("Error deserializing JSON: \(error)") return nil } } private func xcrun(_ arguments: [String]) -> Data? { autoreleasepool { let task = Process() task.launchPath = "/usr/bin/xcrun" task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() task.waitUntilExit() let taskSucceeded = task.terminationStatus == EXIT_SUCCESS return taskSucceeded ? data : nil } } }
0
// // VisibleFolder.swift // git-annex-turtle // // Created by Andrew Ringler on 1/20/18. // Copyright © 2018 Andrew Ringler. All rights reserved. // import Foundation class VisibleFolder: Equatable, Hashable, Comparable, CustomStringConvertible { let parent: WatchedFolder let relativePath: String let absolutePath: String init(relativePath: String, parent: WatchedFolder) { self.relativePath = relativePath self.parent = parent self.absolutePath = PathUtils.absolutePath(for: relativePath, in: parent) } static func pretty<T>(_ visibleFolders: T) -> String where T: Sequence, T.Iterator.Element : VisibleFolder { return visibleFolders.map { "\($0.absolutePath)" }.joined(separator: ",") } static func ==(lhs: VisibleFolder, rhs: VisibleFolder) -> Bool { return lhs.absolutePath == rhs.absolutePath } static func <(lhs: VisibleFolder, rhs: VisibleFolder) -> Bool { return lhs.absolutePath < rhs.absolutePath } var hashValue: Int { return absolutePath.hashValue } public var description: String { return "VisibleFolder: '\(relativePath)' \(parent.uuid.uuidString)" } }
0
// // Component.swift // FirebladeECS // // Created by Christian Treffs on 08.10.17. // /// **Component** /// /// A component represents the raw data for one aspect of an entity. public protocol Component: AnyObject { /// Unique, immutable identifier of this component type. static var identifier: ComponentIdentifier { get } /// Unique, immutable identifier of this component type. var identifier: ComponentIdentifier { get } } extension Component { public static var identifier: ComponentIdentifier { ComponentIdentifier(Self.self) } @inline(__always) public var identifier: ComponentIdentifier { Self.identifier } }
0
// // UIViewController+ShowAlertMessage.swift // OkDataSourcesExample // // Created by Roberto Frontado on 4/8/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import UIKit extension UIViewController { func showAlertMessage(message: String) { let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } }
0
// // FeedModel.swift // Example // // Created by Russell Warwick on 13/07/2021. // import Foundation struct FeedModel { let id: String let title: String let subtitle: String? let tag: String? let image: String? init(id: String = UUID().uuidString, title: String, subtitle: String? = nil, tag: String? = nil, image: String?) { self.id = id self.title = title self.subtitle = subtitle self.tag = tag self.image = image } }
0
// // AnchorInfoResponse.swift // stellarsdk // // Created by Razvan Chelemen on 08/09/2018. // Copyright © 2018 Soneso. All rights reserved. // import Foundation public struct AnchorInfoResponse: Decodable { public var deposit: [String:DepositAsset] public var withdraw: [String:WithdrawAsset] public var transactions: AnchorTransactionsInfo public var transaction: AnchorTransactionInfo? public var fee: AnchorFeeInfo? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case deposit = "deposit" case withdraw = "withdraw" case transactions = "transactions" case transaction = "transaction" case fee = "fee" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) deposit = try values.decode([String:DepositAsset].self, forKey: .deposit) withdraw = try values.decode([String:WithdrawAsset].self, forKey: .withdraw) transactions = try values.decode(AnchorTransactionsInfo.self, forKey: .transactions) transaction = try values.decodeIfPresent(AnchorTransactionInfo.self, forKey: .transaction) fee = try values.decodeIfPresent(AnchorFeeInfo.self, forKey: .fee) } } public struct DepositAsset: Decodable { public var enabled: Bool public var authenticationRequired: Bool? public var feeFixed: Double? public var feePercent: Double? public var minAmount:Double? public var maxAmount:Double? public var fields: [String:AnchorField]? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case enabled = "enabled" case authenticationRequired = "authentication_required" case feeFixed = "fee_fixed" case feePercent = "fee_percent" case minAmount = "min_amount" case maxAmount = "max_amount" case fields = "fields" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decode(Bool.self, forKey: .enabled) authenticationRequired = try values.decodeIfPresent(Bool.self, forKey: .authenticationRequired) feeFixed = try values.decodeIfPresent(Double.self, forKey: .feeFixed) feePercent = try values.decodeIfPresent(Double.self, forKey: .feePercent) minAmount = try values.decodeIfPresent(Double.self, forKey: .minAmount) maxAmount = try values.decodeIfPresent(Double.self, forKey: .maxAmount) fields = try values.decodeIfPresent([String:AnchorField].self, forKey: .fields) } } public struct WithdrawAsset: Decodable { public var enabled: Bool public var authenticationRequired: Bool? public var feeFixed: Double? public var feePercent: Double? public var minAmount:Double? public var maxAmount:Double? public var types: [String:WithdrawType]? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case enabled = "enabled" case authenticationRequired = "authentication_required" case feeFixed = "fee_fixed" case feePercent = "fee_percent" case minAmount = "min_amount" case maxAmount = "max_amount" case types = "types" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decode(Bool.self, forKey: .enabled) authenticationRequired = try values.decodeIfPresent(Bool.self, forKey: .authenticationRequired) feeFixed = try values.decodeIfPresent(Double.self, forKey: .feeFixed) feePercent = try values.decodeIfPresent(Double.self, forKey: .feePercent) minAmount = try values.decodeIfPresent(Double.self, forKey: .minAmount) maxAmount = try values.decodeIfPresent(Double.self, forKey: .maxAmount) types = try values.decodeIfPresent([String:WithdrawType].self, forKey: .types) } } public struct AnchorField: Decodable { public var description: String public var optional: Bool? public var choices: [String]? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case description = "description" case optional = "optional" case choices = "choices" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) description = try values.decode(String.self, forKey: .description) optional = try values.decodeIfPresent(Bool.self, forKey: .optional) choices = try values.decodeIfPresent([String].self, forKey: .choices) } } public struct WithdrawType: Decodable { public var fields: [String:AnchorField]? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case fields = "fields" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) fields = try values.decodeIfPresent([String:AnchorField].self, forKey: .fields) } } public struct AnchorTransactionsInfo: Decodable { public var enabled: Bool public var authenticationRequired:Bool? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case enabled case authenticationRequired = "authentication_required" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decode(Bool.self, forKey: .enabled) authenticationRequired = try values.decodeIfPresent(Bool.self, forKey: .authenticationRequired) } } public struct AnchorTransactionInfo: Decodable { public var enabled: Bool public var authenticationRequired:Bool? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case enabled case authenticationRequired = "authentication_required" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decode(Bool.self, forKey: .enabled) authenticationRequired = try values.decodeIfPresent(Bool.self, forKey: .authenticationRequired) } } public struct AnchorFeeInfo: Decodable { public var enabled: Bool public var authenticationRequired:Bool? /// Properties to encode and decode private enum CodingKeys: String, CodingKey { case enabled case authenticationRequired = "authentication_required" } /** Initializer - creates a new instance by decoding from the given decoder. - Parameter decoder: The decoder containing the data */ public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) enabled = try values.decode(Bool.self, forKey: .enabled) authenticationRequired = try values.decodeIfPresent(Bool.self, forKey: .authenticationRequired) } }
0
// // Profile.swift // ios-app // // Created by Fernando Cejas on 05.11.21. // Copyright © 2021 Fernando Cejas. All rights reserved. // import Foundation struct Profile: Identifiable { let id = UUID() var name = String.empty var email = String.empty }
0
// @copyright Trollwerks Inc. import Foundation enum Document { case html case wordpress } enum Visited: String { case yes = "✅" case no = "◻️" }
0
// JFBrightnessView.swift // JFPlayerDemo // // Created by jumpingfrog0 on 14/12/2016. // // // Copyright (c) 2016 Jumpingfrog0 LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import SceneKit class JFVrPlayerControlBar: SCNNode { var playOrPausePlane: SCNPlane! override init() { super.init() let layerPlane = SCNPlane(width: 2, height: 1.5) layerPlane.firstMaterial?.isDoubleSided = true layerPlane.firstMaterial?.diffuse.contents = UIColor.black layerPlane.firstMaterial?.diffuse.wrapS = .clamp layerPlane.firstMaterial?.diffuse.wrapT = .clamp layerPlane.firstMaterial?.diffuse.mipFilter = .nearest layerPlane.firstMaterial?.locksAmbientWithDiffuse = true layerPlane.firstMaterial?.shininess = 0.0 let layerNode = SCNNode(geometry: layerPlane) layerNode.position = SCNVector3(x: 0, y: 0, z: -5) layerNode.physicsBody = SCNPhysicsBody.static() layerNode.physicsBody?.restitution = 1.0 playOrPausePlane = SCNPlane(width: 0.5, height: 0.5) playOrPausePlane.firstMaterial?.isDoubleSided = true playOrPausePlane.firstMaterial?.diffuse.contents = JFImageResourcePath("JFPlayer_pause") playOrPausePlane.firstMaterial?.diffuse.wrapS = .clamp playOrPausePlane.firstMaterial?.diffuse.wrapT = .clamp playOrPausePlane.firstMaterial?.diffuse.mipFilter = .nearest playOrPausePlane.firstMaterial?.locksAmbientWithDiffuse = true playOrPausePlane.firstMaterial?.shininess = 0.0 let playOrPauseNode = SCNNode(geometry: playOrPausePlane) playOrPauseNode.position = SCNVector3(x: 0, y: 0, z: -4) playOrPauseNode.name = "PlayorPauseButton" playOrPauseNode.physicsBody = SCNPhysicsBody.static() playOrPauseNode.physicsBody?.restitution = 1.0 // layerNode.eulerAngles = SCNVector3Make(GLKMathDegreesToRadians(-60), 0, 0) let rotationNode = SCNNode() rotationNode.position = SCNVector3(x: 0, y: 0, z: 0) addChildNode(rotationNode) rotationNode.addChildNode(layerNode) rotationNode.addChildNode(playOrPauseNode) let rotate = SCNAction.rotate(by: CGFloat(-M_PI * 1.0 / 3), around: SCNVector3(x: 1, y: 0, z: 0), duration: 0.0) rotationNode.runAction(rotate) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateUI(shouldPause: Bool) { if shouldPause { playOrPausePlane.firstMaterial?.diffuse.contents = JFImageResourcePath("JFPlayer_play") } else { playOrPausePlane.firstMaterial?.diffuse.contents = JFImageResourcePath("JFPlayer_pause") } } }
0
extension FluentBenchmarker { public func testBatch() throws { try self.testBatch_create() try self.testBatch_update() try self.testBatch_delete() } private func testBatch_create() throws { try runTest(#function, [ GalaxyMigration() ]) { let galaxies = Array("abcdefghijklmnopqrstuvwxyz").map { letter in return Galaxy(name: .init(letter)) } try galaxies.create(on: self.database).wait() let count = try Galaxy.query(on: self.database).count().wait() XCTAssertEqual(count, 26) } } private func testBatch_update() throws { try runTest(#function, [ GalaxyMigration(), GalaxySeed() ]) { try Galaxy.query(on: self.database).set(\.$name, to: "Foo") .update().wait() let galaxies = try Galaxy.query(on: self.database).all().wait() for galaxy in galaxies { XCTAssertEqual(galaxy.name, "Foo") } } } private func testBatch_delete() throws { try runTest(#function, [ GalaxyMigration(), ]) { let galaxies = Array("abcdefghijklmnopqrstuvwxyz").map { letter in return Galaxy(name: .init(letter)) } try EventLoopFuture.andAllSucceed(galaxies.map { $0.create(on: self.database) }, on: self.database.eventLoop).wait() let count = try Galaxy.query(on: self.database).count().wait() XCTAssertEqual(count, 26) try galaxies[..<5].delete(on: self.database).wait() let postDeleteCount = try Galaxy.query(on: self.database).count().wait() XCTAssertEqual(postDeleteCount, 21) } } }
0
import SwiftUI import Speechly struct MicrophoneButton: View { let onStart: () -> Void let onStop: () -> Void var body: some View { MicButtonWrapper(onStart: onStart, onStop: onStop) .frame(width: 80, height: 80) } } /// Wrap the UIKit MicrophoneButtonView to be usable in SwiftUI struct MicButtonWrapper: UIViewRepresentable { let onStart: () -> Void let onStop: () -> Void func makeCoordinator() -> Coordinator { return Coordinator(self) } func makeUIView(context: Context) -> Speechly.MicrophoneButtonView { let view = Speechly.MicrophoneButtonView(delegate: context.coordinator) view.reloadAuthorizationStatus() return view } func updateUIView(_ uiView: Speechly.MicrophoneButtonView, context: Context) { } } extension MicButtonWrapper { class Coordinator: MicrophoneButtonDelegate { var parent: MicButtonWrapper init(_ parent: MicButtonWrapper) { self.parent = parent } func didOpenMicrophone(_ button: MicrophoneButtonView) { parent.onStart() } func didCloseMicrophone(_ button: MicrophoneButtonView) { parent.onStop() } } } struct MicrophoneButton_Previews: PreviewProvider { static var previews: some View { MicrophoneButton(onStart: {}, onStop: {}) } }
0
// // CurrencyTests.swift // FloatCoinTests // // Created by Kaunteya Suryawanshi on 16/02/18. // Copyright © 2018 Kaunteya Suryawanshi. All rights reserved. // import XCTest class CurrencyTests: XCTestCase { let inr = Currency("INR") func testCurrencyIsUpperCased() { XCTAssertEqual(Currency("btc").stringValue, "BTC", "Currency must be uppercases in initializer") } func testLocale() { XCTAssertEqual(Locale("INR")!.identifier, "en_IN") XCTAssertEqual(Locale("GBP")!.identifier, "en_GB") XCTAssertNil(Locale("BTC")) } func testCurrencySymbols() { XCTAssertEqual(Currency("INR").formatted(price: 1234), "₹ 1,234") XCTAssertEqual(Currency("USD").formatted(price: 1234), "$1,234") XCTAssertEqual(Currency("EUR").formatted(price: 1234), "€1 234") XCTAssertEqual(Currency("GBP").formatted(price: 1234), "£1,234") } func testInvalidCurrency() { XCTAssertEqual(Currency("BTC").formatted(price: 1234), "BTC 1,234") XCTAssertEqual(Currency("BTC").formatted(price: 0.1), "BTC 0.10000") XCTAssertEqual(Currency("BTC").formatted(price: 0.12), "BTC 0.12000") } func testsVerySmallNumbers() { XCTAssertEqual(inr.formatted(price: 0.0071234), "₹ 0.00712") XCTAssertEqual(inr.formatted(price: 0.00071234), "₹ 0.000712") XCTAssertEqual(inr.formatted(price: 0.000071234), "₹ 0.0000712") XCTAssertEqual(inr.formatted(price: 0.0000071234), "₹ 0.00000712") XCTAssertEqual(inr.formatted(price: 0.00000071234), "₹ 0.000000712") XCTAssertEqual(inr.formatted(price: 0.000000071234), "₹ 0.0000000712") XCTAssertEqual(inr.formatted(price: 0.0000000071234), "₹ 0.00000000712") XCTAssertEqual(inr.formatted(price: 0.000000007), "₹ 0.00000000700") } func testDigit0() { // 5 digits after decimal point XCTAssertEqual(inr.formatted(price: 0.1), "₹ 0.10000") XCTAssertEqual(inr.formatted(price: 0.11), "₹ 0.11000") XCTAssertEqual(inr.formatted(price: 0.111), "₹ 0.11100") XCTAssertEqual(inr.formatted(price: 0.1111), "₹ 0.11110") XCTAssertEqual(inr.formatted(price: 0.11111), "₹ 0.11111") XCTAssertEqual(inr.formatted(price: 0.111111), "₹ 0.11111") XCTAssertEqual(inr.formatted(price: 0.1111111), "₹ 0.11111") } func testDigit1() { // 3 digits after decimal point XCTAssertEqual(inr.formatted(price: 1), "₹ 1.000") XCTAssertEqual(inr.formatted(price: 1.1), "₹ 1.100") XCTAssertEqual(inr.formatted(price: 1.11), "₹ 1.110") XCTAssertEqual(inr.formatted(price: 1.111), "₹ 1.111") XCTAssertEqual(inr.formatted(price: 1.1111), "₹ 1.111") } func testDigit2() { // 2 digits after decimal point XCTAssertEqual(inr.formatted(price: 11), "₹ 11.00") XCTAssertEqual(inr.formatted(price: 11.0), "₹ 11.00") XCTAssertEqual(inr.formatted(price: 11.1), "₹ 11.10") XCTAssertEqual(inr.formatted(price: 11.11), "₹ 11.11") XCTAssertEqual(inr.formatted(price: 11.111), "₹ 11.11") XCTAssertEqual(inr.formatted(price: 11.1111), "₹ 11.11") } func testDigit3() { // Only one digit after decimal point XCTAssertEqual(inr.formatted(price: 111), "₹ 111.0") XCTAssertEqual(inr.formatted(price: 111.0), "₹ 111.0") XCTAssertEqual(inr.formatted(price: 111.1), "₹ 111.1") XCTAssertEqual(inr.formatted(price: 111.12), "₹ 111.1") XCTAssertEqual(inr.formatted(price: 111.123), "₹ 111.1") } func testDigitMorethan3() { XCTAssertEqual(inr.formatted(price: 1234), "₹ 1,234") XCTAssertEqual(inr.formatted(price: 12345), "₹ 12,345") XCTAssertEqual(inr.formatted(price: 123456), "₹ 1,23,456") XCTAssertEqual(inr.formatted(price: 1234567), "₹ 12,34,567") XCTAssertEqual(inr.formatted(price: 12345678), "₹ 1,23,45,678") XCTAssertEqual(inr.formatted(price: 12345678.1), "₹ 1,23,45,678") XCTAssertEqual(inr.formatted(price: 12345678.12), "₹ 1,23,45,678") XCTAssertEqual(inr.formatted(price: 12345678.123), "₹ 1,23,45,678") } }
0
// // ConstantKey.swift // iFeiBo // // Created by Alexcai on 2017/9/16. // Copyright © 2017年 Alexcai. All rights reserved. // import Foundation let kFBHomeControllerID = "Home" let kFBLoginConttollerID = "Login" let kFBStatusLoginItemID = "LoginItem" let kFBAppKey = "" let kFBOAuth2URLPath = "" // MARK: - weibo API URL let WBAppID = "3847062016" let WBAppSecretKey = "r8w5u6pxuf0wog8s4m2uupcea7j85x9y" let WBAppReDirectURL = "http://alexiuce.github.io" let WBOAuth2URL = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppID)&scope=all&response_type=code&redirect_uri=\(WBAppReDirectURL)" let WBTokenURL = "https://api.weibo.com/oauth2/access_token" /** 获取当前登录用户及其所关注(授权)用户的最新微博 */ let WBStatusURL = "https://api.weibo.com/2/statuses/home_timeline.json"
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 protocol e : S<T where g: NSObject { struct B<T where g: T where g: j { func a(Any) { case c, { var e: A? { class c : j { func a func a() { if true { [k<h : a { class case c, enum